public static Guid Execute(DocumentTransaction tx, UpdateCommand command) { var values = ConvertAnonymousToProjections(command.Table, command.Projections); values[DocumentTable.EtagColumn] = tx.CommitId; values[DocumentTable.ModifiedAtColumn] = DateTimeOffset.Now; values[DocumentTable.LastOperationColumn] = Operation.Updated; var sql = new SqlBuilder() .Append($"update {tx.Store.Database.FormatTableNameAndEscape(command.Table.Name)}") .Append($"set {string.Join(", ", from column in values.Keys select column.Name + " = @" + column.Name)}") .Append($"where {DocumentTable.IdColumn.Name}=@Id") .Append(!command.LastWriteWins, $"and {DocumentTable.EtagColumn.Name}=@ExpectedEtag") .ToString(); var parameters = Parameters.FromProjections(values); parameters.Add("@Id", command.Id, SqlTypeMap.Convert(DocumentTable.IdColumn).DbType, null); if (!command.LastWriteWins) { parameters.Add("@ExpectedEtag", command.ExpectedEtag, SqlTypeMap.Convert(DocumentTable.EtagColumn).DbType, null); } DocumentWriteCommand.Execute(tx, new SqlDatabaseCommand { Sql = sql, Parameters = parameters, ExpectedRowCount = 1 }); return(tx.CommitId); }
protected void Page_Load(object sender, System.EventArgs e) { try { if (Request["btnCancel"] != null) { DocumentTransaction.End(); Response.Redirect("~/CloseWindow.html"); return; } if (!DocumentTransaction.IsActive()) { throw new BipFatalException(); } doc = DocumentTransaction.Current.Document; if (doc.Id < 1) { btnUpdate.Visible = false; } else { btnCreate.Visible = false; } CtrlDocInfoView.Document = doc; DataBind(); } catch (Exception ex) { ProcessException(ex); } }
public DocumentTransaction GetTransaction(DocumentEngine engine, bool create, bool isInternal) { var transaction = Slot.Value; if (create && transaction == null) { bool alreadyLock; lock (TransactionList) { alreadyLock = TransactionList.Values.Any(x => x.ThreadId == Environment.CurrentManagedThreadId); transaction = new DocumentTransaction(GetNextTransactionID(), engine, this, isInternal); TransactionList[transaction.TransactionId] = transaction; } if (!alreadyLock) { Locker.EnterTransaction(); } Slot.Value = transaction; } return(transaction); }
public static IEnumerable <Commit <byte[]> > Execute(DocumentTransaction tx, ReadEventsByCommitIds command) { if (!command.Ids.Any()) { return(Enumerable.Empty <Commit <byte[]> >()); } var parameters = new DynamicParameters(); foreach (var param in command.Ids.Select((value, i) => (name: $"@p{i}", value: value))) { parameters.Add(param.name, param.value); } var sql = $@" SELECT Position, EventId, CommitId, StreamId, SequenceNumber, Name, Generation, Metadata, Data FROM {tx.Store.Database.FormatTableNameAndEscape(command.Table.Name)} WHERE CommitId IN ({string.Join(", ", parameters.ParameterNames.Select(x => $"@{x}"))}) ORDER BY Position"; var commits = new[] { Commit.Empty <byte[]>() }.Concat( from row in tx.SqlConnection.Query <Row>(sql, parameters, tx.SqlTransaction) group row by row.CommitId into grouping let last = grouping.Last() select Commit.Create(grouping.Key, last.Generation, last.Position, grouping.Select(Row.ToEvent).ToList()) ).ToList(); return (from id in command.Ids join commit in commits on id equals commit.Id into cs from commit in cs.DefaultIfEmpty() select commit); }
public static Guid Execute(DocumentTransaction tx, InsertCommand command) { var values = ConvertAnonymousToProjections(command.Table, command.Projections); values[DocumentTable.IdColumn] = command.Id; values[DocumentTable.EtagColumn] = tx.CommitId; values[DocumentTable.CreatedAtColumn] = DateTimeOffset.Now; values[DocumentTable.ModifiedAtColumn] = DateTimeOffset.Now; values[DocumentTable.LastOperationColumn] = Operation.Inserted; var sql = $@" insert into {tx.Store.Database.FormatTableNameAndEscape(command.Table.Name)} ({string.Join(", ", from column in values.Keys select column.Name)}) values ({string.Join(", ", from column in values.Keys select "@" + column.Name)});"; var parameters = Parameters.FromProjections(values); DocumentWriteCommand.Execute(tx, new SqlDatabaseCommand { Sql = sql, Parameters = parameters, ExpectedRowCount = 1 }); return(tx.CommitId); }
public override void BulkAppend(DocumentContext context, DocumentTransaction transaction) { var formatting = context.Formatting == Format.Indented ? Formatting.Indented : Formatting.None; var json = new JSONSerializer(Logger); json.AppendRows(context.Storage, context.Documents.Select(d => d.Data).ToList(), formatting); }
public override void BulkDelete(DocumentContext context, DocumentTransaction transaction) { var formatting = context.Formatting == Format.Indented ? Formatting.Indented : Formatting.None; var json = new JSONSerializer(Logger); var map = new DocumentMap(context.Primary, context.Primary); json.DeleteRows(context.Storage, context.Documents.Select(d => d.Data).ToList(), map, formatting); }
public static Position Execute(DocumentTransaction tx, GetPositionOf command) { var sql = $@" SELECT ISNULL(MIN(Position), -1) as [begin], ISNULL(MAX(Position), -1) AS [end] FROM {tx.Store.Database.FormatTableNameAndEscape(command.Table.Name)} WHERE CommitId = @CommitId"; return(tx.SqlConnection.QuerySingleOrDefault <Position>(sql, new { command.CommitId }, tx.SqlTransaction) ?? new Position(-1L, -1L)); }
private void btnConfDelete_Click(object sender, System.EventArgs e) { try { doc.Delete(); DocumentTransaction.End(); Response.Redirect("~/CloseWindow.html"); } catch (Exception ex) { this.ProcessException(ex); } }
protected void btnCreate_Click(object sender, System.EventArgs e) { try { int id = doc.Create(); DocumentTransaction.End(); Response.Redirect("~/CloseWindow.html"); } catch (Exception ex) { this.ProcessException(ex); } }
protected void Page_Load(object sender, System.EventArgs e) { try { DocumentEnt doc = new DocumentEnt(); doc.New(); DocumentTransaction.Begin(doc); Response.Redirect("DocFileUpload.aspx"); } catch (Exception ex) { this.ProcessException(ex); } }
public static IEnumerable <Commit <byte[]> > Execute(DocumentTransaction tx, ReadEvents command) { if (tx.SqlTransaction.IsolationLevel != IsolationLevel.Snapshot) { throw new InvalidOperationException("Reads from event store is best done in snapshot isolation so they don't block writes."); } var sql = $@" SELECT Position, EventId, CommitId, StreamId, SequenceNumber, Name, Generation, Metadata, Data FROM {tx.Store.Database.FormatTableNameAndEscape(command.Table.Name)} WHERE Position >= @fromPosition {(!command.ReadPastActiveTransactions ? "AND RowVersion < min_active_rowversion()" : "")} ORDER BY Position ASC"; return(tx.SqlConnection.Query <Row>(sql, new { fromPosition = command.FromPositionIncluding }, tx.SqlTransaction, buffered: false).Batch()); }
private void Page_Load(object sender, System.EventArgs e) { try { if (Request["btnCancel"] != null) { DocumentTransaction.End(); Response.Redirect("~/CloseWindow.html"); return; } PanPreview.Visible = false; if (!DocumentTransaction.IsActive()) { throw new BipFatalException(); } doc = DocumentTransaction.Current.Document; lblFileName.Text = doc.FileName; if (Page.IsPostBack == false) { ddlFileType.DataSource = DocFileType.FindAll(); ddlFileType.DataTextField = "Name"; ddlFileType.DataValueField = "Id"; ddlFileType.DataBind(); //ddlFileType.Items.Insert(0, new ListItem("", "0")); ListUtils.SelectSingleListItem(ddlFileType.Items, doc.FileTypeId.ToString()); } else { int fileType = Convert.ToInt32(ddlFileType.SelectedItem.Value); if (fileType == 0) { throw new BipGenericException(Bip.Components.BipResources.GetString("StMustSelectFileType")); } doc.ConfigureFileType(Convert.ToInt32(ddlFileType.SelectedItem.Value)); } if (doc.Id > 0) { btnBack.Visible = false; } } catch (Exception ex) { ProcessException(ex); } }
protected void Page_Load(object sender, System.EventArgs e) { try { int id = Convert.ToInt32(Request["Id"]); DocumentEnt doc = new DocumentEnt(); doc.Load(id); DocumentTransaction.Begin(doc); Response.Redirect("DocumentEdit.aspx"); } catch (Exception ex) { this.ProcessException(ex); } }
public static Commit <byte[]> Execute(DocumentTransaction tx, LoadParentCommit command) { if (command.CommitId == Guid.Empty) { return(null); } var tablename = tx.Store.Database.FormatTableNameAndEscape(command.Table.Name); var sql = $@"SELECT EventId, Position, CommitId, StreamId, SequenceNumber, Name, Generation, Data, Metadata FROM {tablename} WHERE CommitId = ( SELECT TOP 1 CommitId FROM {tablename} WHERE Position < ISNULL( (SELECT MIN(Position) FROM {tablename} WHERE CommitId = @id), (SELECT MAX(Position) + 1 FROM {tablename}) ) ORDER BY Position DESC ) ORDER BY Position"; var rows = tx.SqlConnection.Query <Row>(sql, new { id = command.CommitId }, transaction: tx.SqlTransaction).ToList(); // if no parent commit is found, the initial, transient commit is parent if (!rows.Any()) { return(new Commit <byte[]>(Guid.Empty, 0, -1, -1)); } var lastRow = rows.Last(); return(Commit.Create(lastRow.CommitId, lastRow.Generation, lastRow.Position, rows.Select(Row.ToEvent).ToList())); }
public void ReleaseTransaction(DocumentTransaction transaction) { bool isKeepLocked; lock (TransactionList) { TransactionList.Remove(transaction.TransactionId); isKeepLocked = TransactionList.Values.Any(x => x.ThreadId == Environment.CurrentManagedThreadId); } if (!isKeepLocked) { Locker.ExitTransaction(); } Slot.Value = null; }
protected void Page_Load(object sender, System.EventArgs e) { try { if (Page.IsPostBack) { if (Request["btnCancel"] != null) { DocumentTransaction.End(); Response.Redirect("~/CloseWindow.html"); return; } if (UploadedFile.PostedFile == null || UploadedFile.PostedFile.ContentLength == 0 || UploadedFile.PostedFile.FileName == null) { throw new BipGenericException(Bip.Components.BipResources.GetString("StrFileUploadError")); } DocumentEnt doc = null; if (!DocumentTransaction.IsActive()) { doc = new DocumentEnt(); doc.New(); DocumentTransaction.Begin(doc); } else { doc = DocumentTransaction.Current.Document; } doc.UploadFile(UploadedFile.PostedFile.InputStream, System.IO.Path.GetFileName(UploadedFile.PostedFile.FileName)); //doc.FileName = ; Response.Redirect("DocFileTypeEdit.aspx"); } } catch (Exception ex) { ProcessException(ex); } // Put user code to initialize the page here }
public async Task <IEnumerable <UserSoldItemsDto> > GetAsync(UserSoldDocsQuery query, CancellationToken token) { const int pageSize = 20; User userAlias = null; DocumentTransaction transactionAlias = null; Document documentAlias = null; UserSoldItemsDto userSoldDto = null; var cte = QueryOver.Of(() => documentAlias) .Where(w => w.User.Id == query.UserId) .Select(s => s.Id); var userCountry = QueryOver.Of(() => userAlias) .Where(w => w.Id == query.UserId) .Select(s => s.Country); var t = _session.QueryOver(() => transactionAlias) .Inner.JoinAlias(r => r.Document, () => documentAlias, r => r.Id == transactionAlias.Document.Id) .Inner.JoinAlias(r => r.User, () => userAlias, r => r.Id == transactionAlias.User.Id) .WithSubquery.WhereProperty(w => w.Document.Id).In(cte); if (!string.IsNullOrEmpty(query.Country)) { t.WithSubquery.WhereValue(query.Country).Eq(userCountry); } return(await t.Where(w => w.User.Id != query.UserId) .SelectList(s => s.Select(x => x.Created).WithAlias(() => userSoldDto.TransactionTime) .Select(x => x.Price).WithAlias(() => userSoldDto.TransactionPrice) .Select(x => x.Document.Id).WithAlias(() => userSoldDto.ItemId) .Select(x => documentAlias.Name).WithAlias(() => userSoldDto.ItemName) .Select(x => documentAlias.TimeStamp.CreationTime).WithAlias(() => userSoldDto.ItemCreated) .Select(x => documentAlias.Course.Id).WithAlias(() => userSoldDto.ItemCourse) .Select(x => documentAlias.Status.State).WithAlias(() => userSoldDto.ItemState) .Select(x => documentAlias.DocumentType).WithAlias(() => userSoldDto.ItemType) .Select(x => userAlias.Name).WithAlias(() => userSoldDto.PurchasedUserName) .Select(x => userAlias.Email).WithAlias(() => userSoldDto.PurchasedUserEmail) .Select(x => userAlias.Transactions.Balance).WithAlias(() => userSoldDto.PurchasedUserBalance) ).TransformUsing(Transformers.AliasToBean <UserSoldItemsDto>()) .Skip(query.Page * pageSize).Take(pageSize).ListAsync <UserSoldItemsDto>()); }
public static Guid Execute(DocumentTransaction tx, DeleteCommand command) { // Note that last write wins can actually still produce a ConcurrencyException if the // row was already deleted, which would result in 0 resulting rows changed var sql = new SqlBuilder(); var parameters = new Parameters(); if (tx.Store.Configuration.SoftDelete) { sql .Append($"update {tx.Store.Database.FormatTableNameAndEscape(command.Table.Name)}") .Append($"set {DocumentTable.IdColumn.Name} = @NewId") .Append($", {DocumentTable.LastOperationColumn.Name} = {(byte) Operation.Deleted}") .Append($"where {DocumentTable.IdColumn.Name} = @Id") .Append(!command.LastWriteWins, $"and {DocumentTable.EtagColumn.Name} = @ExpectedEtag"); parameters.Add("@NewId", $"{command.Key}/{Guid.NewGuid()}", SqlTypeMap.Convert(DocumentTable.IdColumn).DbType, null); } else { sql .Append($"delete from {tx.Store.Database.FormatTableNameAndEscape(command.Table.Name)}") .Append($"where {DocumentTable.IdColumn.Name} = @Id") .Append(!command.LastWriteWins, $"and {DocumentTable.EtagColumn.Name} = @ExpectedEtag"); } parameters.Add("@Id", command.Key, SqlTypeMap.Convert(DocumentTable.IdColumn).DbType, null); if (!command.LastWriteWins) { parameters.Add("@ExpectedEtag", command.ExpectedEtag, SqlTypeMap.Convert(DocumentTable.EtagColumn).DbType, null); } DocumentWriteCommand.Execute(tx, new SqlDatabaseCommand { Sql = sql.ToString(), Parameters = parameters, ExpectedRowCount = 1 }); return(tx.CommitId); }
public static IEnumerable <Commit <byte[]> > Execute(DocumentTransaction tx, ReadStream command) { if (tx.SqlTransaction.IsolationLevel != IsolationLevel.Snapshot) { throw new InvalidOperationException("Reads from event store is best done in snapshot isolation so they don't block writes."); } var sql = $@" SELECT Position, EventId, CommitId, @Id AS [StreamId], SequenceNumber, Name, Generation, Metadata, Data FROM {tx.Store.Database.FormatTableNameAndEscape(command.Table.Name)} WHERE StreamId = @Id AND SequenceNumber >= @fromStreamSeq AND Position <= @toPosition ORDER BY SequenceNumber {(command.Direction == Direction.Forward ? "ASC" : "DESC")}"; // Using DbString over just string as a important performance optimization, // see https://github.com/StackExchange/dapper-dot-net/issues/288 var idParameter = new DbString { Value = command.StreamId, IsAnsi = false, IsFixedLength = false, Length = 850 }; return(tx.SqlConnection.Query <Row>(sql, new { Id = idParameter, command.FromStreamSeq, command.ToPosition }, tx.SqlTransaction, buffered: false).Batch()); }
public DocumentWriter(IDocumentEngine engine, string typeOf) { Ensure.NotNullOrEmpty(typeOf, "TypeOf is empty"); TypeOf = typeOf; Engine = engine; Meta = engine.GetTypeMeta(typeOf); IsPartialStore = Engine.Option.SupportPartialStorage; if (IsPartialStore) { PartialStoreLimit = Engine.Option.SupportPartialStorageSize; } Transaction = Engine.GetThreadTransaction(); if (Transaction == null) { Transaction = Engine.BeginInternalTransaction(); } Transaction.EnterTypeOfLock(typeOf); }
public static void Execute(DocumentTransaction tx, SqlDatabaseCommand preparedCommand) { tx.Store.Stats.NumberOfRequests++; tx.Store.Stats.NumberOfCommands++; // NOTE: Sql parameter threshold is actually lower than the stated 2100 (or maybe extra // params are added some where in the stack) so we cut it some slack and say 2000. if (preparedCommand.Parameters.Count >= 2000) { throw new InvalidOperationException("Cannot execute a single command with more than 2000 parameters."); } var rowcount = tx.SqlConnection.Execute(preparedCommand.Sql, preparedCommand.Parameters, tx.SqlTransaction); if (rowcount != preparedCommand.ExpectedRowCount) { throw new ConcurrencyException( $"Someone beat you to it. Expected {preparedCommand.ExpectedRowCount} changes, but got {rowcount}. " + $"The transaction is rolled back now, so no changes were actually made."); } tx.Store.Stats.LastWrittenEtag = tx.CommitId; }
public static string Execute(Func <object, string> serializer, DocumentTransaction tx, EnqueueCommand command) { var tablename = tx.Store.Database.FormatTableNameAndEscape(command.Table.Name); var discriminator = tx.Store.Configuration.TypeMapper.ToDiscriminator(command.Message.GetType()); try { tx.SqlConnection.Execute(@$ " set nocount on; insert into {tablename} (Topic, Id, CommitId, Discriminator, Message) values (@Topic, @Id, @CommitId, @Discriminator, @Message); set nocount off;", new { command.Topic, command.Message.Id, tx.CommitId, Discriminator = discriminator, Message = serializer(command.Message) }, tx.SqlTransaction); } catch (SqlException e) { // Enqueuing is idempotent. It should ignore exceptions from primary key violations and just not insert the message. if (e.Number == 2627) { return(command.Message.Id); } throw; } return(command.Message.Id); }
public static HybridDbMessage Execute(Func <string, Type, object> deserializer, DocumentTransaction tx, DequeueCommand command) { var tablename = tx.Store.Database.FormatTableNameAndEscape(command.Table.Name); var msg = (tx.SqlConnection.Query <(string Message, string Discriminator)>(@$ " set nocount on; delete top(1) from {tablename} with (rowlock, readpast) output deleted.Message, deleted.Discriminator where Topic = @Topic; set nocount off;", new { command.Topic }, tx.SqlTransaction )).SingleOrDefault(); if (msg == default) { return(null); } var type = tx.Store.Configuration.TypeMapper.ToType(typeof(HybridDbMessage), msg.Discriminator); return((HybridDbMessage)deserializer(msg.Message, type)); }
private void btnCancel_Click(object sender, System.EventArgs e) { DocumentTransaction.End(); Response.Redirect("~/CloseWindow.html"); }
public override void DataBind() { if (Request["Id"] != null) { IsEditMode = false; doc = new DocumentEnt(); doc.Load(Convert.ToInt32(Request["Id"])); hlDownloadFile.NavigateUrl = "~/Documents/DocFileDownload.aspx?Org=1&Id=" + doc.Id.ToString(); if (Page.IsPostBack == false && Request.UrlReferrer != null && Session["MAIN_PAGE"] == null) { if (Request.UrlReferrer.AbsolutePath.ToLower().IndexOf("Documents") == -1) { Session["MAIN_PAGE"] = Request.UrlReferrer.ToString(); } } } else { //Session.Remove("MAIN_PAGE"); IsEditMode = true; if (!DocumentTransaction.IsActive()) { throw new BipFatalException(); } doc = DocumentTransaction.Current.Document; hlDownloadFile.NavigateUrl = "~/Documents/DocFileDownload.aspx?Org=1&TC=1"; } if (doc.Id < 1) { PanExistingDocAttrs.Visible = false; } else { lblId.Text = doc.Id.ToString(); lblCreationTime.Text = doc.CreationTime.ToString(); } ShowParentDocLink(); ShowPreviousVersionDocLink(); if (doc.RefDocuments != null) { doc.RefDocuments.GetEnumerator().Reset(); } if (doc.RefDocuments == null || !doc.RefDocuments.GetEnumerator().MoveNext()) { PanRelatedDocView.Visible = false; } else { grdRelatedDocs.DataSource = DocumentEnt.FindEnum(doc.RefDocuments); grdRelatedDocs.DataBind(); } if (doc.Groups != null) { dlGroups.DataSource = GroupEnt.FindEnum(doc.Groups); dlGroups.DataBind(); } else { dlGroups.Visible = false; } LoadAttributes(); }
public override void BulkAppend(DocumentContext context, DocumentTransaction transaction) { }
protected void Page_Load(object sender, System.EventArgs e) { try { bool isInFrame = (Request["frame"] != null); PanFileNotShown.Visible = false; try { string s_id = Request["Id"]; string s_transaction = Request["TC"]; bool original = true; if (Request["Org"] == null || Request["Org"].Length == 0) { original = false; } bool isInline = (Request["inline"] != null && Request["inline"].Length > 0); DocumentEnt doc = new DocumentEnt(); if (s_id != null && s_id.Length > 0) { int id = Convert.ToInt32(s_id); doc.Load(id); } else if (s_transaction == "1" && DocumentTransaction.IsActive()) { doc = DocumentTransaction.Current.Document; } else { throw new BipFatalException(); } DocFileType fileType = new DocFileType(doc.FileTypeId); bool isText = (fileType.ContentType.Trim().ToLower() == "text/plain"); if (isInline == false) { Response.Clear(); Response.ContentType = fileType.ContentType; Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + doc.FileName + "\""); Response.BinaryWrite(doc.DownloadFile(original)); Response.End(); return; } if (isText == false) { if (fileType.ShowInBrowser == false) { PanFileNotShown.Visible = true; lblFileType.Text = fileType.Name; if (s_transaction == null) { hlDownload.NavigateUrl = "~/Documents/DocFileDownload.aspx?id=" + doc.Id.ToString(); } else { hlDownload.NavigateUrl = "~/Documents/DocFileDownload.aspx?TC=1"; } hlDownload.Text = doc.FileName; return; } Response.Clear(); Response.ContentType = fileType.ContentType; Response.AppendHeader("Content-Disposition", "inline; filename=\"" + doc.FileName + "\""); Response.BinaryWrite(doc.DownloadFile(original)); Response.End(); return; } byte [] buffer = doc.DownloadFile(original); // this should not be hardcoded Decoder d = Encoding.GetEncoding("Windows-1252").GetDecoder(); char [] chars = new char[buffer.Length]; d.GetChars(buffer, 0, buffer.Length, chars, 0); textFileContents.InnerText = new string(chars); } catch (Exception ex) { if (ex is System.Threading.ThreadAbortException || ex is System.Threading.ThreadInterruptedException) { throw ex; } if (!isInFrame) { throw ex; } Response.Clear(); Response.Redirect("~/Error.aspx?error=" + HttpUtility.UrlEncode(ex.Message)); } } catch (Exception ex) { ProcessException(ex); } //HttpUtility.HtmlEncode( }
public override void BulkDelete(DocumentContext context, DocumentTransaction transaction) { }
public override void SubmitChanges(DocumentContext context, DocumentTransaction transaction) { throw new NotImplementedException(); }