Example #1
0
        public TextReader SerializeText(object instance, DocumentMap map)
        {
            if (!map.ExpectLargeDocuments)
            {
                // Serializing directly to a string is faster for small documents
                var text = JsonConvert.SerializeObject(instance, SerializerSettings);
                if (text.Length > NevermoreDefaults.LargeDocumentCutoffSize)
                {
                    map.ExpectLargeDocuments = true;
                }
                return(new StringReader(text));
            }

            // The MemoryStream is not disposed/not in a using intentionally, since it will be sent to a DbParameter.
            // CommandExecutor disposes all parameters at the end of the execution.
            var memoryStream = MemoryStreamManager.GetStream("JsonNetSerializer:SerializeText:" + map.Type.Name);

            using (var writer = new StreamWriter(memoryStream, Encoding.UTF8, 2048, true))
            {
                var serializer = JsonSerializer.Create(SerializerSettings);
                using var jsonTextWriter = new JsonTextWriter(writer);
                jsonTextWriter.ArrayPool = arrayPoolAdapter;
                serializer.Serialize(jsonTextWriter, instance);
            }

            memoryStream.Seek(0, SeekOrigin.Begin);
            return(new StreamReader(memoryStream, Encoding.UTF8));
        }
        private async Task ProcessProjectAsync(
            Project project,
            DocumentMap documentMap)
        {
            using (Logger.LogBlock(FunctionId.FindReference_ProcessProjectAsync, project.Name, _cancellationToken))
            {
                // make sure we hold onto compilation while we search documents belong to this project
                var compilation = await project.GetCompilationAsync(_cancellationToken).ConfigureAwait(false);

                var documentTasks = new List<Task>();
                foreach (var kvp in documentMap)
                {
                    var document = kvp.Key;

                    if (document.Project == project)
                    {
                        var documentQueue = kvp.Value;

                        documentTasks.Add(Task.Run(() => ProcessDocumentQueueAsync(
                            document, documentQueue), _cancellationToken));
                    }
                }

                await Task.WhenAll(documentTasks).ConfigureAwait(false);

                GC.KeepAlive(compilation);
            }
        }
        // Builds a mapping of FileName -> (DocumentId, Requests[])
        // This grouping is later used to process each document at a time.
        static DocumentMap BuildDiffDocumentMap(IEnumerable <DiffRequest> requests)
        {
            var documentIdMap = new DocumentMap();

            foreach (var request in requests)
            {
                if (!(request.filename.EndsWith(".cs") || request.filename.EndsWith(".vb")))
                {
                    Console.WriteLine($"WARNING: {request.filename} is not a .cs or .vb file. Skipping");
                    continue;
                }

                if (documentIdMap.ContainsKey(request.filename))
                {
                    documentIdMap[request.filename].Add(request);
                }
                else
                {
                    documentIdMap.Add(request.filename, new List <DiffRequest>()
                    {
                        request
                    });
                }
            }
            return(documentIdMap);
        }
Example #4
0
 public async Task BeforeDeleteAsync <TDocument>(object id, DocumentMap map, IWriteTransaction transaction) where TDocument : class
 {
     foreach (var hook in hooks)
     {
         await hook.BeforeDeleteAsync <TDocument>(id, map, transaction);
     }
 }
Example #5
0
        public DocumentReaderExpressionBuilder(DocumentMap map, ITypeHandlerRegistry typeHandlers)
        {
            type              = map.Type;
            this.map          = map;
            this.typeHandlers = typeHandlers;

            var contextType = typeof(DocumentReaderContext);

            dataReaderArgument = Expression.Parameter(typeof(DbDataReader), "reader");
            contextArgument    = Expression.Parameter(contextType, "context");
            result             = DeclareLocal(map.Type, "result");
            deserializeAsLocal = DeclareLocal(typeof(Type), "deserializeAsType");

            columnField                 = contextType.GetField(nameof(DocumentReaderContext.Column));
            deserializeTextMethod       = contextType.GetMethod(nameof(DocumentReaderContext.DeserializeText), BindingFlags)?.MakeGenericMethod(type);
            deserializeCompressedMethod = contextType.GetMethod(nameof(DocumentReaderContext.DeserializeCompressed), BindingFlags)?.MakeGenericMethod(type);
            resolveTypeMethod           = contextType.GetMethod(nameof(DocumentReaderContext.ResolveType), BindingFlags);
            selectPreferredResultMethod = contextType.GetMethod(nameof(DocumentReaderContext.SelectPreferredResult), BindingFlags)?.MakeGenericMethod(type);
            propertyHandlerWriteMethod  = typeof(IPropertyHandler).GetMethod(nameof(IPropertyHandler.Write), BindingFlags);

            if (columnField == null || deserializeTextMethod == null || deserializeCompressedMethod == null || resolveTypeMethod == null || selectPreferredResultMethod == null || propertyHandlerWriteMethod == null)
            {
                throw new InvalidOperationException("Could not find one or more required methods.");
            }
        }
