Beispiel #1
0
        protected virtual void ExecuteSave()
        {
            if (IsUpdate)
            {
                if (Row.IsAnyFieldAssigned)
                {
                    var idField = Row.IdField;

                    if (idField.IndexCompare(Old, Row) != 0)
                    {
                        var update = new SqlUpdate(Row.Table);
                        update.Set(Row);
                        update.Where(idField == new ValueCriteria(idField.AsSqlValue(Old)));
                        InvokeSaveAction(() => update.Execute(Connection, ExpectedRows.One));
                    }
                    else
                    {
                        InvokeSaveAction(() => Connection.UpdateById(Row));
                    }

                    Response.EntityId = idField.AsObject(Row);
                    InvalidateCacheOnCommit();
                }
            }
            else if (IsCreate)
            {
                var idField = Row.IdField;
                if (idField is object &&
                    idField.Flags.HasFlag(FieldFlags.AutoIncrement))
                {
                    InvokeSaveAction(() =>
                    {
                        var entityId      = Connection.InsertAndGetID(Row);
                        Response.EntityId = entityId;
                        Row.IdField.AsObject(Row, Row.IdField.ConvertValue(entityId, CultureInfo.InvariantCulture));
                    });
                }
                else
                {
                    InvokeSaveAction(() =>
                    {
                        Connection.Insert(Row);
                    });

                    if (idField is object)
                    {
                        Response.EntityId = idField.AsObject(Row);
                    }
                }

                InvalidateCacheOnCommit();
            }
        }
        protected virtual void ExecuteSave()
        {
            if (IsUpdate)
            {
                if (Row.IsAnyFieldAssigned)
                {
                    var idField = (Field)Row.IdField;

                    if (idField.IndexCompare(Old, Row) != 0)
                    {
                        var update = new SqlUpdate(Row.Table);
                        update.Set(Row);
                        update.Where(idField == new ValueCriteria(idField.AsObject(Old)));
                        update.Execute(Connection, ExpectedRows.One);
                    }
                    else
                    {
                        Connection.UpdateById(Row);
                    }

                    Response.EntityId = idField.AsObject(Row);
                    InvalidateCacheOnCommit();
                }
            }
            else if (IsCreate)
            {
                var idField = Row.IdField as Field;
                if (!ReferenceEquals(null, idField) &&
                    idField.Flags.HasFlag(FieldFlags.AutoIncrement))
                {
                    var entityId = Connection.InsertAndGetID(Row);
                    Response.EntityId = entityId;
                    Row.IdField[Row]  = entityId;
                }
                else
                {
                    Connection.Insert(Row);
                    if (!ReferenceEquals(null, idField))
                    {
                        Response.EntityId = ((Field)idField).AsObject(Row);
                    }
                }

                InvalidateCacheOnCommit();
            }
        }
Beispiel #3
0
        protected virtual void ExecuteDelete()
        {
            var isActiveDeletedRow = Row as IIsActiveDeletedRow;
            var isDeletedRow       = Row as IIsDeletedRow;
            var deleteLogRow       = Row as IDeleteLogRow;
            var idField            = (Field)Row.IdField;
            var id = idField.ConvertValue(Request.EntityId, CultureInfo.InvariantCulture);

            if (isActiveDeletedRow == null && isDeletedRow == null && deleteLogRow == null)
            {
                if (new SqlDelete(Row.Table)
                    .WhereEqual(idField, id)
                    .Execute(Connection) != 1)
                {
                    throw DataValidation.EntityNotFoundError(Row, id);
                }
            }
            else
            {
                if (isDeletedRow != null || isActiveDeletedRow != null)
                {
                    var updateLogRow = Row as IUpdateLogRow;
                    var update       = new SqlUpdate(Row.Table)
                                       .WhereEqual(idField, id)
                                       .Where(ServiceQueryHelper.GetNotDeletedCriteria(Row));

                    if (isActiveDeletedRow != null)
                    {
                        update.Set(isActiveDeletedRow.IsActiveField, -1);
                    }
                    else if (isDeletedRow != null)
                    {
                        update.Set(isDeletedRow.IsDeletedField, true);
                    }

                    if (deleteLogRow != null)
                    {
                        update.Set(deleteLogRow.DeleteDateField, DateTimeField.ToDateTimeKind(DateTime.Now,
                                                                                              deleteLogRow.DeleteDateField.DateTimeKind))
                        .Set((Field)deleteLogRow.DeleteUserIdField, Authorization.UserId.TryParseID());
                    }
                    else if (updateLogRow != null)
                    {
                        update.Set(updateLogRow.UpdateDateField, DateTimeField.ToDateTimeKind(DateTime.Now,
                                                                                              updateLogRow.UpdateDateField.DateTimeKind))
                        .Set((Field)updateLogRow.UpdateUserIdField, Authorization.UserId.TryParseID());
                    }

                    if (update.Execute(Connection) != 1)
                    {
                        throw DataValidation.EntityNotFoundError(Row, id);
                    }
                }
                else //if (deleteLogRow != null)
                {
                    if (new SqlUpdate(Row.Table)
                        .Set(deleteLogRow.DeleteDateField, DateTimeField.ToDateTimeKind(DateTime.Now,
                                                                                        deleteLogRow.DeleteDateField.DateTimeKind))
                        .Set((Field)deleteLogRow.DeleteUserIdField, Authorization.UserId.TryParseID())
                        .WhereEqual(idField, id)
                        .Where(new Criteria((Field)deleteLogRow.DeleteUserIdField).IsNull())
                        .Execute(Connection) != 1)
                    {
                        throw DataValidation.EntityNotFoundError(Row, id);
                    }
                }
            }

            InvalidateCacheOnCommit();
        }
