fixed seed data duplicates

fixed seed data duplicates

--- ContosoUniversity.Data/SeedData.cs
+++ ContosoUniversity.Data/SeedData.cs
@@ -32,17 +32,13 @@

         private void InitializeEnrollments()
         {
-            var studentCount = _unitOfWork.StudentRepository.GetAll().Count();
-            if (studentCount == 0)
-            {
-                InitializeStudents();
-            }
-
-            var courseCount = _unitOfWork.CourseRepository.GetAll().Count();
-            if (courseCount == 0)
-            {
-                InitializeCourses();
-            }
+            if (IsInitialized(_unitOfWork.EnrollmentRepository.GetAll()))
+            {
+                return;
+            }
+
+            InitializeStudents();
+            InitializeCourses();

             var students = _unitOfWork.StudentRepository.GetAll().ToArray();
             var courses = _unitOfWork.CourseRepository.GetAll().ToArray();
@@ -115,17 +111,13 @@

         private void InitializeCourseAssignment()
         {
-            var instructorsCount = _unitOfWork.InstructorRepository.GetAll().Count();
-            if (instructorsCount == 0)
-            {
-                InitializeInstructors();
-            }
-
-            var courseCount = _unitOfWork.CourseRepository.GetAll().Count();
-            if (courseCount == 0)
-            {
-                InitializeCourses();
-            }
+            if (IsInitialized(_unitOfWork.CourseAssignmentRepository.GetAll()))
+            {
+                return;
+            }
+
+            InitializeInstructors();
+            InitializeCourses();

             var instructors = _unitOfWork.InstructorRepository.GetAll().ToArray();
             var courses = _unitOfWork.CourseRepository.GetAll().ToArray();
@@ -177,11 +169,12 @@

         private void InitializeOfficeAssignment()
         {
-            var instructorsCount = _unitOfWork.InstructorRepository.GetAll().Count();
-            if (instructorsCount == 0)
-            {
-                InitializeInstructors();
-            }
+            if (IsInitialized(_unitOfWork.OfficeAssignmentRepository.GetAll()))
+            {
+                return;
+            }
+
+            InitializeInstructors();

             var instructors = _unitOfWork.InstructorRepository.GetAll().ToArray();
             var officeAssignments = new OfficeAssignment[]
@@ -202,11 +195,13 @@

         private void InitializeCourses()
         {
-            var departmentCount = _unitOfWork.DepartmentRepository.GetAll().Count();
-            if (departmentCount == 0)
-            {
-                InitializeDeparments();
-            }
+            if (IsInitialized(_unitOfWork.CourseRepository.GetAll()))
+            {
+                return;
+            }
+
+            InitializeDeparments();
+
             var departments = _unitOfWork.DepartmentRepository.GetAll().ToArray();
             var courses = new Course[]
             {
@@ -244,6 +239,11 @@

         private void InitializeStudents()
         {
+            if (IsInitialized(_unitOfWork.StudentRepository.GetAll()))
+            {
+                return;
+            }
+
             var students = new Student[]
             {
                 new Student{FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse("2005-09-01")},
@@ -267,17 +267,12 @@

         private void InitializeDeparments()
         {
-            var departmentCount =  _unitOfWork.DepartmentRepository.GetAll().Count();
-            if (departmentCount > 0)
-            {
-                return;
-            }
-
-            var instructorCount = _unitOfWork.InstructorRepository.GetAll().Count();
-            if (instructorCount == 0)
-            {
-                InitializeInstructors();
-            }
+            if (IsInitialized(_unitOfWork.DepartmentRepository.GetAll()))
+            {
+                return;
+            }
+
+            InitializeInstructors();

             var instructors = _unitOfWork.InstructorRepository.GetAll().ToArray();
             var departments = new Department[]
@@ -298,8 +293,7 @@

         private void InitializeInstructors()
         {
-            var instructorCount = _unitOfWork.InstructorRepository.GetAll().Count();
-            if (instructorCount > 0)
+            if (IsInitialized(_unitOfWork.InstructorRepository.GetAll()))
             {
                 return;
             }
@@ -321,5 +315,7 @@

             _unitOfWork.Commit();
         }
+
+        private bool IsInitialized(IQueryable<BaseEntity> query) => query.Count() > 0;
     }
 }


using usermanager

using usermanager

removed help function because it's literally one line

--- Controllers/SchedulerController.cs
+++ Controllers/SchedulerController.cs
@@ -28,7 +28,7 @@
         [HttpGet]
         public async Task<IActionResult> Index()
         {
-            var user = await GetCurrentUserAsync();
+            var user = await _userManager.GetUserAsync(HttpContext.User);

             if (user != null) {
                 return View();
@@ -39,27 +39,18 @@
         [HttpPost]
         public async Task<IActionResult> CreateEvent(EventViewModel model)
         {
-            var currentUser = await GetCurrentUserAsync();
+            var currentUser = await _userManager.GetUserAsync(HttpContext.User);
             var eventDbModel = EventModelMapper.MapFrom(currentUser, model);
             var newEvent = _eventRepo.Create(eventDbModel);

-            var invitees = model.InviteeEmails = new List<string>();
-            invitees.Add("someEmail@gmail.com");
-            invitees.Add("someOtherEmail@gmail.com");
-
             foreach(var email in model.InviteeEmails)
             {
-                var userId = email;
-                var inviteeDbModel = InviteeModelMapper.MapFrom(newEvent, userId);
+                var inviteeUser = await _userManager.FindByEmailAsync(email);
+                var inviteeDbModel = InviteeModelMapper.MapFrom(newEvent, inviteeUser);
                 _inviteeRepo.Create(inviteeDbModel);
             }

             return View(model);
         }
-
-        private Task<ApplicationUser> GetCurrentUserAsync()
-        {
-            return _userManager.GetUserAsync(HttpContext.User);
-        }
     }
 }


Removed see reference

Removed see reference

--- Core2D/Editor/ProjectExtensions.cs
+++ Core2D/Editor/ProjectExtensions.cs
@@ -13,7 +13,7 @@
 namespace Core2D.Editor
 {
     /// <summary>
-    /// <see cref="Project"/> extension methods.
+    /// Project extension methods.
     /// </summary>
     public static class ProjectExtensions
     {


fix console comand Show Neighbours and enable it

--- OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/LocalGridServiceConnector.cs
+++ OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/LocalGridServiceConnector.cs
@@ -52,6 +52,7 @@

         private IGridService m_GridService;
         private RegionInfoCache m_RegionInfoCache;
+        private HashSet<Scene> m_scenes = new HashSet<Scene>();

         private bool m_Enabled;

@@ -68,7 +69,7 @@

         public LocalGridServicesConnector(IConfigSource source, RegionInfoCache regionInfoCache)
         {
-            m_log.DebugFormat("{0} LocalGridServicesConnector instantiated directly witj cache.", LogHeader);
+            m_log.DebugFormat("{0} LocalGridServicesConnector instantiated directly with cache.", LogHeader);
             InitialiseService(source, regionInfoCache);
         }

@@ -153,6 +154,11 @@
             if (!m_Enabled)
                 return;

+            lock(m_scenes)
+            {
+                if(!m_scenes.Contains(scene))
+                    m_scenes.Add(scene);
+            }
             scene.RegisterModuleInterface<IGridService>(this);

             GridRegion r = new GridRegion(scene.RegionInfo);
@@ -165,6 +171,12 @@
         {
             if (!m_Enabled)
                 return;
+
+            lock(m_scenes)
+            {
+                if(m_scenes.Contains(scene))
+                    m_scenes.Remove(scene);
+            }

             m_RegionInfoCache.Remove(scene.RegionInfo.ScopeID, scene.RegionInfo.RegionHandle);
             scene.EventManager.OnRegionUp -= OnRegionUp;
@@ -221,14 +233,7 @@
         public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
         {

-            // try in cache by handler first
-//            ulong regionHandle = Util.RegionWorldLocToHandle((uint)x, (uint)y);
-
             bool inCache = false;
-//            GridRegion rinfo = m_RegionInfoCache.Get(scopeID, regionHandle, out inCache);
-//            if (inCache)
-//                return rinfo;
-
             GridRegion rinfo = m_RegionInfoCache.Get(scopeID, (uint)x, (uint)y, out inCache);
             if (inCache)
                 return rinfo;
@@ -297,22 +302,26 @@

         public void HandleShowNeighboursCommand(string module, string[] cmdparams)
         {
+            if(!m_Enabled || m_scenes.Count == 0)
+                return;
+
             System.Text.StringBuilder caps = new System.Text.StringBuilder();
-/*   temporary broken
-            lock (m_LocalCache)
-            {
-                foreach (KeyValuePair<UUID, RegionCache> kvp in m_LocalCache)
-                {
-                    caps.AppendFormat("*** Neighbours of {0} ({1}) ***\n", kvp.Value.RegionName, kvp.Key);
-                    List<GridRegion> regions = kvp.Value.GetNeighbours();
-                    foreach (GridRegion r in regions)
-                        caps.AppendFormat("    {0} @ {1}-{2}\n", r.RegionName, Util.WorldToRegionLoc((uint)r.RegionLocX), Util.WorldToRegionLoc((uint)r.RegionLocY));
-                }
+
+            List<Scene> scenes;
+            lock (m_scenes)
+                scenes = new List<Scene>(m_scenes);
+
+            foreach (Scene s in scenes)
+            {
+                RegionInfo sr = s.RegionInfo;
+                caps.AppendFormat("*** Neighbours of {0} ({1}) ***\n", sr.RegionName, sr.RegionID);
+                List<GridRegion> regions = GetNeighbours(sr.ScopeID, sr.RegionID);
+                foreach (GridRegion r in regions)
+                    caps.AppendFormat("    {0} @ {1}-{2}\n", r.RegionName, Util.WorldToRegionLoc((uint)r.RegionLocX), Util.WorldToRegionLoc((uint)r.RegionLocY));
             }

             MainConsole.Instance.Output(caps.ToString());
-*/
-            MainConsole.Instance.Output("Neighbours list not avaiable in this version\n");
+
         }
     }
 }


Fixed Client.Screen lazy instantiation. (it wasn't instantiated at all before).

--- tibiaapi/Objects/Client.cs
+++ tibiaapi/Objects/Client.cs
@@ -486,6 +486,18 @@
         }

         /// <summary>
+        /// Get the client's screen (for displaying text)
+        /// </summary>
+        public Screen Screen
+        {
+            get
+            {
+                if (screen == null) screen = new Screen(this);
+                return screen;
+            }
+        }
+
+        /// <summary>
         /// Get the time the client was started.
         /// </summary>
         /// <returns></returns>
@@ -508,14 +520,6 @@
         public IntPtr ProcessHandle
         {
             get { return processHandle; }
-        }
-
-        /// <summary>
-        /// Get the client's screen (for displaying text)
-        /// </summary>
-        public Screen Screen
-        {
-            get { return screen; }
         }

         public ContextMenu ContextMenu


更新Sample中日志的写法

更新Sample中日志的写法

--- Senparc.Weixin.MP.Sample/Senparc.Weixin.MP.Sample/Controllers/WeixinController.cs
+++ Senparc.Weixin.MP.Sample/Senparc.Weixin.MP.Sample/Controllers/WeixinController.cs
@@ -80,6 +80,7 @@
             //v4.2.2之后的版本，可以设置每个人上下文消息储存的最大数量，防止内存占用过多，如果该参数小于等于0，则不限制
             var maxRecordCount = 10;

+            var logPath = Server.MapPath(string.Format("~/App_Data/MP/{0}/",DateTime.Now.ToString("YYYY-MM-dd")));

             //自定义MessageHandler，对微信请求的详细判断操作都在这里面。
             var messageHandler = new CustomMessageHandler(Request.InputStream, postModel, maxRecordCount);
@@ -87,10 +88,12 @@
             {

                 //测试时可开启此记录，帮助跟踪数据，使用前请确保App_Data文件夹存在，且有读写权限。
-                messageHandler.RequestDocument.Save(Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_" + messageHandler.RequestMessage.FromUserName + ".txt"));
+                messageHandler.RequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_{1}.txt", DateTime.Now.Ticks, messageHandler.RequestMessage.FromUserName)));
                 if (messageHandler.UsingEcryptMessage)
                 {
-                    messageHandler.EcryptRequestDocument.Save(Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_Ecrypt_" + messageHandler.RequestMessage.FromUserName + ".txt"));
+                    messageHandler.EcryptRequestDocument.Save(Path.Combine(logPath,
+                        string.Format("{0}_Request_Ecrypt_{1}.txt", DateTime.Now.Ticks,
+                            messageHandler.RequestMessage.FromUserName)));
                 }

                 /* 如果需要添加消息去重功能，只需打开OmitRepeatedMessage功能，SDK会自动处理。
@@ -110,13 +113,17 @@

                 if (messageHandler.ResponseDocument != null)
                 {
-                    messageHandler.ResponseDocument.Save(Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Response_" + messageHandler.ResponseMessage.ToUserName + ".txt"));
+                    messageHandler.ResponseDocument.Save(Path.Combine(logPath,
+                        string.Format("{0}_Response_{1}.txt", DateTime.Now.Ticks,
+                            messageHandler.RequestMessage.FromUserName)));
                 }

                 if (messageHandler.UsingEcryptMessage)
                 {
                     //记录加密后的响应信息
-                    messageHandler.FinalResponseDocument.Save(Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Response_Final_" + messageHandler.ResponseMessage.ToUserName + ".txt"));
+                    messageHandler.FinalResponseDocument.Save(Path.Combine(logPath,
+                        string.Format("{0}_Response_Final_{1}.txt", DateTime.Now.Ticks,
+                            messageHandler.RequestMessage.FromUserName)));
                 }

                 //return Content(messageHandler.ResponseDocument.ToString());//v0.7-


Switch to decimals for wunderground API conversion math for better precision. Offset the pressure so it matches reality (not sure why wunderground changes what is uploaded).

--- SensorSeed/HomeOutsideWeatherStation/Controllers/DataController/DataController.cs
+++ SensorSeed/HomeOutsideWeatherStation/Controllers/DataController/DataController.cs
@@ -32,8 +32,8 @@
         {
             using (var context = new SensorSeedDataContext())
             {
-                double? humidity = null;
-                double? temperature = null;
+                decimal? humidity = null;
+                decimal? temperature = null;

                 string url = "https://rtupdate.wunderground.com/weatherstation/updateweatherstation.php";
                 url += "?ID=KNELINCO88";
@@ -45,29 +45,29 @@
                 }
                 if (data.WindSpeed.HasValue)
                 {
-                    url += "&windspeedmph=" + Convert.ToDouble(data.WindSpeed.Value)*0.621371;
-                    url += "&winddir_avg2m=" + Convert.ToDouble(data.WindSpeed.Value)*0.621371;
+                    url += "&windspeedmph=" + data.WindSpeed.Value*(decimal)0.621371;
+                    url += "&winddir_avg2m=" + data.WindSpeed.Value*(decimal)0.621371;
                 }
                 if (data.GustSpeed.HasValue)
                 {
-                    url += "&windgustmph=" + Convert.ToDouble(data.GustSpeed.Value)*0.621371;
+                    url += "&windgustmph=" + data.GustSpeed.Value*(decimal)0.621371;
                 }
                 if (context.HomeOutsideWeatherStationDatas.Where(x => x.Timestamp > (DateTime.UtcNow.AddMinutes(-10))).Average(x => x.GustSpeed).HasValue)
                 {
-                    url += "&windgustmph_10m=" + Convert.ToDouble(context.HomeOutsideWeatherStationDatas.Where(x => x.Timestamp > (DateTime.UtcNow.AddMinutes(-10))).Average(x => x.GustSpeed)) * 0.621371;
+                    url += "&windgustmph_10m=" + context.HomeOutsideWeatherStationDatas.Where(x => x.Timestamp > (DateTime.UtcNow.AddMinutes(-10))).Average(x => x.GustSpeed) * (decimal)0.621371;
                 }
                 if (data.Humidity.HasValue || data.HumidityDHT22.HasValue)
                 {
-                    double humidityAverage = 0;
-                    int humidityPointCount = 0;
+                    decimal humidityAverage = 0;
+                    decimal humidityPointCount = 0;
                     if (data.Humidity.HasValue)
                     {
-                        humidityAverage += Convert.ToDouble(data.Humidity.Value);
+                        humidityAverage += data.Humidity.Value;
                         humidityPointCount++;
                     }
                     if (data.HumidityDHT22.HasValue)
                     {
-                        humidityAverage += Convert.ToDouble(data.HumidityDHT22.Value);
+                        humidityAverage += data.HumidityDHT22.Value;
                         humidityPointCount++;
                     }
                     url += "&humidity=" + humidityAverage / humidityPointCount;
@@ -75,42 +75,45 @@
                 }
                 if (data.Temperature.HasValue || data.Temperature180.HasValue || data.TemperatureDHT22.HasValue)
                 {
-                    double temperatureAverage = 0;
-                    double temperaturePointCount = 0;
+                    decimal temperatureAverage = 0;
+                    decimal temperaturePointCount = 0;
                     if (data.Temperature.HasValue)
                     {
-                        temperatureAverage += Convert.ToDouble(data.Temperature.Value);
+                        temperatureAverage += data.Temperature.Value;
                         temperaturePointCount++;
                     }
                     if (data.Temperature180.HasValue)
                     {
-                        temperatureAverage += Convert.ToDouble(data.Temperature180.Value);
+                        temperatureAverage += data.Temperature180.Value;
                         temperaturePointCount++;
                     }
                     if (data.TemperatureDHT22.HasValue)
                     {
-                        temperatureAverage += Convert.ToDouble(data.TemperatureDHT22.Value);
+                        temperatureAverage += data.TemperatureDHT22.Value;
                         temperaturePointCount++;
                     }
-                    url += "&tempf=" + (((temperatureAverage/temperaturePointCount) * 1.8) + 32);
+                    url += "&tempf=" + (((temperatureAverage/temperaturePointCount) * (decimal)1.8) + (decimal)32);
                     temperature = ((temperatureAverage/temperaturePointCount));
                 }
                 if (context.HomeOutsideWeatherStationDatas.Where(x => x.Timestamp > DateTime.UtcNow.AddMinutes(-60)).Sum(x => x.Rain).HasValue)
                 {
-                    url += "&rainin=" + Convert.ToDouble(context.HomeOutsideWeatherStationDatas.Where(x => x.Timestamp > DateTime.UtcNow.AddMinutes(-60)).Sum(x => x.Rain)) * 0.0393701;
+                    url += "&rainin=" + context.HomeOutsideWeatherStationDatas.Where(x => x.Timestamp > DateTime.UtcNow.AddMinutes(-60)).Sum(x => x.Rain) * (decimal)0.0393701;
                 }
                 if (context.HomeOutsideWeatherStationDatas.Where(x => x.Timestamp > DateTime.Today.ToUniversalTime()).Sum(x => x.Rain).HasValue)
                 {
-                    url += "&dailyrainin=" + Convert.ToDouble(context.HomeOutsideWeatherStationDatas.Where(x => x.Timestamp > DateTime.Today.ToUniversalTime()).Sum(x => x.Rain)) * 0.0393701;
+                    url += "&dailyrainin=" + context.HomeOutsideWeatherStationDatas.Where(x => x.Timestamp > DateTime.Today.ToUniversalTime()).Sum(x => x.Rain) * (decimal)0.0393701;
                 }
                 if (data.Pressure.HasValue)
                 {
-                    url += "&baromin=" + Convert.ToDouble(data.Pressure.Value) * 0.029529983071445; // might be wrong conversion factor, todo:
+                    // For some reason the wunderground API changes the pressure when it is uploaded, this offsets that.
+                    decimal offsetPressureValue = data.Pressure.Value - (decimal)43.69;
+                    url += "&baromin=" + offsetPressureValue * (decimal)0.029529983071445;
                 }
                 if (temperature.HasValue && humidity.HasValue)
                 {
-                    url += "&dewptf=" + ((WeatherDataConversions.DewPoint(temperature.Value, humidity.Value) * 1.8) + 32);
-                }
+                    url += "&dewptf=" + ((WeatherDataConversions.DewPoint((double)temperature.Value, (double)humidity.Value) * 1.8) + 32);
+                }
+                url += "&realtime=1&rtfreq=155";

                 HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
                 request.AutomaticDecompression = DecompressionMethods.GZip;


Fix wrong filesystem in docstring

Fix wrong filesystem in docstring

--- Library/DiscUtils.Ext/ExtFileSystemOptions.cs
+++ Library/DiscUtils.Ext/ExtFileSystemOptions.cs
@@ -25,7 +25,7 @@
 namespace DiscUtils.Ext
 {
     /// <summary>
-    /// FAT file system options.
+    /// EXT file system options.
     /// </summary>
     public sealed class ExtFileSystemOptions : DiscFileSystemOptions
     {


only lacking external references

only lacking external references

--- Tests.Integration.Presentation.Web/GDPR/V2/DataProcessingRegistrationApiV2Test.cs
+++ Tests.Integration.Presentation.Web/GDPR/V2/DataProcessingRegistrationApiV2Test.cs
@@ -923,14 +923,28 @@
             var role = (await DataProcessingRegistrationV2Helper.GetRolesAsync(token, organization.Uuid, 0, 1)).First();
             var system = await ItSystemHelper.CreateItSystemInOrganizationAsync(CreateName(), organization.Id, AccessModifier.Public);
             var systemUsage = await ItSystemUsageV2Helper.PostAsync(token, new CreateItSystemUsageRequestDTO { OrganizationUuid = organization.Uuid, SystemUuid = system.Uuid });
+            var oversightDate1 = CreateOversightDate();
+            var oversightDate2 = CreateOversightDate();
+            var oversightOption = (await OptionV2ApiHelper.GetOptionsAsync(OptionV2ApiHelper.ResourceName.DataProcessingRegistrationOversight, organization.Uuid, 10, 0)).RandomItem();
+
+            var oversightInput = new DataProcessingRegistrationOversightWriteRequestDTO()
+            {
+                OversightOptionUuids = new[] { oversightOption.Uuid },
+                OversightOptionsRemark = A<string>(),
+                OversightInterval = A<OversightIntervalChoice>(),
+                OversightIntervalRemark = A<string>(),
+                IsOversightCompleted = YesNoUndecidedChoice.Yes,
+                OversightCompletedRemark = A<string>(),
+                OversightDates = new[] { oversightDate1, oversightDate2 }
+            };
             var request = new CreateDataProcessingRegistrationRequestDTO()
             {
                 Name = CreateName(),
                 General = generalDataWriteRequestDto,
-                Oversight = null,           //TODO
+                Oversight = oversightInput,
                 ExternalReferences = null,  //TODO - awaiting jmo branch
                 OrganizationUuid = organization.Uuid,
-                SystemUsageUuids = new []{systemUsage.Uuid},
+                SystemUsageUuids = new[] { systemUsage.Uuid },
                 Roles = new[] { new RoleAssignmentRequestDTO { RoleUuid = role.Uuid, UserUuid = userForRole.Uuid } }
             };

@@ -939,7 +953,13 @@
             dto = await DataProcessingRegistrationV2Helper.GetDPRAsync(token, dto.Uuid);

             //Assert
-            //TODO: Assertions
+            AssertGeneralData(organization, dataResponsible, generalDataWriteRequestDto, basisForTransfer, dto);
+            AssertMultiAssignment(request.SystemUsageUuids, dto.SystemUsages);
+            AssertOversight(oversightInput, dto.Oversight);
+            Assert.Equal(request.Name, dto.Name);
+            AssertOrganizationReference(organization, dto.OrganizationContext);
+            AssertSingleRight(role, userForRole, dto.Roles);
+            //TODO: Assertions for external references
         }

         private static void AssertEmptiedOversight(DataProcessingRegistrationOversightResponseDTO actual)


fixed code issue

fixed code issue

--- MQTTnet.Core/Server/MqttClientMessageQueue.cs
+++ MQTTnet.Core/Server/MqttClientMessageQueue.cs
@@ -56,7 +56,7 @@
             {
                 if (_pendingPublishPackets.Count == 0)
                 {
-                    await Task.Delay(TimeSpan.FromMilliseconds(5));
+                    await Task.Delay(TimeSpan.FromMilliseconds(5)).ConfigureAwait(false);
                     continue;
                 }


Relaxed EditWhileIteratingThreaded

Relaxed EditWhileIteratingThreaded

--- Tests/SystemTests/CollectionsTests/ConcurrentTests/ConcurrentDictionaryTestsEx.cs
+++ Tests/SystemTests/CollectionsTests/ConcurrentTests/ConcurrentDictionaryTestsEx.cs
@@ -86,6 +86,7 @@
     public partial class ConcurrentDictionaryTestsEx
     {
 #if !NETCOREAPP2_0
+
         // We should not rely on ConcurrentDictionary ordering
         // .NET CORE 2.0 seems to be unstable
         [Test]
@@ -142,7 +143,7 @@

             Assert.IsNull(value);
             var array = found.ToArray();
-            if (!array.IsSupersetOf(new[] {"0", "c"}))
+            if (!array.IsSupersetOf(new[] { "0", "c" }))
             {
                 foreach (var item in array)
                 {
@@ -164,9 +165,9 @@
         public void EditWhileIteratingThreaded()
         {
             var dictionary = new ConcurrentDictionary<string, string>();
-            Assert.IsTrue(dictionary.TryAdd("0", "1"));
-            Assert.IsTrue(dictionary.TryAdd("a", "b"));
-            int[] expectedCount = {2};
+            Assert.IsTrue(dictionary.TryAdd("original_key", "original_value"));
+            Assert.IsTrue(dictionary.TryAdd("original_key_to_remove", "original_value_to_remove"));
+            int[] expectedCount = { 2 };
             Assert.AreEqual(expectedCount[0], dictionary.Count);
             string value = null;
             var foundCount = 0;
@@ -176,7 +177,7 @@

             void Remover()
             {
-                var removed = dictionary.TryRemove("a", out value);
+                var removed = dictionary.TryRemove("original_key_to_remove", out value);
                 if (Volatile.Read(ref didRemove) == 0 && removed)
                 {
                     expectedCount[0]--;
@@ -190,7 +191,7 @@

             void Adder()
             {
-                var added = dictionary.TryAdd("c", "d");
+                var added = dictionary.TryAdd("added_key", "added_value");
                 if (Volatile.Read(ref didAdd) == 0 && added)
                 {
                     expectedCount[0]++;
@@ -214,6 +215,7 @@
                     var t = new Thread(Remover);
                     t.Start();
                     t.Join();
+                    Assert.AreEqual(1, didRemove);
                 }
                 if (foundCount == 1)
                 {
@@ -230,6 +232,7 @@
                     var t = new Thread(Adder);
                     t.Start();
                     t.Join();
+                    Assert.AreEqual(1, didAdd);
                 }
                 if (foundCount == 1)
                 {
@@ -243,24 +246,24 @@
                 Assert.AreEqual(expectedCount[0], dictionary.Count);
             }

-            Assert.IsNull(value);
             var array = found.ToArray();
-            if (!array.IsSupersetOf(new[] {"0", "c"}))
-            {
-                foreach (var item in array)
-                {
-                    Debug.WriteLine(item);
-                }
-
+            if (array[0] == "original_key")
+            {
+                if (array.Length > 1 && array[1] == "added_key" && array.Length > 2)
+                {
+                    Assert.Fail();
+                }
+            }
+            else if (array[0] != "original_key_to_remove")
+            {
                 Assert.Fail();
             }

             Assert.AreEqual(2, expectedCount[0]);
-            Assert.AreEqual(1, didAdd);
-            Assert.AreEqual(1, didRemove);
             Assert.IsTrue(foundCount - expectedCount[0] < 2, "foundCount: {0}, expectedCount:{1}", foundCount, expectedCount[0]);
             Assert.AreEqual(expectedCount[0], dictionary.Count);
         }
+
 #endif
     }
 }


Add support for object resources contained in secondary node sections

--- XbfAnalyzer/Xbf/XbfReader.cs
+++ XbfAnalyzer/Xbf/XbfReader.cs
@@ -1,5 +1,6 @@
 using System;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.IO;
 using System.Linq;
 using System.Text;
@@ -235,7 +236,7 @@
                     case 0x13: // Object collection begin
                         {
                             string propertyName = GetPropertyNameV2(reader.ReadUInt16());
-                            var objects = ReadObjectCollectionV2(reader, endPosition);
+                            var objects = ReadObjectCollectionV2(reader, endPosition, false);
                             obj.Properties.Add(new XbfObjectProperty(propertyName, objects));
                         }
                         break;
@@ -272,7 +273,7 @@
             throw new Exception("Reached end of stream before finishing object");
         }

-        private List<XbfObject> ReadObjectCollectionV2(BinaryReaderEx reader, int endPosition)
+        private List<XbfObject> ReadObjectCollectionV2(BinaryReaderEx reader, int endPosition, bool isSecondaryNodeSection)
         {
             List<XbfObject> result = new List<XbfObject>();

@@ -307,133 +308,65 @@

                     case 0x0F: // Reference to a different code section
                         {
-                            // The first value is the index of the node section that contains the fully-expanded nodes for this VisualStateGroup collection.
+                            // The first value is the index of the node section that contains the fully-expanded nodes for this collection.
                             int nodeSection = reader.Read7BitEncodedInt();

-                            // Get the expanded nodes from the specified section
+                            // Read the expanded nodes from the specified section
                             long originalPosition = reader.BaseStream.Position;
                             int newPosition = _firstNodeSectionPosition + _nodeSectionOffsets[nodeSection].Item1;
                             int newEndPosition = _firstNodeSectionPosition + _nodeSectionOffsets[nodeSection].Item2;

-                            // The first four bytes are: 0x01 (???), 0x13 (collection begin), 0x4681 (VisualStateManager.VisualStateGroups)
-                            newPosition += 4;
-
-                            // Go to the new position and read the objects
                             reader.BaseStream.Position = newPosition;
-                            var objectCollection = ReadObjectCollectionV2(reader, newEndPosition);
-                            // Add the objects to our list (although we could probably just replace our list since it should be empty)
+
+                            // Skip ahead to the actual values in the collection
+                            while (reader.BaseStream.Position < newEndPosition)
+                            {
+                                controlByte = reader.ReadByte();
+
+                                if (controlByte == 0x01) // Not sure what this means -- seems to appear at the beginning of visual state sections
+                                    continue;
+
+                                if (controlByte == 0x13)
+                                {
+                                    // This will be the property name we're getting values for. We already know what this value is (it should have appeared already, after the 0x14 that signaled the beginning of this collection).
+                                    reader.ReadUInt16();
+                                    break;
+                                }
+
+                                throw new Exception(string.Format("Unexpected control byte 0x{0:X2} in secondary node section", controlByte));
+                            }
+
+                            // Get the values
+                            var objectCollection = ReadObjectCollectionV2(reader, newEndPosition, true);
+
+                            // Add the objects to our list. (We could probably just replace our list since it should be empty.)
                             result.AddRange(objectCollection);

                             // Return to the original position
                             reader.BaseStream.Position = originalPosition;

+                            // Now we need to determine where this 0x0F section ends.
                             // All of the data we need is in the specified node section (that we just read from), but we still have to parse the remainder of this 0x0F section to determine how long it is.
-                            // I'm going to leave most of the parsing code here for now for clarity and in case I need it later.
-
-                            reader.ReadBytes(3); // TODO
-
-                            // Number of visual states
-                            int visualStateCount = reader.Read7BitEncodedInt();
-                            // The following bytes indicate which visual states belong in each group
-                            int[] visualStateGroupMemberships = new int[visualStateCount];
-                            for (int i = 0; i < visualStateCount; i++)
-                                visualStateGroupMemberships[i] = reader.Read7BitEncodedInt();
-
-                            // Number of visual states (again?)
-                            int visualStateCount2 = reader.Read7BitEncodedInt();
-                            if (visualStateCount != visualStateCount2)
-                                throw new Exception("Visual state counts did not match"); // TODO: What does it mean when this happens? Will it ever happen?
-
-                            // Get the VisualState objects
-                            var visualStates = new XbfObject[visualStateCount2];
-                            for (int i = 0; i < visualStateCount2; i++)
+
+                            reader.ReadBytes(2); // TODO -- I've only seen 0x0000 for these
+
+                            // Get the type of nodes contained in this section (?)
+                            int type = reader.Read7BitEncodedInt();
+
+                            switch (type)
                             {
-                                int nameID = reader.ReadUInt16();
-
-                                reader.ReadBytes(2); // TODO
-
-                                // Get the Setters for this VisualState
-                                int setterCount = reader.Read7BitEncodedInt();
-                                for (int j = 0; j < setterCount; j++)
-                                {
-                                    int setterOffset = reader.Read7BitEncodedInt();
-                                }
-
-                                // Get the AdaptiveTriggers for this VisualState
-                                int adaptiveTriggerCount = reader.Read7BitEncodedInt();
-                                for (int j = 0; j < adaptiveTriggerCount; j++)
-                                {
-                                    // I'm not sure what this second count is for -- possibly for the number of properties set on the trigger
-                                    int count2 = reader.Read7BitEncodedInt();
-                                    for (int k = 0; k < count2; k++)
-                                        reader.Read7BitEncodedInt(); // TODO (probably node stream offsets)
-                                }
-
-                                // Get the StateTriggers for this VisualState
-                                int stateTriggerCount = reader.Read7BitEncodedInt();
-                                for (int j = 0; j < stateTriggerCount; j++)
-                                {
-                                    reader.Read7BitEncodedInt();
-                                }
-
-                                int count = reader.Read7BitEncodedInt(); // TODO: What is this a count of?
-                                for (int j = 0; j < count; j++)
-                                {
-                                    reader.Read7BitEncodedInt(); // TODO
-                                }
-
-                                reader.ReadByte(); // TODO
-
-                                var vs = new XbfObject();
-                                vs.TypeName = "VisualState";
-                                vs.Name = StringTable[nameID];
-
-                                visualStates[i] = vs;
+                                case 2: // Styles
+                                    SkipStyleBytes(reader);
+                                    break;
+                                case 371: // Objects
+                                    SkipObjectBytes(reader);
+                                    break;
+                                case 5: // Visual states
+                                    SkipVisualStateBytes(reader);
+                                    break;
+                                default:
+                                    throw new Exception(string.Format("Unknown node type {0} while parsing referenced code section", type));
                             }
-
-                            // Number of VisualStateGroups
-                            int visualStateGroupCount = reader.Read7BitEncodedInt();
-
-                            // Get the VisualStateGroup objects
-                            var visualStateGroups = new XbfObject[visualStateGroupCount];
-                            for (int i = 0; i < visualStateGroupCount; i++)
-                            {
-                                int nameID = reader.ReadUInt16();
-                                reader.ReadByte(); // TODO
-
-                                // The offset within the node section for this VisualStateGroup
-                                int objectOffset = reader.Read7BitEncodedInt();
-
-                                var vsg = new XbfObject();
-                                vsg.TypeName = "VisualStateGroup";
-                                vsg.Name = StringTable[nameID];
-
-                                // Get the visual states that belong to this group
-                                var states = new List<XbfObject>();
-                                for (int j = 0; j < visualStateGroupMemberships.Length; j++)
-                                {
-                                    if (visualStateGroupMemberships[j] == i)
-                                        states.Add(visualStates[j]);
-                                }
-                                if (states.Count > 0)
-                                    vsg.Properties.Add(new XbfObjectProperty("States", states));
-
-                                visualStateGroups[i] = vsg;
-                            }
-
-                            reader.ReadBytes(5); // TODO
-
-                            // At the end we have a list of string references
-                            int stringCount = reader.Read7BitEncodedInt();
-                            for (int i = 0; i < stringCount; i++)
-                            {
-                                int nameID = reader.ReadUInt16(); // TODO
-                                System.Diagnostics.Debug.Print("Found string \"{0}\"", StringTable[nameID]);
-                            }
-
-                            // At this point we have a list of VisualStateGroup objects in the visualStateGroups variable.
-                            // These could be added to the result, but we already have them there from parsing the specified node section.
-                            //result.AddRange(visualStateGroups);
                         }
                         break;

@@ -458,7 +391,132 @@
                 }
             }

-            throw new Exception("Reached end of stream before finishing object collection");
+            if (!isSecondaryNodeSection)
+                throw new Exception("Reached end of stream before finishing object collection");
+
+            Debug.WriteLine("WARNING: ignoring early end-of-stream in secondary node section at position 0x{0:X}", reader.BaseStream.Position);
+            return result;
+        }
+
+        private void SkipStyleBytes(BinaryReaderEx reader)
+        {
+            throw new NotImplementedException();
+        }
+
+        private void SkipObjectBytes(BinaryReaderEx reader)
+        {
+            int count = reader.Read7BitEncodedInt();
+            for (int i = 0; i < count; i++)
+            {
+                reader.ReadUInt16(); // Name
+                reader.Read7BitEncodedInt(); // Secondary node stream offset
+            }
+            reader.ReadBytes(4); // Unknown
+        }
+
+        private void SkipVisualStateBytes(BinaryReaderEx reader)
+        {
+            // Number of visual states
+            int visualStateCount = reader.Read7BitEncodedInt();
+            // The following bytes indicate which visual states belong in each group
+            int[] visualStateGroupMemberships = new int[visualStateCount];
+            for (int i = 0; i < visualStateCount; i++)
+                visualStateGroupMemberships[i] = reader.Read7BitEncodedInt();
+
+            // Number of visual states (again?)
+            int visualStateCount2 = reader.Read7BitEncodedInt();
+            if (visualStateCount != visualStateCount2)
+                throw new Exception("Visual state counts did not match"); // TODO: What does it mean when this happens? Will it ever happen?
+
+            // Get the VisualState objects
+            var visualStates = new XbfObject[visualStateCount2];
+            for (int i = 0; i < visualStateCount2; i++)
+            {
+                int nameID = reader.ReadUInt16();
+
+                reader.ReadBytes(2); // TODO
+
+                // Get the Setters for this VisualState
+                int setterCount = reader.Read7BitEncodedInt();
+                for (int j = 0; j < setterCount; j++)
+                {
+                    int setterOffset = reader.Read7BitEncodedInt();
+                }
+
+                // Get the AdaptiveTriggers for this VisualState
+                int adaptiveTriggerCount = reader.Read7BitEncodedInt();
+                for (int j = 0; j < adaptiveTriggerCount; j++)
+                {
+                    // I'm not sure what this second count is for -- possibly for the number of properties set on the trigger
+                    int count2 = reader.Read7BitEncodedInt();
+                    for (int k = 0; k < count2; k++)
+                        reader.Read7BitEncodedInt(); // TODO (probably node stream offsets)
+                }
+
+                // Get the StateTriggers for this VisualState
+                int stateTriggerCount = reader.Read7BitEncodedInt();
+                for (int j = 0; j < stateTriggerCount; j++)
+                {
+                    reader.Read7BitEncodedInt();
+                }
+
+                int count = reader.Read7BitEncodedInt(); // TODO: What is this a count of?
+                for (int j = 0; j < count; j++)
+                {
+                    reader.Read7BitEncodedInt(); // TODO
+                }
+
+                reader.ReadByte(); // TODO
+
+                var vs = new XbfObject();
+                vs.TypeName = "VisualState";
+                vs.Name = StringTable[nameID];
+
+                visualStates[i] = vs;
+            }
+
+            // Number of VisualStateGroups
+            int visualStateGroupCount = reader.Read7BitEncodedInt();
+
+            // Get the VisualStateGroup objects
+            var visualStateGroups = new XbfObject[visualStateGroupCount];
+            for (int i = 0; i < visualStateGroupCount; i++)
+            {
+                int nameID = reader.ReadUInt16();
+                reader.ReadByte(); // TODO
+
+                // The offset within the node section for this VisualStateGroup
+                int objectOffset = reader.Read7BitEncodedInt();
+
+                var vsg = new XbfObject();
+                vsg.TypeName = "VisualStateGroup";
+                vsg.Name = StringTable[nameID];
+
+                // Get the visual states that belong to this group
+                var states = new List<XbfObject>();
+                for (int j = 0; j < visualStateGroupMemberships.Length; j++)
+                {
+                    if (visualStateGroupMemberships[j] == i)
+                        states.Add(visualStates[j]);
+                }
+                if (states.Count > 0)
+                    vsg.Properties.Add(new XbfObjectProperty("States", states));
+
+                visualStateGroups[i] = vsg;
+            }
+
+            reader.ReadBytes(5); // TODO
+
+            // At the end we have a list of string references
+            int stringCount = reader.Read7BitEncodedInt();
+            for (int i = 0; i < stringCount; i++)
+            {
+                int nameID = reader.ReadUInt16(); // TODO
+                System.Diagnostics.Debug.Print("Found string \"{0}\"", StringTable[nameID]);
+            }
+
+            // At this point we have a list of VisualStateGroup objects in the visualStateGroups variable.
+            // These could be added to the result, but we already have them there from parsing the specified node section.
         }

         private string GetTypeNameV2(int id)


Prevent displaying stars

Prevent displaying stars

--- EDDiscovery/UserControls/Overlays/UserControlSurveyor.cs
+++ EDDiscovery/UserControls/Overlays/UserControlSurveyor.cs
@@ -311,7 +311,7 @@
                                     (sd.HasMeaningfulVolcanism && hasVolcanismToolStripMenuItem.Checked) ||
                                     (sd.nEccentricity.HasValue && sd.nEccentricity >= eccentricityLimit && highEccentricityToolStripMenuItem.Checked) ||
                                     (sd.Terraformable && terraformableToolStripMenuItem.Checked) ||
-                                    (lowRadiusToolStripMenuItem.Checked && sd.nRadius.HasValue && sd.nRadius < lowRadiusLimit) ||
+                                    (sd.IsPlanet && lowRadiusToolStripMenuItem.Checked && sd.nRadius.HasValue && sd.nRadius < lowRadiusLimit) ||
                                     (sn.Signals != null && hasSignalsToolStripMenuItem.Checked) ||
                                     (sd.IsStar && showAllStarsToolStripMenuItem.Checked) ||
                                     (sd.IsPlanet && showAllPlanetsToolStripMenuItem.Checked) ||


(GH-458) Update Wyam reference from 2.2.7 to 2.2.8

--- Cake.Recipe/Content/toolsettings.cake
+++ Cake.Recipe/Content/toolsettings.cake
@@ -41,7 +41,7 @@
         string reSharperTools = "#tool nuget:?package=JetBrains.ReSharper.CommandLineTools&version=2019.2.2",
         string reSharperReportsTool = "#tool nuget:?package=ReSharperReports&version=0.4.0",
         string kuduSyncTool = "#tool nuget:?package=KuduSync.NET&version=1.5.2",
-        string wyamTool = "#tool nuget:?package=Wyam&version=2.2.7",
+        string wyamTool = "#tool nuget:?package=Wyam&version=2.2.8",
         string msbuildExtensionPackTool = "#tool nuget:?package=MSBuild.Extension.Pack&version=1.9.1",
         string xunitTool = "#tool nuget:?package=xunit.runner.console&version=2.4.1",
         string nunitTool = "#tool nuget:?package=NUnit.ConsoleRunner&version=3.10.0",


add filter when notifying observers

add filter when notifying observers

--- CoAP.NET/Server/Resources/Resource.cs
+++ CoAP.NET/Server/Resources/Resource.cs
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011-2014, Longxiang He <helongxiang@smeshlink.com>,
+ * Copyright (c) 2011-2015, Longxiang He <helongxiang@smeshlink.com>,
  * SmeshLink Technology Co.
  *
  * This program is distributed in the hope that it will be useful,
@@ -401,21 +401,45 @@
         /// transitively ancestor. If no ancestor defines its own executor, the
         /// thread that has called this method performs the notification.
         ///
+        /// <seealso cref="Changed(Func<ObserveRelation, Boolean>)"/>
         public void Changed()
+        {
+            Changed(null);
+        }
+
+        ///
+        /// Notifies a filtered set of CoAP clients that have established an observe
+	    /// relation with this resource that the state has changed by reprocessing
+	    /// their original request that has established the relation. The notification
+	    /// is done by the executor of this resource or on the executor of its parent or
+	    /// transitively ancestor. If no ancestor defines its own executor, the
+        /// thread that has called this method performs the notification.
+        ///
+        /// <param name="filter">the filter to select set of relations,
+        /// or null if all clients should be notified</param>
+        public void Changed(Func<ObserveRelation, Boolean> filter)
         {
             IExecutor executor = this.Executor;
             if (executor != null)
-                executor.Start(() => NotifyObserverRelations());
+                executor.Start(() => NotifyObserverRelations(filter));
             else
-                NotifyObserverRelations();
-        }
-
-        private void NotifyObserverRelations()
+                NotifyObserverRelations(filter);
+        }
+
+        ///
+        /// Notifies all CoAP clients that have established an observe relation with
+	    /// this resource that the state has changed by reprocessing their original
+        /// request that has established the relation.
+        ///
+        /// <param name="filter">the filter to select set of relations,
+        /// or null if all clients should be notified</param>
+        protected void NotifyObserverRelations(Func<ObserveRelation, Boolean> filter)
         {
             _notificationOrderer.GetNextObserveNumber();
             foreach (ObserveRelation relation in _observeRelations.Values)
             {
-                relation.NotifyObservers();
+                if (filter == null || filter(relation))
+                    relation.NotifyObservers();
             }
         }


Removed the assembly version number

Removed the assembly version number

--- ComputeClient/SolutionAssemblyInfo.cs
+++ ComputeClient/SolutionAssemblyInfo.cs
@@ -16,6 +16,6 @@
 [assembly: AssemblyCopyright("Copyright © Dimension Data 2015")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyCulture("")]
-[assembly: AssemblyVersion("3.0.235.0")]
-[assembly: AssemblyFileVersion("3.0.235.0")]
-[assembly: AssemblyInformationalVersion("3.0.235-develop")]+[assembly: AssemblyVersion("3.0.0.0")]
+[assembly: AssemblyFileVersion("3.0.0.0")]
+[assembly: AssemblyInformationalVersion("3.0.0")]


moved IsUnsigned to Tools

moved IsUnsigned to Tools

--- src/FastExpressionCompiler/FastExpressionCompiler.cs
+++ src/FastExpressionCompiler/FastExpressionCompiler.cs
@@ -3222,7 +3222,7 @@

                     case ExpressionType.AddChecked:
                     case ExpressionType.AddAssignChecked:
-                        il.Emit(IsUnsigned(exprType) ? OpCodes.Add_Ovf_Un : OpCodes.Add_Ovf);
+                        il.Emit(exprType.IsUnsigned() ? OpCodes.Add_Ovf_Un : OpCodes.Add_Ovf);
                         return true;

                     case ExpressionType.Subtract:
@@ -3232,7 +3232,7 @@

                     case ExpressionType.SubtractChecked:
                     case ExpressionType.SubtractAssignChecked:
-                        il.Emit(IsUnsigned(exprType) ? OpCodes.Sub_Ovf_Un : OpCodes.Sub_Ovf);
+                        il.Emit(exprType.IsUnsigned() ? OpCodes.Sub_Ovf_Un : OpCodes.Sub_Ovf);
                         return true;

                     case ExpressionType.Multiply:
@@ -3242,7 +3242,7 @@

                     case ExpressionType.MultiplyChecked:
                     case ExpressionType.MultiplyAssignChecked:
-                        il.Emit(IsUnsigned(exprType) ? OpCodes.Mul_Ovf_Un : OpCodes.Mul_Ovf);
+                        il.Emit(exprType.IsUnsigned() ? OpCodes.Mul_Ovf_Un : OpCodes.Mul_Ovf);
                         return true;

                     case ExpressionType.Divide:
@@ -3286,9 +3286,6 @@

                 return false;
             }
-
-            private static bool IsUnsigned(Type type) =>
-                type == typeof(byte) || type == typeof(ushort) || type == typeof(uint) || type == typeof(ulong);

             private static bool TryEmitLogicalOperator(BinaryExpression expr,
                 IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent)
@@ -3416,6 +3413,9 @@
         internal static bool IsValueType(this Type type) => type.GetTypeInfo().IsValueType;
         internal static bool IsPrimitive(this Type type) => type.GetTypeInfo().IsPrimitive;

+        internal static bool IsUnsigned(this Type type) =>
+            type == typeof(byte) || type == typeof(ushort) || type == typeof(uint) || type == typeof(ulong);
+
         internal static bool IsNullable(this Type type) =>
             type.GetTypeInfo().IsGenericType && type.GetTypeInfo().GetGenericTypeDefinition() == typeof(Nullable<>);


Added REST support for Authentication and SendMessage

--- MXitConnectionModule/SharpConnectionHelper.cs
+++ MXitConnectionModule/SharpConnectionHelper.cs
@@ -1,4 +1,8 @@
-using System;
+/// Mxit-Net-Connection-Helper
+/// Author: Eric Clements (Kazazoom) - eric@kazazoom.com
+/// License: BSD-3 (https://github.com/Kazazoom/mxit-net-connection-helper/blob/master/license.txt)
+
+using System;
 using System.Configuration;
 using System.Reflection;
 using System.Threading;
@@ -17,6 +21,15 @@

 namespace MXitConnectionModule
 {
+    /// <summary>
+    /// This singleton will manage C# API connections for you. It will do re-connection and retry logic transparently.
+    /// Call it from your Controller Class Start method with:
+    ///     MXitConnectionModule.ExternalAppAPI.CommsCallback callback = new Callback();
+    ///     MXitConnectionModule.ConnectionManager.Instance.InitializeConnection(externalAppNameTemp, externalAppPasswordTemp, callback);
+    ///
+    /// And where you want to send a message, simply call:
+    ///     MXitConnectionModule.ConnectionManager.Instance.SendMessage((MessageToSend)message);
+    /// </summary>
     class SharpConnectionHelperSingleton
     {
         private static readonly ILog logger = LogManager.GetLogger(typeof(SharpConnectionHelperSingleton));
@@ -234,7 +247,7 @@
             else
             {
                 //isTestMode:
-                return (new UserInfo("27832919456", "eric", DateTime.Now, "ZA", "ZA", "Johannesburg", DeviceInfo.DefaultDevice, GenderType.Male, "ZA"));
+                return (new UserInfo("yourmxitid", "yourname", DateTime.Now, "ZA", "ZA", "Johannesburg", DeviceInfo.DefaultDevice, GenderType.Male, "ZA"));
             }
         }


using TryGetIndexByRef

using TryGetIndexByRef

--- src/FastExpressionCompiler/FastExpressionCompiler.cs
+++ src/FastExpressionCompiler/FastExpressionCompiler.cs
@@ -2570,11 +2570,8 @@
                 // the only possibility that we are here is because we are in the nested lambda,
                 // and it uses the parameter or variable from the outer lambda
                 var nonPassedParams = closure.NonPassedParameters;
-                var nonPassedParamIndex = nonPassedParams.Length - 1;
-                while (nonPassedParamIndex != -1 && !ReferenceEquals(nonPassedParams[nonPassedParamIndex], paramExpr))
-                    --nonPassedParamIndex;
-                if (nonPassedParamIndex == -1)
-                    return false; // what??? no chance
+                if (!nonPassedParams.TryGetIndexByRef(paramExpr, out var nonPassedParamIndex))
+                    return false;

                 // Load non-passed argument from Closure - closure object is always a first argument
                 il.Emit(OpCodes.Ldarg_0);
@@ -2616,11 +2613,8 @@
                 // the only possibility that we are here is because we are in the nested lambda,
                 // and it uses the parameter or variable from the outer lambda
                 var nonPassedParams = closure.NonPassedParameters;
-                var nonPassedParamIndex = nonPassedParams.Length - 1;
-                while (nonPassedParamIndex != -1 && !ReferenceEquals(nonPassedParams[nonPassedParamIndex], paramExpr))
-                    --nonPassedParamIndex;
-                if (nonPassedParamIndex == -1)
-                    return false; // what??? no chance
+                if (!nonPassedParams.TryGetIndexByRef(paramExpr, out var nonPassedParamIndex))
+                    return false;

                 // Load non-passed argument from Closure - closure object is always a first argument
                 il.Emit(OpCodes.Ldarg_0);


Allow FileInfo redirection to take advantage of async operations on FileStream

--- MedallionShell/Streams/ProcessStreamReader.cs
+++ MedallionShell/Streams/ProcessStreamReader.cs
@@ -128,11 +128,11 @@
         /// </summary>
         public Task PipeToAsync(FileInfo file, bool leaveReaderOpen = false)
         {
-            Throw.IfNull(file, "file");
+            Throw.IfNull(file, nameof(file));

             // used over FileInfo.OpenWrite to get read file share, which seems potentially useful and
-            // not that harmful
-            var stream = new FileStream(file.FullName, FileMode.Create, FileAccess.Write, FileShare.Read);
+            // not that harmful. This also allows us to enable async. Note that 4096 is the default FileStream buffer size
+            var stream = new FileStream(file.FullName, FileMode.Create, FileAccess.Write, FileShare.Read, bufferSize: 4096, useAsync: true);
             return this.PipeToAsync(stream, leaveReaderOpen: leaveReaderOpen, leaveStreamOpen: false);
         }


Bug fix in unit test

Bug fix in unit test

--- DD4T.ViewModels.UnitTests/Tests.cs
+++ DD4T.ViewModels.UnitTests/Tests.cs
@@ -176,7 +176,7 @@
             var newModel = ViewModelDefaults.Builder.BuildCPViewModel<ContentContainerViewModel>(cp);
             //test
             Assert.AreEqual(3, newModel.Links.Count);
-            Assert.AreEqual(cp.Component.Id,
+            Assert.AreEqual(cp.Component.Fields["links"].EmbeddedValues[0]["internalLink"].LinkedComponentValues[0].Id,
                 newModel.Links.FirstOrDefault<EmbeddedLinkViewModel>().InternalLink.Id);
         }


Corrected a lack of caching issue

Corrected a lack of caching issue

git-svn-id: d0def854dd7af056e86ca9c2262ea22710193966@218 72444466-9f5c-4d9b-9c6f-db583910f96c

--- Framework/Cqrs.Azure.DocumentDb/AzureDocumentDbHelper.cs
+++ Framework/Cqrs.Azure.DocumentDb/AzureDocumentDbHelper.cs
@@ -60,6 +60,7 @@
 					Logger.LogDebug(string.Format("Returning the existing database took {0}", DateTime.Now - start), "AzureDocumentDbHelper\\CreateOrReadDatabase");
 					try
 					{
+						AzureDocumentDbConnectionCache.SetDatabase(databaseCacheKey, result);
 						return result;
 					}
 					finally


Remove more usages of Microsoft.VisualBasic.

--- source/SharpFlame/Painters/TileList.cs
+++ source/SharpFlame/Painters/TileList.cs
@@ -1,5 +1,4 @@
 using System;
-using Microsoft.VisualBasic;
 using SharpFlame.Mapping;
 using SharpFlame.Mapping.Tiles;

@@ -41,7 +40,8 @@
             int intRandom = 0;
             int Total = 0;

-            intRandom = (int)(Conversion.Int(VBMath.Rnd() * TileChanceTotal));
+            Random rnd = new Random ();
+            intRandom = rnd.Next () * TileChanceTotal;
             for ( A = 0; A <= TileCount - 1; A++ )
             {
                 Total += Convert.ToInt32(Tiles[A].Chance);


Dead code cleanup.

Dead code cleanup.

--- src/Features/Core/Portable/CodeRefactoringHelpers.cs
+++ src/Features/Core/Portable/CodeRefactoringHelpers.cs
@@ -47,130 +47,6 @@
             return !beginningNode.Span.IntersectsWith(selection.Start) || !endNode.Span.IntersectsWith(selection.End - 1);
         }

-        public static Task<bool> RefactoringSelectionIsValidAsync(
-            Document document, TextSpan selection, SyntaxNode node, CancellationToken cancellation)
-        {
-            return RefactoringSelectionIsValidAsync(document, selection, node, ImmutableArray<SyntaxNode>.Empty, cancellation);
-        }
-
-        /// <summary>
-        /// <para>
-        /// Determines if a refactoring should be offered for a given node, given the specified selection in a document.
-        /// The refactoring is offered either if the selection is zero-width and not inside one of the specified holes
-        /// or if the selection contains the entire node and perhaps some whitespace.
-        /// </para>
-        /// <para>
-        /// Note: this function considers the span containing the node to start at the earliest preceding whitespace
-        /// (including up to one newline) before the node’s <see cref="SyntaxNode.SpanStart"/> and up through the last
-        /// whitespace following the <see cref="SyntaxNode.Span"/>’s <see cref="TextSpan.End"/>.
-        /// </para>
-        /// <para>
-        /// For the <paramref name="holes"/>, the position is considered invalid if it is *within* the hole, not if it
-        /// is touching the hole edges.
-        /// </para>
-        /// </summary>
-        public static async Task<bool> RefactoringSelectionIsValidAsync(
-            Document document,
-            TextSpan selection,
-            SyntaxNode node,
-            ImmutableArray<SyntaxNode> holes,
-            CancellationToken cancellationToken)
-        {
-            if (selection.Length == 0)
-            {
-                return await RefactoringPositionIsValidAsync(
-                    document, selection.Start, node, holes, cancellationToken).ConfigureAwait(false);
-            }
-
-            // If we have a selection, it needs to be selecting at least the full node. We allow the selection to start
-            // in whitespace (including up to one newline) before the start of the node, and we allow it to end after
-            // the end of the node and the end of the line the node ends on.
-            var expandedSpan = await GetExpandedNodeSpan(document, node, cancellationToken).ConfigureAwait(false);
-            if ((selection.Start >= expandedSpan.Start && selection.Start <= node.SpanStart) &&
-                (selection.End >= node.Span.End && selection.End <= expandedSpan.End))
-            {
-                return true;
-            }
-
-            return false;
-        }
-
-        /// <summary>
-        /// <para>
-        /// Determines if a refactoring should be offered for a given node, given the specified position in a document.
-        /// The refactoring is offered if the position is somewhere on the span containing the node and not in any of
-        /// the specified <paramref name="holes"/> to avoid.
-        /// </para>
-        /// <para>
-        /// Note: this function considers the span containing the node to start at the earliest preceding whitespace
-        /// (including up to one newline) before the node’s <see cref="SyntaxNode.SpanStart"/> and up through the last
-        /// whitespace following the <see cref="SyntaxNode.Span"/>’s <see cref="TextSpan.End"/>.
-        /// </para>
-        /// <para>
-        /// For the <paramref name="holes"/>, the position is considered invalid if it is *within* the hole, not if it
-        /// is touching the hole edges.
-        /// </para>
-        /// </summary>
-        public static async Task<bool> RefactoringPositionIsValidAsync(
-            Document document,
-            int position,
-            SyntaxNode node,
-            ImmutableArray<SyntaxNode> holes,
-            CancellationToken cancellationToken)
-        {
-            var expandedSpan = await GetExpandedNodeSpan(document, node, cancellationToken).ConfigureAwait(false);
-            if (!expandedSpan.IntersectsWith(position))
-            {
-                // Position isn’t within the node’s widened span. Definitely not valid here.
-                return false;
-            }
-
-            foreach (var hole in holes)
-            {
-                if (position > hole.Span.Start && position < hole.Span.End)
-                {
-                    // Position was in one of the holes. Not valid here.
-                    return false;
-                }
-            }
-
-            return true;
-        }
-
-        private static Task<TextSpan> GetExpandedNodeSpan(Document document, SyntaxNode node, CancellationToken cancellationToken)
-        {
-            return GetExpandedTextSpan(document, node.Span, cancellationToken);
-        }
-
-        private static async Task<TextSpan> GetExpandedTextSpan(Document document, TextSpan span, CancellationToken cancellationToken)
-        {
-            var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
-
-            var nodeStartLine = sourceText.Lines.GetLineFromPosition(span.Start);
-
-            // Enable vertical selections that catch the previous line break and perhaps some whitespace.
-            if (nodeStartLine.LineNumber != 0)
-            {
-                nodeStartLine = sourceText.Lines[nodeStartLine.LineNumber - 1];
-            }
-
-            var nodeEndLine = sourceText.Lines.GetLineFromPosition(span.End);
-
-            var start = span.Start;
-            var end = span.End;
-
-            while (start > nodeStartLine.Start && char.IsWhiteSpace(sourceText[start - 1]))
-            {
-                start--;
-            }
-
-            while (end < nodeEndLine.End && char.IsWhiteSpace(sourceText[end]))
-            {
-                end++;
-            }
-
-            return TextSpan.FromBounds(start, end);
-        }

         /// <summary>
         /// Trims leading and trailing whitespace from <paramref name="span"/>.


Fix login for invited users.

Fix login for invited users.

--- backend/src/Squidex/Areas/IdentityServer/Controllers/Account/AccountController.cs
+++ backend/src/Squidex/Areas/IdentityServer/Controllers/Account/AccountController.cs
@@ -228,8 +228,9 @@
             }

             var isLoggedIn = result.Succeeded;
-
-            IUser? user;
+            var isLocked = false;
+
+            IUser? user = null;

             if (isLoggedIn)
             {
@@ -244,24 +245,41 @@
                     throw new DomainException(T.Get("users.noEmailAddress"));
                 }

-                var values = new UserValues
+                user = await userService.FindByEmailAsync(email!, HttpContext.RequestAborted);
+
+                // If we have a login, we reject this user, otherwise you can login to an account you do not own.
+                if (user != null && await HasLoginAsync(user))
                 {
-                    CustomClaims = login.Principal.Claims.GetSquidexClaims().ToList()
-                };
-
-                user = await userService.CreateAsync(email, values, identityOptions.LockAutomatically, HttpContext.RequestAborted);
-
-                await userService.AddLoginAsync(user.Id, login, HttpContext.RequestAborted);
-
-                (isLoggedIn, var locked) = await LoginAsync(login);
-
-                if (locked)
+                    user = null;
+                }
+
+                if (user == null)
                 {
-                    return View(nameof(LockedOut));
+                    var values = new UserValues
+                    {
+                        CustomClaims = login.Principal.Claims.GetSquidexClaims().ToList()
+                    };
+
+                    var locked = identityOptions.LockAutomatically;
+
+                    // Try to create a user. If the user exists an exception message is shown to the user.
+                    user = await userService.CreateAsync(email!, values, locked, HttpContext.RequestAborted);
                 }
-            }
-
-            if (!isLoggedIn)
+
+                if (user != null)
+                {
+                    await userService.AddLoginAsync(user.Id, login, HttpContext.RequestAborted);
+
+                    // Login might fail if the user is locked out.
+                    (isLoggedIn, isLocked) = await LoginAsync(login);
+                }
+            }
+
+            if (isLocked)
+            {
+                return View(nameof(LockedOut));
+            }
+            else if (!isLoggedIn)
             {
                 return RedirectToAction(nameof(Login));
             }
@@ -273,6 +291,18 @@
             {
                 return RedirectToReturnUrl(returnUrl);
             }
+        }
+
+        private async Task<bool> HasLoginAsync(IUser user)
+        {
+            if (await userService.HasPasswordAsync(user, HttpContext.RequestAborted))
+            {
+                return true;
+            }
+
+            var logins = await userService.GetLoginsAsync(user, HttpContext.RequestAborted);
+
+            return logins.Count > 0;
         }

         private async Task<(bool Success, bool Locked)> LoginAsync(UserLoginInfo externalLogin)


cleanup orphaned rules

cleanup orphaned rules

--- src/FilterLists.Services/Snapshot/SnapshotService.cs
+++ src/FilterLists.Services/Snapshot/SnapshotService.cs
@@ -33,6 +33,7 @@
         private async Task CleanupFailedSnapshots()
         {
             DbContext.RemoveRange(DbContext.SnapshotRules.Where(sr => !sr.Snapshot.WasSuccessful));
+            DbContext.RemoveRange(DbContext.Rules.Where(r => !r.SnapshotRules.Any()));
             await DbContext.SaveChangesAsync();
         }


Fix Post ratjer than Pre

Fix Post ratjer than Pre

--- DLaB.Xrm.Base/Plugin/Extensions.cs
+++ DLaB.Xrm.Base/Plugin/Extensions.cs
@@ -338,16 +338,13 @@
         /// <returns></returns>
         public static RegisteredEvent GetEvent(this IPluginExecutionContext context, IEnumerable<RegisteredEvent> events)
         {
-            return events.FirstOrDefault(a =>
-                (int)a.Stage == context.Stage
-                && a.MessageName == context.MessageName
-                && (string.IsNullOrWhiteSpace(a.EntityLogicalName) || a.EntityLogicalName == context.PrimaryEntityName)
-                )
-                ?? events.FirstOrDefault(a =>
-                (int)a.Stage == context.Stage
-                && a.Message == RegisteredEvent.Any
-                && (string.IsNullOrWhiteSpace(a.EntityLogicalName) || a.EntityLogicalName == context.PrimaryEntityName)
-                );
+            return events.Where(
+                    e =>
+                        (int) e.Stage == context.Stage
+                        && (e.MessageName == context.MessageName || e.Message == RegisteredEvent.Any)
+                        && (string.IsNullOrWhiteSpace(e.EntityLogicalName) || e.EntityLogicalName == context.PrimaryEntityName))
+                .OrderBy(e => e.MessageName == RegisteredEvent.Any) // Favor the specific message match first
+                .FirstOrDefault();
         }

         #region GetFirstSharedVariable
@@ -423,9 +420,9 @@
         /// <param name="context"></param>
         /// <param name="imageName"></param>
         /// <returns></returns>
-        public static T GetPostEntity<T>(this IExecutionContext context, string imageName) where T : Entity
-        {
-            return context.PreEntityImages.GetEntity<T>(imageName, DLaBExtendedPluginContextBase.PluginImageNames.PostImage);
+        public static T GetPostEntity<T>(this IExecutionContext context, string imageName = null) where T : Entity
+        {
+            return context.PostEntityImages.GetEntity<T>(imageName, DLaBExtendedPluginContextBase.PluginImageNames.PostImage);
         }

         #endregion Get(Pre/Post)Entities


Added content length to response

Added content length to response

--- Middlewares/Middlewares/EchoBodyMiddleWare.cs
+++ Middlewares/Middlewares/EchoBodyMiddleWare.cs
@@ -31,6 +31,7 @@
                     var body = await reader.ReadToEndAsync();
                     var bytes = Encoding.UTF8.GetBytes(body);

+                    response.ContentLength = bytes.Length;
                     await response.WriteAsync(bytes);
                 }
             }


fix getEntryByName for S3 File system

fix getEntryByName for S3 File system

--- src/FubarDev.FtpServer.FileSystem.S3/S3FileSystem.cs
+++ src/FubarDev.FtpServer.FileSystem.S3/S3FileSystem.cs
@@ -5,7 +5,6 @@
 using System;
 using System.Collections.Generic;
 using System.IO;
-using System.Linq;
 using System.Threading;
 using System.Threading.Tasks;

@@ -66,7 +65,7 @@
                 prefix += '/';
             }

-            return ListObjectsAsync(prefix, cancellationToken);
+            return ListObjectsAsync(prefix, false, cancellationToken);
         }

         /// <inheritdoc />
@@ -75,19 +74,18 @@
             string name,
             CancellationToken cancellationToken)
         {
-            var prefix = S3Path.Combine(((S3DirectoryEntry)directoryEntry).Key, name);
-
-            var objects = await ListObjectsAsync(prefix, cancellationToken);
-
-            if (objects.Count == 1 && objects.Single() is IUnixFileEntry entry)
-            {
+            var key = S3Path.Combine(((S3DirectoryEntry)directoryEntry).Key, name);
+
+            var entry = await GetObjectAsync(key, cancellationToken);
+            if (entry != null)
                 return entry;
-            }
-
+
+            // not a file search for directory
+            key += '/';
+
+            var objects = await ListObjectsAsync(key, true, cancellationToken);
             if (objects.Count > 0)
-            {
-                return new S3DirectoryEntry(prefix);
-            }
+                return new S3DirectoryEntry(key);

             return null;
         }
@@ -218,8 +216,35 @@
             return Task.FromResult(entry);
         }

+        private async Task<IUnixFileSystemEntry?> GetObjectAsync(string key, CancellationToken cancellationToken)
+        {
+            try
+            {
+                var s3Object = await _client.GetObjectMetadataAsync(
+                    new GetObjectMetadataRequest
+                    {
+                        BucketName = _options.BucketName,
+                        Key = key,
+                    }, cancellationToken);
+
+                if (key.EndsWith("/"))
+                    return new S3DirectoryEntry(key);
+
+                return new S3FileEntry(key, s3Object.Headers.ContentLength)
+                {
+                    LastWriteTime = s3Object.LastModified,
+                };
+            }
+            catch (AmazonS3Exception)
+            {
+            }
+
+            return null;
+        }
+
         private async Task<IReadOnlyList<IUnixFileSystemEntry>> ListObjectsAsync(
             string prefix,
+            bool includeSelf,
             CancellationToken cancellationToken)
         {
             var objects = new List<IUnixFileSystemEntry>();
@@ -247,7 +272,11 @@
                 {
                     if (s3Object.Key.EndsWith("/") && s3Object.Key == prefix)
                     {
-                        continue; // this is the folder itself
+                        // this is the folder itself
+                        if (includeSelf)
+                            objects.Add(new S3DirectoryEntry(s3Object.Key));
+
+                        continue;
                     }

                     objects.Add(


修改未接任務提醒只提醒每日或每週的任務

修改未接任務提醒只提醒每日或每週的任務

--- Grabacr07.KanColleViewer/ViewModels/GamePageViewModel.cs
+++ Grabacr07.KanColleViewer/ViewModels/GamePageViewModel.cs
@@ -46,7 +46,10 @@
 					return;
 			}

-			List<Quest> Quests = KanColleClient.Current.Homeport.Quests.All.Where(x => x.State == QuestState.None && x.Id / 100 == prefix).ToList();
+			List<Quest> Quests = KanColleClient.Current.Homeport.Quests.All
+				.Where(x => x.Type == QuestType.Daily || x.Type == QuestType.Weekly)
+				.Where(x => x.State == QuestState.None && x.Id / 100 == prefix)
+				.ToList();
 			if (Quests.Count > 0)
 			{
 				WindowsNotification.Notifier.Show(


Add button to test From-UrlEncoded with AntiCSRF in Header

--- ModelBindingASPNET4/Views/Home/ApiTest.cshtml
+++ ModelBindingASPNET4/Views/Home/ApiTest.cshtml
@@ -42,6 +42,9 @@

                 <button id="btnSubmitUrlEncodedWithAntiCsrf" type="submit" class="btn btn-default">Submit Form Encoded with AntiCSRF in Body</button>
+

+

+                <button id="btnSubmitUrlEncodedWithAntiCsrfInHeader" type="submit" class="btn btn-default">Submit Form Encoded with AntiCSRF in Header</button>

                 <button id="btnSubmitJsonWithAntiCsrf" type="submit" class="btn btn-default">Submit JSON with AntiCSRF in Header</button>
@@ -153,6 +156,15 @@
             return false;
         });

+        $('#btnSubmitUrlEncodedWithAntiCsrfInHeader').click(function () {
+            var $form = $(this).closest('form');
+            var data = $form.serialize();
+
+            postToControllerWithAntiCSRF(data, "application/x-www-form-urlencoded; charset=utf-8");
+
+            return false;
+        });
+
     </script>
 }


Added better support for native printing of constant sized arrays as C# fixed buffers.

--- src/Generator/Generators/CSharp/CSharpTypePrinter.cs
+++ src/Generator/Generators/CSharp/CSharpTypePrinter.cs
@@ -31,6 +31,7 @@
     {
         public string Type;
         public TypeMap TypeMap;
+        public string NameSuffix;

         public static implicit operator CSharpTypePrinterResult(string type)
         {
@@ -90,6 +91,20 @@
         public CSharpTypePrinterResult VisitArrayType(ArrayType array,
             TypeQualifiers quals)
         {
+            if (ContextKind == CSharpTypePrinterContextKind.Native &&
+                array.SizeType == ArrayType.ArraySize.Constant)
+            {
+                PrimitiveType primitive;
+                if (!array.Type.Desugar().IsPrimitiveType(out primitive))
+                    throw new NotSupportedException();
+
+                return new CSharpTypePrinterResult()
+                {
+                    Type = string.Format("fixed {0}", array.Type.Visit(this, quals)),
+                    NameSuffix = string.Format("[{0}]", array.Size)
+                };
+            }
+
             return string.Format("{0}[]", array.Type.Visit(this));

             // C# only supports fixed arrays in unsafe sections


Bucket SaveChangesAsync Test

Bucket SaveChangesAsync Test

--- MongoFramework.Tests/MongoDbBucketSetTests.cs
+++ MongoFramework.Tests/MongoDbBucketSetTests.cs
@@ -59,6 +59,29 @@
 			Assert.IsTrue(dbSet.Any(b => b.Group.Name == "Group1" && b.Items.Any(i => i.Label == "Entry1")));
 		}

+		[TestMethod]
+		public async Task SuccessfullyInsertAndQueryBackEntityBucketsAsync()
+		{
+			var database = TestConfiguration.GetDatabase();
+			var dbSet = new MongoDbBucketSet<EntityGroup, SubEntityClass>(new BucketSetOptions
+			{
+				BucketSize = 100
+			});
+			dbSet.SetDatabase(database);
+
+			dbSet.Add(new EntityGroup
+			{
+				Name = "Group1"
+			}, new SubEntityClass
+			{
+				Label = "Entry1"
+			});
+
+			Assert.IsFalse(dbSet.Any(b => b.Group.Name == "Group1"));
+			await dbSet.SaveChangesAsync();
+			Assert.IsTrue(dbSet.Any(b => b.Group.Name == "Group1" && b.Items.Any(i => i.Label == "Entry1")));
+		}
+
 		[TestMethod, ExpectedException(typeof(ArgumentException))]
 		public void InvalidBucketSize()
 		{


Only take visible controls into account for Extent.

--- src/GitHub.UI/Controls/ScollingVerticalStackPanel.cs
+++ src/GitHub.UI/Controls/ScollingVerticalStackPanel.cs
@@ -153,7 +153,12 @@
                     isFixed ? availableSize.Width : double.PositiveInfinity,
                     double.PositiveInfinity);
                 child.Measure(childConstraint);
-                maxWidth = Math.Max(maxWidth, child.DesiredSize.Width);
+
+                if (height - VerticalOffset < availableSize.Height)
+                {
+                    maxWidth = Math.Max(maxWidth, child.DesiredSize.Width);
+                }
+
                 height += child.DesiredSize.Height;
             }

@@ -167,16 +172,24 @@
         protected override Size ArrangeOverride(Size finalSize)
         {
             var y = -VerticalOffset;
+            var thisRect = new Rect(finalSize);
+            var visibleMaxWidth = 0.0;

             foreach (FrameworkElement child in Children)
             {
                 var isFixed = GetIsFixed(child);
                 var x = isFixed ? 0 : -HorizontalOffset;
-                child.Arrange(new Rect(x, y, child.DesiredSize.Width, child.DesiredSize.Height));
+                var childRect = new Rect(x, y, child.DesiredSize.Width, child.DesiredSize.Height);
+                child.Arrange(childRect);
                 y += child.DesiredSize.Height;
-            }
-
-            UpdateScrollInfo(new Size(ExtentWidth, ExtentHeight), finalSize);
+
+                if (childRect.IntersectsWith(thisRect) && childRect.Right > visibleMaxWidth)
+                {
+                    visibleMaxWidth = childRect.Right;
+                }
+            }
+
+            UpdateScrollInfo(new Size(visibleMaxWidth, ExtentHeight), new Size(finalSize.Width, finalSize.Height));
             return finalSize;
         }

@@ -184,6 +197,7 @@
         {
             ExtentWidth = extent.Width;
             ExtentHeight = extent.Height;
+            ScrollOwner?.InvalidateScrollInfo();
             ViewportWidth = viewport.Width;
             ViewportHeight = viewport.Height;
             ScrollOwner?.InvalidateScrollInfo();


Fix warnings

Fix warnings

--- NBitcoin/BIP174/PartiallySignedTransaction.cs
+++ NBitcoin/BIP174/PartiallySignedTransaction.cs
@@ -220,7 +220,6 @@
 			// It will be reassigned in `ReadWriteAsVarString` so no worry to assign 0 length array here.
 			byte[] k = new byte[0];
 			byte[] v = new byte[0];
-			var txFound = false;
 			stream.ReadWriteAsVarString(ref k);
 			while (k.Length != 0)
 			{
@@ -240,7 +239,6 @@
 							throw new FormatException("Malformed global tx. Unexpected size.");
 						if (tx.Inputs.Any(txin => txin.ScriptSig != Script.Empty || txin.WitScript != WitScript.Empty))
 							throw new FormatException("Malformed global tx. It should not contain any scriptsig or witness by itself");
-						txFound = true;
 						break;
 					case PSBTConstants.PSBT_GLOBAL_XPUB when XPubVersionBytes != null:
 						if (k.Length != 1 + XPubVersionBytes.Length + 74)
@@ -264,7 +262,7 @@
 				}
 				stream.ReadWriteAsVarString(ref k);
 			}
-			if (!txFound)
+			if (tx is null)
 				throw new FormatException("Invalid PSBT. No global TX");

 			int i = 0;


Fixed regression due to code cleanup

Fixed regression due to code cleanup

--- Nop.Plugin.Api/Services/CustomerApiService.cs
+++ Nop.Plugin.Api/Services/CustomerApiService.cs
@@ -518,10 +518,10 @@
         {
             return _cacheManager.Get(Configurations.NEWSLETTER_SUBSCRIBERS_KEY, () =>
             {
-                IEnumerable<String> subscriberEmails = from nls in _subscriptionRepository.Table
+                IEnumerable<String> subscriberEmails = (from nls in _subscriptionRepository.TableNoTracking
                     where nls.StoreId == _storeContext.CurrentStore.Id
                           && nls.Active
-                    select nls.Email;
+                    select nls.Email).ToList();

                 subscriberEmails = subscriberEmails.Where(e => !String.IsNullOrEmpty(e)).Select(e => e.ToLowerInvariant());


Included a test for json with invalid characters between.

--- src/Lime.Protocol.Tcp.UnitTests/TcpTransportTests.cs
+++ src/Lime.Protocol.Tcp.UnitTests/TcpTransportTests.cs
@@ -450,6 +450,97 @@

         [TestMethod]
         [TestCategory("ReceiveAsync")]
+        public async Task ReceiveAsync_MultipleReadsMultipleEnvelopesWithInvalidCharsBetween_ReadEnvelopeJsonFromStream()
+        {
+            var content = DataUtil.CreateTextContent();
+            var message = DataUtil.CreateMessage(content);
+
+            int messagesCount = DataUtil.CreateRandomInt(100) + 1;
+
+            var messageJsonQueue = new Queue<string>();
+
+            for (int i = 0; i < messagesCount; i++)
+            {
+                string messageJson;
+
+                do
+                {
+                    messageJson = DataUtil.CreateMessageJson();
+                } while (messageJsonQueue.Contains(messageJson));
+
+                messageJsonQueue.Enqueue(messageJson);
+            }
+
+            var messagesJsons = "  asdlkajsdkaskdasjkld  " + string.Join(" asdasdas ", messageJsonQueue);
+
+            var cancelationToken = DataUtil.CreateCancellationToken();
+
+            var bufferParts = DataUtil.CreateRandomInt(1000) + 1;
+
+            byte[] messageBuffer = Encoding.UTF8.GetBytes(
+                messagesJsons);
+
+            var bufferPartSize = messageBuffer.Length / bufferParts;
+
+
+            byte[][] messageBufferParts = new byte[bufferParts][];
+
+            for (int i = 0; i < bufferParts; i++)
+            {
+                if (i + 1 == bufferParts)
+                {
+                    messageBufferParts[i] = messageBuffer
+                        .Skip(i * bufferPartSize)
+                        .ToArray();
+                }
+                else
+                {
+                    messageBufferParts[i] = messageBuffer
+                    .Skip(i * bufferPartSize)
+                    .Take(bufferPartSize)
+                    .ToArray();
+                }
+            }
+
+            int bufferSize = messageBuffer.Length + DataUtil.CreateRandomInt(1000);
+            var stream = new TestStream(messageBufferParts);
+            var target = await GetTargetAndOpenAsync(bufferSize, stream);
+
+            _envelopeSerializer
+                .Setup(e => e.Deserialize(It.Is<string>(s => messageJsonQueue.Contains(s))))
+                .Returns(message)
+                .Callback(() => messageJsonQueue.Dequeue())
+                .Verifiable();
+
+            try
+            {
+                for (int i = 0; i < messagesCount; i++)
+                {
+                    var actual = await target.ReceiveAsync(cancelationToken);
+                    Assert.AreEqual(message, actual);
+                }
+
+                _stream.Verify();
+                _envelopeSerializer.Verify();
+
+                Assert.AreEqual(messageBufferParts.Length, stream.ReadCount);
+                Assert.AreEqual(0, messageJsonQueue.Count);
+            }
+            catch (Exception)
+            {
+                Debug.WriteLine("Buffer parts: {0}", messageBuffer.Length);
+                Debug.WriteLine("Buffer part size: {0}", bufferPartSize);
+                Debug.WriteLine("Buffer: ");
+                Debug.Write(messagesJsons);
+                Debug.WriteLine("");
+                Debug.Flush();
+
+                throw;
+            }
+        }
+
+        [TestMethod]
+        [TestCategory("ReceiveAsync")]
         public async Task ReceiveAsync_SingleReadBiggerThenBuffer_ClosesStreamAndThrowsInvalidOperationException()
         {
             var content = DataUtil.CreateTextContent();


Update RequestPostProcessorBehavior.cs

Update RequestPostProcessorBehavior.cs

fix: typo

--- src/MediatR/Pipeline/RequestPostProcessorBehavior.cs
+++ src/MediatR/Pipeline/RequestPostProcessorBehavior.cs
@@ -1,4 +1,4 @@
-.namespace MediatR.Pipeline
+namespace MediatR.Pipeline
 {
     using System.Collections.Generic;
     using System.Linq;


Network thread count defaults

Network thread count defaults

--- src/Microsoft.AspNet.Server.Kestrel/KestrelServer.cs
+++ src/Microsoft.AspNet.Server.Kestrel/KestrelServer.cs
@@ -75,14 +75,37 @@
                 _disposables.Push(engine);
                 _disposables.Push(dateHeaderValueManager);

+                // Actual core count would be a better number
+                // rather than logical cores which includes hyper-threaded cores.
+                // Divide by 2 for hyper-threading, and good defaults (still need threads to do webserving).
+                // Can be user overriden using IKestrelServerInformation.ThreadCount
+                var threadCount = Environment.ProcessorCount >> 1;
+
+                if (threadCount < 1)
+                {
+                    // Ensure shifted value is at least one
+                    threadCount = 1;
+                }
+                else if (threadCount > 16)
+                {
+                    // Receive Side Scaling RSS Processor count currently maxes out at 16
+                    // would be better to check the NIC's current hardware queues; but xplat...
+                    threadCount = 16;
+                }
+
                 if (information.ThreadCount < 0)
                 {
                     throw new ArgumentOutOfRangeException(nameof(information.ThreadCount),
                         information.ThreadCount,
                         "ThreadCount cannot be negative");
                 }
+                else if (information.ThreadCount > 0)
+                {
+                    // ThreadCount has been user set, use that value
+                    threadCount = information.ThreadCount;
+                }

-                engine.Start(information.ThreadCount == 0 ? 1 : information.ThreadCount);
+                engine.Start(threadCount);
                 var atLeastOneListener = false;

                 foreach (var address in information.Addresses)


Case insensitive X-GitHub-Request-Id

Case insensitive X-GitHub-Request-Id

--- Octokit/Clients/Enterprise/EnterpriseProbe.cs
+++ Octokit/Clients/Enterprise/EnterpriseProbe.cs
@@ -1,4 +1,5 @@
 using System;
+using System.Linq;
 using System.Net;
 using System.Net.Http;
 using System.Text.RegularExpressions;
@@ -103,7 +104,8 @@

         static bool IsEnterpriseResponse(IResponse response)
         {
-            return response.Headers.ContainsKey("X-GitHub-Request-Id");
+            // Use fix from https://github.com/octokit/octokit.net/pull/2175
+            return response.Headers.Any(h => string.Equals(h.Key, "X-GitHub-Request-Id", StringComparison.OrdinalIgnoreCase));
         }
     }

@@ -125,4 +127,4 @@
         /// </summary>
         Failed
     }
-}
+}


Fix JSON serialization for ZonedDateTime to use rrrr.

--- src/NodaTime.Serialization.JsonNet/NodaConverters.cs
+++ src/NodaTime.Serialization.JsonNet/NodaConverters.cs
@@ -64,7 +64,7 @@
         public static JsonConverter CreateZonedDateTimeConverter(IDateTimeZoneProvider provider)
         {
             return new NodaPatternConverter<ZonedDateTime>(
-                ZonedDateTimePattern.CreateWithInvariantCulture("yyyy'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFo<G> z", provider),
+                ZonedDateTimePattern.CreateWithInvariantCulture("rrrr'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFo<G> z", provider),
                 CreateIsoValidator<ZonedDateTime>(x => x.Calendar));
         }


* Okay, fixed the path cut offset, however the inner wall isn't properly 'cut' from the hull, so slightly better support, but still limited.

--- OpenSim/Region/Physics/Meshing/Meshmerizer.cs
+++ OpenSim/Region/Physics/Meshing/Meshmerizer.cs
@@ -415,9 +415,9 @@
             {
                 double fProfileBeginAngle = profileBegin / 50000.0 * 360.0;
                 // In degree, for easier debugging and understanding
-                fProfileBeginAngle -= (90.0 + 45.0); // for some reasons, the SL client counts from the corner -X/-Y
+                //fProfileBeginAngle -= (90.0 + 45.0); // for some reasons, the SL client counts from the corner -X/-Y
                 double fProfileEndAngle = 360.0 - profileEnd / 50000.0 * 360.0; // Pathend comes as complement to 1.0
-                fProfileEndAngle -= (90.0 + 45.0);
+                //fProfileEndAngle -= (90.0 + 45.0);
                 if (fProfileBeginAngle < fProfileEndAngle)
                     fProfileEndAngle -= 360.0;


Make media paths / urls mapping working under a virtual folder. (#3200)

--- src/OrchardCore.Modules/OrchardCore.Media/Startup.cs
+++ src/OrchardCore.Modules/OrchardCore.Media/Startup.cs
@@ -2,6 +2,7 @@
 using System.IO;
 using Fluid;
 using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Routing;
 using Microsoft.AspNetCore.StaticFiles;
 using Microsoft.Extensions.Configuration;
@@ -16,7 +17,6 @@
 using OrchardCore.DisplayManagement.Handlers;
 using OrchardCore.Environment.Shell;
 using OrchardCore.Environment.Shell.Configuration;
-using OrchardCore.FileStorage;
 using OrchardCore.FileStorage.FileSystem;
 using OrchardCore.Liquid;
 using OrchardCore.Media.Deployment;
@@ -80,7 +80,11 @@
                 var mediaPath = GetMediaPath(shellOptions.Value, shellSettings);
                 var fileStore = new FileSystemStore(mediaPath);

-                var mediaUrlBase = "/" + fileStore.Combine(shellSettings.RequestUrlPrefix, AssetsUrlPrefix);
+                var httpContextAccessor = serviceProvider.GetRequiredService<IHttpContextAccessor>();
+                var pathBase = httpContextAccessor.HttpContext.Request.PathBase;
+
+                // 'PathBase' includes the 'RequestUrlPrefix' and may start by a virtual folder.
+                var mediaUrlBase = pathBase.Add(AssetsUrlPrefix);

                 return new MediaFileStore(fileStore, mediaUrlBase);
             });


Initialize setup supported cultures only if there is a meta package (#6357)

--- src/OrchardCore.Modules/OrchardCore.Setup/Startup.cs
+++ src/OrchardCore.Modules/OrchardCore.Setup/Startup.cs
@@ -19,7 +19,7 @@
         private readonly string _defaultCulture = CultureInfo.InstalledUICulture.Name;

         private string[] _supportedCultures = new string[] {
-            "ar", "cs", "da", "de", "el", "en", "es", "fa", "fi", "fr", "he", "hr", "hu", "id", "it", "ja", "ko", "lt", "mk", "nl", "pl", "pt", "ru", "sk", "sl", "sr-cyrl-rs", "sr-latn-rs", "sv", "tr", "uk", "vi", "zh-CN", "zh-TW"
+            "ar", "cs", "de", "el", "en", "es", "fa", "fr", "it", "ja", "pl", "ru", "sv", "tr", "vi", "zh-CN", "zh-TW"
         };

         public Startup(IShellConfiguration shellConfiguration)


Added explicit parameter subtype specification. This allows the subtype of
a property to be specified in the config file allowing an appropriate
converter to be found for the string value. This allows the following to
be specified in the config file:

<layout type="log4net.Layout.PatternLayout" value="%d [%t] %-5p %c [%x] - %m%n" />

This leverages the pattern layout TypeConverter to convert the value into the
required type.

git-svn-id: 223c0ba935819ffdcafdc68147dc609b4e469b1e@312066 13f79535-47bb-0310-9956-ffa450edef68

--- src/Repository/Hierarchy/XmlHierarchyConfigurator.cs
+++ src/Repository/Hierarchy/XmlHierarchyConfigurator.cs
@@ -552,6 +552,35 @@
 						LogLog.Debug("XmlConfigurator: Security exception while trying to expand environment variables. Error Ignored. No Expansion.");
 					}
 #endif
+
+					// Check if a specific subtype is specified on the element using the 'type' attribute
+					string subTypeString = element.GetAttribute(TYPE_ATTR);
+					if (subTypeString != null && subTypeString.Length > 0)
+					{
+						// Read the explicit subtype
+						try
+						{
+							Type subType = SystemInfo.GetTypeFromString(subTypeString, true, true);
+
+							LogLog.Debug("XmlConfigurator: Parameter ["+name+"] specified subtype ["+subType.FullName+"]");
+
+							if (!propertyType.IsAssignableFrom(subType))
+							{
+								LogLog.Error("XmlConfigurator: Subtype ["+subType.FullName+"] set on ["+name+"] is not a subclass of property type ["+propertyType.FullName+"]");
+							}
+							else
+							{
+								// The subtype specified is found and is actually a subtype of the property
+								// type, therefore we can switch to using this type.
+								propertyType = subType;
+							}
+						}
+						catch(Exception ex)
+						{
+							LogLog.Error("XmlConfigurator: Failed to find type ["+subTypeString+"] set on ["+name+"]", ex);
+						}
+					}
+
 					// Now try to convert the string value to an acceptable type
 					// to pass to this property.


Suffix name for type with additional assembly name

This is so that there is no conflict when the same typename is used in different
assemblies. This happens frequently in linqpad interactive sessions because each
change in a script creates a new assembly which is loaded in the same AppDomain.

--- src/RestEase/Implementation/ImplementationBuilder.cs
+++ src/RestEase/Implementation/ImplementationBuilder.cs
@@ -221,6 +221,7 @@
             {
                 sb.Append(type.FullName.Replace('.', '+'));
             }
+            sb.Append("<>").Append(typeInfo.Assembly.GetName().Name.Replace('.', '+'));
         }

         private string CreateImplementationName(Type interfaceType)


Make 'requester' field in generated implementation readonly

--- src/RestEase/Implementation/ImplementationBuilder.cs
+++ src/RestEase/Implementation/ImplementationBuilder.cs
@@ -100,7 +100,7 @@
             typeBuilder.AddInterfaceImplementation(interfaceType);

             // Define a field which holds a reference to the IRequester
-            var requesterField = typeBuilder.DefineField("requester", typeof(IRequester), FieldAttributes.Private);
+            var requesterField = typeBuilder.DefineField("requester", typeof(IRequester), FieldAttributes.Private | FieldAttributes.InitOnly);

             // Add a constructor which takes the IRequester and assigns it to the field
             // public Name(IRequester requester)


Reissue minimize window message after the game exits

--- OriginSteamOverlayLauncher/ProcessTracking.cs
+++ OriginSteamOverlayLauncher/ProcessTracking.cs
@@ -188,7 +188,16 @@
                 */
             if (setHnd.LauncherPath != String.Empty && Program.IsRunningPID(launcherProc.Id) && !setHnd.DoNotClose)
             {// found the launcher left after the game exited
-                Thread.Sleep(setHnd.PostGameWaitTime * 1000); // let Origin sync with the cloud
+                Thread.Sleep(1000);
+
+                // resend the message to minimize our launcher
+                if (setHnd.MinimizeLauncher)
+                    Program.MinimizeWindow(launcherProc.MainWindowHandle);
+
+                // let Origin sync with the cloud
+                Thread.Sleep(setHnd.PostGameWaitTime - 1 * 1000);
+
+                // finally, kill our launcher proctree
                 Program.KillProcTreeByName(launcherName);
             }