Example #6
0
        public static void WriteTableSchema(DocumentMap mapping, string tableNameOverride, StringBuilder result)
        {
            var tableName = tableNameOverride ?? mapping.TableName;

            result.AppendLine("CREATE TABLE [TestSchema].[" + tableName + "] (");
            result.Append($"  [Id] {GetDatabaseType(mapping.IdColumn)} NOT NULL CONSTRAINT [PK_{tableName}_Id] PRIMARY KEY CLUSTERED, ").AppendLine();

            foreach (var column in mapping.WritableIndexedColumns())
            {
                result.AppendFormat("  [{0}] {1} {2}, ", column.ColumnName, GetDatabaseType(column).ToUpperInvariant(), IsNullable(column) ? "NULL" : "NOT NULL").AppendLine();
            }

            result.AppendFormat("  [JSON] NVARCHAR(MAX) NOT NULL").AppendLine();
            result.AppendLine(")");

            foreach (var unique in mapping.UniqueConstraints)
            {
                result.AppendFormat("ALTER TABLE [TestSchema].[{0}] ADD CONSTRAINT [UQ_{1}] UNIQUE({2})", tableName,
                                    unique.ConstraintName,
                                    string.Join(", ", unique.Columns.Select(ix => "[" + ix + "]"))).AppendLine();
            }

            foreach (var referencedDocumentMap in mapping.RelatedDocumentsMappings)
            {
                var refTblName    = referencedDocumentMap.TableName;
                var refSchemaName = referencedDocumentMap.SchemaName;
                result.AppendLine($"IF NOT EXISTS (SELECT name from sys.tables WHERE name = '{refTblName}')");
                result.AppendLine($"    CREATE TABLE TestSchema.[{refTblName}] (");
                result.AppendLine($"        [{referencedDocumentMap.IdColumnName}] nvarchar(50) NOT NULL,");
                result.AppendLine($"        [{referencedDocumentMap.IdTableColumnName}] nvarchar(50) NOT NULL,");
                result.AppendLine($"        [{referencedDocumentMap.RelatedDocumentIdColumnName}] nvarchar(50) NOT NULL,");
                result.AppendLine($"        [{referencedDocumentMap.RelatedDocumentTableColumnName}] nvarchar(50) NOT NULL ");
                result.AppendLine("    )");
            }
        }
        private async Task ProcessProjectAsync(
            Project project,
            DocumentMap documentMap)
        {
            using (Logger.LogBlock(FunctionId.FindReference_ProcessProjectAsync, project.Name, _cancellationToken))
            {
                if (project.SupportsCompilation)
                {
                    // make sure we hold onto compilation while we search documents belong to this project
                    var compilation = await project.GetCompilationAsync(_cancellationToken).ConfigureAwait(false);

                    var documentTasks = new List <Task>();
                    foreach (var(document, documentQueue) in documentMap)
                    {
                        if (document.Project == project)
                        {
                            documentTasks.Add(Task.Factory.StartNew(() => ProcessDocumentQueueAsync(document, documentQueue), _cancellationToken, TaskCreationOptions.None, _scheduler).Unwrap());
                        }
                    }

                    await Task.WhenAll(documentTasks).ConfigureAwait(false);

                    GC.KeepAlive(compilation);
                }
            }
        }
