Report: work with indexes in ExcelRepBuilder

--- Report/RepBuilder/ExcelRepBuilder.cs
+++ Report/RepBuilder/ExcelRepBuilder.cs
@@ -630,32 +630,21 @@
             /// <summary>
             /// Найти столбец в таблице по индексу
             /// </summary>
-            /// <param name="columnIndex">Индекс искомого столбца</param>
-            /// <param name="exact">Получен столбец с указанным индексом (true) или с ближайшим большим (false)</param>
-            /// <returns>Столбец, удовлетворяющий критерию поиска, или null, если индексы всех столбцов меньше заданного</returns>
-            public Column FindColumn(int columnIndex, out bool exact)
+            /// <param name="columnIndex">Индекс искомого столбца, начиная с 1</param>
+            /// <returns>Столбец, удовлетворяющий критерию поиска, или null, если столбец не найден</returns>
+            public Column FindColumn(int columnIndex)
             {
                 int index = 0;
                 foreach (Column column in columns)
                 {
-                    if (column.Index > 0)
-                        index = column.Index;
-                    else
-                        index++;
+                    index = column.Index > 0 ? column.Index : index + 1;

                     if (index == columnIndex)
-                    {
-                        exact = true;
                         return column;
-                    }
                     else if (index > columnIndex)
-                    {
-                        exact = false;
-                        return column;
-                    }
-                }
-
-                exact = false;
+                        return null;
+                }
+
                 return null;
             }

@@ -975,38 +964,58 @@
             /// <summary>
             /// Найти ячейку в строке по индексу
             /// </summary>
-            /// <param name="cellIndex">Индекс искомой ячейки</param>
-            /// <param name="exact">Получена ячейка с указанным индексом (true) или с ближайшим большим (false)</param>
-            /// <returns>Ячейка, удовлетворяющая критерию поиска, или null, если индексы всех ячеек меньше заданного</returns>
-            public Cell FindCell(int cellIndex, out bool exact)
+            /// <param name="cellIndex">Индекс искомой ячейки, начиная с 1</param>
+            /// <returns>Ячейка, удовлетворяющая критерию поиска, или null, если ячейка не найдена</returns>
+            public Cell FindCell(int cellIndex)
             {
                 int index = 0;
                 foreach (Cell cell in cells)
                 {
-                    XmlAttribute attr = cell.Node.Attributes["ss:MergeAcross"];
-                    int merge = attr == null ? 0 : int.Parse(attr.Value);
-
+                    index = cell.Index > 0 ? cell.Index : index + 1;
+                    int endIndex = index + cell.MergeAcross;
+
+                    if (index <= cellIndex && cellIndex <= endIndex)
+                        return cell;
+                    else if (index > endIndex)
+                        return null;
+
+                    index = endIndex;
+                }
+
+                return null;
+            }
+
+            /// <summary>
+            /// Рассчитать индекс в строке для заданной ячейки
+            /// </summary>
+            /// <param name="cell">Ячейка, индекс которой рассчитывается</param>
+            /// <returns>Индекс заданной ячейки, начинающийся от 1,
+            /// или 0, если ячейка не относится к данной строке</returns>
+            public int CalcCellIndex(Cell cell)
+            {
+                if (cell.ParentRow == this)
+                {
                     if (cell.Index > 0)
-                        index = cell.Index;
+                    {
+                        return cell.Index;
+                    }
                     else
-                        index++;
-
-                    if (index == cellIndex || index < cellIndex && cellIndex <= index + merge)
                     {
-                        exact = true;
-                        return cell;
+                        int index = 0;
+                        foreach (Cell c in cells)
+                        {
+                            index = c.Index > 0 ? c.Index : index + 1;
+                            if (c == cell)
+                                return index;
+                            index += c.MergeAcross;
+                        }
+                        return 0;
                     }
-                    else if (index > cellIndex)
-                    {
-                        exact = false;
-                        return cell;
-                    }
-
-                    index += merge;
-                }
-
-                exact = false;
-                return null;
+                }
+                else
+                {
+                    return 0;
+                }
             }

             /// <summary>


Fix #177: Lock untranslatable columns in Excel

