/// <summary>
        /// Update notifications status
        /// </summary>
        /// <param name="storageConsistencyMode">Storage consistency mode</param>
        /// <param name="userHandle">User handle</param>
        /// <param name="appHandle">App handle</param>
        /// <param name="readActivityHandle">Read activity handle</param>
        /// <param name="readNotificationsStatusEntity">Read notifications status entity</param>
        /// <returns>Update notifications status task</returns>
        public async Task UpdateNotificationsStatus(
            StorageConsistencyMode storageConsistencyMode,
            string userHandle,
            string appHandle,
            string readActivityHandle,
            INotificationsStatusEntity readNotificationsStatusEntity)
        {
            CTStore store = await this.tableStoreManager.GetStore(ContainerIdentifier.Notifications);

            ObjectTable statusTable = this.tableStoreManager.GetTable(ContainerIdentifier.Notifications, TableIdentifier.NotificationsStatus) as ObjectTable;
            CountTable  countTable  = this.tableStoreManager.GetTable(ContainerIdentifier.Notifications, TableIdentifier.NotificationsCount) as CountTable;

            Transaction transaction = new Transaction();

            if (readNotificationsStatusEntity == null)
            {
                NotificationsStatusEntity notificationsStatusEntity = new NotificationsStatusEntity()
                {
                    ReadActivityHandle = readActivityHandle
                };

                transaction.Add(Operation.Insert(statusTable, userHandle, appHandle, notificationsStatusEntity));
            }
            else
            {
                readNotificationsStatusEntity.ReadActivityHandle = readActivityHandle;
                transaction.Add(Operation.Replace(statusTable, userHandle, appHandle, readNotificationsStatusEntity as NotificationsStatusEntity));
            }

            transaction.Add(Operation.InsertOrReplace(countTable, userHandle, appHandle, 0));
            await store.ExecuteTransactionAsync(transaction, storageConsistencyMode.ToConsistencyMode());
        }
Beispiel #2
0
        protected override async Task Invoke(MapDocument document, CommandParameters parameters)
        {
            var selBox = document.Selection.GetSelectionBoundingBox();

            var tl = document.Map.Data.GetOne <TransformationFlags>() ?? new TransformationFlags();

            var transaction = new Transaction();

            foreach (var mo in document.Selection.GetSelectedParents().ToList())
            {
                var objBox      = mo.BoundingBox;
                var translation = GetTranslation(selBox, objBox);
                if (translation == Vector3.Zero)
                {
                    continue;
                }

                var tform = Matrix4x4.CreateTranslation(translation);

                var transformOperation = new BspEditor.Modification.Operations.Mutation.Transform(tform, mo);
                transaction.Add(transformOperation);

                // Check for texture transform
                if (tl.TextureLock)
                {
                    transaction.Add(new TransformTexturesUniform(tform, mo.FindAll()));
                }
            }

            if (!transaction.IsEmpty)
            {
                await MapDocumentOperation.Perform(document, transaction);
            }
        }
Beispiel #3
0
        protected override async Task Invoke(MapDocument document, CommandParameters parameters)
        {
            var selBox = document.Selection.GetSelectionBoundingBox();

            var axis    = parameters.Get <Vector3>("Axis");
            var amount  = parameters.Get <float>("Angle");
            var radians = (float)MathHelper.DegreesToRadians(amount);

            var tl = document.Map.Data.GetOne <TransformationFlags>() ?? new TransformationFlags();

            var transaction = new Transaction();

            var tform = Matrix4x4.CreateTranslation(-selBox.Center)
                        * Matrix4x4.CreateFromAxisAngle(axis, radians)
                        * Matrix4x4.CreateTranslation(selBox.Center);

            var transformOperation = new BspEditor.Modification.Operations.Mutation.Transform(tform, document.Selection.GetSelectedParents());

            transaction.Add(transformOperation);

            // Check for texture transform
            if (tl.TextureLock)
            {
                transaction.Add(new TransformTexturesUniform(tform, document.Selection));
            }

            await MapDocumentOperation.Perform(document, transaction);
        }
Beispiel #4
0
        private void SelectObject(Solid closestObject)
        {
            // Nothing was clicked, don't change the selection
            if (closestObject == null)
            {
                return;
            }

            var operation = new Transaction();

            // Ctrl doesn't toggle selection, only adds to it.
            // Ctrl+clicking a selected solid will do nothing.

            if (!KeyboardState.Ctrl)
            {
                // Ctrl isn't down, so we want to clear the selection
                operation.Add(new Deselect(Document.Selection.Where(x => !ReferenceEquals(x, closestObject)).ToList()));
            }

            if (!closestObject.IsSelected)
            {
                // The clicked object isn't selected yet, select it.
                operation.Add(new Select(closestObject));
            }

            if (!operation.IsEmpty)
            {
                MapDocumentOperation.Perform(Document, operation);
            }
        }
        /// <summary>
        /// removes the order passed in from the persistent storage. Also the order detail rows belonging with this order will be
        /// removed. It is wise to refresh the gui after this action, since collections and other data elements have to refreshed to illustrate the
        /// change.
        /// </summary>
        /// <param name="orderToRemove">Order entity to remove from the persistent storage</param>
        /// <returns>true if the removal was succesful, false otherwise</returns>
        private bool RemoveOrder(OrderEntity orderToRemove)
        {
            Transaction removalTrans = new Transaction(System.Data.IsolationLevel.ReadCommitted, "RemoveOrder");
            bool        toReturn     = false;

            try
            {
                // first remove the orderdetail rows of this order
                removalTrans.Add(orderToRemove.OrderDetails);
                orderToRemove.OrderDetails.DeleteMulti();

                // remove the order itself
                removalTrans.Add(orderToRemove);
                toReturn = orderToRemove.Delete();

                // done
                removalTrans.Commit();
            }
            catch (Exception ex)
            {
                removalTrans.Rollback();
                throw ex;
            }
            finally
            {
                removalTrans.Dispose();
            }

            return(toReturn);
        }