Example #8
0
 public async Task AfterUpdateAsync <TDocument>(TDocument document, DocumentMap map, IWriteTransaction transaction) where TDocument : class
 {
     foreach (var hook in hooks)
     {
         await hook.AfterUpdateAsync(document, map, transaction);
     }
 }
        public PreparedCommand PrepareDelete(DocumentMap mapping, Where where, CommandParameterValues parameters, DeleteOptions options = null)
        {
            options ??= DeleteOptions.Default;

            var actualTableName  = options.TableName ?? mapping.TableName;
            var actualSchemaName = options.SchemaName ?? configuration.GetSchemaNameOrDefault(mapping);

            if (!mapping.RelatedDocumentsMappings.Any())
            {
                return(new PreparedCommand($"DELETE FROM [{actualSchemaName}].[{actualTableName}]{options.Hint??""} {where.GenerateSql()}", parameters, RetriableOperation.Delete, mapping, options.CommandTimeout));
            }

            var statement = new StringBuilder();

            statement.AppendLine("DECLARE @Ids as TABLE (Id nvarchar(400))");
            statement.AppendLine();
            statement.AppendLine("INSERT INTO @Ids");
            statement.AppendLine($"SELECT [{mapping.IdColumn.ColumnName}]");
            statement.AppendLine($"FROM [{actualSchemaName}].[{actualTableName}] WITH (ROWLOCK)");
            statement.AppendLine(where.GenerateSql());
            statement.AppendLine();

            statement.AppendLine($"DELETE FROM [{actualSchemaName}].[{actualTableName}] WITH (ROWLOCK) WHERE [{mapping.IdColumn.ColumnName}] in (SELECT Id FROM @Ids)");

            foreach (var relMap in mapping.RelatedDocumentsMappings.Select(m => (tableName: m.TableName, schema: configuration.GetSchemaNameOrDefault(m), idColumnName: m.IdColumnName)).Distinct())
            {
                statement.AppendLine($"DELETE FROM [{relMap.schema}].[{relMap.tableName}] WITH (ROWLOCK) WHERE [{relMap.idColumnName}] in (SELECT Id FROM @Ids)");
            }

            return(new PreparedCommand(statement.ToString(), parameters, RetriableOperation.Delete, mapping, options.CommandTimeout));
        }
        void AppendRelatedDocumentStatementsForInsert(
            StringBuilder sb,
            CommandParameterValues parameters,
            DocumentMap mapping,
            IReadOnlyList <object> documents)
        {
            var relatedDocumentData = GetRelatedDocumentTableData(mapping, documents);

            foreach (var data in relatedDocumentData.Where(g => g.Related.Length > 0))
            {
                var relatedVariablePrefix = $"{data.TableName.ToLower()}_";

                sb.AppendLine($"INSERT INTO [{data.SchemaName}].[{data.TableName}] ([{data.IdColumnName}], [{data.IdTableColumnName}], [{data.RelatedDocumentIdColumnName}], [{data.RelatedDocumentTableColumnName}]) VALUES");
                var related = data.Related;

                for (var x = 0; x < related.Length; x++)
                {
                    var parentIdVariable  = related[x].parentIdVariable;
                    var relatedDocumentId = related[x].relatedDocumentId;
                    var relatedTableName  = related[x].relatedTableName;

                    var relatedVariableName = relatedVariablePrefix + x;
                    parameters.Add(relatedVariableName, relatedDocumentId);
                    if (x > 0)
                    {
                        sb.Append(",");
                    }
                    sb.AppendLine($"(@{parentIdVariable}, '{mapping.TableName}', @{relatedVariableName}, '{relatedTableName}')");
                }
            }
        }
Example #11
0
 public void AfterDelete <TDocument>(string id, DocumentMap map, IWriteTransaction transaction) where TDocument : class
 {
     foreach (var hook in hooks)
     {
         hook.AfterDelete <TDocument>(id, map, transaction);
     }
 }
Example #12
0
 private static void HandleDocumentMap(DocumentMap documentMap, PDFLabel currentLabel, int currentLevel)
 {
     while (documentMap.MoveNext())
     {
         DocumentMapNode current  = documentMap.Current;
         PDFLabel        pDFLabel = new PDFLabel(current.Id, current.Label);
         if (current.Level > currentLevel)
         {
             if (currentLabel.Children == null)
             {
                 currentLabel.Children = new List <PDFLabel>();
             }
             currentLabel.Children.Add(pDFLabel);
             pDFLabel.Parent = currentLabel;
             currentLevel++;
         }
         else if (current.Level == currentLevel)
         {
             currentLabel.Parent.Children.Add(pDFLabel);
             pDFLabel.Parent = currentLabel.Parent;
         }
         else
         {
             for (int num = currentLevel - current.Level; num >= 0; num--)
             {
                 currentLabel = currentLabel.Parent;
             }
             currentLabel.Children.Add(pDFLabel);
             pDFLabel.Parent = currentLabel;
             currentLevel    = current.Level;
         }
         currentLabel = pDFLabel;
     }
 }