Beispiel #4
0
        /// <summary>
        /// Logs the error to SQL
        /// If the rollup conditions are met, then the matching error will have a DuplicateCount += @DuplicateCount (usually 1, unless in retry) rather than a distinct new row for the error
        /// </summary>
        /// <param name="error">The error to log</param>
        protected override void LogError(Error error)
        {
            using (var c = GetConnection())
            {
                if (RollupThreshold.HasValue && error.ErrorHash.HasValue)
                {
                    if (isSqlServer)
                    {
                        var queryParams = new Serenity.Data.DynamicParameters(new
                        {
                            error.DuplicateCount,
                            error.ErrorHash,
                            ApplicationName = error.ApplicationName.Truncate(50),
                            minDate         = DateTime.UtcNow.Add(RollupThreshold.Value.Negate())
                        });

                        queryParams.Add("@newGUID", dbType: DbType.Guid, direction: ParameterDirection.Output);
                        var count = c.Execute(@"
Update Exceptions 
    Set DuplicateCount = DuplicateCount + @DuplicateCount,
        @newGUID = GUID
    Where Id In (Select Top 1 Id
                From Exceptions 
                Where ErrorHash = @ErrorHash
                    And ApplicationName = @ApplicationName
                    And DeletionDate Is Null
                    And CreationDate >= @minDate)", queryParams);
                        // if we found an error that's a duplicate, jump out
                        if (count > 0)
                        {
                            error.GUID = queryParams.Get <Guid>("@newGUID");
                            return;
                        }
                    }
                    else
                    {
                        var update = new SqlUpdate("Exceptions")
                                     .SetTo("DuplicateCount", "[DuplicateCount] + @DuplicateCount")
                                     .Where(new Criteria("[Id]").In(new Criteria("(" +
                                                                                 new SqlQuery()
                                                                                 .Dialect(c.GetDialect())
                                                                                 .Select("[Id]")
                                                                                 .From("Exceptions")
                                                                                 .Take(1)
                                                                                 .Where(hashMatch))) + ")");


                        update.SetParam("@DuplicateCount", error.DuplicateCount);
                        update.SetParam("@ErrorHash", error.ErrorHash);
                        update.SetParam("@ApplicationName", error.ApplicationName.Truncate(50));
                        update.SetParam("@minDate", DateTime.UtcNow.Add(RollupThreshold.Value.Negate()));

                        var count = update.Execute(c, ExpectedRows.Ignore);

                        // if we found an exception that's a duplicate, jump out
                        if (count > 0)
                        {
                            var q = new SqlQuery()
                                    .Dialect(c.GetDialect())
                                    .From("Exceptions")
                                    .Select("GUID")
                                    .Take(1)
                                    .Where(hashMatch);

                            q.SetParam("@ErrorHash", error.ErrorHash);
                            q.SetParam("@ApplicationName", error.ApplicationName.Truncate(50));
                            q.SetParam("@minDate", DateTime.UtcNow.Add(RollupThreshold.Value.Negate()));

                            error.GUID = c.Query <Guid>(q).First();

                            return;
                        }
                    }

                    error.FullJson = error.ToJson();

                    c.Execute(@"
Insert Into Exceptions ([GUID], [ApplicationName], [MachineName], [CreationDate], [Type], [IsProtected], [Host], [Url], [HTTPMethod], [IPAddress], [Source], [Message], [Detail], [StatusCode], [SQL], [FullJson], [ErrorHash], [DuplicateCount])
Values (@GUID, @ApplicationName, @MachineName, @CreationDate, @Type, @IsProtected, @Host, @Url, @HTTPMethod, @IPAddress, @Source, @Message, @Detail, @StatusCode, @SQL, @FullJson, @ErrorHash, @DuplicateCount)",
                              new
                    {
                        error.GUID,
                        ApplicationName = error.ApplicationName.Truncate(50),
                        MachineName     = error.MachineName.Truncate(50),
                        error.CreationDate,
                        Type = error.Type.Truncate(100),
                        error.IsProtected,
                        Host       = error.Host.Truncate(100),
                        Url        = error.Url.Truncate(500),
                        HTTPMethod = error.HTTPMethod.Truncate(10),     // this feels silly, but you never know when someone will up and go crazy with HTTP 1.2!
                        error.IPAddress,
                        Source  = error.Source.Truncate(100),
                        Message = error.Message.Truncate(1000),
                        error.Detail,
                        error.StatusCode,
                        error.SQL,
                        error.FullJson,
                        error.ErrorHash,
                        error.DuplicateCount
                    });
                }
            }
        }
Beispiel #5
0
        public TUndeleteResponse Process(IUnitOfWork unitOfWork, UndeleteRequest request)
        {
            UnitOfWork = unitOfWork ?? throw new ArgumentNullException("unitOfWork");

            ValidatePermissions();

            Request  = request;
            Response = new TUndeleteResponse();

            if (request.EntityId == null)
            {
                throw DataValidation.RequiredError("EntityId", Localizer);
            }

            Row = new TRow();

            var isActiveDeletedRow = Row as IIsActiveDeletedRow;
            var isDeletedRow       = Row as IIsDeletedRow;
            var deleteLogRow       = Row as IDeleteLogRow;

            if (isActiveDeletedRow == null && isDeletedRow == null && deleteLogRow == null)
            {
                throw new NotImplementedException();
            }

            var idField = Row.IdField;
            var id      = idField.ConvertValue(Request.EntityId, CultureInfo.InvariantCulture);

            LoadEntity();

            ValidateRequest();

            if ((isDeletedRow != null && isDeletedRow.IsDeletedField[Row] != true) ||
                (isActiveDeletedRow != null && isActiveDeletedRow.IsActiveField[Row] >= 0) ||
                (deleteLogRow != null && deleteLogRow.DeleteUserIdField.IsNull(Row)))
            {
                Response.WasNotDeleted = true;
            }
            else
            {
                OnBeforeUndelete();

                var update = new SqlUpdate(Row.Table)
                             .WhereEqual(idField, id);

                if (isActiveDeletedRow != null)
                {
                    update.Set(isActiveDeletedRow.IsActiveField, 1)
                    .WhereEqual(isActiveDeletedRow.IsActiveField, -1);
                }
                else if (isDeletedRow != null)
                {
                    update.Set(isDeletedRow.IsDeletedField, false)
                    .WhereEqual(isDeletedRow.IsDeletedField, 1);
                }

                if (deleteLogRow != null)
                {
                    update.Set(deleteLogRow.DeleteUserIdField, null)
                    .Set(deleteLogRow.DeleteDateField, null);

                    if (isActiveDeletedRow == null && isDeletedRow == null)
                    {
                        update.Where(deleteLogRow.DeleteUserIdField.IsNotNull());
                    }
                }

                if (update.Execute(Connection) != 1)
                {
                    throw DataValidation.EntityNotFoundError(Row, id, Localizer);
                }

                InvalidateCacheOnCommit();

                OnAfterUndelete();

                DoAudit();
            }

            OnReturn();

            return(Response);
        }