Beispiel #6
0
        public static Boolean CreateMessage(string title, string body, MessageType type, int deviceId)
        {
            var transaction = new Transaction(IsolationLevel.ReadCommitted, "create message");

            try
            {
                var messageEntity = new MessageEntity {
                    MessageType = type, Title = title, Body = body, CreateTime = DateTime.Now, StartTime = DateTime.Now
                };
                transaction.Add(messageEntity);
                messageEntity.Save();

                var deviceMessage = new DeviceMessageEntity {
                    DeviceId = deviceId, MessageId = messageEntity.MessageId
                };
                transaction.Add(deviceMessage);
                deviceMessage.Save();

                transaction.Commit();

                return(true);
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                Loggers.LogException(GlobalSettings.SYSTEM_DAEMON_USER_ID, ex);
                return(false);
            }
            finally
            {
                transaction.Dispose();
            }
        }
Beispiel #7
0
        /// <summary>
        /// Insert user topic
        /// </summary>
        /// <param name="storageConsistencyMode">Storage consistency mode</param>
        /// <param name="userHandle">User handle</param>
        /// <param name="appHandle">App handle</param>
        /// <param name="topicHandle">Topic handle</param>
        /// <returns>Insert user topic task</returns>
        public async Task InsertUserTopic(
            StorageConsistencyMode storageConsistencyMode,
            string userHandle,
            string appHandle,
            string topicHandle)
        {
            TopicFeedEntity topicFeedEntity = new TopicFeedEntity()
            {
                AppHandle   = appHandle,
                TopicHandle = topicHandle,
                UserHandle  = userHandle
            };

            CTStore store = await this.tableStoreManager.GetStore(ContainerIdentifier.UserTopics);

            FeedTable  feedTable  = this.tableStoreManager.GetTable(ContainerIdentifier.UserTopics, TableIdentifier.UserTopicsFeed) as FeedTable;
            CountTable countTable = this.tableStoreManager.GetTable(ContainerIdentifier.UserTopics, TableIdentifier.UserTopicsCount) as CountTable;

            Transaction transaction = new Transaction();

            transaction.Add(Operation.Insert(feedTable, userHandle, appHandle, topicHandle, topicFeedEntity));
            transaction.Add(Operation.Insert(feedTable, userHandle, MasterApp.AppHandle, topicHandle, topicFeedEntity));
            transaction.Add(Operation.InsertOrIncrement(countTable, userHandle, appHandle));
            transaction.Add(Operation.InsertOrIncrement(countTable, userHandle, MasterApp.AppHandle));
            await store.ExecuteTransactionAsync(transaction, storageConsistencyMode.ToConsistencyMode());
        }
Beispiel #8
0
        protected override async Task Invoke(MapDocument document, CommandParameters parameters)
        {
            var selBox = document.Selection.GetSelectionBoundingBox();

            var tl = document.Map.Data.GetOne <TransformationFlags>() ?? new TransformationFlags();

            var transaction = new Transaction();

            var tform = Matrix4x4.CreateTranslation(-selBox.Center)
                        * Matrix4x4.CreateScale(GetScale())
                        * Matrix4x4.CreateTranslation(selBox.Center);

            var transformOperation = new BspEditor.Modification.Operations.Mutation.Transform(tform, document.Selection.GetSelectedParents());

            transaction.Add(transformOperation);

            transaction.Add(new FlipFaces(document.Selection));

            // Check for texture transform
            if (tl.TextureLock)
            {
                transaction.Add(new TransformTexturesUniform(tform, document.Selection));
            }

            await MapDocumentOperation.Perform(document, transaction);
        }
Beispiel #9
0
        public async Task Fix(MapDocument document, Problem problem)
        {
            var tc = await document.Environment.GetTextureCollection();

            // Get the default texture to apply
            var first = tc.GetBrowsableTextures()
                        .OrderBy(t => t, StringComparer.CurrentCultureIgnoreCase)
                        .Where(item => item.Length > 0)
                        .Select(item => new { item, c = Char.ToLower(item[0]) })
                        .Where(t => t.c >= 'a' && t.c <= 'z')
                        .Select(t => t.item)
                        .FirstOrDefault();

            var transaction = new Transaction();

            foreach (var obj in problem.Objects)
            {
                foreach (var face in obj.Data.Intersect(problem.ObjectData).OfType <Face>())
                {
                    var clone = (Face)face.Clone();
                    clone.Texture.Name = first;

                    transaction.Add(new RemoveMapObjectData(obj.ID, face));
                    transaction.Add(new AddMapObjectData(obj.ID, clone));
                }
            }

            await MapDocumentOperation.Perform(document, transaction);
        }