Example #13
0
 public void BeforeInsert <TDocument>(TDocument document, DocumentMap map, IWriteTransaction transaction) where TDocument : class
 {
     foreach (var hook in hooks)
     {
         hook.BeforeInsert(document, map, transaction);
     }
 }
Example #14
0
 public void AfterUpdate <TDocument>(TDocument document, DocumentMap map, IWriteTransaction transaction) where TDocument : class
 {
     foreach (var hook in hooks)
     {
         hook.AfterUpdate(document, map, transaction);
     }
 }
Example #15
0
 public async Task AfterDeleteAsync <TDocument>(string id, DocumentMap map, IWriteTransaction transaction) where TDocument : class
 {
     foreach (var hook in hooks)
     {
         await hook.AfterDeleteAsync <TDocument>(id, map, transaction);
     }
 }
Example #16
0
 private void InitializeComponent()
 {
     this.DocMap = new FastColoredTextBoxNS.DocumentMap();
     ((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
     this.SuspendLayout();
     //
     // DocMap
     //
     this.DocMap.BackColor        = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
     this.DocMap.ForeColor        = System.Drawing.Color.Black;
     this.DocMap.Location         = new System.Drawing.Point(259, 74);
     this.DocMap.Name             = "DocMap";
     this.DocMap.Scale            = 0.25F;
     this.DocMap.ScrollbarVisible = false;
     this.DocMap.Size             = new System.Drawing.Size(71, 137);
     this.DocMap.TabIndex         = 6;
     this.DocMap.Target           = this;
     this.DocMap.Text             = "documentMap1";
     //
     // luatextbox
     //
     this.AutoScrollMinSize = new System.Drawing.Size(27, 14);
     this.BackColor         = System.Drawing.SystemColors.Control;
     this.Controls.Add(this.DocMap);
     this.LeftBracket      = '(';
     this.LeftBracket2     = '{';
     this.Name             = "luatextbox";
     this.RightBracket     = ')';
     this.RightBracket2    = '}';
     this.ShowFoldingLines = true;
     this.Size             = new System.Drawing.Size(330, 211);
     ((System.ComponentModel.ISupportInitialize)(this)).EndInit();
     this.ResumeLayout(false);
 }
 /// <summary>
 /// Initialises a new instance of the DocumentMapXmlRenderer.
 /// </summary>
 /// <param name="documentMap">The <paramref name="documentMap"/> to render.</param>
 /// <param name="includeSafeName">Indicates if the safename attribute should be rendered</param>
 public DocumentMapXmlRenderer(
     DocumentMap documentMap,
     bool includeSafeName)
 {
     _documentMap     = documentMap;
     _includeSafeName = includeSafeName;
 }
Example #18
0
        void InstallSchema()
        {
            Console.WriteLine("Performing migration");
            var migrator = new DatabaseMigrator();

            migrator.Migrate(Store);

            var output = new StringBuilder();

            SchemaGenerator.WriteTableSchema(new CustomerMap(), null, output);

            var mappings = new DocumentMap[]
            {
                new CustomerMap(),
                new ProductMap(),
                new LineItemMap()
            };

            Mappings.Install(mappings);

            using (var transaction = Store.BeginTransaction(IsolationLevel.ReadCommitted))
            {
                output.Clear();

                foreach (var map in mappings)
                {
                    SchemaGenerator.WriteTableSchema(map, null, output);
                }

                transaction.ExecuteScalar <int>(output.ToString());

                transaction.Commit();
            }
        }
 public ProjectData(ProjectId projectId, ImmutableArray <MonoDevelopMetadataReference> metadataReferences, MonoDevelopWorkspace ws)
 {
     this.projectId          = projectId;
     workspaceRef            = new WeakReference <MonoDevelopWorkspace> (ws);
     DocumentData            = new DocumentMap(projectId);
     this.metadataReferences = new List <MonoDevelopMetadataReference> (metadataReferences);
 }
Example #20
0
        public void GenerateMap_WhenAssemblyHasTypesWithoutNamespace_TypesAreContainedInNoneNamespaceContainer()
        {
            const string TypeName          = "Issue45_TypeWithNoNamespace";
            const string NoneNamespaceName = "NoneNamespaces";

            List <DocumentedAssembly> assemblies         = new List <DocumentedAssembly>();
            DocumentedAssembly        documentedAssembly = new DocumentedAssembly {
                FileName = DocumentationFile
            };
            EntryCreator creator = new EntryCreator();

            assemblies.Add(documentedAssembly);

            GroupedNamespaceDocumentMapper mapper = new GroupedNamespaceDocumentMapper(assemblies, false, creator);

            DocumentMap result = mapper.GenerateMap();

            AssemblyDef assembly = documentedAssembly.LoadedAssembly;

            TypeDef type  = assembly.FindType(string.Empty, TypeName);
            Entry   entry = result.FindById(type.GetGloballyUniqueId());

            Assert.AreSame(type, entry.Item);                               // the type has been mapped
            Assert.AreEqual(NoneNamespaceName, entry.Parent.Parent.SubKey); // is part of the nonenamespace container
        }
Example #21
0
        CommandParameterValues InstanceToParameters(object instance, DocumentMap mapping, string prefix = null)
        {
            var result = new CommandParameterValues
            {
                [$"{prefix}Id"] = mapping.IdColumn.ReaderWriter.Read(instance)
            };

            var mType = mapping.InstanceTypeResolver.GetTypeFromInstance(instance);

            result[$"{prefix}JSON"] = JsonConvert.SerializeObject(instance, mType, jsonSerializerSettings);

            foreach (var c in mappings.Get(mType).IndexedColumns)
            {
                var value = c.ReaderWriter.Read(instance);
                if (value != null && value != DBNull.Value && value is string && c.MaxLength > 0)
                {
                    var attemptedLength = ((string)value).Length;
                    if (attemptedLength > c.MaxLength)
                    {
                        throw new StringTooLongException(string.Format("An attempt was made to store {0} characters in the {1}.{2} column, which only allows {3} characters.", attemptedLength, mapping.TableName, c.ColumnName, c.MaxLength));
                    }
                }
                else if (value != null && value != DBNull.Value && value is DateTime && value.Equals(DateTime.MinValue))
                {
                    value = SqlDateTime.MinValue.Value;
                }

                result[$"{prefix}{c.ColumnName}"] = value;
            }
            return(result);
        }
        private async Task ProcessDocumentQueueAsync(
            Document document,
            DocumentMap.ValueSet documentQueue)
        {
            await _progress.OnFindInDocumentStartedAsync(document).ConfigureAwait(false);

            SemanticModel model = null;
            try
            {
                model = await document.GetSemanticModelAsync(_cancellationToken).ConfigureAwait(false);

                // start cache for this semantic model
                FindReferenceCache.Start(model);

                foreach (var symbolAndFinder in documentQueue)
                {
                    var symbol = symbolAndFinder.symbolAndProjectId;
                    var finder = symbolAndFinder.finder;

                    await ProcessDocumentAsync(document, symbol, finder).ConfigureAwait(false);
                }
            }
            finally
            {
                FindReferenceCache.Stop(model);

                await _progress.OnFindInDocumentCompletedAsync(document).ConfigureAwait(false);
            }
        }
Example #23
0
        public void DeleteInternal(DocumentMap mapping, string id, int?commandTimeoutSeconds)
        {
            var statement = $"DELETE from dbo.[{mapping.TableName}] WHERE Id = @Id";

            using (new TimedSection(Log, ms => $"Delete took {ms}ms in transaction '{name}': {statement}", 300))
                using (var command = sqlCommandFactory.CreateCommand(connection, transaction, statement, new CommandParameterValues {
                    { "Id", id }
                }, mapping, commandTimeoutSeconds))
                {
                    AddCommandTrace(command.CommandText);
                    try
                    {
                        // We can retry deletes because deleting something that doesn't exist will silently do nothing
                        command.ExecuteNonQueryWithRetry(GetRetryPolicy(RetriableOperation.Delete), "Delete " + mapping.TableName);
                    }
                    catch (SqlException ex)
                    {
                        throw WrapException(command, ex);
                    }
                    catch (Exception ex)
                    {
                        Log.DebugException($"Exception in relational transaction '{name}'", ex);
                        throw;
                    }
                }
        }
Example #24
0
        //private DockPanel _DockPanel;
        //private DockState _DockState;

        public EditorContainer(Editor editor, DockPanel dock, DockState dockState = DockState.Document)
        {
            Editor = editor;
            Editor.UndoRedoStateChanged += Editor_UndoRedoStateChanged;
            Editor.TextChangedDelayed   += Editor_TextChangedDelayed;
            Splitter = new Splitter()
            {
                Dock = DockStyle.Right, BackColor = SystemColors.ControlDarkDark, Width = 4
            };
            DocumentMap = new DocumentMap()
            {
                Target      = editor,
                Dock        = DockStyle.Right,
                Width       = DocumentMapInitialWidth,
                MinimumSize = new Size(DocumentMapMinimumWidth, 0),
                Scale       = DocumentMapInitialWidth * DocumentMapScaleFactor,
                BackColor   = EditorSyntax.Styles.Background,
                ForeColor   = Color.FromArgb(0, 122, 204)
            };
            DocumentMap.DoubleClick += DocumentMap_DoubleClick;
            DocumentMap.MouseWheel  += DocumentMap_MouseWheel;
            Splitter.SplitterMoved  += Splitter_SplitterMoved;
            Name        = Editor.File.FileName;
            ToolTipText = Editor.File.Path;
            Controls.Add(Editor);
            Controls.Add(Splitter);
            Controls.Add(DocumentMap);
            UpdateText(true);
            FormClosing += EditorContainer_FormClosing;
            FormClosed  += EditorContainer_FormClosed;
            System.Threading.Thread.Sleep(10);
            dock.Invoke(new Action(() => { Show(dock, dockState); }));
        }
Example #25
0
        private async Task ProcessProjectAsync(
            Project project,
            DocumentMap documentMap)
        {
            using (Logger.LogBlock(FunctionId.FindReference_ProcessProjectAsync, project.Name, _cancellationToken))
            {
                if (project.SupportsCompilation)
                {
                    // make sure we hold onto compilation while we search documents belong to this project
                    var compilation = await project.GetCompilationAsync(_cancellationToken).ConfigureAwait(false);

                    var documentTasks = new List <Task>();
                    foreach (var kvp in documentMap)
                    {
                        var document = kvp.Key;

                        if (document.Project == project)
                        {
                            var documentQueue = kvp.Value;

                            documentTasks.Add(Task.Run(() => ProcessDocumentQueueAsync(
                                                           document, documentQueue), _cancellationToken));
                        }
                    }

                    await Task.WhenAll(documentTasks).ConfigureAwait(false);

                    GC.KeepAlive(compilation);
                }
            }
        }
        string AppendRelatedDocumentStatementsForUpdate(
            string statement,
            CommandParameterValues parameters,
            DocumentMap mapping,
            object document)
        {
            var relatedDocumentData = GetRelatedDocumentTableData(mapping, new[] { document });

            if (relatedDocumentData.Count == 0)
            {
                return(statement);
            }

            var sb = new StringBuilder();

            sb.AppendLine(statement);
            sb.AppendLine();

            if (relatedDocumentData.Any(d => d.Related.Any()))
            {
                sb.AppendLine("DECLARE @references as TABLE (Reference nvarchar(400), ReferenceTable nvarchar(400))");
            }

            foreach (var data in relatedDocumentData)
            {
                if (data.Related.Any())
                {
                    var relatedVariablePrefix = $"{data.TableName.ToLower()}_";

                    sb.AppendLine();
                    sb.AppendLine("DELETE FROM @references");
                    sb.AppendLine();

                    var valueBlocks = data.Related.Select((r, idx) => $"(@{relatedVariablePrefix}{idx}, '{r.relatedTableName}')");
                    sb.Append("INSERT INTO @references VALUES ");
                    sb.AppendLine(string.Join(", ", valueBlocks));
                    sb.AppendLine();

                    sb.AppendLine($"DELETE FROM [{data.SchemaName}].[{data.TableName}] WHERE [{data.IdColumnName}] = @{IdVariableName}");
                    sb.AppendLine($"    AND [{data.RelatedDocumentIdColumnName}] not in (SELECT Reference FROM @references)");
                    sb.AppendLine();

                    sb.AppendLine($"INSERT INTO [{data.SchemaName}].[{data.TableName}] ([{data.IdColumnName}], [{data.IdTableColumnName}], [{data.RelatedDocumentIdColumnName}], [{data.RelatedDocumentTableColumnName}])");
                    sb.AppendLine($"SELECT @{IdVariableName}, '{mapping.TableName}', Reference, ReferenceTable FROM @references t");
                    sb.AppendLine($"WHERE NOT EXISTS (SELECT null FROM [{data.SchemaName}].[{data.TableName}] r WHERE r.[{data.IdColumnName}] = @{IdVariableName} AND r.[{data.RelatedDocumentIdColumnName}] = t.Reference )");

                    for (var x = 0; x < data.Related.Length; x++)
                    {
                        parameters.Add(relatedVariablePrefix + x, data.Related[x].relatedDocumentId);
                    }
                }
                else
                {
                    sb.AppendLine($"DELETE FROM [{data.SchemaName}].[{data.TableName}] WHERE [{data.IdColumnName}] = @Id");
                }
            }

            return(sb.ToString());
        }
Example #27
0
 public virtual void ContributeTo(IDbCommand command, DocumentMap mapping = null)
 {
     command.CommandType = CommandType;
     foreach (var pair in this)
     {
         ContributeParameter(command, pair.Key, pair.Value, mapping);
     }
 }
Example #28
0
        static int Main(string[] args)
        {
            DocumentMap documentMap = BuildDiffDocumentMap(ParseDiffs(ConsoleLines()));

            Console.WriteLine($"INFO: {documentMap.Count} files to process");
            ApplyChanges(documentMap);
            return(0);
        }
Example #29
0
        public void When_Referenced_It_Is_Added_To_Reference_Fields()
        {
            var orderMap = new DocumentMap<Order>();
            orderMap.Reference(o => o.Customer);

            Assert.AreEqual(1, orderMap.GetReferencedFields().Count);
            Assert.IsTrue(orderMap.GetReferencedFields().Any(m => m.Name == "Customer" && m.Type == typeof(Customer)));
        }
Example #30
0
        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);
        }