--- ResXManager.Model/ExcelExtensions.cs
+++ ResXManager.Model/ExcelExtensions.cs
@@ -2,9 +2,7 @@
 {
     using System;
     using System.Collections.Generic;
-    using System.Diagnostics;
     using System.Diagnostics.CodeAnalysis;
-    using System.Diagnostics.Contracts;
     using System.Globalization;
     using System.IO;
     using System.Linq;
@@ -35,9 +33,6 @@

         public static void ExportExcelFile([NotNull] this ResourceManager resourceManager, [NotNull] string filePath, [CanBeNull] IResourceScope scope, ExcelExportMode exportMode)
         {
-            Contract.Requires(resourceManager != null);
-            Contract.Requires(filePath != null);
-
             if (exportMode == ExcelExportMode.Text)
             {
                 ExportToText(filePath, scope ?? new FullScope(resourceManager.ResourceEntities));
@@ -46,10 +41,9 @@

             using (var package = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook))
             {
-                Contract.Assume(package != null);
-
                 var workbookPart = package.AddWorkbookPart();
-                Contract.Assume(workbookPart != null);
+
+                GeneratedCode.GeneratedClass.AddStylesToWorkbookPart(workbookPart);

                 if (exportMode == ExcelExportMode.MultipleSheets)
                 {
@@ -79,9 +73,6 @@

         private static void ExportToMultipleSheets([NotNull] ResourceManager resourceManager, [NotNull] WorkbookPart workbookPart, [CanBeNull] IResourceScope scope)
         {
-            Contract.Requires(resourceManager != null);
-            Contract.Requires(workbookPart != null);
-
             var entitiesQuery = GetMultipleSheetEntities(resourceManager);

             if (scope != null)
@@ -94,47 +85,48 @@

             workbookPart.Workbook = new Workbook().AppendItem(entities.Aggregate(new Sheets(), (seed, item) => seed.AppendItem(item.CreateSheet())));

+            var dataAppender = new DataAppender(_fixedColumnHeaders.Length);
+
             foreach (var item in entities)
             {
-                Contract.Assume(item != null);
-
-                var worksheetPart = workbookPart.AddNewPart<WorksheetPart>(item.Id);
-                Contract.Assume(worksheetPart != null);
-                worksheetPart.Worksheet = new Worksheet().AppendItem(item.GetDataRows(scope).Aggregate(new SheetData(), AppendRow));
+                workbookPart
+                    .AddNewPart<WorksheetPart>(item.Id)
+                    .Worksheet = new Worksheet()
+                        .AppendItem(item.GetDataRows(scope).Aggregate(new SheetData(), dataAppender.AppendRow))
+                        .Protect();
             }
         }

         private static void ExportToSingleSheet([NotNull] WorkbookPart workbookPart, [NotNull] IResourceScope scope)
         {
-            Contract.Requires(workbookPart != null);
-            Contract.Requires(scope != null);
-
             var languages = scope.Languages.Concat(scope.Comments).Distinct().ToArray();
             var entries = scope.Entries.ToArray();

             var sheet = new Sheet { Name = "ResXResourceManager", Id = "Id1", SheetId = 1 };
-            workbookPart.Workbook = new Workbook().AppendItem(new Sheets(sheet));
-            var worksheetPart = workbookPart.AddNewPart<WorksheetPart>(sheet.Id);
-            Contract.Assume(worksheetPart != null);
-            var worksheet = new Worksheet();
-
-            worksheetPart.Worksheet = worksheet;

             var headerRow = _singleSheetFixedColumnHeaders.Concat(languages.GetLanguageColumnHeaders(scope));
             var dataRows = entries.Select(e => new[] { e.Container.ProjectName, e.Container.UniqueName }.Concat(e.GetDataRow(languages, scope)));
-
             var rows = new[] { headerRow }.Concat(dataRows);

-            worksheet.AppendItem(rows.Aggregate(new SheetData(), AppendRow));
+            var dataAppender = new DataAppender(_singleSheetFixedColumnHeaders.Length);
+
+            workbookPart.Workbook = new Workbook().AppendItem(new Sheets(sheet));
+
+            workbookPart
+                .AddNewPart<WorksheetPart>(sheet.Id)
+                .Worksheet = new Worksheet()
+                    .AppendItem(rows.Aggregate(new SheetData(), dataAppender.AppendRow))
+                    .Protect();
+        }
+
+        private static Worksheet Protect(this Worksheet worksheet)
+        {
+            return worksheet.AppendItem(new SheetProtection { Sheet = true, Objects = true, Scenarios = true, FormatColumns = false, FormatRows = false, Sort = false, AutoFilter = false });
         }

         [NotNull, ItemNotNull]
         public static IList<EntryChange> ImportExcelFile([NotNull] this ResourceManager resourceManager, [NotNull] string filePath)
         {
-            Contract.Requires(resourceManager != null);
-            Contract.Requires(filePath != null);
-            Contract.Ensures(Contract.Result<IEnumerable<EntryChange>>() != null);
-
             var content = File.ReadAllText(filePath);

             if (content.StartsWith(string.Join("\t", _singleSheetFixedColumnHeaders), StringComparison.OrdinalIgnoreCase))
@@ -144,17 +136,10 @@

             using (var package = SpreadsheetDocument.Open(filePath, false))
             {
-                Contract.Assume(package != null);
                 var workbookPart = package.WorkbookPart;
-                Contract.Assume(workbookPart != null);
-
                 var workbook = workbookPart.Workbook;
-                Contract.Assume(workbook != null);
-
                 var sharedStrings = workbookPart.GetSharedStrings();
-
                 var sheets = workbook.Sheets;
-                Contract.Assume(sheets != null);

                 var firstSheet = sheets.OfType<Sheet>().FirstOrDefault();
                 if (firstSheet == null)
@@ -173,11 +158,6 @@
         [NotNull, ItemNotNull]
         private static IEnumerable<EntryChange> ImportSingleSheet([NotNull] ResourceManager resourceManager, [NotNull, ItemNotNull] Sheet firstSheet, [NotNull] WorkbookPart workbookPart, [ItemNotNull][CanBeNull] IList<SharedStringItem> sharedStrings)
         {
-            Contract.Requires(resourceManager != null);
-            Contract.Requires(firstSheet != null);
-            Contract.Requires(workbookPart != null);
-            Contract.Ensures(Contract.Result<IEnumerable<EntryChange>>() != null);
-
             var data = firstSheet.GetRows(workbookPart).Select(row => row.GetCellValues(sharedStrings)).ToArray();

             return ImportSingleSheet(resourceManager, data);
@@ -191,16 +171,12 @@

             var firstRow = data.FirstOrDefault();

-            Contract.Assume(firstRow != null);
-
             var headerRow = (IList<string>)firstRow.Skip(2).ToArray();

             var rowsByProject = data.Skip(1).GroupBy(row => row.FirstOrDefault() ?? string.Empty, row => (IList<string>)row.Skip(1).ToArray());

             foreach (var projectRows in rowsByProject)
             {
-                Contract.Assume(projectRows != null);
-
                 var projectName = projectRows.Key;

                 if (string.IsNullOrEmpty(projectName))
@@ -210,8 +186,6 @@

                 foreach (var fileRows in rowsByFile)
                 {
-                    Contract.Assume(fileRows != null);
-
                     var uniqueName = fileRows.Key;
                     if (string.IsNullOrEmpty(uniqueName))
                         continue;
@@ -240,11 +214,6 @@
         [NotNull, ItemNotNull]
         private static IEnumerable<EntryChange> ImportMultipleSheets([NotNull] ResourceManager resourceManager, [NotNull][ItemNotNull] Sheets sheets, [NotNull] WorkbookPart workbookPart, [ItemNotNull][CanBeNull] IList<SharedStringItem> sharedStrings)
         {
-            Contract.Requires(resourceManager != null);
-            Contract.Requires(sheets != null);
-            Contract.Requires(workbookPart != null);
-            Contract.Ensures(Contract.Result<IEnumerable<EntryChange>>() != null);
-
             var entities = GetMultipleSheetEntities(resourceManager).ToArray();

             var changes = sheets.OfType<Sheet>()
@@ -257,10 +226,6 @@
         [ItemNotNull]
         private static IList<string>[] GetTable([NotNull][ItemNotNull] this Sheet sheet, [NotNull] WorkbookPart workbookPart, [ItemNotNull][CanBeNull] IList<SharedStringItem> sharedStrings)
         {
-            Contract.Requires(sheet != null);
-            Contract.Requires(workbookPart != null);
-            Contract.Ensures(Contract.Result<IList<string>[]>() != null);
-
             return sheet.GetRows(workbookPart)
                 .Select(row => row.GetCellValues(sharedStrings))
                 .ToArray();
@@ -277,9 +242,6 @@
         [ItemNotNull]
         private static IList<string> GetCellValues([NotNull][ItemNotNull] this Row row, [ItemNotNull][CanBeNull] IList<SharedStringItem> sharedStrings)
         {
-            Contract.Requires(row != null);
-            Contract.Ensures(Contract.Result<IList<string>>() != null);
-
             return row.OfType<Cell>().GetCellValues(sharedStrings).ToArray();
         }

@@ -287,10 +249,6 @@
         [ItemNotNull]
         private static IEnumerable<Row> GetRows([NotNull][ItemNotNull] this Sheet sheet, [NotNull] WorkbookPart workbookPart)
         {
-            Contract.Requires(sheet != null);
-            Contract.Requires(workbookPart != null);
-            Contract.Ensures(Contract.Result<IEnumerable<Row>>() != null);
-
             var worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id);

             return worksheetPart?.Worksheet?.ChildElements?.OfType<SheetData>()?.FirstOrDefault()?.OfType<Row>() ?? Enumerable.Empty<Row>();
@@ -299,11 +257,7 @@
         [NotNull]
         private static ResourceEntity FindResourceEntity([NotNull][ItemNotNull] this IEnumerable<MultipleSheetEntity> entities, [NotNull][ItemNotNull] Sheet sheet)
         {
-            Contract.Requires(entities != null);
-            Contract.Requires(sheet != null);
-            Contract.Ensures(Contract.Result<ResourceEntity>() != null);
-
-            var name = GetName(sheet);
+            var name = sheet.Name.Value;

             var entity = entities.Where(item => item.SheetName.Equals(name, StringComparison.OrdinalIgnoreCase))
                 .Select(item => item.ResourceEntity)
@@ -315,77 +269,77 @@
             return entity;
         }

-        [ContractVerification(false)]
-        [NotNull]
-        private static string GetName([NotNull][ItemNotNull] this Sheet sheet)
-        {
-            Contract.Requires(sheet != null);
-            Contract.Ensures(Contract.Result<string>() != null);
-
-            return sheet.Name.Value;
-        }
-
-        [ItemNotNull]
-        [CanBeNull]
-        private static SheetData AppendRow([NotNull][ItemNotNull] SheetData sheetData, [NotNull][ItemNotNull] IEnumerable<string> rowData)
-        {
-            Contract.Requires(sheetData != null);
-            Contract.Requires(rowData != null);
-
-            var row = (sheetData.ChildElements?.OfType<Row>()?.Count() ?? 0) + 1;
-            var column = 1;
-            return sheetData.AppendItem(rowData.Aggregate(new Row(), (seed, item) => seed.AppendItem(CreateCell(item, row, column++))));
-        }
-
-        [NotNull]
-        [ItemNotNull]
-        private static Cell CreateCell([CanBeNull] string text, int row, int column)
-        {
-            Contract.Ensures(Contract.Result<Cell>() != null);
-
-            return new Cell
-            {
-                DataType = CellValues.InlineString,
-                CellReference = CreateCellReference(row, column),
-                InlineString = new InlineString
-                {
-                    Text = new Text(text ?? string.Empty)
+        private class DataAppender
+        {
+            private readonly int _numberOfFixedColumns;
+
+            public DataAppender(int numberOfFixedColumns)
+            {
+                _numberOfFixedColumns = numberOfFixedColumns;
+            }
+
+            [ItemNotNull]
+            [CanBeNull]
+            public SheetData AppendRow([NotNull] [ItemNotNull] SheetData sheetData, [NotNull] [ItemNotNull] IEnumerable<string> rowData)
+            {
+                var row = (sheetData.ChildElements?.OfType<Row>()?.Count() ?? 0) + 1;
+                var column = 1;
+                return sheetData.AppendItem(rowData.Aggregate(new Row(), (seed, item) => seed.AppendItem(CreateCell(item, row, column++))));
+            }
+
+            [NotNull]
+            [ItemNotNull]
+            private Cell CreateCell([CanBeNull] string text, int row, int column)
+            {
+                var cell = new Cell
+                {
+                    DataType = CellValues.InlineString,
+                    CellReference = CreateCellReference(row, column),
+                    InlineString = new InlineString
                     {
-                        Space = SpaceProcessingModeValues.Preserve
+                        Text = new Text(text ?? string.Empty)
+                        {
+                            Space = SpaceProcessingModeValues.Preserve
+                        }
                     }
+                };
+
+                if ((row <= 1) || (column <= _numberOfFixedColumns))
+                {
+                    cell.StyleIndex = 1; // locked
                 }
-            };
-        }
-
-        [NotNull]
-        private static string CreateCellReference(int row, int column)
-        {
-            return GetExcelColumnName(column) + row.ToString(CultureInfo.InvariantCulture);
-        }
-
-        // From: https://stackoverflow.com/questions/181596/how-to-convert-a-column-number-eg-127-into-an-excel-column-eg-aa
-        [NotNull]
-        private static string GetExcelColumnName(int columnNumber)
-        {
-            var dividend = columnNumber;
-            var columnName = string.Empty;
-
-            while (dividend > 0)
-            {
-                var modulo = (dividend - 1) % 26;
-                columnName = Convert.ToChar(65 + modulo) + columnName;
-                dividend = (dividend - modulo) / 26;
-            }
-
-            return columnName;
+
+                return cell;
+            }
+
+            [NotNull]
+            private static string CreateCellReference(int row, int column)
+            {
+                return GetExcelColumnName(column) + row.ToString(CultureInfo.InvariantCulture);
+            }
+
+            // From: https://stackoverflow.com/questions/181596/how-to-convert-a-column-number-eg-127-into-an-excel-column-eg-aa
+            [NotNull]
+            private static string GetExcelColumnName(int columnNumber)
+            {
+                var dividend = columnNumber;
+                var columnName = string.Empty;
+
+                while (dividend > 0)
+                {
+                    var modulo = (dividend - 1) % 26;
+                    columnName = Convert.ToChar(65 + modulo) + columnName;
+                    dividend = (dividend - modulo) / 26;
+                }
+
+                return columnName;
+            }
         }

         [ItemNotNull]
         [CanBeNull]
         private static IList<SharedStringItem> GetSharedStrings([NotNull] this WorkbookPart workbookPart)
         {
-            Contract.Requires(workbookPart != null);
-
             var sharedStringsPart = workbookPart.SharedStringTablePart;

             var stringTable = sharedStringsPart?.SharedStringTable;
@@ -396,9 +350,6 @@
         [CanBeNull]
         private static string GetText([NotNull][ItemNotNull] this CellType cell, [ItemNotNull][CanBeNull] IList<SharedStringItem> sharedStrings)
         {
-            Contract.Requires(cell != null);
-            Contract.Ensures(Contract.Result<string>() != null);
-
             var cellValue = cell.CellValue;
             var dataType = cell.DataType;

@@ -442,14 +393,10 @@
         [ItemNotNull]
         private static IEnumerable<string> GetCellValues([NotNull][ItemNotNull] this IEnumerable<Cell> cells, [ItemNotNull][CanBeNull] IList<SharedStringItem> sharedStrings)
         {
-            Contract.Requires(cells != null);
-            Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
-
             var columnIndex = 0;

             foreach (var cell in cells)
             {
-                Contract.Assume(cell != null);
                 var cellColumnIndex = new ExcelRange(cell.CellReference).StartColumnIndex;

                 while (columnIndex < cellColumnIndex)
@@ -473,8 +420,6 @@
         [CanBeNull]
         private static IEnumerable<string> GetLanguageColumnHeaders([NotNull] this CultureKey language, [CanBeNull] IResourceScope scope)
         {
-            Contract.Requires(language != null);
-
             var cultureKeyName = language.ToString();

             if ((scope == null) || scope.Comments.Contains(language))
@@ -488,9 +433,6 @@
         [CanBeNull]
         private static IEnumerable<string> GetLanguageDataColumns([NotNull] this ResourceTableEntry entry, [NotNull] CultureKey language, [CanBeNull] IResourceScope scope)
         {
-            Contract.Requires(entry != null);
-            Contract.Requires(language != null);
-
             if ((scope == null) || scope.Comments.Contains(language))
                 yield return entry.Comments.GetValue(language);

@@ -509,9 +451,6 @@
         [NotNull, ItemNotNull]
         private static IEnumerable<IEnumerable<string>> GetHeaderRows([NotNull][ItemNotNull] this IEnumerable<CultureKey> languages, [CanBeNull] IResourceScope scope)
         {
-            Contract.Requires(languages != null);
-            Contract.Ensures(Contract.Result<IEnumerable<IEnumerable<string>>>() != null);
-
             var languageColumnHeaders = languages.GetLanguageColumnHeaders(scope);

             yield return _fixedColumnHeaders.Concat(languageColumnHeaders);
@@ -521,9 +460,6 @@
         [ItemNotNull]
         private static IEnumerable<string> GetLanguageColumnHeaders([NotNull][ItemNotNull] this IEnumerable<CultureKey> languages, [CanBeNull] IResourceScope scope)
         {
-            Contract.Requires(languages != null);
-            Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
-
             return languages.SelectMany(lang => lang.GetLanguageColumnHeaders(scope));
         }

@@ -540,10 +476,6 @@
         [ItemNotNull]
         private static IEnumerable<IEnumerable<string>> GetDataRows([NotNull] this ResourceEntity entity, [NotNull][ItemNotNull] IEnumerable<CultureKey> languages, [CanBeNull] IResourceScope scope)
         {
-            Contract.Requires(entity != null);
-            Contract.Requires(languages != null);
-            Contract.Ensures(Contract.Result<IEnumerable<IEnumerable<string>>>() != null);
-
             var entries = scope?.Entries.Where(entry => entry.Container == entity) ?? entity.Entries;

             return entries.Select(entry => entry.GetDataRow(languages, scope));
@@ -562,10 +494,6 @@
         [ItemNotNull]
         private static IEnumerable<string> GetDataRow([NotNull] this ResourceTableEntry entry, [NotNull][ItemNotNull] IEnumerable<CultureKey> languages, [CanBeNull] IResourceScope scope)
         {
-            Contract.Requires(entry != null);
-            Contract.Requires(languages != null);
-            Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
-
             return new[] { entry.Key }.Concat(entry.GetLanguageDataColumns(languages, scope));
         }

@@ -573,10 +501,6 @@
         [ItemNotNull]
         private static IEnumerable<string> GetLanguageDataColumns([NotNull] this ResourceTableEntry entry, [NotNull][ItemNotNull] IEnumerable<CultureKey> languages, [CanBeNull] IResourceScope scope)
         {
-            Contract.Requires(entry != null);
-            Contract.Requires(languages != null);
-            Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
-
             return languages.SelectMany(l => entry.GetLanguageDataColumns(l, scope));
         }

@@ -596,9 +520,6 @@
         [ItemNotNull]
         private static IEnumerable<MultipleSheetEntity> GetMultipleSheetEntities([NotNull] ResourceManager resourceManager)
         {
-            Contract.Requires(resourceManager != null);
-            Contract.Ensures(Contract.Result<IEnumerable<MultipleSheetEntity>>() != null);
-
             var uniqueNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

             return resourceManager.ResourceEntities
@@ -610,22 +531,16 @@
         private class MultipleSheetEntity
         {
             private const int MaxSheetNameLength = 31;
-            [NotNull]
-            private readonly ResourceEntity _resourceEntity;
+
             [CanBeNull]
             private readonly UInt32Value _sheetId;
-            [NotNull]
-            private readonly string _sheetName;

             public MultipleSheetEntity([NotNull] ResourceEntity resourceEntity, int index, [NotNull][ItemNotNull] ISet<string> uniqueNames)
             {
-                Contract.Requires(resourceEntity != null);
-                Contract.Requires(uniqueNames != null);
-
-                _resourceEntity = resourceEntity;
+                ResourceEntity = resourceEntity;

                 var sheetName = GetSheetName(resourceEntity, uniqueNames);
-                _sheetName = sheetName;
+                SheetName = sheetName;

                 Id = "Id" + index + 1;
                 _sheetId = UInt32Value.FromUInt32((uint)index + 1);
@@ -634,10 +549,6 @@
             [NotNull]
             private static string GetSheetName([NotNull] ResourceEntity resourceEntity, [NotNull][ItemNotNull] ISet<string> uniqueNames)
             {
-                Contract.Requires(resourceEntity != null);
-                Contract.Requires(uniqueNames != null);
-                Contract.Ensures(Contract.Result<string>() != null);
-
                 var name = string.Join("|", resourceEntity.ProjectName, resourceEntity.BaseName);

                 if ((name.Length > MaxSheetNameLength) || uniqueNames.Contains(name))
@@ -658,51 +569,28 @@
             [NotNull]
             private static string GenrateShortName(int i, [NotNull] string name)
             {
-                Contract.Requires(name != null);
-                Contract.Ensures(Contract.Result<string>() != null);
-
                 var suffix = "~" + i;
-                Contract.Assume(suffix.Length < MaxSheetNameLength);
                 var prefixLenght = Math.Min(name.Length, MaxSheetNameLength - suffix.Length);

                 return name.Substring(0, prefixLenght) + suffix;
             }

             [NotNull]
-            public string SheetName
-            {
-                get
-                {
-                    Contract.Ensures(Contract.Result<string>() != null);
-                    return _sheetName;
-                }
-            }
-
-            [NotNull]
-            public ResourceEntity ResourceEntity
-            {
-                get
-                {
-                    Contract.Ensures(Contract.Result<ResourceEntity>() != null);
-                    return _resourceEntity;
-                }
-            }
+            public string SheetName { get; }
+
+            [NotNull]
+            public ResourceEntity ResourceEntity { get; }

             [CanBeNull]
-            public string Id
-            {
-                get;
-            }
+            public string Id { get; }

             [NotNull]
             [ItemNotNull]
             public Sheet CreateSheet()
             {
-                Contract.Ensures(Contract.Result<Sheet>() != null);
-
                 return new Sheet
                 {
-                    Name = _sheetName,
+                    Name = SheetName,
                     SheetId = _sheetId,
                     Id = Id
                 };
@@ -712,23 +600,12 @@
             [ItemNotNull]
             public IEnumerable<IEnumerable<string>> GetDataRows([CanBeNull] IResourceScope scope)
             {
-                Contract.Ensures(Contract.Result<IEnumerable<IEnumerable<string>>>() != null);
-
-                var languages = _resourceEntity.Languages
+                var languages = ResourceEntity.Languages
                     .Select(l => l.CultureKey)
                     .ToArray();

                 return languages.GetHeaderRows(scope)
-                    .Concat(_resourceEntity.GetDataRows(languages, scope));
-            }
-
-            [ContractInvariantMethod]
-            [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for code contracts.")]
-            [Conditional("CONTRACTS_FULL")]
-            private void ObjectInvariant()
-            {
-                Contract.Invariant(_resourceEntity != null);
-                Contract.Invariant(_sheetName != null);
+                    .Concat(ResourceEntity.GetDataRows(languages, scope));
             }
         }

@@ -736,8 +613,6 @@
         {
             public FullScope([NotNull][ItemNotNull] ICollection<ResourceEntity> entities)
             {
-                Contract.Requires(entities != null);
-
                 Entries = entities.SelectMany(entity => entity.Entries)
                     .ToArray();

@@ -767,4 +642,103 @@
             }
         }
     }
+
+    namespace GeneratedCode
+    {
+        using DocumentFormat.OpenXml.Packaging;
+        using DocumentFormat.OpenXml.Spreadsheet;
+        using DocumentFormat.OpenXml;
+
+        // Generated from an empty document using the OpenXML SDK Productivity Tool
+        [SuppressMessage("ReSharper", "All")]
+        public static class GeneratedClass
+        {
+            public static void AddStylesToWorkbookPart(WorkbookPart part)
+            {
+                var workbookStylesPart = part.AddNewPart<WorkbookStylesPart>("WorkbookStyles");
+
+                var stylesheet1 = new Stylesheet { MCAttributes = new MarkupCompatibilityAttributes { Ignorable = "x14ac" } };
+                stylesheet1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
+                stylesheet1.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac");
+
+                var fonts1 = new Fonts { Count = 1U, KnownFonts = true };
+
+                var font1 = new Font();
+                var fontSize1 = new FontSize { Val = 11D };
+                var color1 = new Color { Theme = 1U };
+                var fontName1 = new FontName { Val = "Calibri" };
+                var fontFamilyNumbering1 = new FontFamilyNumbering { Val = 2 };
+                var fontScheme1 = new FontScheme { Val = FontSchemeValues.Minor };
+
+                font1.Append(fontSize1);
+                font1.Append(color1);
+                font1.Append(fontName1);
+                font1.Append(fontFamilyNumbering1);
+                font1.Append(fontScheme1);
+
+                fonts1.Append(font1);
+
+                var fills1 = new Fills { Count = 2U };
+
+                var fill1 = new Fill();
+                var patternFill1 = new PatternFill { PatternType = PatternValues.None };
+
+                fill1.Append(patternFill1);
+
+                var fill2 = new Fill();
+                var patternFill2 = new PatternFill { PatternType = PatternValues.Gray125 };
+
+                fill2.Append(patternFill2);
+
+                fills1.Append(fill1);
+                fills1.Append(fill2);
+
+                var borders1 = new Borders { Count = 1U };
+
+                var border1 = new Border();
+                var leftBorder1 = new LeftBorder();
+                var rightBorder1 = new RightBorder();
+                var topBorder1 = new TopBorder();
+                var bottomBorder1 = new BottomBorder();
+                var diagonalBorder1 = new DiagonalBorder();
+
+                border1.Append(leftBorder1);
+                border1.Append(rightBorder1);
+                border1.Append(topBorder1);
+                border1.Append(bottomBorder1);
+                border1.Append(diagonalBorder1);
+
+                borders1.Append(border1);
+
+                var cellStyleFormats1 = new CellStyleFormats { Count = 1U };
+                var cellStyleFormat = new CellFormat { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U };
+
+                cellStyleFormats1.Append(cellStyleFormat);
+
+                var cellFormats = new CellFormats { Count = 2U };
+
+                // index 0 (default) => unlocked
+                var cellFormat0 = new CellFormat { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U, FormatId = 0U, ApplyProtection = true }.AppendItem(new Protection { Locked = false });
+                // index 1 => locked
+                var cellFormat1 = new CellFormat { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U, FormatId = 0U };
+
+                cellFormats.Append(cellFormat0);
+                cellFormats.Append(cellFormat1);
+
+                var cellStyles1 = new CellStyles { Count = 1U };
+                var cellStyle1 = new CellStyle { Name = "Normal", FormatId = 0U, BuiltinId = 0U };
+
+                cellStyles1.Append(cellStyle1);
+
+                stylesheet1.Append(fonts1);
+                stylesheet1.Append(fills1);
+                stylesheet1.Append(borders1);
+                stylesheet1.Append(cellStyleFormats1);
+                stylesheet1.Append(cellFormats);
+                stylesheet1.Append(cellStyles1);
+
+                workbookStylesPart.Stylesheet = stylesheet1;
+            }
+        }
+    }
 }


Fix #88: Only import primary cell text, ignore any metadata.

--- ResXManager.Model/ExcelExtensions.cs
+++ ResXManager.Model/ExcelExtensions.cs
@@ -353,46 +353,41 @@
             return stringTable?.OfType<SharedStringItem>().ToArray();
         }

-        [NotNull]
+        [CanBeNull]
         private static string GetText([NotNull][ItemNotNull] this CellType cell, [ItemNotNull][CanBeNull] IList<SharedStringItem> sharedStrings)
         {
             Contract.Requires(cell != null);
             Contract.Ensures(Contract.Result<string>() != null);

             var cellValue = cell.CellValue;
-
             var dataType = cell.DataType;

-            if (cellValue != null)
-            {
-                var text = cellValue.Text ?? string.Empty;
-
-                if ((dataType != null) && (dataType == CellValues.SharedString))
-                {
-                    if (sharedStrings != null)
-                    {
-                        if (int.TryParse(text, out var index) && (index >= 0) && (index < sharedStrings.Count))
-                        {
-                            var stringItem = sharedStrings[index];
-                            var descendants = stringItem?.Descendants<OpenXmlLeafTextElement>();
-                            if (descendants != null)
-                            {
-                                text = string.Concat(descendants.Select(element => element.Text));
-                            }
-                        }
-                    }
-                }
-
-                return text;
-            }
-            else
-            {
-                var descendants = cell.Descendants<OpenXmlLeafTextElement>();
-                Contract.Assume(descendants != null);
-                var content = descendants.Select(element => element.Text);
-                var text = string.Concat(content);
-                return text;
-            }
+            if (cellValue == null)
+                return GetTextFromTextElement(cell);
+
+            var text = cellValue.Text;
+
+            if ((dataType != null) && (dataType == CellValues.SharedString) && (sharedStrings != null) && (int.TryParse(text, out var index) && (index >= 0) && (index < sharedStrings.Count)))
+            {
+                var stringItem = sharedStrings[index];
+
+                return GetTextFromTextElement(stringItem) ?? text;
+            }
+
+            return text;
+
+        }
+
+        private static string GetTextFromTextElement([NotNull] OpenXmlElement cell)
+        {
+            // ReSharper disable AssignNullToNotNullAttribute
+            // ReSharper disable PossibleNullReferenceException
+            return cell.ChildElements
+                .OfType<OpenXmlLeafTextElement>()
+                .Select(item => item.Text)
+                .FirstOrDefault();
+            // ReSharper restore AssignNullToNotNullAttribute
+            // ReSharper restore PossibleNullReferenceException
         }

         [NotNull]
@@ -415,7 +410,7 @@
                     columnIndex += 1;
                 }

-                var text = cell.GetText(sharedStrings);
+                var text = cell.GetText(sharedStrings) ?? string.Empty;
                 // depending on how multi-line text is pasted into Excel, \r\n might be translated into _x000D_\n,
                 // because Excel internally only use \n as line delimiter.
                 text = text.Replace("_x000D_\n", "\n");


Upgraded MutableSparseFloatArrayTest to version 3.1.0 compatibility.

--- src/BoboBrowse.Tests/Util/MutableSparseFloatArrayTest.cs
+++ src/BoboBrowse.Tests/Util/MutableSparseFloatArrayTest.cs
@@ -1,4 +1,30 @@
-namespace BoboBrowse.Net.Util
+/**
+ * Bobo Browse Engine - High performance faceted/parametric search implementation
+ * that handles various types of semi-structured data.  Written in Java.
+ *
+ * Copyright (C) 2005-2006  spackle
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ *
+ * To contact the project administrators for the bobo-browse project,
+ * please go to https://sourceforge.net/projects/bobo-browse/, or
+ * contact owner@browseengine.com.
+ */
+
+// Version compatibility level: 3.1.0
+namespace BoboBrowse.Net.Util
 {
     using BoboBrowse.Net.Facets.Filter;
     using BoboBrowse.Net.Search;
@@ -24,56 +50,101 @@
         [Test]
         public void TestMute()
         {
-            try
+            var rand = new Random();
+
+            float[] orig = new float[1024];
+            MutableSparseFloatArray fromEmpty = new MutableSparseFloatArray(new float[1024]);
+			float density = 0.2f;
+			int idx = 0;
+			while (rand.NextDouble() > density) {
+				idx++;
+			}
+            int count = 0;
+			while (idx < orig.Length)
             {
-                var rand = new Random();
+				float val = (float)rand.NextDouble();
+				orig[idx] = val;
+				fromEmpty.Set(idx, val);
+				count++;
+				idx += 1;
+				while (rand.NextDouble() > density) {
+					idx++;
+				}
+			}

-                float[] orig = new float[1024];
-                MutableSparseFloatArray fromEmpty = new MutableSparseFloatArray(new float[1024]);
-			    float density = 0.2f;
-			    int idx = 0;
-			    while (rand.NextDouble() > density) {
-				    idx++;
-			    }
-                int count = 0;
-			    while (idx < orig.Length)
+            float[] copy =new float[orig.Length];
+            Array.Copy(orig, 0, copy, 0, orig.Length);
+			MutableSparseFloatArray fromPartial = new MutableSparseFloatArray(copy);
+
+            // do 128 modifications
+			int mods = 128;
+			for (int i = 0; i < mods; i++) {
+				float val = (float)rand.NextDouble();
+				idx = rand.Next(orig.Length);
+				orig[idx] = val;
+				fromEmpty.Set(idx, val);
+				fromPartial.Set(idx, val);
+			}
+
+            for (int i = 0; i < orig.Length; i++)
+            {
+                Assert.True(orig[i] == fromEmpty.Get(i), "orig " + orig[i] + " wasn't the same as fromEmpty " + fromEmpty.Get(i) + " at i=" + i);
+                Assert.True(orig[i] == fromPartial.Get(i), "orig " + orig[i] + " wasn't the same as fromPartial " + fromPartial.Get(i) + " at i=" + i);
+            }
+
+            Console.WriteLine("success!");
+        }
+
+        [Test]
+        public void TestSpeed()
+        {
+            Random r = new Random();
+
+            float[] orig = new float[16 * 1024 * 1024];
+            MutableSparseFloatArray arr = new MutableSparseFloatArray(new float[orig.Length]);
+
+            for (int i = 0; i < 32 * 1024; i++)
+            {
+                int idx = r.Next(orig.Length);
+                if (r.Next(1000) % 2 == 0)
                 {
-				    float val = (float)rand.NextDouble();
-				    orig[idx] = val;
-				    fromEmpty.Set(idx, val);
-				    count++;
-				    idx += 1;
-				    while (rand.NextDouble() > density) {
-					    idx++;
-				    }
-			    }
+                    Assert.True(orig[idx] == arr.Get(idx), "orig " + orig[idx] + " not the same as arr " + arr.Get(idx) + " at idx=" + idx);
+                }
+                else
+                {
+                    float val = (float)r.NextDouble();
+                    orig[idx] = val;
+                    arr.Set(idx, val);
+                }
+            }

-                float[] copy =new float[orig.Length];
-                Array.Copy(orig, 0, copy, 0, orig.Length);
-			    MutableSparseFloatArray fromPartial = new MutableSparseFloatArray(copy);
+            // repeat it, but timed
+            orig = new float[orig.Length];
+            arr = new MutableSparseFloatArray(new float[orig.Length]);
+            int[] idxs = new int[1024 * 1024];
+            float[] vals = new float[idxs.Length];
+            for (int i = 0; i < idxs.Length; i++)
+            {
+                idxs[i] = r.Next(orig.Length);
+                vals[i] = (float)r.NextDouble();
+            }

-                // do 128 modifications
-			    int mods = 128;
-			    for (int i = 0; i < mods; i++) {
-				    float val = (float)rand.NextDouble();
-				    idx = rand.Next(orig.Length);
-				    orig[idx] = val;
-				    fromEmpty.Set(idx, val);
-				    fromPartial.Set(idx, val);
-			    }
+            long markTime = System.Environment.TickCount;
+            for (int i = 0; i < idxs.Length; i++)
+            {
+                orig[i] = vals[i];
+            }
+            long elapsedTimePrim = System.Environment.TickCount - markTime;

-                for (int i = 0; i < orig.Length; i++)
-                {
-                    Assert.True(orig[i] == fromEmpty.Get(i), "orig " + orig[i] + " wasn't the same as fromEmpty " + fromEmpty.Get(i) + " at i=" + i);
-                    Assert.True(orig[i] == fromPartial.Get(i), "orig " + orig[i] + " wasn't the same as fromPartial " + fromPartial.Get(i) + " at i=" + i);
-                }
+            markTime = System.Environment.TickCount;
+            for (int i = 0; i < idxs.Length; i++)
+            {
+                arr.Set(idxs[i], vals[i]);
+            }
+            long elapsedTimeMutable = System.Environment.TickCount - markTime;

-                Console.WriteLine("success!");
-            }
-            catch (Exception e)
-            {
-                Assert.Fail(e.ToString());
-            }
+            Console.WriteLine("elapsed time on the primitive array: " + elapsedTimePrim + "; elapsed time on the mutable condensed arr: " + elapsedTimeMutable);
+            Console.WriteLine("ratio of time to do it on the mutable condensed arr, to time on primitive array: " + (double)elapsedTimeMutable / elapsedTimePrim);
         }
     }
 }


revert unintended merge conflict

revert unintended merge conflict

--- src/CSharp/CodeCracker/Usage/RethrowExceptionAnalyzer.cs
+++ src/CSharp/CodeCracker/Usage/RethrowExceptionAnalyzer.cs
@@ -24,7 +24,7 @@
             MessageFormat,
             Category,
             DiagnosticSeverity.Warning,
-            isEnabledByDefault: false,
+            isEnabledByDefault: true,
             description: Description,
             helpLink: HelpLink.ForDiagnostic(diagnosticId));


(GH-3879)(GH-3880) Scope cache per script host * Include script host in the cache filename * Move hash from file to the cache filename * fixes #3879 * fixes #3880

--- src/Cake/Infrastructure/Scripting/RoslynScriptSession.cs
+++ src/Cake/Infrastructure/Scripting/RoslynScriptSession.cs
@@ -98,29 +98,17 @@
         public void Execute(Script script)
         {
             var scriptName = _settings.Script.GetFilename();
-            var cacheDLLFileName = $"{scriptName}.dll";
-            var cacheHashFileName = $"{scriptName}.hash";
-            var cachedAssembly = _scriptCachePath.CombineWithFilePath(cacheDLLFileName);
-            var hashFile = _scriptCachePath.CombineWithFilePath(cacheHashFileName);
-            string scriptHash = default;
+            FilePath cachedAssembly = _scriptCacheEnabled
+                                        ? GetCachedAssemblyPath(script, scriptName)
+                                        : default;
+
             if (_scriptCacheEnabled && _fileSystem.Exist(cachedAssembly) && !_regenerateCache)
             {
-                _log.Verbose($"Cache enabled: Checking cache build script ({cacheDLLFileName})");
-                scriptHash = FastHash.GenerateHash(Encoding.UTF8.GetBytes(string.Concat(script.Lines)));
-                var cachedHash = _fileSystem.Exist(hashFile)
-                               ? _fileSystem.GetFile(hashFile).ReadLines(Encoding.UTF8).FirstOrDefault()
-                               : string.Empty;
-                if (scriptHash.Equals(cachedHash, StringComparison.Ordinal))
-                {
-                    _log.Verbose("Running cached build script...");
-                    RunScriptAssembly(cachedAssembly.FullPath);
-                    return;
-                }
-                else
-                {
-                    _log.Verbose("Cache check failed.");
-                }
-            }
+                _log.Verbose("Running cached build script...");
+                RunScriptAssembly(cachedAssembly.FullPath);
+                return;
+            }
+
             // Generate the script code.
             var generator = new RoslynCodeGenerator();
             var code = generator.Generate(script);
@@ -205,19 +193,11 @@
                 {
                     _fileSystem.GetDirectory(_scriptCachePath).Create();
                 }
-                if (string.IsNullOrWhiteSpace(scriptHash))
-                {
-                    scriptHash = FastHash.GenerateHash(Encoding.UTF8.GetBytes(string.Concat(script.Lines)));
-                }
+
                 var emitResult = compilation.Emit(cachedAssembly.FullPath);

                 if (emitResult.Success)
                 {
-                    using (var stream = _fileSystem.GetFile(hashFile).OpenWrite())
-                    using (var writer = new StreamWriter(stream, Encoding.UTF8))
-                    {
-                        writer.Write(scriptHash);
-                    }
                     RunScriptAssembly(cachedAssembly.FullPath);
                 }
             }
@@ -226,6 +206,15 @@
                 roslynScript.RunAsync(_host).GetAwaiter().GetResult();
             }
         }
+
+        private FilePath GetCachedAssemblyPath(Script script, FilePath scriptName)
+            => _scriptCachePath.CombineWithFilePath(
+                string.Join(
+                    '.',
+                    scriptName.GetFilenameWithoutExtension().FullPath,
+                    _host.GetType().Name,
+                    FastHash.GenerateHash(Encoding.UTF8.GetBytes(string.Concat(script.Lines))),
+                    "dll"));

         private void RunScriptAssembly(string assemblyPath)
         {


removed unnecessary part of method comments

--- src/ChannelAdvisorAccess/Services/Items/IItemsService.cs
+++ src/ChannelAdvisorAccess/Services/Items/IItemsService.cs
@@ -156,7 +156,7 @@
 		/// Removes the list of Labels from the list of SKUs.
 		/// </summary>
 		/// <param name="labels">List of Labels (Maximum of 3 Labels)</param>
-		/// <param name="skus">List of SKUs (Maximum of 500 SKUs)</param>
+		/// <param name="skus">List of SKUs</param>
 		/// <param name="reason">Specifies the reason for removing the assignment of the Labels</param>
 		/// <see href="http://developer.channeladvisor.com/display/cadn/RemoveLabelListFromInventoryItemList"/>
 		void RemoveLabelListFromItemList( string[] labels, string[] skus, string reason );
@@ -165,7 +165,7 @@
 		/// Removes the list of Labels from the list of SKUs.
 		/// </summary>
 		/// <param name="labels">List of Labels (Maximum of 3 Labels)</param>
-		/// <param name="skus">List of SKUs (Maximum of 500 SKUs)</param>
+		/// <param name="skus">List of SKUs</param>
 		/// <param name="reason">Specifies the reason for removing the assignment of the Labels</param>
 		/// <see href="http://developer.channeladvisor.com/display/cadn/RemoveLabelListFromInventoryItemList"/>
 		Task RemoveLabelListFromItemListAsync( string[] labels, string[] skus, string reason );
@@ -175,7 +175,7 @@
 		/// </summary>
 		/// <param name="labels">List of Labels (Maximum of 3 Labels)</param>
 		/// <param name="createLabelIfNotExist">Specifies whether or not to create the Label if it does not already exist.</param>
-		/// <param name="skus">List of SKUs (Maximum of 500 SKUs)</param>
+		/// <param name="skus">List of SKUs</param>
 		/// <param name="reason">Specifies the reason for the assignment of the Labels</param>
 		/// <see href="http://developer.channeladvisor.com/display/cadn/AssignLabelListToInventoryItemList"/>
 		void AssignLabelListToItemList( string[] labels, bool createLabelIfNotExist, string[] skus, string reason );
@@ -185,7 +185,7 @@
 		/// </summary>
 		/// <param name="labels">List of Labels (Maximum of 3 Labels)</param>
 		/// <param name="createLabelIfNotExist">Specifies whether or not to create the Label if it does not already exist.</param>
-		/// <param name="skus">List of SKUs (Maximum of 500 SKUs)</param>
+		/// <param name="skus">List of SKUs</param>
 		/// <param name="reason">Specifies the reason for the assignment of the Labels</param>
 		/// <see href="http://developer.channeladvisor.com/display/cadn/AssignLabelListToInventoryItemList"/>
 		Task AssignLabelListToItemListAsync( string[] labels, bool createLabelIfNotExist, string[] skus, string reason );


adding cache to tablerepository

adding cache to tablerepository

--- src/Common/src/SSDTDevPack.Common/Dac/TableRepository.cs
+++ src/Common/src/SSDTDevPack.Common/Dac/TableRepository.cs
@@ -8,22 +8,31 @@
     public class TableRepository
     {
         private readonly string _path;
+        private List<TableDescriptor> _tables;

         public TableRepository(string path)
         {
             _path = path;
         }
+

         public List<TableDescriptor> Get()
+        {
+            if (_tables == null)
+                BuildTables();
+
+            return _tables;
+        }
+
+        private void BuildTables()
         {
             var model = Model.Get(_path);
             var dacTables = model.GetObjects<TSqlTable>(DacQueryScopes.UserDefined);

-            var tables = dacTables.Select(t => new TableDescriptor(t)).ToList();
+            _tables = dacTables.Select(t => new TableDescriptor(t)).ToList();

             Model.Close(model);

-            return tables;
         }
     }
 }


Update ImageToolViewModel.cs

Update ImageToolViewModel.cs

--- src/Core2D/ViewModels/Editor/Tools/ImageToolViewModel.cs
+++ src/Core2D/ViewModels/Editor/Tools/ImageToolViewModel.cs
@@ -68,9 +68,7 @@
                 _image = factory.CreateImageShape(
                     (double) sx, (double) sy,
                     (ShapeStyleViewModel) style.Copy(null),
-                    key,
-                    false,
-                    false);
+                    key);

                 editor.SetShapeName(_image);

@@ -96,8 +94,11 @@
             {
                 if (_image is { })
                 {
-                    _image.BottomRight.X = (double) sx;
-                    _image.BottomRight.Y = (double) sy;
+                    if (_image.BottomRight is { })
+                    {
+                        _image.BottomRight.X = (double)sx;
+                        _image.BottomRight.Y = (double)sy;
+                    }

                     var result = selection.TryToGetConnectionPoint((double) sx, (double) sy);
                     if (result is { })
@@ -191,8 +192,11 @@
                     {
                         selection.TryToHoverShape((double)sx, (double)sy);
                     }
-                    _image.BottomRight.X = (double)sx;
-                    _image.BottomRight.Y = (double)sy;
+                    if (_image.BottomRight is { })
+                    {
+                        _image.BottomRight.X = (double)sx;
+                        _image.BottomRight.Y = (double)sy;
+                    }
                     editor.Project.CurrentContainer?.WorkingLayer?.RaiseInvalidateLayer();
                     Move(_image);
                 }
@@ -204,13 +208,19 @@
     public void ToStateBottomRight()
     {
         var editor = ServiceProvider.GetService<ProjectEditorViewModel>();
-        _selection = new ImageSelection(
-            ServiceProvider,
-            editor.Project.CurrentContainer.HelperLayer,
-            _image,
-            editor.PageState.HelperStyle);
-
-        _selection.ToStateBottomRight();
+        if (editor is { }
+            && editor.Project?.CurrentContainer?.HelperLayer is { }
+            && editor.PageState?.HelperStyle is { }
+            && _image is { })
+        {
+            _selection = new ImageSelection(
+                ServiceProvider,
+                editor.Project.CurrentContainer.HelperLayer,
+                _image,
+                editor.PageState.HelperStyle);
+
+            _selection.ToStateBottomRight();
+        }
     }

     public void Move(BaseShapeViewModel? shape)
@@ -236,7 +246,7 @@
                 break;
             case State.BottomRight:
             {
-                if (editor.Project.CurrentContainer?.WorkingLayer is { })
+                if (editor.Project.CurrentContainer?.WorkingLayer is { } && _image is { })
                 {
                     editor.Project.CurrentContainer.WorkingLayer.Shapes = editor.Project.CurrentContainer.WorkingLayer.Shapes.Remove(_image);
                     editor.Project.CurrentContainer?.WorkingLayer?.RaiseInvalidateLayer();


Minor fix and files are deleted

Minor fix and files are deleted

--- src/DatenMeister.Tests/Modules/Actions/ExportXmiTests.cs
+++ src/DatenMeister.Tests/Modules/Actions/ExportXmiTests.cs
@@ -32,11 +32,10 @@

             Assert.That(File.Exists(temporaryStorage), Is.True);

-            var fileContent = File.ReadAllText(temporaryStorage);
+            var fileContent = await File.ReadAllTextAsync(temporaryStorage);
             Assert.That(fileContent.Contains("source1.2"), Is.True);

+            File.Delete(temporaryStorage);
         }
-
-
     }
 }


Added: clearing of used buffers before checking in to BufferManager.

--- src/EventStore/EventStore.Transport.Tcp/TcpConnection.cs
+++ src/EventStore/EventStore.Transport.Tcp/TcpConnection.cs
@@ -342,6 +342,8 @@
             {
                 var tuple = res[i];
                 bytes += tuple.Item1.Count;
+
+                Array.Clear(tuple.Item1.Array, tuple.Item1.Offset, tuple.Item2);
                 BufferManager.CheckIn(new ArraySegment<byte>(tuple.Item1.Array, tuple.Item1.Offset, tuple.Item2)); // dispose buffers
             }
             NotifyReceiveDispatched(bytes);
@@ -412,6 +414,7 @@
                 socketArgs.AcceptSocket = null;
                 if (socketArgs.Buffer != null)
                 {
+                    Array.Clear(socketArgs.Buffer, socketArgs.Offset, socketArgs.Count);
                     BufferManager.CheckIn(new ArraySegment<byte>(socketArgs.Buffer, socketArgs.Offset, socketArgs.Count));
                     socketArgs.SetBuffer(null, 0, 0);
                 }


Remove redundant pattern check

Remove redundant pattern check

--- src/Features/Core/Portable/Workspace/BackgroundParser.cs
+++ src/Features/Core/Portable/Workspace/BackgroundParser.cs
@@ -37,11 +37,8 @@
             _taskScheduler = taskSchedulerFactory.CreateBackgroundTaskScheduler();
             _workspace.WorkspaceChanged += this.OnWorkspaceChanged;

-            if (workspace is Workspace editorWorkspace)
-            {
-                editorWorkspace.DocumentOpened += this.OnDocumentOpened;
-                editorWorkspace.DocumentClosed += this.OnDocumentClosed;
-            }
+            workspace.DocumentOpened += this.OnDocumentOpened;
+            workspace.DocumentClosed += this.OnDocumentClosed;
         }

         private void OnDocumentOpened(object sender, DocumentEventArgs args)


Nasty little bug escaping Host arguments!

--- src/Gallio/Gallio/Runtime/Hosting/IsolatedProcessHost.cs
+++ src/Gallio/Gallio/Runtime/Hosting/IsolatedProcessHost.cs
@@ -171,8 +171,9 @@
             hostArguments.Append(@" /timeout:").Append((int)WatchdogTimeout.TotalSeconds);
             hostArguments.Append(@" /owner-process:").Append(Process.GetCurrentProcess().Id);
             if (HostSetup.ApplicationBaseDirectory != null)
-                hostArguments.Append(@" ""/application-base-directory:").Append(FileUtils.StripTrailingBackslash(HostSetup.ApplicationBaseDirectory)).Append('"');
-            hostArguments.Append(@" ""/configuration-file:").Append(temporaryConfigurationFilePath).Append('"');
+                hostArguments.Append(@" /application-base-directory:""").Append(
+                    FileUtils.StripTrailingBackslash(HostSetup.ApplicationBaseDirectory)).Append('"');
+            hostArguments.Append(@" /configuration-file:""").Append(temporaryConfigurationFilePath).Append('"');
             if (HostSetup.ShadowCopy)
                 hostArguments.Append(@" /shadow-copy");
             if (HostSetup.Debug)


- no longer sorting data by name after getting it from the kh site. 'sort' order will just be order of entry into data storage.

--- src/Implementation/FrannHammer.NetCore.WebApi/Startup.cs
+++ src/Implementation/FrannHammer.NetCore.WebApi/Startup.cs
@@ -180,12 +180,6 @@
             _uniqueData.AddRange(JsonConvert.DeserializeObject<List<UniqueData>>(File.ReadAllText(fileLocationResolver.Unique)));
 #endif

-            _characterData.Sort((c1, c2) => c1.OwnerId.CompareTo(c2.OwnerId));
-            _moveData.Sort((m1, m2) => m1.Name.CompareTo(m2.Name));
-            _movementData.Sort((m1, m2) => m1.Name.CompareTo(m2.Name));
-            _characterAttributeRowData.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
-            _uniqueData.Sort((u1, u2) => u1.Name.CompareTo(u2.Name));
-
             //write pulled data to local
             //File.WriteAllText(fileLocationResolver.Character, JsonConvert.SerializeObject(_characterData));
             //File.WriteAllText(fileLocationResolver.Move, JsonConvert.SerializeObject(_moveData));


added PRODUCTAVAILABLE to signing fields

--- SecureFormSigner/SecureFormSigner.cs
+++ SecureFormSigner/SecureFormSigner.cs
@@ -49,6 +49,7 @@
 						Key == "PRODUCTNAME" ||
 						Key == "PRODUCTPRICE" ||
 						Key.StartsWith("PRODUCTPRICE(") ||
+						Key.StartsWith("PRODUCTAVAILABLE(") ||
 						Key == "PRODUCTLISTPRICE" ||
 						Key == "PRODUCTWEIGHT" ||
 						Key == "PRODUCTWIDTH" ||


Add incident fields used for querying

Add incident fields used for querying

--- src/Noobot.Modules.IncidentManagement/Models/Incident.cs
+++ src/Noobot.Modules.IncidentManagement/Models/Incident.cs
@@ -15,6 +15,9 @@
 			this.Title = incidentTitle;
 			this.DeclaredBy = declaredBy;
 			this.DeclaredDateTimeUtc = DateTime.UtcNow;
+
+			this.Resolved = false;
+			this.Closed = false;
 		}

 		public Incident()
@@ -31,9 +34,13 @@

 		public DateTime DeclaredDateTimeUtc { get; set; }

+		public bool Resolved { get; set; }
+
 		public string ResolvedBy { get; set; }

 		public DateTime? ResolvedDateTimeUtc { get; set; }
+
+		public bool Closed { get; set; }

 		public string ClosedBy { get; set; }

@@ -45,12 +52,14 @@
 		{
 			this.ResolvedDateTimeUtc = DateTime.UtcNow;
 			this.ResolvedBy = resolvedBy;
+			this.Resolved = true;
 		}

 		public void MarkAsClosed(string closedBy)
 		{
 			this.ClosedDateTimeUtc = DateTime.UtcNow;
 			this.ClosedBy = closedBy;
+			this.Closed = true;
 		}

 		public void SetRowKey(int rowKey)


add mobile application type

add mobile application type

--- App/App.Entities/Security/ApplicationType.cs
+++ App/App.Entities/Security/ApplicationType.cs
@@ -5,5 +5,6 @@
         JavaScript = 0,
         NativeConfidential = 1,
         ExternalInterface = 2,
+        Mobile = 3,
     }
 }


change IEnumerableTExtensions to internal

--- src/QIFGet/MvbaCore/Extensions/IEnumerableTExtensions.cs
+++ src/QIFGet/MvbaCore/Extensions/IEnumerableTExtensions.cs
@@ -13,7 +13,7 @@

 namespace System.Collections.Generic
 {
-    public static class IEnumerableTExtensions
+    internal static class IEnumerableTExtensions
     {
         public static IEnumerable<T> ForEach<T>(this IEnumerable<T> items, Action<T> action)
         {
@@ -104,7 +104,7 @@
         }
     }

-    public class ContinuingEnumerator<T> : IEnumerable<T>
+    internal class ContinuingEnumerator<T> : IEnumerable<T>
     {
         private readonly IEnumerator<T> _enumerator;
         private readonly Func<T, T, bool> _keepGrouping;


Исправлено отсутствие экранирования двойных кавычек в объекте ЗаписьJson

--- src/ScriptEngine.HostedScript/Library/Json/JSONWriter.cs
+++ src/ScriptEngine.HostedScript/Library/Json/JSONWriter.cs
@@ -123,6 +123,7 @@
              if (_settings.EscapeSingleQuotes == true || !_settings.UseDoubleQuotes)
                 fval = fval.Replace("'", "\\'");

+            fval = fval.Replace("\"", "\\\"");

             _writer.WriteRawValue(_writer.QuoteChar + fval + _writer.QuoteChar);
         }


Update FractalNoise.cs

Update FractalNoise.cs

--- Assets/ProceduralNoise/Noise/FractalNoise.cs
+++ Assets/ProceduralNoise/Noise/FractalNoise.cs
@@ -1,8 +1,6 @@
 using System;
 using System.Collections;
 using UnityEngine;
-
-//TEST COMMENT

 namespace ProceduralNoiseProject
 {


Remove all non-stage-ready games in Collection Update

--- Assets/Scripts/Global/MicrogameCollection.cs
+++ Assets/Scripts/Global/MicrogameCollection.cs
@@ -112,9 +112,11 @@
                 .Concat(Directory.GetDirectories(Path.Combine(microgameFolderLocation, "_Finished")))
                 .Concat(Directory.GetDirectories(Path.Combine(microgameFolderLocation, "_Bosses")));
         var buildScenes = EditorBuildSettings.scenes.ToList();
-
-
-        //Add stage ready games
+
+        //Remove all microgames from path
+        buildScenes = buildScenes.Where(a => !a.path.Replace('\\', '/').Contains(MicrogameAssetPath.Replace('\\', '/'))).ToList();
+
+        //Re-add stage ready games
         foreach (var microgame in stageReadyMicrogames.Concat(finishedMicrogames))
         {
             var microgameFolder = microgameFolders.FirstOrDefault(a => a.Contains(microgame.microgameId));
@@ -127,7 +129,9 @@
                     {
                         foreach (var scenePath in scenePaths)
                         {
-                            buildScenes.Add(new EditorBuildSettingsScene("Assets" + scenePath.Substring(Application.dataPath.Length), true));
+                            var newBuildScene = new EditorBuildSettingsScene("Assets" + scenePath.Substring(Application.dataPath.Length), true);
+                            if (!newBuildScene.guid.Empty())
+                                buildScenes.Add(newBuildScene);
                         }
                     }
                     else
@@ -223,7 +227,7 @@
     }

     /// <summary>
-    /// Returns a copied list of all boss microgmaes, regardless of completion, in MicrogameCollection.Microgame type
+    /// Returns a copied list of all boss microgames, regardless of completion, in MicrogameCollection.Microgame type
     /// </summary>
     /// <returns></returns>
     public List<Microgame> getCollectionBossMicrogames()


* Added error message when something breaks.

--- Assets/Watson/Widgets/Avatar/AvatarWidget.cs
+++ Assets/Watson/Widgets/Avatar/AvatarWidget.cs
@@ -123,6 +123,8 @@
         [SerializeField]
         private string m_RecognizeFailure = "I'm sorry, but I didn't understand your question.";
         [SerializeField]
+        private string m_Error = "Oh bugger, something has gone wrong.";
+        [SerializeField]
         private string m_Pipeline = "thunderstone";
         [SerializeField]
         private Input m_levelInput = new Input("Level", typeof(FloatData), "OnLevelInput");
@@ -158,7 +160,13 @@
                     EventManager.Instance.SendEvent(Constants.Event.ON_CHANGE_AVATAR_STATE_FINISH, this, value);
 					// if we went into an error state, automatically try to reconnect after a timeout..
                     if (m_State == AvatarState.ERROR)
+                    {
+                        if ( m_FocusQuestion != null )
+                            m_FocusQuestion.OnLeaveTheSceneAndDestroy();
+
                         Invoke("StartAvatar", m_RestartInterval);
+                        m_TextOutput.SendData( new TextData( m_Error ) );
+                    }
                 }

 				if(m_State == AvatarState.CONNECTING || m_State == AvatarState.ERROR)


Store filename in FFmpegReader for debugging purposes

Without it, it is impossible to see which file the reader is reading.

--- AudioAlign/AudioAlign.FFmpeg/FFmpegReader.cs
+++ AudioAlign/AudioAlign.FFmpeg/FFmpegReader.cs
@@ -14,11 +14,13 @@
             interop = new InteropWrapper();
         }

+        private string filename; // store source filename for debugging
         private bool disposed = false;
         private IntPtr instance = IntPtr.Zero;
         private OutputConfig outputConfig;

         public FFmpegReader(string filename) {
+            this.filename = filename;
             instance = interop.stream_open(filename);

             IntPtr ocp = interop.stream_get_output_config(instance);


Restore

Restore

--- src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspace.cs
+++ src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspace.cs
@@ -8,11 +8,6 @@
 using System.Threading.Tasks;
 using Microsoft.CodeAnalysis.ErrorReporting;
 using Microsoft.CodeAnalysis.Host;
-<<<<<<< HEAD
-=======
-using Microsoft.CodeAnalysis.Host.Mef;
-using Microsoft.CodeAnalysis.Options;
->>>>>>> upstream/main
 using Microsoft.CodeAnalysis.Serialization;
 using Microsoft.CodeAnalysis.SolutionCrawler;
 using Roslyn.Utilities;
@@ -31,7 +26,6 @@
         private readonly SemaphoreSlim _gate = new(initialCount: 1);

         /// <summary>
-<<<<<<< HEAD
         /// Cache of checksums/solutions for any request that came through.
         /// </summary>
         private readonly ChecksumToSolutionCache _anyBranchSolutionCache;
@@ -43,30 +37,12 @@
         /// <see cref="_anyBranchSolutionCache"/> otherwise.
         /// </summary>
         private readonly ChecksumToSolutionCache _primaryBranchSolutionCache;
-=======
-        /// The last solution for the primary branch fetched from the client.
-        /// </summary>
-        private (Checksum checksum, Solution solution) _lastRequestedPrimaryBranchSolution;
-
-        /// <summary>
-        /// The last solution requested by a service.
-        /// </summary>
-        private (Checksum checksum, Solution solution) _lastRequestedAnyBranchSolution;
->>>>>>> upstream/main

         /// <summary>
         /// Used to make sure we never move remote workspace backward. this version is the WorkspaceVersion of primary
         /// solution in client (VS) we are currently caching.
         /// </summary>
         private int _currentRemoteWorkspaceVersion = -1;
-
-        /// <summary>
-        /// Mapping from solution-checksum to the solution computed for it.  This is used so that we can hold a solution
-        /// around as long as the checksum for it is being used in service of some feature operation (e.g.
-        /// classification).  As long as we're holding onto it, concurrent feature requests for the same solution
-        /// checksum can share the computation of that particular solution and avoid duplicated concurrent work.
-        /// </summary>
-        private readonly Dictionary<Checksum, ReferenceCountedDisposable<LazySolution>> _solutionChecksumToLazySolution = new();

         // internal for testing purposes.
         internal RemoteWorkspace(HostServices hostServices, string? workspaceKind)
@@ -103,10 +79,8 @@
             if (currentSolutionChecksum == solutionChecksum)
                 return;

-            // Do a no-op run.  This will still ensure that we compute and cache this checksum/solution pair for future
-            // callers. note we call directly into SlowGetSolutionAndRunAsync (skipping TryFastGetSolutionAndRunAsync)
-            // as we always want to cache the primary workspace we are being told about here.
-            await SlowGetSolutionAndRunAsync(
+            // Do a no-op run.  This will still ensure that we compute and cache this checksum/solution pair for future callers.
+            await RunWithSolutionAsync(
                 assetProvider,
                 solutionChecksum,
                 workspaceVersion,
@@ -145,7 +119,6 @@
             Func<Solution, ValueTask<T>> implementation,
             CancellationToken cancellationToken)
         {
-<<<<<<< HEAD
             // Gets or creates a solution corresponding to the requested checksum.  This will always succeed, and will
             // increment the ref count of that solution until we release it at the end of our using block.
             using var refCountedSolution = await GetOrCreateSolutionAsync(
@@ -164,81 +137,12 @@
             // computing. In the event of cancellation, we do not wait here for the refCountedLazySolution to clean up,
             // even if this was the last use of this solution.
             var newSolution = await refCountedSolution.Task.WithCancellation(cancellationToken).ConfigureAwait(false);
-=======
-            // Fast path if this solution checksum is for a solution we're already caching. This also avoids us then
-            // trying to actually mutate the workspace for the simple case of asking for the same thing the last call
-            // asked about.
-            var (solution, result) = await TryFastGetSolutionAndRunAsync().ConfigureAwait(false);
-            if (solution != null)
-                return (solution, result);
-
-            // Wasn't the same as the last thing we cached, actually get the corresponding solution and run the
-            // requested callback against it.
-            return await SlowGetSolutionAndRunAsync(
-                assetProvider, solutionChecksum, workspaceVersion, fromPrimaryBranch, implementation, cancellationToken).ConfigureAwait(false);
-
-            async ValueTask<(Solution? solution, T result)> TryFastGetSolutionAndRunAsync()
-            {
-                Solution solution;
-                using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
-                {
-                    if (_lastRequestedPrimaryBranchSolution.checksum == solutionChecksum)
-                    {
-                        solution = _lastRequestedPrimaryBranchSolution.solution;
-                    }
-                    else if (_lastRequestedAnyBranchSolution.checksum == solutionChecksum)
-                    {
-                        solution = _lastRequestedAnyBranchSolution.solution;
-                    }
-                    else
-                    {
-                        return default;
-                    }
-                }
-
-                var result = await implementation(solution).ConfigureAwait(false);
-                return (solution, result);
-            }
-        }
-
-        private async ValueTask<(Solution solution, T result)> SlowGetSolutionAndRunAsync<T>(
-            AssetProvider assetProvider,
-            Checksum solutionChecksum,
-            int workspaceVersion,
-            bool fromPrimaryBranch,
-            Func<Solution, ValueTask<T>> doWorkAsync,
-            CancellationToken cancellationToken)
-        {
-            // See if anyone else is computing this solution for this checksum.  If so, just piggy-back on that.  No
-            // need for us to force the same computation to happen ourselves.
-            var currentSolution = this.CurrentSolution;
-
-            // We use a reference-counted solution that implements IAsyncDisposable. The computation of 'newSolution'
-            // uses eager cancellation, but the asynchronous disposable applies lazy cancellation to the final task that
-            // causes cancellation to propagate to the backing lazy operation.
-            var refCountedLazySolution = await GetLazySolutionAsync().ConfigureAwait(false);
-            await using var configuredAsyncDisposable = refCountedLazySolution.ConfigureAwait(false);
-
-            // Actually get the solution, computing it ourselves, or getting the result that another caller was
-            // computing. In the event of cancellation, we do not wait here for the refCountedLazySolution to clean up,
-            // even if this was the last use of this solution.
-            var newSolution = await refCountedLazySolution.Target.Task.WithCancellation(cancellationToken).ConfigureAwait(false);
-
-            // We may have just done a lot of work to determine the up to date primary branch solution.  See if we
-            // can move the workspace forward to that solution snapshot.
-            if (fromPrimaryBranch)
-                (newSolution, _) = await this.TryUpdateWorkspaceCurrentSolutionAsync(workspaceVersion, newSolution, cancellationToken).ConfigureAwait(false);
-
-            // Store this around so that if another call comes through, they will see the solution we just computed.
-            await SetLastRequestedSolutionAsync(newSolution).ConfigureAwait(false);
->>>>>>> upstream/main

             // Now, pass it to the callback to do the work.  Any other callers into us will be able to benefit from
             // using this same solution as well
-            var result = await doWorkAsync(newSolution).ConfigureAwait(false);
+            var result = await implementation(newSolution).ConfigureAwait(false);

             return (newSolution, result);
-<<<<<<< HEAD
         }

         private async ValueTask<ChecksumToSolutionCache.RefCountedSolution> GetOrCreateSolutionAsync(
@@ -290,61 +194,6 @@
                     return primaryBranchSolution;
                 },
                 cancellationToken).ConfigureAwait(false);
-=======
-
-            async ValueTask<ReferenceCountedDisposable<LazySolution>> GetLazySolutionAsync()
-            {
-                using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
-                {
-                    if (_solutionChecksumToLazySolution.TryGetValue(solutionChecksum, out var refCountedLazySolution))
-                    {
-                        var lazySolutionInstance = refCountedLazySolution.TryAddReference();
-                        if (lazySolutionInstance is not null)
-                            return lazySolutionInstance;
-
-                        // Remove the value since it's clearly no longer usable. The cleanupAsync method would have
-                        // removed this value, but has not completed its execution yet.
-                        _solutionChecksumToLazySolution.Remove(solutionChecksum);
-                    }
-
-                    // We're the first call that is asking about this checksum.  Create a lazy to compute it with a
-                    // refcount of 1 (for 'us').
-                    refCountedLazySolution = null;
-                    var lazySolution = new LazySolution(
-                        getSolutionAsync: cancellationToken => ComputeSolutionAsync(assetProvider, solutionChecksum, currentSolution, cancellationToken),
-                        cleanupAsync: async () =>
-                        {
-                            // We use CancellationToken.None here as we have to ensure the lazy solution is removed from the
-                            // checksum map, or else we will have a memory leak.  This should hopefully not ever be an issue as we
-                            // only ever hold this gate for very short periods of time in order to set do basic operations on our
-                            // state.
-                            using var _ = await _gate.DisposableWaitAsync(CancellationToken.None).ConfigureAwait(false);
-
-                            // Only remove a value from the map if it still exists and holds the same expected instance
-                            if (_solutionChecksumToLazySolution.TryGetValue(solutionChecksum, out var remainingRefCountedLazySolution)
-                                && remainingRefCountedLazySolution == refCountedLazySolution)
-                            {
-                                _solutionChecksumToLazySolution.Remove(solutionChecksum);
-                            }
-                        });
-                    refCountedLazySolution = new ReferenceCountedDisposable<LazySolution>(lazySolution);
-                    _solutionChecksumToLazySolution.Add(solutionChecksum, refCountedLazySolution);
-                    return refCountedLazySolution;
-                }
-            }
-
-            async ValueTask SetLastRequestedSolutionAsync(Solution solution)
-            {
-                using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
-                {
-                    // Quick caches of the last solutions we computed.  That way if return all the way out and something
-                    // else calls back in, we have a likely chance of a cache hit.
-                    _lastRequestedAnyBranchSolution = (solutionChecksum, solution);
-                    if (fromPrimaryBranch)
-                        _lastRequestedPrimaryBranchSolution = (solutionChecksum, solution);
-                }
-            }
->>>>>>> upstream/main
         }

         /// <summary>


removing unused imports

removing unused imports

--- src/client/Microsoft.Rest.ClientRuntime/ServiceClient.cs
+++ src/client/Microsoft.Rest.ClientRuntime/ServiceClient.cs
@@ -3,7 +3,6 @@

 using System;
 using System.Collections.Generic;
-using SysDiag = System.Diagnostics;
 using System.Linq;
 using System.Net.Http;
 using System.Net.Http.Headers;


See if this makes Razor happy

See if this makes Razor happy

--- Battery-Commander.Web/Views/APFT/List.cshtml
+++ Battery-Commander.Web/Views/APFT/List.cshtml
@@ -25,7 +25,7 @@
                         @Html.DisplayFor(_ => model.Date)

-
+
                     @Html.DisplayFor(_ => model.TotalScore)
                     @if(model.IsAlternateAerobicEvent)
                     {
@@ -46,4 +46,4 @@

         }

-
+


Bug fix

Bug fix

--- src/cstsd.Lexical.TypeScript/NetTsControllerConverter.cs
+++ src/cstsd.Lexical.TypeScript/NetTsControllerConverter.cs
@@ -99,7 +99,7 @@
                 DefaultValue = "\"" + route + "\"",
                 FieldDeclarationType = FieldDeclarationType.Const,
                 FieldType = new TsType { Name = "string"},
-                IsPublic = true,
+                IsStatic = true,
                 Name = netMethod.Name + "Url"
             };
             return a;


Updated AndNode.cs to 4.0.2 compatibility.

--- src/BoboBrowse.Net/BoboBrowse.Net/Search/Section/AndNode.cs
+++ src/BoboBrowse.Net/BoboBrowse.Net/Search/Section/AndNode.cs
@@ -17,7 +17,7 @@
 //* See the License for the specific language governing permissions and
 //* limitations under the License.

-// Version compatibility level: 3.2.0
+// Version compatibility level: 4.0.2
 namespace BoboBrowse.Net.Search.Section
 {
     using Lucene.Net.Search;


Extended InventoryItem serializable model

--- src/Booma.API.Common/Character/Models/Item/InventoryItem.cs
+++ src/Booma.API.Common/Character/Models/Item/InventoryItem.cs
@@ -3,6 +3,7 @@
 using System.Runtime.Serialization;
 using System.Text;
 using FreecraftCore.Serializer;
+using Reinterpret.Net;

 namespace Booma
 {
@@ -39,6 +40,18 @@
 		[IgnoreDataMember]
 		public bool IsEquipped => EquippedSlot > 0;

+		[IgnoreDataMember]
+		public ItemClassType @Class => (ItemClassType) ItemData1[0];
+
+		[IgnoreDataMember]
+		public byte SubClass => ItemData1[1];
+
+		/// <summary>
+		/// Unique identifier that comtains the <see cref="ItemId"/> and the <see cref="@Class"/> and <see cref="SubClass"/>.
+		/// </summary>
+		[IgnoreDataMember]
+		public ulong FullItemId => (ulong)ItemId << 32 | (ulong)ItemData1.Reinterpret<ushort>();
+
 		//Maybe this is the slot its equipped in?
 		[WireMember(1)]
 		public ushort EquippedSlot { get; internal set; }
@@ -47,8 +60,9 @@
 		[WireMember(2)]
 		public ushort Technique { get; internal set; }

+		[EnumSize(PrimitiveSizeType.UInt32)]
 		[WireMember(3)]
-		public uint Flags { get; internal set; }
+		public InventoryItemFlags Flags { get; internal set; }

 		//We don't use EMPTY here so it's easier to interact with these chunks.
 		[KnownSize(12)]
@@ -63,7 +77,7 @@
 		[WireMember(6)]
 		public byte[] ItemData2 { get; set; } = new byte[4];

-		public InventoryItem(uint itemId, ushort equippedSlot, ushort technique, uint flags, byte[] itemData1, byte[] itemData2)
+		public InventoryItem(uint itemId, ushort equippedSlot, ushort technique, InventoryItemFlags flags, byte[] itemData1, byte[] itemData2)
 		{
 			EquippedSlot = equippedSlot;
 			Technique = technique;
@@ -73,7 +87,7 @@
 			ItemId = itemId;
 		}

-		public InventoryItem(uint itemId, ushort equippedSlot, ushort technique, uint flags)
+		public InventoryItem(uint itemId, ushort equippedSlot, ushort technique, InventoryItemFlags flags)
 		{
 			EquippedSlot = equippedSlot;
 			Technique = technique;
@@ -86,10 +100,25 @@
 			ItemData1[1] = type;
 		}

+		public void SetWeaponTemplateId(byte id)
+		{
+			ItemData1[2] = id;
+		}
+
 		public void SetEmpty()
 		{
 			SetWeaponType(0xFF);
 			ItemId = 0xFFFFFFFF;
+		}
+
+		public void Equip()
+		{
+			Flags |= InventoryItemFlags.Equipped;
+		}
+
+		public void UnEquip()
+		{
+			Flags &= ~InventoryItemFlags.Equipped;
 		}

 		/// <summary>


Switched custom constructors over to internal to simplify API for external callers

--- src/Breeze.BusinessTime/Rules/PipelinedDbContextProvider.cs
+++ src/Breeze.BusinessTime/Rules/PipelinedDbContextProvider.cs
@@ -9,26 +9,44 @@
 {
     public class PipelinedDbContextProvider<T>: EFContextProvider<T> where T : DbContext, new()
     {
+        public PipelinedDbContextProvider()
+        {
+            BeforeSaveEntitiesDelegate = ExecuteBeforePipeline;
+            AfterSaveEntitiesDelegate = ExecuteAfterPipeline;
+        }
+
+        internal PipelinedDbContextProvider(IProcessBreezeRequests processBefore, IProcessBreezeRequests processAfter)
+            : this(processBefore)
+        {
+            if (processAfter == null)
+                throw new ArgumentException("Argument processAfter (IProcessBreezeRequests) was null.");
+
+            BeforePipeline.Add(processBefore);
+        }
+
+        internal PipelinedDbContextProvider(IProcessBreezeRequests processBefore)
+            : this()
+        {
+            if (processBefore == null)
+                throw new ArgumentException("Argument processBefore (IProcessBreezeRequests) was null.");
+
+            BeforePipeline.Add(processBefore);
+        }
+
         private List<IProcessBreezeRequests> _beforePipeline;
-        private List<IProcessBreezeRequests> _afterPipeline;
-
         public List<IProcessBreezeRequests> BeforePipeline
         {
             get { return _beforePipeline ?? (_beforePipeline = new List<IProcessBreezeRequests>()); }
             protected set { _beforePipeline = value; }
         }

+        private List<IProcessBreezeRequests> _afterPipeline;
         public List<IProcessBreezeRequests> AfterPipeline
         {
             get { return _afterPipeline ?? (_afterPipeline = new List<IProcessBreezeRequests>()); }
             protected set { _afterPipeline = value; }
         }

-        public PipelinedDbContextProvider()
-        {
-            BeforeSaveEntitiesDelegate = ExecuteBeforePipeline;
-            AfterSaveEntitiesDelegate = ExecuteAfterPipeline;
-        }

         private void ExecuteAfterPipeline(Dictionary<Type, List<EntityInfo>> saveMap, List<KeyMapping> keyMappings)
         {
@@ -57,24 +75,6 @@
             ));
         }

-        public PipelinedDbContextProvider(IProcessBreezeRequests processBefore, IProcessBreezeRequests processAfter)
-            : this(processBefore)
-        {
-            if (processAfter == null)
-                throw new ArgumentException("Argument processAfter (IProcessBreezeRequests) was null.");
-
-            BeforePipeline.Add(processBefore);
-        }
-
-        public PipelinedDbContextProvider(IProcessBreezeRequests processBefore)
-            : this()
-        {
-            if(processBefore == null)
-                throw new ArgumentException("Argument processBefore (IProcessBreezeRequests) was null.");
-
-            BeforePipeline.Add(processBefore);
-        }
-
         protected Dictionary<Type, List<EntityInfo>> ExecuteBeforePipeline(Dictionary<Type, List<EntityInfo>> saveMap)
         {
             ExecutePipeline(BeforePipeline, saveMap);


Prettify form

Prettify form

--- src/Dangl.WebDocumentation/Views/Admin/CreateProject.cshtml
+++ src/Dangl.WebDocumentation/Views/Admin/CreateProject.cshtml
@@ -15,42 +15,50 @@

             <form asp-controller="Admin" asp-action="CreateProject" method="post" class="form-horizontal" role="form">

-

+

-                        <input asp-for="ProjectName" class="form-control"/>
+                        <input asp-for="ProjectName" class="form-control" placeholder="Name"/>

-

+

-                        <input asp-for="IsPublic"/>
+

+
+                                <input asp-for="IsPublic" />
+                                Public Access
+
+

-

+

-                        <input asp-for="PathToIndexPage" class="form-control"/>
+                        <input asp-for="PathToIndexPage" class="form-control" placeholder="Path to Index" />

-

+

                         @{
-                            foreach (var availableUser in Model.AvailableUsers)
+                            if (Model.AvailableUsers != null)
                             {
-                                <input type="checkbox" id="User_@availableUser" name="SelectedUsers" value="@availableUser"/>
-                                @availableUser
-

+                                foreach (var availableUser in Model.AvailableUsers)
+                                {
+                                    <input type="checkbox" id="User_@availableUser" name="SelectedUsers" value="@availableUser"/>
+                                    @availableUser
+

+                                }
                             }
                         }

-

+

-                        <button type="submit" class="btn btn-default">Create Project</button>
+                        <button type="submit" class="btn btn-raised btn-primary">Create Project</button>

             </form>


Fixed MessageQueue race condition

Fixed MessageQueue race condition

--- src/Discord.Net/Net/Rest/RequestQueue/RequestQueueBucket.cs
+++ src/Discord.Net/Net/Rest/RequestQueue/RequestQueueBucket.cs
@@ -16,8 +16,8 @@
         private readonly ConcurrentQueue<RestRequest> _queue;
         private readonly SemaphoreSlim _lock;
         private Task _resetTask;
-        private DateTime? _retryAfter;
-        private bool _waitingToProcess;
+        private bool _waitingToProcess, _destroyed; //TODO: Remove _destroyed
+        private int _id;

         public int WindowMaxCount { get; }
         public int WindowSeconds { get; }
@@ -44,10 +44,12 @@
             WindowSeconds = windowSeconds;
             _queue = new ConcurrentQueue<RestRequest>();
             _lock = new SemaphoreSlim(1, 1);
+            _id = new System.Random().Next(0, int.MaxValue);
         }

         public void Queue(RestRequest request)
         {
+            if (_destroyed) throw new Exception();
             //Assume this obj's parent is under lock

             _queue.Enqueue(request);
@@ -75,7 +77,7 @@
                     //If we're waiting to reset (due to a rate limit exception, or preemptive check), abort
                     if (WindowCount == WindowMaxCount) return;
                     //Get next request, return if queue is empty
-                    if (!_queue.TryPeek(out request)) return;
+                    if (!_queue.TryPeek(out request)) break;

                     try
                     {
@@ -88,17 +90,20 @@
                     }
                     catch (HttpRateLimitException ex) //Preemptive check failed, use Discord's time instead of our own
                     {
-                        if (_resetTask == null)
-                        {
-                            //No reset has been queued yet, lets create one as if this *was* preemptive
+                        WindowCount = WindowMaxCount;
+                        var task = _resetTask;
+                        if (task != null)
+                        {
+                            Debug($"External rate limit: Extended to {ex.RetryAfterMilliseconds} ms");
+                            var retryAfter = DateTime.UtcNow.AddMilliseconds(ex.RetryAfterMilliseconds);
+                            await task.ConfigureAwait(false);
+                            int millis = (int)Math.Ceiling((DateTime.UtcNow - retryAfter).TotalMilliseconds);
+                            _resetTask = ResetAfter(millis);
+                        }
+                        else
+                        {
+                            Debug($"External rate limit: Reset in {ex.RetryAfterMilliseconds} ms");
                             _resetTask = ResetAfter(ex.RetryAfterMilliseconds);
-                            Debug($"External rate limit: Reset in {ex.RetryAfterMilliseconds} ms");
-                        }
-                        else
-                        {
-                            //A preemptive reset is already queued, set RetryAfter to extend it
-                            _retryAfter = DateTime.UtcNow.AddMilliseconds(ex.RetryAfterMilliseconds);
-                            Debug($"External rate limit: Extended to {ex.RetryAfterMilliseconds} ms");
                         }
                         return;
                     }
@@ -132,6 +137,25 @@
                         Debug($"Internal rate limit: Reset in {WindowSeconds * 1000} ms");
                     }
                 }
+
+                //If queue is empty, non-global, and there is no active rate limit, remove this bucket
+                if (_resetTask == null && _bucketGroup == BucketGroup.Guild)
+                {
+                    try
+                    {
+                        await _parent.Lock().ConfigureAwait(false);
+                        if (_queue.IsEmpty) //Double check, in case a request was queued before we got both locks
+                        {
+                            Debug($"Destroy");
+                            _parent.DestroyGuildBucket((GuildBucket)_bucketId, _guildId);
+                            _destroyed = true;
+                        }
+                    }
+                    finally
+                    {
+                        _parent.Unlock();
+                    }
+                }
             }
             finally
             {
@@ -155,36 +179,14 @@
             {
                 await Lock().ConfigureAwait(false);

-                //If an extension has been planned, start a new wait task
-                if (_retryAfter != null)
-                {
-                    _resetTask = ResetAfter((int)(_retryAfter.Value - DateTime.UtcNow).TotalMilliseconds);
-                    _retryAfter = null;
-                    return;
-                }
-
                 Debug($"Reset");
+
                 //Reset the current window count and set our state back to normal
                 WindowCount = 0;
                 _resetTask = null;

                 //Wait is over, work through the current queue
                 await ProcessQueue().ConfigureAwait(false);
-
-                //If queue is empty and non-global, remove this bucket
-                if (_bucketGroup == BucketGroup.Guild && _queue.IsEmpty)
-                {
-                    try
-                    {
-                        await _parent.Lock().ConfigureAwait(false);
-                        if (_queue.IsEmpty) //Double check, in case a request was queued before we got both locks
-                            _parent.DestroyGuildBucket((GuildBucket)_bucketId, _guildId);
-                    }
-                    finally
-                    {
-                        _parent.Unlock();
-                    }
-                }
             }
             finally
             {
@@ -217,7 +219,7 @@
                     name = "Unknown";
                     break;
             }
-            System.Diagnostics.Debug.WriteLine($"[{name}] {text}");
+            System.Diagnostics.Debug.WriteLine($"[{name} {_id}] {text}");
         }
     }
 }


Reverted AssemblyInfo back to correct form

--- src/EventStore/EventStore.Common/Properties/AssemblyInfo.cs
+++ src/EventStore/EventStore.Common/Properties/AssemblyInfo.cs
@@ -1,29 +1,29 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+// Copyright (c) 2012, Event Store LLP
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// Redistributions of source code must retain the above copyright notice,
+// this list of conditions and the following disclaimer.
+// Redistributions in binary form must reproduce the above copyright
+// notice, this list of conditions and the following disclaimer in the
+// documentation and/or other materials provided with the distribution.
+// Neither the name of the Event Store LLP nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 using System.Reflection;
 using System.Runtime.InteropServices;
@@ -33,15 +33,13 @@
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyCompany("Event Store LLP")]
 [assembly: AssemblyProduct("EventStore.Common")]
-[assembly: AssemblyCopyright("Copyright  Event Store LLP. All rights reserved.")]
+[assembly: AssemblyCopyright("Copyright © Event Store LLP. All rights reserved.")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyCulture("")]

-
+//NOTE: Do not change these, they will be modified during the build by TeamCity.
 [assembly: AssemblyVersion("0.0.0.0")]
 [assembly: AssemblyFileVersion("0.0.0.0")]

 [assembly: ComVisible(false)]
 [assembly: Guid("ccc6be24-ec1c-4a7e-98ae-892648fb1e4b")]
-
-[assembly: AssemblyInformationalVersion("0.0.0.0.Unavailable@0000000000000000000000000000000000000000@Mon, 1 Jan 1970 00:00:00 +0000")]


log og string for invalid URL syntax

log og string for invalid URL syntax

--- src/FilterLists.Agent/Features/Urls/BuildGitHubIssueBody.cs
+++ src/FilterLists.Agent/Features/Urls/BuildGitHubIssueBody.cs
@@ -32,7 +32,7 @@
                     body.Append("
");
                     foreach (var result in fileReults.Results)
                     {
-                        body.Append($"
{result.Url.AbsoluteUri}");
+                        body.Append($"
{result.Url.OriginalString}");
                         body.Append("
");
                         foreach (var message in result.Messages)
                             body.Append($"
{message}
");


Changed announcer statments to heading method

--- src/FluentMigrator.Tests/Integration/IntegrationTestBase.cs
+++ src/FluentMigrator.Tests/Integration/IntegrationTestBase.cs
@@ -58,7 +58,7 @@
 				return;

             var announcer = new TextWriterAnnouncer(System.Console.Out);
-            announcer.Say("\n\n******************Testing Migration against MS SQL Server******************\n\n");
+            announcer.Heading("Testing Migration against MS SQL Server");

             using (var connection = new SqlConnection(serverOptions.ConnectionString))
             {
@@ -78,7 +78,7 @@
 				return;

             var announcer = new TextWriterAnnouncer(System.Console.Out);
-            announcer.Say("\n\n******************Testing Migration against SQLite******************\n\n");
+            announcer.Heading("Testing Migration against SQLite");

             using (var connection = new SQLiteConnection(serverOptions.ConnectionString))
             {
@@ -93,7 +93,7 @@
 				return;

             var announcer = new TextWriterAnnouncer(System.Console.Out);
-            announcer.Say("\n\n******************Testing Migration against MySQL Server******************\n\n");
+            announcer.Heading("Testing Migration against MySQL Server");

             using (var connection = new MySqlConnection(serverOptions.ConnectionString))
             {