Beispiel #10
0
        /// <summary>
        /// Delete popular topic
        /// </summary>
        /// <param name="storageConsistencyMode">Storage consistency mode</param>
        /// <param name="timeRange">Time range</param>
        /// <param name="hostAppHandle">Hosting app handle: Master app or client app</param>
        /// <param name="appHandle">App handle</param>
        /// <param name="topicHandle">Topic handle</param>
        /// <param name="topicUserHandle">User handle</param>
        /// <returns>Delete popular topic task</returns>
        public async Task DeletePopularTopic(
            StorageConsistencyMode storageConsistencyMode,
            TimeRange timeRange,
            string hostAppHandle,
            string appHandle,
            string topicHandle,
            string topicUserHandle)
        {
            TopicRankFeedEntity topicRankFeedEntity = new TopicRankFeedEntity()
            {
                AppHandle   = appHandle,
                TopicHandle = topicHandle,
                UserHandle  = topicUserHandle
            };
            var serializedEntity = StoreSerializers.MinimalTopicRankFeedEntitySerialize(topicRankFeedEntity);

            CTStore store = await this.tableStoreManager.GetStore(ContainerIdentifier.PopularTopics);

            Transaction   transaction = new Transaction();
            RankFeedTable topicsTable = this.tableStoreManager.GetTable(ContainerIdentifier.PopularTopics, TableIdentifier.PopularTopicsFeed) as RankFeedTable;
            string        feedKey     = this.GetPopularTopicsFeedKey(timeRange, hostAppHandle);

            transaction.Add(Operation.DeleteIfExists(topicsTable, ContainerIdentifier.PopularTopics.ToString(), feedKey, serializedEntity));

            if (timeRange != TimeRange.AllTime)
            {
                RankFeedTable expirationsTable = this.tableStoreManager.GetTable(ContainerIdentifier.PopularTopics, TableIdentifier.PopularTopicsExpirationsFeed) as RankFeedTable;
                transaction.Add(Operation.DeleteIfExists(expirationsTable, ContainerIdentifier.PopularTopics.ToString(), feedKey, serializedEntity));
            }

            await store.ExecuteTransactionAsync(transaction, storageConsistencyMode.ToConsistencyMode());
        }
        private async Task ApplyChanges(Func <IMapObject, Face, Task <bool> > apply)
        {
            var sel = GetFaceSelection();

            var edit  = new Transaction();
            var found = false;

            foreach (var it in sel.GetSelectedFaces())
            {
                var clone  = (Face)it.Value.Clone();
                var result = await apply(it.Key, clone);

                if (!result)
                {
                    continue;
                }

                found = true;

                edit.Add(new RemoveMapObjectData(it.Key.ID, it.Value));
                edit.Add(new AddMapObjectData(it.Key.ID, clone));
            }

            if (found)
            {
                await MapDocumentOperation.Perform(Document, edit);
                await FaceSelectionChanged();
            }
        }
Beispiel #12
0
        public async Task Invoke(IContext context, CommandParameters parameters)
        {
            var md = context.Get <MapDocument>("ActiveDocument");

            if (md == null || md.Selection.IsEmpty)
            {
                return;
            }

            var at = md.Map.Data.GetOne <ActiveTexture>();

            if (String.IsNullOrWhiteSpace(at?.Name))
            {
                return;
            }

            var edit = new Transaction();

            foreach (var solid in md.Selection.OfType <Solid>())
            {
                foreach (var face in solid.Faces)
                {
                    var clone = (Face)face.Clone();
                    clone.Texture.Name = at.Name;

                    edit.Add(new RemoveMapObjectData(solid.ID, face));
                    edit.Add(new AddMapObjectData(solid.ID, clone));
                }
            }

            if (!edit.IsEmpty)
            {
                await MapDocumentOperation.Perform(md, edit);
            }
        }
        /// <summary>
        /// Lists a used mailbox messages.
        /// </summary>
        /// <param name="count"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public static Transaction UpdateInboxCount(int count, UserEntity user)
        {
            var transaction = new Transaction(IsolationLevel.ReadCommitted, "mailbox update");

            try
            {
                var countSetting = new UserSettingEntity(user.UserId, "SupportInboxCount")
                {
                    UserId = user.UserId,
                    Name   = "SupportInboxCount",
                    Value  = count.ToString(CultureInfo.InvariantCulture)
                };
                transaction.Add(countSetting);
                countSetting.Save();

                var timeSetting = new UserSettingEntity(user.UserId, "SupportInboxUpdated")
                {
                    UserId = user.UserId,
                    Name   = "SupportInboxUpdated",
                    Value  = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)
                };
                transaction.Add(timeSetting);
                timeSetting.Save();

                return(transaction);
            }
            catch
            {
                transaction.Rollback();
                transaction.Dispose();
            }
            return(null);
        }