Example #31
0
 public PreparedCommand(string statement, CommandParameterValues parameterValues, RetriableOperation operation = RetriableOperation.None, DocumentMap mapping = null, TimeSpan?commandTimeout = null, CommandBehavior commandBehavior = CommandBehavior.Default)
 {
     Mapping         = mapping;
     Statement       = statement;
     ParameterValues = parameterValues;
     Operation       = operation;
     CommandTimeout  = commandTimeout;
     CommandBehavior = commandBehavior;
 }
Example #32
0
 public void When_Set_Mapped_Fields_It_Is_Added_To_Primitive_Fields()
 {
     var customerMap = new DocumentMap<Customer>();
     customerMap.Map(c => c.Name);
     customerMap.Map(c => c.Address);
     Assert.AreEqual(2, customerMap.GetMappedFields().Count);
     Assert.IsTrue(customerMap.GetMappedFields().Any(m => m.Name == "Name" && m.Type == typeof(string)));
     Assert.IsTrue(customerMap.GetMappedFields().Any(m => m.Name == "Address" && m.Type == typeof(string)));
 }
Example #33
0
        //Update ve Merge işlemleri için
        public void MergeRows(DocumentStorage storage, List <JObject> rows, DocumentMap map, Formatting formatting = Formatting.None)
        {
            try
            {
                using (FileStream fsTemp = new FileStream(storage.Tempory, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Write, BufferSize))
                    using (StreamWriter sw = new StreamWriter(fsTemp, Encoding.UTF8, BufferSize))
                        using (JsonTextWriter writer = new JsonTextWriter(sw))
                        {
                            var match = 0;
                            var count = rows.Count;

                            writer.Formatting = formatting;
                            writer.WriteStartArray();

                            using (FileStream fsTarget = new FileStream(storage.Target, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize))
                                using (StreamReader sr = new StreamReader(fsTarget, Encoding.UTF8, false, BufferSize))
                                    using (JsonReader reader = new JsonTextReader(sr))
                                    {
                                        while (reader.Read())
                                        {
                                            if (reader.TokenType == JsonToken.StartObject)
                                            {
                                                JObject readRow = JObject.Load(reader);

                                                if (match < count)
                                                {
                                                    var readId = readRow[map.Target].ToString();

                                                    foreach (JObject row in rows)
                                                    {
                                                        var id = row[map.Source].ToString();

                                                        if (readId == id)
                                                        {
                                                            readRow.Merge(row);
                                                            match++;
                                                            break;
                                                        }
                                                    }
                                                }

                                                readRow.WriteTo(writer);
                                            }
                                        }
                                    }

                            writer.WriteEndArray();
                            writer.Flush();
                        }
            }
            catch (Exception ex)
            {
                Logger?.Fatal(ex);

                throw ex;
            }
        }
Example #34
0
        string AllocateId(DocumentMap mapping)
        {
            if (!string.IsNullOrEmpty(mapping.SingletonId))
            {
                return(mapping.SingletonId);
            }

            return(AllocateId(mapping.TableName, mapping.IdPrefix));
        }
        public void GetPart()
        {
            var map = new DocumentMap<string>();
            map.Add(5, "test");

            var relativeRanges = map.GetRelativeRange(new Range(1, 7));
            Assert.AreEqual(1, relativeRanges.Count);
            Assert.AreEqual("test", relativeRanges[0].Source);
            Assert.AreEqual(new Range(1,5), relativeRanges[0].Range);
        }
        public void GetEmpty()
        {
            var map = new DocumentMap<string>();
            map.Add(5, "test");
            map.Add(0, "test3");
            map.Add(2, "test2");

            var relativeRanges = map.GetRelativeRange(new Range(1, 7));
            Assert.AreEqual(3, relativeRanges.Count);

            Assert.AreEqual("test3", relativeRanges[1].Source);
            Assert.AreEqual(new Range(0,0), relativeRanges[1].Range);
        }
        private async Task<ProjectToDocumentMap> CreateProjectToDocumentMapAsync(ProjectMap projectMap)
        {
            using (Logger.LogBlock(FunctionId.FindReference_CreateDocumentMapAsync, _cancellationToken))
            {
                var finalMap = new ProjectToDocumentMap();

                foreach (var kvp in projectMap)
                {
                    var project = kvp.Key;
                    var projectQueue = kvp.Value;

                    var documentMap = new DocumentMap();

                    foreach (var symbolAndFinder in projectQueue)
                    {
                        _cancellationToken.ThrowIfCancellationRequested();

                        var symbolAndProjectId = symbolAndFinder.symbolAndProjectId;
                        var symbol = symbolAndProjectId.Symbol;
                        var finder = symbolAndFinder.finder;

                        var documents = await finder.DetermineDocumentsToSearchAsync(symbol, project, _documents, _cancellationToken).ConfigureAwait(false);
                        foreach (var document in documents.Distinct().WhereNotNull())
                        {
                            if (_documents == null || _documents.Contains(document))
                            {
                                documentMap.Add(document, symbolAndFinder);
                            }
                        }
                    }

                    Contract.ThrowIfTrue(documentMap.Any(kvp1 => kvp1.Value.Count != kvp1.Value.ToSet().Count));

                    if (documentMap.Count > 0)
                    {
                        finalMap.Add(project, documentMap);
                    }
                }

                return finalMap;
            }
        }
Example #38
0
 public void When_Given_A_NonPrimitive_Id_Type_Throws_Exception()
 {
     var orderMap = new DocumentMap<Order>();
     orderMap.Id(c => c.Customer);
 }
Example #39
0
 public void When_Set_IdField_It_Is_Set_As_Primary_Key()
 {
     var customerMap= new DocumentMap<Customer>();
     customerMap.Id(c => c.Id);
     Assert.AreEqual("Id",customerMap.IdWrapper.Name);
 }
 public void EmptyIsEmptyAndNotNull()
 {
     var map = new DocumentMap<string>();
     Assert.AreEqual(0, map.GetRelativeRange(new Range(0, 7)).Count);
 }
 public void InvalidDoesNotCrash()
 {
     var map = new DocumentMap<string>();
     Assert.AreEqual(0, map.GetRelativeRange(new Range(-5, 0)).Count);
 }