Beispiel #14
0
        /// <summary>
        /// Handles the Click event of the btnSaveAll control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnSaveAll_Click(object sender, EventArgs e)
        {
            // use transaction to commit toDetele and toUpdate items at once
            Transaction transactionManager = new Transaction(IsolationLevel.ReadCommitted, "ProductsTrans");

            try
            {
                // save products
                transactionManager.Add(_productsCollection);
                _productsCollection.SaveMulti();

                // delete products
                transactionManager.Add(_productsToDelete);
                _productsToDelete.DeleteMulti();

                // save the whole transaction
                transactionManager.Commit();

                // no errors... clean the toDetele collection
                _productsToDelete.Clear();

                // successfully message
                MessageBox.Show("Data was saved successfully!", "Products", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            // there are errors. Rollback the transaction and show the errors to the user.
            catch (Exception ex)
            {
                transactionManager.Rollback();
                MessageBox.Show(ex.Message, "Errors", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #15
0
        internal override Transaction GetDeactivationTransaction()
        {
            var transaction = new Transaction($"Deactivation transaction for unit {UnitName}");

            transaction.Add(new SetUnitStateTask(this, UnitState.Deactivating, UnitState.Active));
            transaction.Add(new SetUnitStateTask(this, UnitState.Inactive, UnitState.Deactivating));

            return(transaction);
        }
        private void ApplyPropertyChanges(bool trivial)
        {
            var edit = new Transaction();

            var sel = GetFaceSelection();

            if (trivial)
            {
                // Remember the state before the last change
                if (_memoTextures == null)
                {
                    _memoTextures = sel.ToDictionary(x => x, x => x.Texture.Clone());
                }

                // Once a trivial change is started we know that there will definitely be a matching nontrivial task
                // We aggregate changes so they don't spam the undo stack
                edit.Add(new TrivialOperation(
                             x =>
                {
                    foreach (var it in sel.GetSelectedFaces())
                    {
                        ApplyFaceValues(it.Value);
                    }
                },
                             x =>
                {
                    foreach (var p in sel.GetSelectedParents())
                    {
                        x.Update(p);
                    }
                }
                             ));
            }
            else
            {
                foreach (var it in sel.GetSelectedFaces())
                {
                    // Restore the last committed values
                    if (_memoTextures != null && _memoTextures.ContainsKey(it.Value))
                    {
                        var k = _memoTextures[it.Value];
                        it.Value.Texture.Unclone(k);
                    }

                    var clone = (Face)it.Value.Clone();
                    ApplyFaceValues(clone);

                    edit.Add(new RemoveMapObjectData(it.Key.ID, it.Value));
                    edit.Add(new AddMapObjectData(it.Key.ID, clone));
                }

                // Reset the memory
                _memoTextures = null;
            }

            MapDocumentOperation.Perform(Document, edit);
        }
        public async Task <IOperation> GetOperation(MapDocument doc)
        {
            if (ActionSelect.Checked)
            {
                return(new Transaction(
                           new Deselect(doc.Selection.ToList()),
                           new Select(GetObjects(doc))
                           ));
            }

            var faces = GetObjects(doc).OfType <Solid>()
                        .SelectMany(x => x.Faces.Select(f => new { Face = f, Parent = x }))
                        .Where(x => MatchTextureName(x.Face.Texture.Name))
                        .ToList();

            var rescale = RescaleTextures.Checked;
            var tc      = rescale ? await doc.Environment.GetTextureCollection() : null;

            var replacements = GetReplacements(faces.Select(x => x.Face.Texture.Name));

            var tran = new Transaction();

            foreach (var fp in faces)
            {
                var face   = fp.Face;
                var parent = fp.Parent;

                var clone = (Face)face.Clone();

                var repl = replacements.FirstOrDefault(x => x.Find == face.Texture.Name.ToLowerInvariant());
                if (repl == null)
                {
                    continue;
                }

                if (rescale && tc != null)
                {
                    var find = await tc.GetTextureItem(face.Texture.Name);

                    var replace = await tc.GetTextureItem(repl.Replace);

                    if (find != null && replace != null)
                    {
                        clone.Texture.XScale *= find.Width / (float)replace.Width;
                        clone.Texture.YScale *= find.Height / (float)replace.Height;
                    }
                }

                clone.Texture.Name = repl.Replace;

                tran.Add(new RemoveMapObjectData(parent.ID, face));
                tran.Add(new AddMapObjectData(parent.ID, clone));
            }

            return(tran);
        }
Beispiel #18
0
        internal override Transaction GetActivationTransaction()
        {
            var transaction = new Transaction($"Activation transaction for unit {UnitName}");

            transaction.Add(new SetUnitStateTask(this, UnitState.Activating, UnitState.Inactive | UnitState.Failed));
            transaction.Add(new SetUnitStateTask(this, UnitState.Active, UnitState.Activating));
            transaction.Add(new UpdateUnitActivationTimeTask(this));

            return(transaction);
        }
Beispiel #19
0
		/// <summary>
		/// Updates the user/forum/thread statistics after a message insert. Also makes sure if the thread isn't in a queue and the forum has a default support
		/// queue that the thread is added to that queue
		/// </summary>
		/// <param name="threadID">The thread ID.</param>
		/// <param name="userID">The user ID.</param>
		/// <param name="transactionToUse">The transaction to use.</param>
		/// <param name="postingDate">The posting date.</param>
		/// <param name="addToQueueIfRequired">if set to true, the thread will be added to the default queue of the forum the thread is in, if the forum
		/// has a default support queue and the thread isn't already in a queue.</param>
		/// <remarks>Leaves the passed in transaction open, so it doesn't commit/rollback, it just performs a set of actions inside the
		/// passed in transaction.</remarks>
		internal static void UpdateStatisticsAfterMessageInsert(int threadID, int userID, Transaction transactionToUse, DateTime postingDate, bool addToQueueIfRequired, bool subscribeToThread)
		{
			// user statistics
			UserEntity userUpdater = new UserEntity();
			// set the amountofpostings field to an expression so it will be increased with 1. 
			userUpdater.Fields[(int)UserFieldIndex.AmountOfPostings].ExpressionToApply = (UserFields.AmountOfPostings + 1);
			UserCollection users = new UserCollection();
			transactionToUse.Add(users);
			users.UpdateMulti(userUpdater, (UserFields.UserID == userID));	// update directly on the DB. 

			// thread statistics
			ThreadEntity threadUpdater = new ThreadEntity();
			threadUpdater.ThreadLastPostingDate = postingDate;
			threadUpdater.MarkedAsDone = false;
			ThreadCollection threads = new ThreadCollection();
			transactionToUse.Add(threads);
			threads.UpdateMulti(threadUpdater, (ThreadFields.ThreadID == threadID));

			// forum statistics. Load the forum from the DB, as we need it later on. Use a fieldcompareset predicate to fetch the forum as we don't know the 
			// forumID as we haven't fetched the thread
			ForumCollection forums = new ForumCollection();
			transactionToUse.Add(forums);
			// use a fieldcompare set predicate to select the forumid based on the thread. This filter is equal to
			// WHERE ForumID == (SELECT ForumID FROM Thread WHERE ThreadID=@ThreadID)
			var forumFilter = new FieldCompareSetPredicate(
								ForumFields.ForumID, ThreadFields.ForumID, SetOperator.Equal, (ThreadFields.ThreadID == threadID));
			forums.GetMulti(forumFilter);
			ForumEntity containingForum = null;
			if(forums.Count>0)
			{
				// forum found. There's just one.
				containingForum = forums[0];
				containingForum.ForumLastPostingDate = postingDate;
				// save the forum. Just save the collection
				forums.SaveMulti();
			}

			if(addToQueueIfRequired)
			{
				// If the thread involved isn't in a queue, place it in the default queue of the forum (if applicable)
				SupportQueueEntity containingQueue = SupportQueueGuiHelper.GetQueueOfThread(threadID, transactionToUse);
				if((containingQueue == null) && (containingForum != null) && (containingForum.DefaultSupportQueueID.HasValue))
				{
					// not in a queue, and the forum has a default queue. Add the thread to the queue of the forum
					SupportQueueManager.AddThreadToQueue(threadID, containingForum.DefaultSupportQueueID.Value, userID, transactionToUse);
				}
			}

            //subscribe to thread if indicated
            if(subscribeToThread)
            {
				UserManager.AddThreadToSubscriptions(threadID, userID, transactionToUse);
            }
		}
Beispiel #20
0
        public Task Fix(MapDocument document, Problem problem)
        {
            var transaction = new Transaction();

            foreach (var obj in problem.Objects.SelectMany(x => x.Find(f => f is Entity)).Distinct())
            {
                transaction.Add(new Detatch(obj.Hierarchy.Parent.ID, obj));
                transaction.Add(new Attach(document.Map.Root.ID, obj));
            }

            return(MapDocumentOperation.Perform(document, transaction));
        }
Beispiel #21
0
        public Task Fix(MapDocument document, Problem problem)
        {
            var transaction = new Transaction();

            foreach (var obj in problem.Objects)
            {
                transaction.Add(new Detatch(obj.ID, obj.Hierarchy));
                transaction.Add(new Attach(document.Map.Root.ID, obj.Hierarchy));
            }

            return(MapDocumentOperation.Perform(document, transaction));
        }
Beispiel #22
0
        internal override Transaction GetDeactivationTransaction()
        {
            var transaction = new Transaction($"Deactivation transaction for unit {UnitName}");

            transaction.Add(new SetUnitStateTask(this, UnitState.Deactivating, UnitState.Active));
            transaction.Add(new StopUnitProcessesTask(this));
            //transaction.Add(new SetUnitStateTask(this, UnitState.Inactive, UnitState.Deactivating));

            transaction.OnFailure = new SetUnitStateTask(this, UnitState.Failed);

            return(transaction);
        }
Beispiel #23
0
        public ActionResult Add(ComposeMessage model)
        {
            if (ModelState.IsValid)
            {
                var transaction = new Transaction(IsolationLevel.ReadCommitted, "add message");
                try
                {
                    // add the message
                    var message = new MessageEntity
                    {
                        MessageType = model.Type,
                        Title       = model.Title,
                        Body        = model.Body,
                        CreateTime  = DateTime.UtcNow,
                        StartTime   = model.StartTime.ToUniversalTime(),
                        EndTime     = model.EndTime.HasValue ? model.EndTime.Value.ToUniversalTime() : new DateTime?()
                    };
                    transaction.Add(message);
                    message.Save();

                    // add the devicemessage entities for all the tos
                    foreach (var device in model.Tos)
                    {
                        var dm = new DeviceMessageEntity
                        {
                            DeviceId  = device.DeviceId,
                            MessageId = message.MessageId
                        };
                        transaction.Add(dm);
                        dm.Save();
                    }

                    transaction.Commit();

                    return(new EmptyResult());
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw new HttpException(417, Message.AddError);
                }
                finally
                {
                    transaction.Dispose();
                }
            }

            Response.StatusCode             = 417;
            Response.TrySkipIisCustomErrors = true;

            return(PartialView("Edit", model));
        }
        /// <summary>
        /// Insert notification
        /// </summary>
        /// <param name="storageConsistencyMode">Storage consistency mode</param>
        /// <param name="userHandle">User handle</param>
        /// <param name="appHandle">App handle</param>
        /// <param name="activityHandle">Activity handle</param>
        /// <param name="activityType">Activity type</param>
        /// <param name="actorUserHandle">Actor user handle</param>
        /// <param name="actedOnUserHandle">Acted on user handle</param>
        /// <param name="actedOnContentType">Acted on content type</param>
        /// <param name="actedOnContentHandle">Acted on content handle</param>
        /// <param name="createdTime">Created time</param>
        /// <returns>Insert notification task</returns>
        public async Task InsertNotification(
            StorageConsistencyMode storageConsistencyMode,
            string userHandle,
            string appHandle,
            string activityHandle,
            ActivityType activityType,
            string actorUserHandle,
            string actedOnUserHandle,
            ContentType actedOnContentType,
            string actedOnContentHandle,
            DateTime createdTime)
        {
            ActivityFeedEntity activityFeedEntity = new ActivityFeedEntity()
            {
                ActivityHandle       = activityHandle,
                AppHandle            = appHandle,
                ActivityType         = activityType,
                ActorUserHandle      = actorUserHandle,
                ActedOnUserHandle    = actedOnUserHandle,
                ActedOnContentType   = actedOnContentType,
                ActedOnContentHandle = actedOnContentHandle,
                CreatedTime          = createdTime
            };

            CTStore store = await this.tableStoreManager.GetStore(ContainerIdentifier.Notifications);

            FeedTable  feedTable  = this.tableStoreManager.GetTable(ContainerIdentifier.Notifications, TableIdentifier.NotificationsFeed) as FeedTable;
            CountTable countTable = this.tableStoreManager.GetTable(ContainerIdentifier.Notifications, TableIdentifier.NotificationsCount) as CountTable;

            // do an insert & increment in a transaction.
            // if a queue message for inserting a notification gets processed twice, then this transaction will generate
            // a storage exception on the second attempt (because the insert will fail with a conflict (409) http status)
            try
            {
                Transaction transaction = new Transaction();
                transaction.Add(Operation.Insert(feedTable, userHandle, appHandle, activityHandle, activityFeedEntity));
                transaction.Add(Operation.InsertOrIncrement(countTable, userHandle, appHandle));
                await store.ExecuteTransactionAsync(transaction, storageConsistencyMode.ToConsistencyMode());
            }
            catch (StorageException e)
            {
                // ignore this exception only if item exists (error code 409 conflict)
                if (e.RequestInformation.HttpStatusCode == (int)HttpStatusCode.Conflict)
                {
                    this.log.LogInformation("NotificationsStore.InsertNotification received a conflict on insert" + e.Message);
                }
                else
                {
                    throw e;
                }
            }
        }
Beispiel #25
0
        /// <summary>
        /// Deletes the given role from the system.
        /// </summary>
        /// <param name="roleID">ID of role to delete</param>
        /// <returns>true if succeeded, false otherwise</returns>
        public static bool DeleteRole(int roleID)
        {
            RoleEntity toDelete = SecurityGuiHelper.GetRole(roleID);

            if (toDelete == null)
            {
                // not found
                return(false);
            }

            Transaction trans = new Transaction(IsolationLevel.ReadCommitted, "DeleteRole");

            try
            {
                // remove the role - forum - action right entities
                ForumRoleForumActionRightCollection forumRoleActionRights = new ForumRoleForumActionRightCollection();
                trans.Add(forumRoleActionRights);
                forumRoleActionRights.DeleteMulti(ForumRoleForumActionRightFields.RoleID == roleID);

                // Remove role-audit action entities
                RoleAuditActionCollection roleAuditActions = new RoleAuditActionCollection();
                trans.Add(roleAuditActions);
                roleAuditActions.DeleteMulti(RoleAuditActionFields.RoleID == roleID);

                // remove Role - systemright entities
                RoleSystemActionRightCollection roleSystemRights = new RoleSystemActionRightCollection();
                trans.Add(roleSystemRights);
                roleSystemRights.DeleteMulti(RoleSystemActionRightFields.RoleID == roleID);

                // remove Role - user entities
                RoleUserCollection roleUsers = new RoleUserCollection();
                trans.Add(roleUsers);
                roleUsers.DeleteMulti(RoleUserFields.RoleID == roleID);

                // delete the actual role
                trans.Add(toDelete);
                toDelete.Delete();
                trans.Commit();
                return(true);
            }
            catch
            {
                // error occured, rollback
                trans.Rollback();
                throw;
            }
            finally
            {
                trans.Dispose();
            }
        }
Beispiel #26
0
        public static int AddBonusVacationHours(
            DateTime HireDateAfter,
            int SalariedHours,
            int NonSalariedHours)
        {
            Transaction MyTransaction = new Transaction(
                System.Data.IsolationLevel.RepeatableRead, "MyTransaction");
            int RowsAffected = 0;

            try
            {
                EmployeeCollection Salaried = new EmployeeCollection();
                MyTransaction.Add(Salaried);
                IPredicateExpression SalariedPred =
                    new PredicateExpression();
                SalariedPred.Add(
                    (EmployeeFields.HireDate >= HireDateAfter) &
                    (EmployeeFields.SalariedFlag == true));
                Salaried.GetMulti(SalariedPred);
                foreach (EmployeeEntity Employee in Salaried)
                {
                    Employee.VacationHours += Convert.ToInt16(SalariedHours);
                }
                RowsAffected += Salaried.SaveMulti();
                EmployeeCollection NonSalaried = new EmployeeCollection();
                MyTransaction.Add(NonSalaried);
                IPredicateExpression NonSalariedPred =
                    new PredicateExpression();
                NonSalariedPred.Add(
                    (EmployeeFields.HireDate >= HireDateAfter) &
                    (EmployeeFields.SalariedFlag == false));
                NonSalaried.GetMulti(NonSalariedPred);
                foreach (EmployeeEntity Employee in NonSalaried)
                {
                    Employee.VacationHours += Convert.ToInt16(NonSalariedHours);
                }
                RowsAffected += NonSalaried.SaveMulti();
                MyTransaction.Commit();
            }
            catch (Exception err)
            {
                MyTransaction.Rollback();
                throw new ApplicationException(
                          "Error adding vacation hours: " + err.Message);
            }
            finally
            {
                MyTransaction.Dispose();
            }
            return(RowsAffected);
        }
        public static IInternalTransaction CreateDefaultTransaction(bool isWebTransaction          = true, string uri     = null,
                                                                    string guid                    = null, int?statusCode = null, int?subStatusCode = null, string referrerCrossProcessId = null,
                                                                    string transactionCategory     = "defaultTxCategory", string transactionName = "defaultTxName", bool addSegment = true,
                                                                    IEnumerable <Segment> segments = null, bool sampled = false, IConfigurationService configurationService         = null, Exception exception = null)
        {
            var name = isWebTransaction
                ? TransactionName.ForWebTransaction(transactionCategory, transactionName)
                : TransactionName.ForOtherTransaction(transactionCategory, transactionName);

            segments = segments ?? Enumerable.Empty <Segment>();

            var placeholderMetadataBuilder = new TransactionMetadata();
            var placeholderMetadata        = placeholderMetadataBuilder.ConvertToImmutableMetadata();

            var immutableTransaction = new ImmutableTransaction(name, segments, placeholderMetadata, DateTime.Now, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), guid, false, false, false, 0.5f, false, string.Empty, null, _attribDefSvc.AttributeDefs);
            var priority             = 0.5f;

            var configuration = configurationService?.Configuration ?? GetDefaultConfiguration();
            var errorService  = configurationService != null ? new ErrorService(configurationService) : new ErrorService(Mock.Create <IConfigurationService>());

            var internalTransaction = new Transaction(configuration, immutableTransaction.TransactionName, Mock.Create <ITimer>(), DateTime.UtcNow, Mock.Create <ICallStackManager>(),
                                                      _databaseService, priority, Mock.Create <IDatabaseStatementParser>(), Mock.Create <IDistributedTracePayloadHandler>(),
                                                      errorService, _attribDefSvc.AttributeDefs);

            if (exception != null)
            {
                internalTransaction.NoticeError(exception);
            }

            if (segments.Any())
            {
                foreach (var segment in segments)
                {
                    internalTransaction.Add(segment);
                }
            }
            else if (addSegment)
            {
                internalTransaction.Add(SimpleSegmentDataTests.createSimpleSegmentBuilder(TimeSpan.Zero, TimeSpan.Zero, 0, null, new MethodCallData("typeName", "methodName", 1), Enumerable.Empty <KeyValuePair <string, object> >(), "MyMockedRootNode", false));
            }

            var adaptiveSampler = Mock.Create <IAdaptiveSampler>();

            Mock.Arrange(() => adaptiveSampler.ComputeSampled(ref priority)).Returns(sampled);
            internalTransaction.SetSampled(adaptiveSampler);
            var transactionMetadata = internalTransaction.TransactionMetadata;

            PopulateTransactionMetadataBuilder(transactionMetadata, errorService, uri, statusCode, subStatusCode, referrerCrossProcessId);

            return(internalTransaction);
        }
Beispiel #28
0
        /// <summary>
        /// Delete featured topic
        /// </summary>
        /// <param name="storageConsistencyMode">Storage consistency mode</param>
        /// <param name="appHandle">App handle</param>
        /// <param name="topicHandle">Topic handle</param>
        /// <returns>Delete featured topic task</returns>
        public async Task DeleteFeaturedTopic(
            StorageConsistencyMode storageConsistencyMode,
            string appHandle,
            string topicHandle)
        {
            CTStore store = await this.tableStoreManager.GetStore(ContainerIdentifier.FeaturedTopics);

            FeedTable   table       = this.tableStoreManager.GetTable(ContainerIdentifier.FeaturedTopics, TableIdentifier.FeaturedTopicsFeed) as FeedTable;
            Transaction transaction = new Transaction();

            transaction.Add(Operation.Delete(table, ContainerIdentifier.FeaturedTopics.ToString(), appHandle, topicHandle));
            transaction.Add(Operation.Delete(table, ContainerIdentifier.FeaturedTopics.ToString(), MasterApp.AppHandle, topicHandle));
            await store.ExecuteTransactionAsync(transaction, storageConsistencyMode.ToConsistencyMode());
        }
Beispiel #29
0
        /// <summary>
        /// Insert user
        /// </summary>
        /// <param name="storageConsistencyMode">Storage consistency mode</param>
        /// <param name="userHandle">User handle</param>
        /// <param name="identityProviderType">Identity provider type</param>
        /// <param name="accountId">Account id</param>
        /// <param name="appHandle">App handle</param>
        /// <param name="firstName">First name</param>
        /// <param name="lastName">Last name</param>
        /// <param name="bio">User bio</param>
        /// <param name="photoHandle">Photo handle</param>
        /// <param name="visibility">User visibility</param>
        /// <param name="createdTime">Created time</param>
        /// <param name="requestId">Request Id</param>
        /// <returns>Insert user task</returns>
        public async Task InsertUser(
            StorageConsistencyMode storageConsistencyMode,
            string userHandle,
            IdentityProviderType identityProviderType,
            string accountId,
            string appHandle,
            string firstName,
            string lastName,
            string bio,
            string photoHandle,
            UserVisibilityStatus visibility,
            DateTime createdTime,
            string requestId)
        {
            UserProfileEntity userProfileEntity = new UserProfileEntity()
            {
                FirstName       = firstName,
                LastName        = lastName,
                Bio             = bio,
                CreatedTime     = createdTime,
                LastUpdatedTime = createdTime,
                Visibility      = visibility,
                PhotoHandle     = photoHandle,
                ReviewStatus    = ReviewStatus.Active,
                RequestId       = requestId
            };

            AppFeedEntity appFeedEntity = new AppFeedEntity()
            {
                AppHandle = appHandle
            };

            LinkedAccountFeedEntity linkedAccountFeedEntity = new LinkedAccountFeedEntity()
            {
                IdentityProviderType = identityProviderType,
                AccountId            = accountId
            };

            CTStore store = await this.tableStoreManager.GetStore(ContainerIdentifier.Users);

            ObjectTable profilesTable = this.tableStoreManager.GetTable(ContainerIdentifier.Users, TableIdentifier.UserProfilesObject) as ObjectTable;
            FeedTable   appsTable     = this.tableStoreManager.GetTable(ContainerIdentifier.Users, TableIdentifier.UserAppsFeed) as FeedTable;
            FeedTable   accountsTable = this.tableStoreManager.GetTable(ContainerIdentifier.Users, TableIdentifier.UserLinkedAccountsFeed) as FeedTable;
            Transaction transaction   = new Transaction();

            transaction.Add(Operation.Insert(profilesTable, userHandle, appHandle, userProfileEntity));
            transaction.Add(Operation.Insert(appsTable, userHandle, this.tableStoreManager.DefaultFeedKey, appHandle, appFeedEntity));
            transaction.Add(Operation.Insert(accountsTable, userHandle, this.tableStoreManager.DefaultFeedKey, identityProviderType.ToString(), linkedAccountFeedEntity));
            await store.ExecuteTransactionAsync(transaction, storageConsistencyMode.ToConsistencyMode());
        }
        public Task Fix(MapDocument document, Problem problem)
        {
            var edit = new Transaction();

            foreach (var obj in problem.Objects)
            {
                var copy = (IMapObject)obj.Copy(document.Map.NumberGenerator);

                edit.Add(new Detatch(obj.Hierarchy.Parent.ID, obj));
                edit.Add(new Attach(obj.Hierarchy.Parent.ID, copy));
            }

            return(MapDocumentOperation.Perform(document, edit));
        }
Beispiel #31
0
        public TransactionResult(JObject json, Source resultMessageSource)
        {
            Message = json;

            try
            {
                if (resultMessageSource == Source.transaction_subscription_notification)
                {
                    EngineResult = TransactionEngineResult.FromString(json.GetValue("engine_result").ToObject<string>());
                    Validated = json.GetValue("validated").ToObject<bool>();
                    LedgerHash = Hash256.Translate.FromString(json.GetValue("ledger_hash").ToObject<string>());
                    LedgerIndex = new UInt32(json.GetValue("ledger_index").ToObject<long>());

                    JToken transaction;
                    if (json.TryGetValue("transaction", out transaction))
                    {
                        Txn = (Transaction) StObject.FromJObject(transaction.ToObject<JObject>());
                        Hash = Txn[Hash256.hash];
                    }

                    JToken meta;
                    if (json.TryGetValue("meta", out meta))
                    {
                        Meta = (TransactionMeta)StObject.FromJObject(meta.ToObject<JObject>());
                    }
                }
                else if (resultMessageSource == Source.request_tx_result)
                {
                    JToken validated;
                    Validated = json.TryGetValue("validated", out validated) && validated.ToObject<bool>();

                    JToken meta;
                    if (Validated && !json.TryGetValue("meta", out meta))
                    {
                        throw new InvalidOperationException("It's validated, why doesn't it have meta??");
                    }

                    if (Validated)
                    {
                        Meta = (TransactionMeta)StObject.FromJObject(json.GetValue("meta").ToObject<JObject>());
                        EngineResult = TransactionEngineResult.FromNumber(Meta[UInt8.TransactionResult]);
                        Txn = (Transaction)StObject.FromJObject(json);
                        Hash = Txn[Hash256.hash];
                        LedgerHash = null; // XXXXXX
                    }
                }
                else if (resultMessageSource == Source.request_account_tx)
                {
                    JToken validated;
                    Validated = json.TryGetValue("validated", out validated) && validated.ToObject<bool>();

                    JToken meta;
                    if (Validated && !json.TryGetValue("meta", out meta))
                    {
                        throw new InvalidOperationException("It's validated, why doesn't it have meta??");
                    }

                    if (Validated)
                    {
                        var tx = json.GetValue("tx").ToObject<JObject>();
                        Meta = (TransactionMeta)StObject.FromJObject(json.GetValue("meta").ToObject<JObject>());
                        EngineResult = TransactionEngineResult.FromNumber(Meta[UInt8.TransactionResult]);
                        Txn = (Transaction)StObject.FromJObject(tx);
                        Hash = Txn[Hash256.hash];
                        LedgerIndex = new UInt32(tx.GetValue("ledger_index").ToObject<long>());
                        LedgerHash = null;
                    }
                }
                else if (resultMessageSource == Source.request_account_tx_binary)
                {
                    JToken validated;
                    Validated = json.TryGetValue("validated", out validated) && validated.ToObject<bool>();

                    JToken meta;
                    if (Validated && !json.TryGetValue("meta", out meta))
                    {
                        throw new InvalidOperationException("It's validated, why doesn't it have meta??");
                    }

                    if (Validated)
                    {
                        /*
                        {
                            "ledger_index": 3378767,
                            "meta": "201 ...",
                            "tx_blob": "120 ...",
                            "validated": true
                        },
                        */

                        var tx = json.GetValue("tx_blob").ToObject<string>();
                        byte[] decodedTx = B16.Decode(tx);
                        Meta = (TransactionMeta)StObject.Translate.FromHex(json.GetValue("meta").ToObject<string>());
                        Txn = (Transaction)StObject.Translate.FromBytes(decodedTx);
                        Hash = Hash256.TransactionId(decodedTx);
                        Txn.Add(Field.hash, Hash);

                        EngineResult = Meta.TransactionResult();
                        LedgerIndex = new UInt32(json.GetValue("ledger_index").ToObject<long>());
                        LedgerHash = null;
                    }
                }
            }
            catch (JsonException e)
            {
                throw new ApplicationException("Json deserialization failed.", e);
            }
        }