Refactoring of MapAttendee and Organizer from Caldav to Outlook Finally the organizer is shown in the scheduling tab correctly Move organizer code to MapAttendeesAndOrganizer2To1

--- CalDavSynchronizer/Implementation/EntityMapper.cs
+++ CalDavSynchronizer/Implementation/EntityMapper.cs
@@ -42,6 +42,8 @@
     private const string PR_SENT_REPRESENTING_EMAIL_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x0065001E";
     private const string PR_SENT_REPRESENTING_ADDRTYPE = "http://schemas.microsoft.com/mapi/proptag/0x0064001E";
     private const string PR_SENDER_ADDRTYPE = "http://schemas.microsoft.com/mapi/proptag/0x0C1E001E";
+    private const string PR_SENT_REPRESENTING_ENTRYID = "http://schemas.microsoft.com/mapi/proptag/0x00410102";
+    private const string PR_SENDER_ENTRYID = "http://schemas.microsoft.com/mapi/proptag/0x0C190102";

     private readonly string _outlookEmailAddress;
     private readonly string _serverEmailUri;
@@ -806,95 +808,7 @@

       targetWrapper.Inner.Importance = MapPriority2To1 (source.Priority);

-      MapAttendees2To1 (source, targetWrapper.Inner);
-      if (source.Organizer != null)
-      {
-        string sourceOrganizerEmail = source.Organizer.Value.ToString().Substring (s_mailtoSchemaLength);
-        if (StringComparer.InvariantCultureIgnoreCase.Compare (sourceOrganizerEmail, _outlookEmailAddress) != 0)
-        {
-          targetWrapper.Inner.MeetingStatus = OlMeetingStatus.olMeetingReceived;
-
-            if (source.Organizer.CommonName != null)
-            {
-              try
-              {
-                targetWrapper.Inner.PropertyAccessor.SetProperty(PR_SENT_REPRESENTING_NAME, source.Organizer.CommonName);
-              }
-              catch (System.Runtime.InteropServices.COMException ex)
-              {
-                s_logger.Error("Could not set property PR_SENT_REPRESENTING_NAME for organizer", ex);
-              }
-              try
-              {
-                targetWrapper.Inner.PropertyAccessor.SetProperty(PR_SENDER_NAME, source.Organizer.CommonName);
-              }
-              catch (System.Runtime.InteropServices.COMException ex)
-              {
-                s_logger.Error("Could not set property PR_SENDER_NAME for organizer", ex);
-              }
-            }
-            else
-            {
-              try
-              {
-                targetWrapper.Inner.PropertyAccessor.SetProperty(PR_SENT_REPRESENTING_NAME, sourceOrganizerEmail);
-              }
-              catch (System.Runtime.InteropServices.COMException ex)
-              {
-                s_logger.Error("Could not set property PR_SENT_REPRESENTING_NAME for organizer", ex);
-              }
-              try
-              {
-                targetWrapper.Inner.PropertyAccessor.SetProperty(PR_SENDER_NAME, sourceOrganizerEmail);
-              }
-              catch (System.Runtime.InteropServices.COMException ex)
-              {
-                s_logger.Error("Could not set property PR_SENDER_NAME for organizer", ex);
-              }
-            }
-
-            try
-            {
-              targetWrapper.Inner.PropertyAccessor.SetProperty(PR_SENT_REPRESENTING_EMAIL_ADDRESS, sourceOrganizerEmail);
-            }
-            catch (System.Runtime.InteropServices.COMException ex)
-            {
-              s_logger.Error("Could not set property PR_SENT_REPRESENTING_EMAIL_ADDRESS for organizer", ex);
-            }
-            try
-            {
-              targetWrapper.Inner.PropertyAccessor.SetProperty(PR_SENT_REPRESENTING_ADDRTYPE, "SMTP");
-            }
-            catch (System.Runtime.InteropServices.COMException ex)
-            {
-              s_logger.Error("Could not set property PR_SENT_REPRESENTING_ADDRTYPE for organizer", ex);
-            }
-            try
-            {
-              targetWrapper.Inner.PropertyAccessor.SetProperty(PR_SENDER_EMAIL_ADDRESS, sourceOrganizerEmail);
-            }
-            catch (System.Runtime.InteropServices.COMException ex)
-            {
-              s_logger.Error("Could not set property PR_SENDER_EMAIL_ADDRESS for organizer", ex);
-            }
-            try
-            {
-              targetWrapper.Inner.PropertyAccessor.SetProperty(PR_SENDER_ADDRTYPE, "SMTP");
-            }
-            catch (System.Runtime.InteropServices.COMException ex)
-            {
-              s_logger.Error("Could not set property PR_SENDER_ADDRTYPE for organizer", ex);
-            }
-        }
-        else
-        {
-          targetWrapper.Inner.MeetingStatus = OlMeetingStatus.olMeeting;
-        }
-      }
-      else
-      {
-        targetWrapper.Inner.MeetingStatus = OlMeetingStatus.olNonMeeting;
-      }
+      MapAttendeesAndOrganizer2To1 (source, targetWrapper.Inner);

       if (!isRecurrenceException)
         MapRecurrance2To1 (source, recurrenceExceptionsOrNull, targetWrapper);
@@ -932,7 +846,7 @@
     }

-    private void MapAttendees2To1 (IEvent source, AppointmentItem target)
+    private void MapAttendeesAndOrganizer2To1 (IEvent source, AppointmentItem target)
     {
       var recipientsToDispose = new HashSet<Recipient>();
       try
@@ -966,6 +880,114 @@
           }
         }

+        if (source.Organizer != null)
+        {
+          string sourceOrganizerEmail = source.Organizer.Value.ToString().Substring(s_mailtoSchemaLength);
+          if (StringComparer.InvariantCultureIgnoreCase.Compare(sourceOrganizerEmail, _outlookEmailAddress) != 0)
+          {
+            Recipient targetRecipient = null;
+
+            target.MeetingStatus = OlMeetingStatus.olMeetingReceived;
+
+            targetRecipient = target.Recipients.Add(sourceOrganizerEmail);
+            recipientsToDispose.Add(targetRecipient);
+            targetRecipientsWhichShouldRemain.Add(targetRecipient);
+            targetRecipient.Type = (int)OlMeetingRecipientType.olOrganizer;
+
+            if (targetRecipient.Resolve())
+            {
+              try
+              {
+                target.PropertyAccessor.SetProperty(PR_SENT_REPRESENTING_ENTRYID, target.PropertyAccessor.StringToBinary(targetRecipient.AddressEntry.ID));
+                target.PropertyAccessor.SetProperty(PR_SENDER_ENTRYID, target.PropertyAccessor.StringToBinary(targetRecipient.AddressEntry.ID));
+              }
+              catch (System.Runtime.InteropServices.COMException ex)
+              {
+                s_logger.Error("Could not set property PR_SENDER_ENTRYID for organizer", ex);
+              }
+            }
+
+            if (source.Organizer.CommonName != null)
+            {
+              try
+              {
+                target.PropertyAccessor.SetProperty(PR_SENT_REPRESENTING_NAME, source.Organizer.CommonName);
+              }
+              catch (System.Runtime.InteropServices.COMException ex)
+              {
+                s_logger.Error("Could not set property PR_SENT_REPRESENTING_NAME for organizer", ex);
+              }
+              try
+              {
+                target.PropertyAccessor.SetProperty(PR_SENDER_NAME, source.Organizer.CommonName);
+              }
+              catch (System.Runtime.InteropServices.COMException ex)
+              {
+                s_logger.Error("Could not set property PR_SENDER_NAME for organizer", ex);
+              }
+            }
+            else
+            {
+              try
+              {
+                target.PropertyAccessor.SetProperty(PR_SENT_REPRESENTING_NAME, sourceOrganizerEmail);
+              }
+              catch (System.Runtime.InteropServices.COMException ex)
+              {
+                s_logger.Error("Could not set property PR_SENT_REPRESENTING_NAME for organizer", ex);
+              }
+              try
+              {
+                target.PropertyAccessor.SetProperty(PR_SENDER_NAME, sourceOrganizerEmail);
+              }
+              catch (System.Runtime.InteropServices.COMException ex)
+              {
+                s_logger.Error("Could not set property PR_SENDER_NAME for organizer", ex);
+              }
+            }
+            try
+            {
+              target.PropertyAccessor.SetProperty(PR_SENT_REPRESENTING_EMAIL_ADDRESS, sourceOrganizerEmail);
+            }
+            catch (System.Runtime.InteropServices.COMException ex)
+            {
+              s_logger.Error("Could not set property PR_SENT_REPRESENTING_EMAIL_ADDRESS for organizer", ex);
+            }
+            try
+            {
+              target.PropertyAccessor.SetProperty(PR_SENT_REPRESENTING_ADDRTYPE, "SMTP");
+            }
+            catch (System.Runtime.InteropServices.COMException ex)
+            {
+              s_logger.Error("Could not set property PR_SENT_REPRESENTING_ADDRTYPE for organizer", ex);
+            }
+            try
+            {
+              target.PropertyAccessor.SetProperty(PR_SENDER_EMAIL_ADDRESS, sourceOrganizerEmail);
+            }
+            catch (System.Runtime.InteropServices.COMException ex)
+            {
+              s_logger.Error("Could not set property PR_SENDER_EMAIL_ADDRESS for organizer", ex);
+            }
+            try
+            {
+              target.PropertyAccessor.SetProperty(PR_SENDER_ADDRTYPE, "SMTP");
+            }
+            catch (System.Runtime.InteropServices.COMException ex)
+            {
+              s_logger.Error("Could not set property PR_SENDER_ADDRTYPE for organizer", ex);
+            }
+          }
+          else
+          {
+            target.MeetingStatus = OlMeetingStatus.olMeeting;
+          }
+        }
+        else
+        {
+          target.MeetingStatus = OlMeetingStatus.olNonMeeting;
+        }
+
         for (int i = target.Recipients.Count; i > 0; i--)
         {
           var recipient = target.Recipients[i];


Cleanup ColorTable

Cleanup ColorTable

--- src/Atlas.Drawing/Serialization/BMP/ColorTable.cs
+++ src/Atlas.Drawing/Serialization/BMP/ColorTable.cs
@@ -1,9 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-
-namespace Atlas.Drawing.Serialization.BMP
+namespace Atlas.Drawing.Serialization.BMP
 {
     public class ColorTable
     {


Release meetingItem and fix possible Nullreference Exception if attendee has no Email address

--- CalDavSynchronizer/Implementation/EntityMapper.cs
+++ CalDavSynchronizer/Implementation/EntityMapper.cs
@@ -829,14 +829,17 @@

       if (source.Organizer != null)
       {
-        var ownSourceAttendee = source.Attendees.FirstOrDefault (a => StringComparer.InvariantCultureIgnoreCase.Compare (a.Value.ToString(), _serverEmailUri) == 0);
+        var ownSourceAttendee = source.Attendees.FirstOrDefault (a => StringComparer.InvariantCultureIgnoreCase.Compare ( a.Value!=null?a.Value.ToString():null, _serverEmailUri) == 0);
         if (ownSourceAttendee != null)
         {
           var response = MapParticipation2ToMeetingResponse (ownSourceAttendee.ParticipationStatus);
           if ((response != null) && (MapParticipation2To1 (ownSourceAttendee.ParticipationStatus) != targetWrapper.Inner.ResponseStatus))
           {
-            var newAppointment = targetWrapper.Inner.Respond (response.Value).GetAssociatedAppointment (false);
-            targetWrapper.Replace (newAppointment);
+            using (var newMeetingItem = GenericComObjectWrapper.Create(targetWrapper.Inner.Respond(response.Value)))
+            {
+              var newAppointment = newMeetingItem.Inner.GetAssociatedAppointment(false);
+              targetWrapper.Replace(newAppointment);
+            }
           }
         }
       }


Additional error handling. Add nice message when type can't be root imported

--- src/Bix.Mixers/Fody/ILCloning/ILCloningContext.cs
+++ src/Bix.Mixers/Fody/ILCloning/ILCloningContext.cs
@@ -341,6 +341,13 @@

             // do a root import of the declaring type
             var importedDeclaringType = this.RootImport(method.DeclaringType);
+            if (importedDeclaringType == null)
+            {
+                throw new InvalidOperationException(string.Format(
+                    "Method {0} has declaring type {1} which root-imported as null",
+                    method.FullName,
+                    method.DeclaringType == null ? method.DeclaringType.FullName : "null"));
+            }

             // generic instance methods are handled differently
             if (method.IsGenericInstance)
@@ -408,6 +415,17 @@
                 {
                     // import the method
                     var resolvedMethod = method.Resolve();
+                    var resolvedImportedDeclaringType = importedDeclaringType.Resolve();
+                    if (resolvedImportedDeclaringType == null)
+                    {
+                        // TODO any way to find the referenced assembly from the source reference and copy it over?
+                        throw new InvalidOperationException(string.Format(
+                            "Method {0} has declaring type {1} which root-imported as {2} but which resolved to null. Please make sure that your target project has a direct reference to the assembly containing the root-imported type.",
+                            method.FullName,
+                            method.DeclaringType,
+                            importedDeclaringType.FullName));
+                    }
+
                     var localMethod = importedDeclaringType.Resolve().Methods.FirstOrDefault(possibleMethod => possibleMethod.SignatureEquals(resolvedMethod, this));

                     importedMethod = this.RootTarget.Module.Import(localMethod);


[tests] Disable a out-of-proc test on mono

BuildManager_Tests.ShouldBuildMutatedProjectInstanceWhoseProjectWasPreviouslyBuiltAsAP2PDependency

--- src/Build.UnitTests/BackEnd/BuildManager_Tests.cs
+++ src/Build.UnitTests/BackEnd/BuildManager_Tests.cs
@@ -3906,6 +3906,7 @@
         }

         [Fact]
+        [Trait("Category", "mono-osx-failing")] // out-of-proc nodes not working on mono yet
         public void ShouldBuildMutatedProjectInstanceWhoseProjectWasPreviouslyBuiltAsAP2PDependency()
         {
             var mainProjectContents =


Added notes

Added notes

--- ChangeOrchestrator/Models/DataSourceAggregator.cs
+++ ChangeOrchestrator/Models/DataSourceAggregator.cs
@@ -7,6 +7,9 @@

     //Observer pattern
     //Use transaction(atomic or non-atomic?)
+    //1 Entity = Multi-data sources
+    //1 Entity = Multi-data sources identifier?
+    //1 Entity = Multi-data sources search keys(logs?)
     public class DataSourceAggregator : IDataSourceAggregator
     {
     }


(x) Fixed caching bug where Argument expression calls were not correctly rewritten in subsequent msbuild usages

--- src/Catel.Fody/Weaving/Argument/ArgumentWeaver.cs
+++ src/Catel.Fody/Weaving/Argument/ArgumentWeaver.cs
@@ -24,32 +24,10 @@
         #endregion

         #region Constructors
-        static ArgumentWeaver()
-        {
-            ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.NotNullAttribute"] = new IsNotNullArgumentMethodCallWeaver();
-            ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Argument.IsNotNull"] = new IsNotNullArgumentMethodCallWeaver();
-
-            ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.NotNullOrEmptyAttribute"] = new IsNotNullOrEmptyArgumentMethodCallWeaver();
-            ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Argument.IsNotNullOrEmpty"] = new IsNotNullOrEmptyArgumentMethodCallWeaver();
-
-            ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.NotNullOrWhitespaceAttribute"] = new IsNotNullOrWhitespaceArgumentMethodCallWeaver();
-            ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Argument.IsNotNullOrWhitespace"] = new IsNotNullOrWhitespaceArgumentMethodCallWeaver();
-
-            // TODO: Support the argument checks below in expression checks
-            ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.NotNullOrEmptyArrayAttribute"] = new IsNotNullOrEmptyArrayArgumentMethodCallWeaver();
-            ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.MatchAttribute"] = new IsMatchArgumentMethodCallWeaver();
-            ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.NotMatchAttribute"] = new IsNotMatchArgumentMethodCallWeaver();
-            ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.OfTypeAttribute"] = new IsOfTypeArgumentMethodCallWeave();
-            ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.ImplementsInterfaceAttribute"] = new ImplementsInterfaceArgumentMethodCallWeave();
-            ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.InheritsFromAttribute"] = new InheritsFromArgumentMethodCallWeaver();
-
-            //ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.NotOutOfRangeAttribute"] = new IsNotOutOfRangeMethodCallWeaver();
-            //ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.MinimalAttribute"] = new IsMinimalMethodCallWeaver();
-            //ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.MaximumAttribute"] = new IsMaximumMethodCallWeaver();
-        }
-
         public ArgumentWeaver(TypeDefinition typeDefinition, MsCoreReferenceFinder msCoreReferenceFinder)
         {
+            EnsureCache();
+
             _typeDefinition = typeDefinition;
             _msCoreReferenceFinder = msCoreReferenceFinder;
         }
@@ -178,6 +156,38 @@

             return false;
         }
+
+        private void EnsureCache()
+        {
+            lock (ArgumentMethodCallWeaverBase.WellKnownWeavers)
+            {
+                if (ArgumentMethodCallWeaverBase.WellKnownWeavers.Count > 0)
+                {
+                    return;
+                }
+
+                ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.NotNullAttribute"] = new IsNotNullArgumentMethodCallWeaver();
+                ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Argument.IsNotNull"] = new IsNotNullArgumentMethodCallWeaver();
+
+                ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.NotNullOrEmptyAttribute"] = new IsNotNullOrEmptyArgumentMethodCallWeaver();
+                ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Argument.IsNotNullOrEmpty"] = new IsNotNullOrEmptyArgumentMethodCallWeaver();
+
+                ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.NotNullOrWhitespaceAttribute"] = new IsNotNullOrWhitespaceArgumentMethodCallWeaver();
+                ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Argument.IsNotNullOrWhitespace"] = new IsNotNullOrWhitespaceArgumentMethodCallWeaver();
+
+                // TODO: Support the argument checks below in expression checks
+                ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.NotNullOrEmptyArrayAttribute"] = new IsNotNullOrEmptyArrayArgumentMethodCallWeaver();
+                ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.MatchAttribute"] = new IsMatchArgumentMethodCallWeaver();
+                ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.NotMatchAttribute"] = new IsNotMatchArgumentMethodCallWeaver();
+                ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.OfTypeAttribute"] = new IsOfTypeArgumentMethodCallWeave();
+                ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.ImplementsInterfaceAttribute"] = new ImplementsInterfaceArgumentMethodCallWeave();
+                ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.InheritsFromAttribute"] = new InheritsFromArgumentMethodCallWeaver();
+
+                //ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.NotOutOfRangeAttribute"] = new IsNotOutOfRangeMethodCallWeaver();
+                //ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.MinimalAttribute"] = new IsMinimalMethodCallWeaver();
+                //ArgumentMethodCallWeaverBase.WellKnownWeavers["Catel.Fody.MaximumAttribute"] = new IsMaximumMethodCallWeaver();
+            }
+        }
         #endregion
     }
 }


Fixed error in merge.

Fixed error in merge.

--HG--
branch : 1.3oob

--- src/CommandLine/Common/NuGetResources.Designer.cs
+++ src/CommandLine/Common/NuGetResources.Designer.cs
@@ -349,15 +349,6 @@
         }

         /// <summary>
-        ///   Looks up a localized string similar to List all versions of a package. By default, only the latest package version is displayed..
-        /// </summary>
-        internal static string ListCommandAllVersionsDescription {
-            get {
-                return ResourceManager.GetString("ListCommandAllVersionsDescription", resourceCulture);
-            }
-        }
-
-        /// <summary>
         ///   Looks up a localized string similar to Displays a list of packages at a given source. If no source is specified the default feed is used..
         /// </summary>
         internal static string ListCommandDescription {


Fuzztests Reading a writing to RHost

Fuzztests Reading a writing to RHost

--- src/Host/Protocol/Test/RHostPipe/RHostPipeTest.cs
+++ src/Host/Protocol/Test/RHostPipe/RHostPipeTest.cs
@@ -1,9 +1,6 @@
 // Copyright (c) Microsoft Corporation. All rights reserved.
 // Licensed under the MIT License. See LICENSE in the project root for license information.

-using Microsoft.Common.Core;
-using Microsoft.R.Interpreters;
-using Microsoft.UnitTests.Core.XUnit;
 using System;
 using System.Collections.Generic;
 using System.Diagnostics;
@@ -13,6 +10,11 @@
 using System.Text;
 using System.Threading;
 using System.Threading.Tasks;
+using FluentAssertions;
+using Microsoft.Common.Core;
+using Microsoft.R.Interpreters;
+using Microsoft.UnitTests.Core.XUnit;
+
 using static System.FormattableString;

 namespace Microsoft.R.Host.Protocol.Test.RHostPipe {
@@ -63,40 +65,54 @@
                 EnableRaisingEvents = true,
             };

-            process.ErrorDataReceived += (sender, e) => {
-            };
-
-            process.Exited += delegate {
-            };
-
-            try {
-                process.Start();
-                process.WaitForExit(250);
-                if (process.HasExited && process.ExitCode < 0) {
-                    // RODO: process failed to start
-                }
-            } catch (Exception) {
-                throw;
+            process.Start();
+            process.WaitForExit(250);
+            if (process.HasExited && process.ExitCode < 0) {
+                return;
             }

-            process.BeginErrorReadLine();
+            CancellationTokenSource cts = new CancellationTokenSource(3000);
+            Task.Run(() => {
+                cts.Token.WaitHandle.WaitOne();
+                TryKill(process);
+            }).DoNotWait();

-            await ReadAnyStartupOutputFromRHost(process.StandardOutput.BaseStream);
-            await SendFuzzedInputToRHost(process.StandardInput.BaseStream, input);
-            await ReadAnyOutputFromRHost(process.StandardOutput.BaseStream);
-            process.Kill();
+            await ReadStartupOutputFromRHostAsync(process.StandardOutput.BaseStream, cts.Token);
+            await SendFuzzedInputToRHostAsync(process.StandardInput.BaseStream, input, cts.Token);
+            ReadAnyOutputFromRHostAsync(process.StandardOutput.BaseStream, cts.Token).DoNotWait();
+
+            // Fuzzed input should not kill the host.
+            process.HasExited.Should().BeFalse();
+
+            TryKill(process);
         }

-        private Task ReadAnyStartupOutputFromRHost(Stream stream) {
-            throw new NotImplementedException();
+        private static void TryKill(Process process) {
+            try {
+                process.Kill();
+            } catch (Exception) { }
         }

-        private Task SendFuzzedInputToRHost(Stream stream, byte[] input) {
-            throw new NotImplementedException();
+        private async Task ReadStartupOutputFromRHostAsync(Stream stream, CancellationToken ct) {
+            // Capture R Startup messages.
+            byte[] buffer = new byte[1024*1024];
+            int bytesRead = 0;
+            do {
+                bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, ct);
+            } while (bytesRead == buffer.Length && !ct.IsCancellationRequested);
         }

-        private Task ReadAnyOutputFromRHost(Stream streamy) {
-            throw new NotImplementedException();
+        private async Task SendFuzzedInputToRHostAsync(Stream stream, byte[] input, CancellationToken ct) {
+            await stream.WriteAsync(input, 0, input.Length, ct);
+        }
+
+        private async Task ReadAnyOutputFromRHostAsync(Stream stream, CancellationToken ct) {
+            // Capture R messages after sending fuzzed input.
+            byte[] buffer = new byte[1024 * 1024];
+            int bytesRead = 0;
+            do {
+                bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, ct);
+            } while (!ct.IsCancellationRequested);
         }

         private Interpreter _interpreter;
@@ -107,7 +123,7 @@
             var interpreters = GetInterpreters();
             _interpreter = interpreters.FirstOrDefault();

-            for (int i = 0; i < 10; ++i) {
+            for (int i = 0; i < 100; ++i) {
                 byte[] input = GenerateInput();
                 await RHostPipeFuzzTestRunnerAsync(input);
             }
@@ -118,7 +134,7 @@
             using (BinaryWriter writer = new BinaryWriter(ms)) {
                 // Id =uint64
                 writer.Write(GenerateUInt64());
-                // Requestid = uint64
+                // Request id = uint64
                 writer.Write(GenerateUInt64());
                 // Name
                 writer.Write(GenerateAsciiString().ToCharArray());
@@ -133,27 +149,27 @@
             }
         }

-        private string GenerateAsciiString() {
-            byte[] rbuf = new byte[_rand.Next(0, 1024*1024)];
-            _rand.NextBytes(rbuf);
-            return Encoding.ASCII.GetString(rbuf);
-        }
-
-        private string GenerateUnicodeString(int max = 10000) {
+        private string GenerateAsciiString(int max = 10000) {
             byte[] rbuf = new byte[_rand.Next(0, max)];
             _rand.NextBytes(rbuf);
             return Encoding.ASCII.GetString(rbuf);
         }

+        private string GenerateUTF8String(int max = 10000) {
+            byte[] rbuf = new byte[_rand.Next(0, max)];
+            _rand.NextBytes(rbuf);
+            return Encoding.UTF8.GetString(rbuf);
+        }
+
         private string GenerateJsonArray() {
             if(_rand.Next()%2 == 0) {
                 // return random unicode string
-                return GenerateUnicodeString();
+                return GenerateUTF8String();
             }

             string[] parts = new string[_rand.Next(0,1000)];
             for(int i = 0; i < parts.Length; ++i) {
-                parts[i] = GenerateUnicodeString(100);
+                parts[i] = GenerateUTF8String(100);
             }

             // return a JSON array of random unicode strings


Fix for multiple spaces in the name.

Fix for multiple spaces in the name.

--- src/Jarvis.AvatarService/Support/AvatarBuilder.cs
+++ src/Jarvis.AvatarService/Support/AvatarBuilder.cs
@@ -157,7 +157,11 @@
             //If you not trim and fullname starts with space it throws.
             var sanitizedFullName = Sanitize(fullname).Trim();

-            var tokens = sanitizedFullName.ToUpperInvariant().Split(' ');
+            var tokens = sanitizedFullName
+                .ToUpperInvariant()
+                .Split(' ')
+                .Where(t => !String.IsNullOrEmpty(t))
+                .ToArray();
             string initials = tokens[0].Substring(0, 1);
             if (tokens.Length >= 3)
             {


Added sanitization when file name contains invalid chars.

--- src/Jarvis.AvatarService/Support/AvatarBuilder.cs
+++ src/Jarvis.AvatarService/Support/AvatarBuilder.cs
@@ -44,7 +44,8 @@
         public static string CreateFor(string userId, int size, string fullname)
         {
             var initials = GetInitials(fullname);
-            var pathToFile = Path.Combine(RootFolder, size.ToString(), string.Format("{0}_{1}.png", userId, initials)).ToLowerInvariant();
+            var pathToFileSanitized = FileNameSanitize(initials);
+            var pathToFile = Path.Combine(RootFolder, size.ToString(), string.Format("{0}_{1}.png", userId, pathToFileSanitized)).ToLowerInvariant();

             if (File.Exists(pathToFile))
                 return pathToFile;
@@ -62,8 +63,8 @@
             }

             return pathToFile;
-        }
-
+        }
+
         /// <summary>
         /// Creo un avatar da uno stream mettendolo nella cartella "Avatars"
         /// </summary>
@@ -198,7 +199,26 @@
                     sb.Append(c);
                 }
             }
-
+
+            return sb.ToString();
+        }
+
+        static Char[] invalidChars = Path.GetInvalidFileNameChars();
+
+        private static String FileNameSanitize(string stringToSanitize)
+        {
+            StringBuilder sb = new StringBuilder(stringToSanitize.Length);
+            foreach (var c in stringToSanitize)
+            {
+                if (invalidChars.Contains(c))
+                {
+                    sb.Append(((Int64)c).ToString());
+                }
+                else
+                {
+                    sb.Append(c);
+                }
+            }
             return sb.ToString();
         }
     }


fixed export to excel

fixed export to excel

--- Commencement/Controllers/Services/ExcelService.cs
+++ Commencement/Controllers/Services/ExcelService.cs
@@ -12,28 +12,20 @@
 {
     public interface IExcelService
     {
-        MemoryStream Create(List<string> columns, List<List<string>> rows, HttpServerUtilityBase server);
+        byte[] Create(List<string> columns, List<List<string>> rows, HttpServerUtilityBase server);
     }

     public class ExcelService : IExcelService
     {
-        private const string TemplateLocation = @"~\Content\NPOITemplate.xls";
-
-        public MemoryStream Create(List<string> columns, List<List<string>> rows, HttpServerUtilityBase server)
+        public byte[] Create(List<string> columns, List<List<string>> rows, HttpServerUtilityBase server)
         {
-            // Opening the Excel template...
-            var fs = new FileStream(server.MapPath(TemplateLocation), FileMode.Open, FileAccess.Read);
-
-            // Getting the complete workbook...
-            var templateWorkbook = new HSSFWorkbook(fs, true);
-
-            // Getting the worksheet by its name...
-            var sheet = templateWorkbook.GetSheetAt(0);// GetSheet("Sheet1");
+            var workbook = new HSSFWorkbook();
+            var sheet = workbook.CreateSheet("Sheet1");

             // create header style
-            var headerFont = templateWorkbook.CreateFont();
+            var headerFont = workbook.CreateFont();
             headerFont.Boldweight = (short)FontBoldWeight.BOLD;
-            var headerStyle = templateWorkbook.CreateCellStyle();
+            var headerStyle = workbook.CreateCellStyle();
             headerStyle.FillBackgroundColor = HSSFColor.GREY_40_PERCENT.index;
             headerStyle.FillForegroundColor = HSSFColor.GREY_40_PERCENT.index;
             headerStyle.FillPattern = FillPatternType.SOLID_FOREGROUND;
@@ -68,12 +60,11 @@
                 sheet.AutoSizeColumn(i);
             }

-            var ms = new MemoryStream();
-
-            // Writing the workbook content to the FileStream...
-            templateWorkbook.Write(ms);
-
-            return ms;
+            using (var ms = new MemoryStream())
+            {
+                workbook.Write(ms);
+                return ms.ToArray();
+            }
         }
     }
 }


Support for User project files added. (Still need to refactor IsFlavorDirty property)

--- Common/Product/SharedProject/CommonProjectNode.cs
+++ Common/Product/SharedProject/CommonProjectNode.cs
@@ -70,6 +70,7 @@
         private DiskMerger _currentMerger;
         private readonly HashSet<HierarchyNode> _needBolding = new HashSet<HierarchyNode>();
         private int _idleTriggered;
+        private bool _isUserFileDirty;

         public CommonProjectNode(CommonProjectPackage/*!*/ package, ImageList/*!*/ imageList) {
             Contract.Assert(package != null);
@@ -166,6 +167,24 @@
         public CommonPropertyPage PropertyPage {
             get { return _propPage; }
             set { _propPage = value; }
+        }
+
+        protected internal MSBuild.Project UserBuildProject {
+            get {
+                return userBuildProject;
+            }
+        }
+
+        protected bool IsUserProjectFileDirty {
+            get {
+                string document = this.GetMkDocument();
+
+                if (String.IsNullOrEmpty(document)) {
+                    return this._isUserFileDirty;
+                }
+
+                return (this._isUserFileDirty || !File.Exists(document + PerUserFileExtension));
+            }
         }

         #endregion
@@ -387,7 +406,7 @@
                 _watcher.Dispose();
             }

-            string userProjectFilename = FileName + ".user";
+            string userProjectFilename = FileName + PerUserFileExtension;
             if (File.Exists(userProjectFilename)) {
                 userBuildProject = BuildProject.ProjectCollection.LoadProject(userProjectFilename);
             }
@@ -457,7 +476,8 @@
             base.SaveMSBuildProjectFileAs(newFileName);

             if (userBuildProject != null) {
-                userBuildProject.Save(FileName + ".user");
+                userBuildProject.Save(FileName + PerUserFileExtension);
+                this._isUserFileDirty = false;
             }
         }

@@ -465,7 +485,8 @@
             base.SaveMSBuildProjectFile(filename);

             if (userBuildProject != null) {
-                userBuildProject.Save(filename + ".user");
+                userBuildProject.Save(filename + PerUserFileExtension);
+                this._isUserFileDirty = false;
             }
         }

@@ -503,12 +524,7 @@
                 BuildProject.SetProperty(CommonConstants.ProjectView, newPropValue);
             } else {
                 // save setting in user project file
-                if (userBuildProject == null) {
-                    // user project file doesn't exist yet, create it.
-                    userBuildProject = new MSBuild.Project(BuildProject.ProjectCollection);
-                    userBuildProject.FullPath = FileName + ".user";
-                }
-                userBuildProject.SetProperty(CommonConstants.ProjectView, newPropValue);
+                SetUserProjectProperty(CommonConstants.ProjectView, newPropValue);

             }
             SetProjectFileDirty(true);
@@ -1351,7 +1367,7 @@

         public override int IsDirty(out int isDirty) {
             isDirty = 0;
-            if (IsProjectFileDirty) {
+            if (IsProjectFileDirty || IsUserProjectFileDirty) {
                 isDirty = 1;
                 return VSConstants.S_OK;
             }
@@ -1642,6 +1658,37 @@
             }
         }

+        /// <summary>
+        /// Set value of user project property
+        /// </summary>
+        /// <param name="propertyName">Name of property</param>
+        /// <param name="propertyValue">Value of property</param>
+        public virtual void SetUserProjectProperty(string propertyName, string propertyValue) {
+            Utilities.ArgumentNotNull("propertyName", propertyName);
+
+            if (userBuildProject == null) {
+                // user project file doesn't exist yet, create it.
+                userBuildProject = new MSBuild.Project(BuildProject.ProjectCollection);
+                userBuildProject.FullPath = FileName + PerUserFileExtension;
+            }
+            userBuildProject.SetProperty(propertyName, propertyValue ?? String.Empty);
+            this._isUserFileDirty = true;
+        }
+
+        /// <summary>
+        /// Get value of user project property
+        /// </summary>
+        /// <param name="propertyName">Name of property</param>
+        public virtual string GetUserProjectProperty(string propertyName) {
+            Utilities.ArgumentNotNull("propertyName", propertyName);
+
+            if (userBuildProject == null)
+                return null;
+
+            // If user project file exists during project load/reload userBuildProject is initiated
+            return userBuildProject.GetPropertyValue(propertyName);
+        }
+
         #endregion

         #region IVsProjectSpecificEditorMap2 Members


-Added back bgr fix, since dx still consider bgr as valid whereas it's not.

--- Core/VVVV.DX11.Lib/Effects/DX11ImageShaderNode.cs
+++ Core/VVVV.DX11.Lib/Effects/DX11ImageShaderNode.cs
@@ -364,7 +364,13 @@
                         }

                         //Check format support for render target, and default to rgb8 if not
-                        if (!context.IsSupported(FormatSupport.RenderTarget, fmt)) { fmt = Format.R8G8B8A8_UNorm; }
+                        if (!context.IsSupported(FormatSupport.RenderTarget, fmt))
+                        {
+                            fmt = Format.R8G8B8A8_UNorm;
+                        }
+
+                        //Since device is not capable of telling us BGR not supported
+                        if (fmt == Format.B8G8R8A8_UNorm) { fmt = Format.R8G8B8A8_UNorm; }

                         DX11ResourcePoolEntry<DX11RenderTarget2D> elem = context.ResourcePool.LockRenderTarget(w, h, fmt, new SampleDescription(1, 0), mips, 0);


Some new terms

Some new terms

--- CorporateBsGenerator/Services/GeneratorService.cs
+++ CorporateBsGenerator/Services/GeneratorService.cs
@@ -12,7 +12,7 @@
             "continually", "conveniently", "credibly", "distinctively", "dramatically", "dynamically", "efficiently",
             "energistically", "enthusiastically", "globally", "holisticly", "interactively", "intrinsically", "monotonectally",
             "objectively", "phosfluorescently", "proactively", "professionally", "progressively", "quickly", "rapidiously",
-            "seamlessly", "synergistically", "uniquely", "fungibly"
+            "seamlessly", "synergistically", "uniquely", "fungibly", "disruptively", "randmonly"
             };

         private static List<string> Verbs = new List<string> {
@@ -26,7 +26,8 @@
             "procrastinate", "productivate", "productise", "promote", "provide access to", "pursue", "recaptiualise",
             "reconceptualise", "redefine", "re-engineer", "reintermediate", "reinvent", "repurpose", "restore", "revolutionise",
             "scale", "seize", "simplify", "strategise", "streamline", "supply", "syndicate", "synergise", "synthesize", "target",
-            "transform", "transition", "underwhelm", "unleash", "utilise", "visualise", "whiteboard", "cloudify", "right-shore"
+            "transform", "transition", "underwhelm", "unleash", "utilise", "visualise", "whiteboard", "cloudify", "right-shore",
+            "evangelise"
             };

         private static List<string> Adjectives = new List<string> {


Load "Folder Watcher" file content asynchronously

--- DesktopWidgets/Widgets/FolderWatcher/ViewModel.cs
+++ DesktopWidgets/Widgets/FolderWatcher/ViewModel.cs
@@ -2,6 +2,7 @@
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
+using System.Threading.Tasks;
 using System.Windows.Input;
 using System.Windows.Media.Imaging;
 using DesktopWidgets.Classes;
@@ -176,7 +177,7 @@
                                 x => x.EndsWith(Path.GetExtension(CurrentFilePath), StringComparison.OrdinalIgnoreCase)) &&
                             new FileInfo(CurrentFilePath).Length <= Settings.ShowContentMaxSize;
             if (isContent)
-                CurrentFileContent = File.ReadAllText(CurrentFilePath);
+                new Task(() => { CurrentFileContent = File.ReadAllText(CurrentFilePath); }).Start();
             return isContent;
         }


Small cleanup of Unknown.

Small cleanup of Unknown.

--- src/Qowaiv/Unknown.cs
+++ src/Qowaiv/Unknown.cs
@@ -1,5 +1,4 @@
-using System;
-using System.Collections.Generic;
+using System.Collections.Generic;
 using System.Globalization;
 using System.Linq;
 using System.Resources;
@@ -63,13 +62,13 @@
 		}

 		/// The resource manager managing the culture based string values.
-		private static Dictionary<CultureInfo, String[]> StringValues = new Dictionary<CultureInfo, String[]>()
+		private static Dictionary<CultureInfo, string[]> StringValues = new Dictionary<CultureInfo, string[]>()
 		{
-			{ CultureInfo.InvariantCulture, new string[]{ "?", "UNKNOWN", "NOT KNOWN", "NOTKNOWN" } },
+			{ CultureInfo.InvariantCulture, new []{ "?", "UNKNOWN", "NOT KNOWN", "NOTKNOWN" } },
 		};

 		/// The resource manager managing the culture based string values.
-		private static ResourceManager ResourceManager = new ResourceManager("Qowaiv.UnknownLabels", typeof(Unknown).Assembly);
+		private static readonly ResourceManager ResourceManager = new ResourceManager("Qowaiv.UnknownLabels", typeof(Unknown).Assembly);

 		/// The locker for adding a culture.
 		private static volatile object locker = new object();


Fix warning due to both Interlocked and volatile

--- source/FFImageLoading.Common/Work/WorkScheduler.cs
+++ source/FFImageLoading.Common/Work/WorkScheduler.cs
@@ -52,7 +52,7 @@
 		private bool _exitTasksEarly;
 		private bool _pauseWork;
 		private bool _isRunning;
-		private volatile int _currentPosition;
+		private int _currentPosition;

 		public WorkScheduler(IMiniLogger logger)
 		{
@@ -216,8 +216,8 @@
 		{
 			_logger.Debug(string.Format("Generating/retrieving image: {0}", task.GetKey()));

-			Interlocked.Increment(ref _currentPosition);
-			var currentPendingTask = new PendingTask() { Position = _currentPosition, ImageLoadingTask = task };
+			int position = Interlocked.Increment(ref _currentPosition);
+			var currentPendingTask = new PendingTask() { Position = position, ImageLoadingTask = task };
 			PendingTask alreadyRunningTaskForSameKey = null;
 			lock (_pauseWorkLock)
 			{
@@ -227,7 +227,7 @@
 					if (alreadyRunningTaskForSameKey == null)
 						_pendingTasks.Add(currentPendingTask);
 					else
-						alreadyRunningTaskForSameKey.Position = _currentPosition;
+						alreadyRunningTaskForSameKey.Position = position;
 				}
 			}


search assemblies in bin to support website

--- src/AnyLog/LogFactory.cs
+++ src/AnyLog/LogFactory.cs
@@ -35,6 +35,12 @@
             //Adds all the parts found in the same assembly as the Program class
             catalog.Catalogs.Add(new AssemblyCatalog(typeof(LogFactory).Assembly));
             catalog.Catalogs.Add(new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory, "*.dll"));
+
+            //For website, all assemblies locate in bin directory
+            var binDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin");
+
+            if(Directory.Exists(binDir))
+                catalog.Catalogs.Add(new DirectoryCatalog(binDir, "*.dll"));

             //Create the CompositionContainer with the parts in the catalog
             var container = new CompositionContainer(catalog);


lightweight shell builtin that executes managed applications inprocess in a dedeciated AppDomain

git-svn-id: c3b8989232654601f1acea7403f771adaaa44a81@1330 2c1201b4-01cd-e047-a400-b836ae1fbc61

--- src/Boo/Lang/Builtins.cs
+++ src/Boo/Lang/Builtins.cs
@@ -31,6 +31,7 @@
 	using System;
 	using System.Collections;
 	using System.Diagnostics;
+	using System.IO;
 	using System.Text;
 	using System.Reflection;

@@ -204,6 +205,68 @@
 			p.WaitForExit();
 			return output;
 		}
+
+		internal class AssemblyExecutor : MarshalByRefObject
+		{
+			string _filename;
+			string[] _arguments;
+			string _capturedOutput = "";
+
+			public AssemblyExecutor(string filename, string[] arguments)
+			{
+				_filename = filename;
+				_arguments = arguments;
+			}
+
+			public string CapturedOutput
+			{
+				get
+				{
+					return _capturedOutput;
+				}
+			}
+
+			public void Execute()
+			{
+				StringWriter output = new System.IO.StringWriter();
+				TextWriter saved = Console.Out;
+				try
+				{
+					Console.SetOut(output);
+					//AppDomain.CurrentDomain.ExecuteAssembly(_filename, null, _arguments);
+					Assembly.LoadFrom(_filename).EntryPoint.Invoke(null, new object[1] { _arguments });
+				}
+				finally
+				{
+					Console.SetOut(saved);
+					_capturedOutput = output.ToString();
+				}
+			}
+		}
+
+		/// <summary>
+		/// Execute the specified MANAGED application in a new AppDomain.
+		///
+		/// The base directory for the new application domain will be set to
+		/// directory containing filename (Path.GetDirectoryName(Path.GetFullPath(filename))).
+		/// </summary>
+		public static string shellm(string filename, string[] arguments)
+		{
+			AppDomainSetup setup = new AppDomainSetup();
+			setup.ApplicationBase = Path.GetDirectoryName(Path.GetFullPath(filename));
+
+			AppDomain domain = AppDomain.CreateDomain("shellm", null, setup);
+			try
+			{
+				AssemblyExecutor executor = new AssemblyExecutor(filename, arguments);
+				domain.DoCallBack(new CrossAppDomainDelegate(executor.Execute));
+				return executor.CapturedOutput;
+			}
+			finally
+			{
+				AppDomain.Unload(domain);
+			}
+		}

 		public static EnumerateEnumerator enumerate(object enumerable)
 		{


Added support for Claim.ValueType

Added support for Claim.ValueType

--- lib/JWTPayLoad.cs
+++ lib/JWTPayLoad.cs
@@ -264,11 +264,11 @@
                         this[jsonClaimType] = claimValues;
                     }

-                    claimValues.Add(claim.Value);
+                    claimValues.Add(GetClaimValueUsingValueType(claim));
                 }
                 else
                 {
-                    this.Add(jsonClaimType, claim.Value);
+                    this.Add(jsonClaimType, GetClaimValueUsingValueType(claim));
                 }
             }
         }
@@ -282,6 +282,56 @@
         public string Encode()
         {
             return Base64UrlEncoder.Encode(this.SerializeToJson());
+        }
+
+        internal object GetClaimValueUsingValueType(Claim claim)
+        {
+            if (claim.ValueType == ClaimValueTypes.Integer)
+            {
+                int intValue;
+                if (int.TryParse(claim.Value, out intValue))
+                {
+                    return intValue;
+                }
+            }
+
+            if (claim.ValueType == ClaimValueTypes.Integer32)
+            {
+                Int32 intValue;
+                if (Int32.TryParse(claim.Value, out intValue))
+                {
+                    return intValue;
+                }
+            }
+
+            if (claim.ValueType == ClaimValueTypes.Integer64)
+            {
+                Int64 intValue;
+                if (Int64.TryParse(claim.Value, out intValue))
+                {
+                    return intValue;
+                }
+            }
+
+            if (claim.ValueType == ClaimValueTypes.Boolean)
+            {
+                bool boolValue;
+                if (bool.TryParse(claim.Value, out boolValue))
+                {
+                    return boolValue;
+                }
+            }
+
+            if (claim.ValueType == ClaimValueTypes.Double)
+            {
+                double doubleValue;
+                if (double.TryParse(claim.Value, out doubleValue))
+                {
+                    return doubleValue;
+                }
+            }
+
+            return claim.Value;
         }

         internal string GetStandardClaim(string claimType)


git-svn-id: https://gorgonlib.googlecode.com/svn/branches/2.x@1601 a61f9e97-bd4c-0410-8c65-85b29eaa70ff

--- Dorian/Gorgon/Gorgon.Graphics/Fonts/GorgonFont.cs
+++ Dorian/Gorgon/Gorgon.Graphics/Fonts/GorgonFont.cs
@@ -873,11 +873,13 @@
 						{
 							char first = Convert.ToChar(pair.First);
 							char second = Convert.ToChar(pair.Second);
+                            var kernPair = new GorgonKerningPair(Convert.ToChar(first), Convert.ToChar(second));

 						    if (((availableCharacters.Contains(first)) || (availableCharacters.Contains(second)))
-						        && (pair.KernAmount != 0))
+						        && (pair.KernAmount != 0)
+                                && (!KerningPairs.ContainsKey(kernPair)))
 						    {
-						        KerningPairs.Add(new GorgonKerningPair(Convert.ToChar(first), Convert.ToChar(second)), pair.KernAmount);
+						        KerningPairs.Add(kernPair, pair.KernAmount);
 						    }
 						}
 					}


added Gendarme justifications

added Gendarme justifications

--- EPS.Utility/Reflection/ExtensionMethodSearcher.cs
+++ EPS.Utility/Reflection/ExtensionMethodSearcher.cs
@@ -17,8 +17,8 @@
         /// <remarks>   Collection is not cached. ebrown, 11/9/2010. </remarks>
         /// <typeparam name="T">    The Type to inspect. </typeparam>
         /// <returns>   A <see cref="System.Collections.Generic.List{MethodInfo}"/> with all the extension methods. </returns>
-        [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Scope = "method", Justification = "Convenience Overload / Acceptable usage since we're dealing with Types")]
-        [SuppressMessage("Gendarme.Rules.Design.Generic", "AvoidMethodWithUnusedGenericTypeRule")]
+        [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Convenience Overload / Acceptable usage since we're dealing with Types")]
+        [SuppressMessage("Gendarme.Rules.Design.Generic", "AvoidMethodWithUnusedGenericTypeRule", Justification = "Convenience Overload / Acceptable usage since we're dealing with Types")]
         public static IList<MethodInfo> GetExtensionMethodsInCurrentAssemblies<T>()
         {
             return GetExtensionMethodsInCurrentAssemblies(typeof(T));


Sorts methods

Sorts methods

--- code/Main.cs
+++ code/Main.cs
@@ -671,19 +671,19 @@
 		/// <summary>
 		/// Synchronizes the inbox if the selected day of week is today
 		/// </summary>
+		private void FieldStartTime_TextChanged(object sender, EventArgs e) {
+			if (SchedulerService != null && SchedulerService.GetDayOfWeek(fieldDayOfWeek.SelectedIndex) == DateTime.Now.DayOfWeek) {
+				GmailService.Inbox.Sync();
+			}
+		}
+
+		/// <summary>
+		/// Synchronizes the inbox if the selected day of week is today
+		/// </summary>
 		private void FieldEndTime_TextChanged(object sender, EventArgs e) {
 			if (SchedulerService != null && SchedulerService.GetDayOfWeek(fieldDayOfWeek.SelectedIndex) == DateTime.Now.DayOfWeek) {
 				GmailService.Inbox.Sync();
 			}
 		}
-
-		/// <summary>
-		/// Synchronizes the inbox if the selected day of week is today
-		/// </summary>
-		private void FieldStartTime_TextChanged(object sender, EventArgs e) {
-			if (SchedulerService != null && SchedulerService.GetDayOfWeek(fieldDayOfWeek.SelectedIndex) == DateTime.Now.DayOfWeek) {
-				GmailService.Inbox.Sync();
-			}
-		}
 	}
 }


ignore empty input

ignore empty input

--- src/ConsoleMenu/CMenu.cs
+++ src/ConsoleMenu/CMenu.cs
@@ -271,8 +271,12 @@
 					Console.Write ("$ ");
 					input = Console.ReadLine ();
 				}
+
+				if (string.IsNullOrWhiteSpace (input)) {
+					continue;
+				}
+
 				var cmd = SplitFirstWord (ref input);
-
 				var it = GetMenuItem (cmd, true);
 				if (it == null) {
 					continue;


make this static

make this static

--- src/Security/Items.cs
+++ src/Security/Items.cs
@@ -69,7 +69,7 @@
 		RSA, EC
 	}

-	public class SecKeyChain {
+	public static class SecKeyChain {
 		static NSNumber SetLimit (NSMutableDictionary dict, int max)
 		{
 			NSNumber n = null;


Prioritize anchor before insert (#8936)

Prioritize anchor before insert (#8936)

--- Content.Shared/Construction/EntitySystems/SharedAnchorableSystem.cs
+++ Content.Shared/Construction/EntitySystems/SharedAnchorableSystem.cs
@@ -1,5 +1,6 @@
 using System.Threading.Tasks;
 using Content.Shared.Construction.Components;
+using Content.Shared.Containers.ItemSlots;
 using Content.Shared.Interaction;
 using Content.Shared.Pulling.Components;
 using Content.Shared.Tools.Components;
@@ -12,7 +13,8 @@
     {
         base.Initialize();

-        SubscribeLocalEvent<AnchorableComponent, InteractUsingEvent>(OnInteractUsing, after: new[] { typeof(SharedConstructionSystem) });
+        SubscribeLocalEvent<AnchorableComponent, InteractUsingEvent>(OnInteractUsing,
+            before: new[] { typeof(ItemSlotsSystem) }, after: new[] { typeof(SharedConstructionSystem) });
     }

     private void OnInteractUsing(EntityUid uid, AnchorableComponent anchorable, InteractUsingEvent args)


Updated ALPC flags.

Updated ALPC flags.

--- NtApiDotNet/NtAlpcNative.cs
+++ NtApiDotNet/NtAlpcNative.cs
@@ -111,7 +111,7 @@
     {
         None = 0,
         LpcPort = 0x1000, // Not accessible outside the kernel.
-        Unknown10000 = 0x10000,
+        AllowImpersonation = 0x10000,
         AllowLpcRequests = 0x20000,
         WaitablePort = 0x40000,
         AllowDupObject = 0x80000,
@@ -119,7 +119,12 @@
         LrpcWakePolicy1 = 0x200000,
         LrpcWakePolicy2 = 0x400000,
         LrpcWakePolicy3 = 0x800000,
-        NoCompleteDupObject = 0x2000000, // If not set then object duplication won't complete.
+        Unknown1000000 = 0x1000000,
+        /// <summary>
+        /// If set then object duplication won't complete. Used by RPC to ensure
+        /// multi-handle attributes don't fail when receiving.
+        /// </summary>
+        NoCompleteDupObject = 0x2000000,
     }

     [StructLayout(LayoutKind.Sequential)]


Rework NtSystemInfo class.

Rework NtSystemInfo class.

--- NtApiDotNet/NtSystemInfo.cs
+++ NtApiDotNet/NtSystemInfo.cs
@@ -476,6 +476,19 @@
         public UIntPtr MaximumUserModeAddress;
         public UIntPtr ActiveProcessorsAffinityMask;
         public sbyte NumberOfProcessors;
+    }
+
+    [StructLayout(LayoutKind.Sequential)]
+    public struct SystemElamCertificateInformation
+    {
+        public IntPtr ElamDriverFile;
+    }
+
+    [StructLayout(LayoutKind.Sequential)]
+    public struct SystemCodeIntegrityCertificateInformation
+    {
+        public IntPtr ImageFile;
+        public int Type;
     }

     public enum SystemInformationClass
@@ -1014,7 +1027,7 @@
             return status == NtStatus.STATUS_INFO_LENGTH_MISMATCH || status == NtStatus.STATUS_BUFFER_TOO_SMALL;
         }

-        private static SafeStructureInOutBuffer<T> QuerySystemInfoVariable<T>(SystemInformationClass info_class) where T : new()
+        private static SafeStructureInOutBuffer<T> QueryBuffer<T>(SystemInformationClass info_class) where T : new()
         {
             int length = 0x1000;
             while (true)
@@ -1031,7 +1044,7 @@
                         continue;
                     }
                     status.ToNtException();
-                    return buffer.Detach();
+                    return buffer.Detach(return_length);
                 }
             }
         }
@@ -1046,14 +1059,18 @@
             }
         }

+        private static NtResult<T> QuerySystemInfo<T>(T data, SystemInformationClass info_class, bool throw_on_error) where T : struct
+        {
+            using (var buffer = data.ToBuffer())
+            {
+                return NtSystemCalls.NtQuerySystemInformation(info_class, buffer,
+                    buffer.Length, out int ret_length).CreateResult(throw_on_error, () => buffer.Result);
+            }
+        }
+
         private static T QuerySystemInfo<T>(T data, SystemInformationClass info_class) where T : struct
         {
-            using (var buffer = data.ToBuffer())
-            {
-                NtSystemCalls.NtQuerySystemInformation(info_class, buffer,
-                    buffer.Length, out int ret_length).ToNtException();
-                return buffer.Result;
-            }
+            return QuerySystemInfo(data, info_class, true).Result;
         }

         private static T QuerySystemInfo<T>(SystemInformationClass info_class) where T : struct
@@ -1107,7 +1124,17 @@
             return QuerySystemInfo(new SystemBasicInformation(), SystemInformationClass.SystemBasicInformation);
         }

+        private static NtStatus Set<T>(SystemInformationClass info_class, T value) where T : new()
+        {
+            using (var buffer = value.ToBuffer())
+            {
+                return NtSystemCalls.NtSetSystemInformation(info_class, buffer, buffer.Length);
+            }
+        }
+
         #endregion
+
+        #region Static Methods

         /// <summary>
         /// Get a list of handles
@@ -1117,7 +1144,7 @@
         /// <returns>The list of handles</returns>
         public static IEnumerable<NtHandle> GetHandles(int pid, bool allow_query)
         {
-            using (var buffer = QuerySystemInfoVariable<SystemHandleInformationEx>(SystemInformationClass.SystemExtendedHandleInformation))
+            using (var buffer = QueryBuffer<SystemHandleInformationEx>(SystemInformationClass.SystemExtendedHandleInformation))
             {
                 var handle_info = buffer.Result;
                 int handle_count = handle_info.NumberOfHandles.ToInt32();
@@ -1171,7 +1198,7 @@
         /// <returns>The list of process information.</returns>
         public static IEnumerable<NtProcessInformation> GetProcessInformation()
         {
-            using (var process_info = QuerySystemInfoVariable<SystemProcessInformation>(SystemInformationClass.SystemProcessInformation))
+            using (var process_info = QueryBuffer<SystemProcessInformation>(SystemInformationClass.SystemProcessInformation))
             {
                 int offset = 0;
                 while (true)
@@ -1199,7 +1226,7 @@
         /// <returns>The list of page file names.</returns>
         public static IEnumerable<string> GetPageFileNames()
         {
-            using (var buffer = QuerySystemInfoVariable<SystemPageFileInformation>(SystemInformationClass.SystemPageFileInformation))
+            using (var buffer = QueryBuffer<SystemPageFileInformation>(SystemInformationClass.SystemPageFileInformation))
             {
                 int offset = 0;
                 while (true)
@@ -1215,6 +1242,311 @@
             }
         }

+        /// <summary>
+        /// Create a kernel dump for current system.
+        /// </summary>
+        /// <param name="path">The path to the output file.</param>
+        /// <param name="flags">Flags</param>
+        /// <param name="page_flags">Page flags</param>
+        public static void CreateKernelDump(string path, SystemDebugKernelDumpControlFlags flags, SystemDebugKernelDumpPageControlFlags page_flags)
+        {
+            NtToken.EnableDebugPrivilege();
+            using (NtFile file = NtFile.Create(path, FileAccessRights.Synchronize | FileAccessRights.GenericWrite | FileAccessRights.GenericRead,
+                    FileShareMode.Read, FileOpenOptions.SynchronousIoNonAlert | FileOpenOptions.WriteThrough | FileOpenOptions.NoIntermediateBuffering, FileDisposition.OverwriteIf,
+                    null))
+            {
+                using (var buffer = new SystemDebugKernelDumpConfig()
+                {
+                    FileHandle = file.Handle.DangerousGetHandle(),
+                    Flags = flags,
+                    PageFlags = page_flags
+                }.ToBuffer())
+                {
+                    NtSystemCalls.NtSystemDebugControl(SystemDebugControlCode.KernelCrashDump, buffer, buffer.Length,
+                        SafeHGlobalBuffer.Null, 0, out int ret_length).ToNtException();
+                }
+            }
+        }
+
+        /// <summary>
+        /// Query all system environment value names.
+        /// </summary>
+        /// <returns>A list of names of environment values</returns>
+        public static IEnumerable<string> QuerySystemEnvironmentValueNames()
+        {
+            using (var buffer = EnumEnvironmentValues(SystemEnvironmentValueInformationClass.NamesOnly))
+            {
+                int offset = 0;
+                int size_struct = Marshal.SizeOf(typeof(SystemEnvironmentValueName));
+                while (offset <= buffer.Length - size_struct)
+                {
+                    var struct_buffer = buffer.GetStructAtOffset<SystemEnvironmentValueName>(offset);
+                    SystemEnvironmentValueName name = struct_buffer.Result;
+                    yield return struct_buffer.Data.ReadNulTerminatedUnicodeString();
+                    if (name.NextEntryOffset == 0)
+                    {
+                        break;
+                    }
+                    offset = offset + name.NextEntryOffset;
+                }
+            }
+        }
+
+        /// <summary>
+        /// Query all system environment value names and values.
+        /// </summary>
+        /// <returns>A list of names of environment values</returns>
+        public static IEnumerable<SystemEnvironmentValue> QuerySystemEnvironmentValueNamesAndValues()
+        {
+            using (var buffer = EnumEnvironmentValues(SystemEnvironmentValueInformationClass.NamesAndValues))
+            {
+                int offset = 0;
+                int size_struct = Marshal.SizeOf(typeof(SystemEnvironmentValueNameAndValue));
+                while (offset <= buffer.Length - size_struct)
+                {
+                    var struct_buffer = buffer.GetStructAtOffset<SystemEnvironmentValueNameAndValue>(offset);
+                    SystemEnvironmentValueNameAndValue name = struct_buffer.Result;
+                    yield return new SystemEnvironmentValue(struct_buffer);
+                    if (name.NextEntryOffset == 0)
+                    {
+                        break;
+                    }
+                    offset = offset + name.NextEntryOffset;
+                }
+            }
+        }
+
+        /// <summary>
+        /// Query a single system environment value.
+        /// </summary>
+        /// <param name="name">The name of the value.</param>
+        /// <param name="vendor_guid">The associated vendor guid</param>
+        /// <param name="throw_on_error">True to throw on error.</param>
+        /// <returns>The system environment value.</returns>
+        public static NtResult<SystemEnvironmentValue> QuerySystemEnvironmentValue(string name, Guid vendor_guid, bool throw_on_error)
+        {
+            UnicodeString name_string = new UnicodeString(name);
+            int value_length = 0;
+            NtStatus status = NtSystemCalls.NtQuerySystemEnvironmentValueEx(name_string, ref vendor_guid, null, ref value_length, 0);
+            if (status != NtStatus.STATUS_BUFFER_TOO_SMALL)
+            {
+                return status.CreateResultFromError<SystemEnvironmentValue>(throw_on_error);
+            }
+
+            byte[] value = new byte[value_length];
+            OptionalInt32 attributes = new OptionalInt32();
+            return NtSystemCalls.NtQuerySystemEnvironmentValueEx(name_string, ref vendor_guid, value, ref value_length, attributes)
+                .CreateResult(throw_on_error, () => new SystemEnvironmentValue(name, value, attributes, vendor_guid));
+        }
+
+        /// <summary>
+        /// Query a single system environment value.
+        /// </summary>
+        /// <param name="name">The name of the value.</param>
+        /// <param name="vendor_guid">The associated vendor guid</param>
+        /// <returns>The system environment value.</returns>
+        public static SystemEnvironmentValue QuerySystemEnvironmentValue(string name, Guid vendor_guid)
+        {
+            return QuerySystemEnvironmentValue(name, vendor_guid, true).Result;
+        }
+
+        /// <summary>
+        /// Set a system environment variable.
+        /// </summary>
+        /// <param name="name">The name of the variable.</param>
+        /// <param name="vendor_guid">The vendor GUID</param>
+        /// <param name="value">The value to set</param>
+        /// <param name="attributes">Attributes of the value</param>
+        public static void SetSystemEnvironmentValue(string name, Guid vendor_guid, byte[] value, int attributes)
+        {
+            NtSystemCalls.NtSetSystemEnvironmentValueEx(new UnicodeString(name), ref vendor_guid, value, value.Length, attributes).ToNtException();
+        }
+
+        /// <summary>
+        /// Set a system environment variable.
+        /// </summary>
+        /// <param name="name">The name of the variable.</param>
+        /// <param name="vendor_guid">The vendor GUID</param>
+        /// <param name="value">The value to set</param>
+        /// <param name="attributes">Attributes of the value</param>
+        public static void SetSystemEnvironmentValue(string name, Guid vendor_guid, byte[] value, SystemEnvironmentValueAttribute attributes)
+        {
+            SetSystemEnvironmentValue(name, vendor_guid, value, (int)attributes);
+        }
+
+        /// <summary>
+        /// Set a system environment variable.
+        /// </summary>
+        /// <param name="name">The name of the variable.</param>
+        /// <param name="vendor_guid">The vendor GUID</param>
+        /// <param name="value">The value to set</param>
+        /// <param name="attributes">Attributes of the value</param>
+        public static void SetSystemEnvironmentValue(string name, Guid vendor_guid, string value, int attributes)
+        {
+            SetSystemEnvironmentValue(name, vendor_guid, Encoding.Unicode.GetBytes(value), attributes);
+        }
+
+        /// <summary>
+        /// Set a system environment variable.
+        /// </summary>
+        /// <param name="name">The name of the variable.</param>
+        /// <param name="vendor_guid">The vendor GUID</param>
+        /// <param name="value">The value to set</param>
+        /// <param name="attributes">Attributes of the value</param>
+        public static void SetSystemEnvironmentValue(string name, Guid vendor_guid, string value, SystemEnvironmentValueAttribute attributes)
+        {
+            SetSystemEnvironmentValue(name, vendor_guid, value, (int)attributes);
+        }
+
+        /// <summary>
+        /// Allocate a LUID.
+        /// </summary>
+        /// <returns>The allocated LUID.</returns>
+        public static Luid AllocateLocallyUniqueId()
+        {
+            NtSystemCalls.NtAllocateLocallyUniqueId(out Luid luid).ToNtException();
+            return luid;
+        }
+
+        /// <summary>
+        /// Get the addresses of a list of objects from the handle table and initialize the Address property.
+        /// </summary>
+        /// <param name="objects">The list of objects to initialize.</param>
+        public static void ResolveObjectAddress(IEnumerable<NtObject> objects)
+        {
+            var handles = GetHandles(NtProcess.Current.ProcessId, false).ToDictionary(h => h.Handle, h => h.Object);
+            foreach (var obj in objects)
+            {
+                int obj_handle = obj.Handle.DangerousGetHandle().ToInt32();
+                if (handles.ContainsKey(obj_handle))
+                {
+                    obj.Address = handles[obj_handle];
+                }
+            }
+        }
+
+        /// <summary>
+        /// Get the address of an object in kernel memory from the handle table and initialize the Address property.
+        /// </summary>
+        /// <param name="obj">The object.</param>
+        public static void ResolveObjectAddress(NtObject obj)
+        {
+            ResolveObjectAddress(new[] { obj });
+        }
+
+        /// <summary>
+        /// Query whether a file is trusted for dynamic code.
+        /// </summary>
+        /// <param name="handle">The handle to a file to query.</param>
+        /// <param name="image">Pointer to a memory buffer containing the image.</param>
+        /// <param name="image_size">The size of the in-memory buffer.</param>
+        /// <returns>True if the file is trusted.</returns>
+        [SupportedVersion(SupportedVersion.Windows10_RS4)]
+        public static NtStatus QueryDynamicCodeTrust(SafeKernelObjectHandle handle, IntPtr image, int image_size)
+        {
+            SystemCodeIntegrityVerificationInformation info = new SystemCodeIntegrityVerificationInformation()
+            {
+                FileHandle = handle.DangerousGetHandle(),
+                Image = image,
+                ImageSize = image_size
+            };
+
+            using (var buffer = info.ToBuffer())
+            {
+                return NtSystemCalls.NtQuerySystemInformation(SystemInformationClass.SystemCodeIntegrityVerificationInformation, buffer,
+                    buffer.Length, out int ret_length);
+            }
+        }
+
+        /// <summary>
+        /// Query whether a file is trusted for dynamic code.
+        /// </summary>
+        /// <param name="image">Pointer to a memory buffer containing the image.</param>
+        /// <returns>The status code from the operation. Returns STATUS_SUCCESS is valid.</returns>
+        [SupportedVersion(SupportedVersion.Windows10_RS4)]
+        public static NtStatus QueryDynamicCodeTrust(byte[] image)
+        {
+            using (var buffer = image.ToBuffer())
+            {
+                return QueryDynamicCodeTrust(SafeKernelObjectHandle.Null,
+                    buffer.DangerousGetHandle(), buffer.Length);
+            }
+        }
+
+        /// <summary>
+        /// Query whether a file is trusted for dynamic code.
+        /// </summary>
+        /// <param name="handle">The handle to a file to query.</param>
+        /// <returns>The status code from the operation. Returns STATUS_SUCCESS is valid.</returns>
+        [SupportedVersion(SupportedVersion.Windows10_RS4)]
+        public static NtStatus QueryDynamicCodeTrust(SafeKernelObjectHandle handle)
+        {
+            return QueryDynamicCodeTrust(handle, IntPtr.Zero, 0);
+        }
+
+        /// <summary>
+        /// Set a file is trusted for dynamic code.
+        /// </summary>
+        /// <param name="handle">The handle to a file to set.</param>
+        /// <returns>The status code from the operation.</returns>
+        [SupportedVersion(SupportedVersion.Windows10_RS4)]
+        public static NtStatus SetDynamicCodeTrust(SafeKernelObjectHandle handle)
+        {
+            SystemCodeIntegrityVerificationInformation info = new SystemCodeIntegrityVerificationInformation()
+            {
+                FileHandle = handle.DangerousGetHandle()
+            };
+
+            return Set(SystemInformationClass.SystemCodeIntegrityVerificationInformation, info);
+        }
+
+        /// <summary>
+        /// Get list of root silos.
+        /// </summary>
+        /// <returns>The list of root silos.</returns>
+        public static IReadOnlyCollection<int> GetRootSilos()
+        {
+            using (var buffer = QueryBuffer<SystemRootSiloInformation>(SystemInformationClass.SystemRootSiloInformation))
+            {
+                var result = buffer.Result;
+                int[] silos = new int[result.NumberOfSilos];
+                buffer.Data.ReadArray(0, silos, 0, silos.Length);
+                return silos.ToList().AsReadOnly();
+            }
+        }
+
+        /// <summary>
+        /// Set the ELAM certificate information.
+        /// </summary>
+        /// <param name="image_file">The signed file containing an ELAM certificate resource.</param>
+        /// <returns>The NT status code.</returns>
+        public static NtStatus SetElamCertificate(NtFile image_file)
+        {
+            SystemElamCertificateInformation info = new SystemElamCertificateInformation()
+            { ElamDriverFile = image_file.Handle.DangerousGetHandle() };
+            return Set(SystemInformationClass.SystemElamCertificateInformation, info);
+        }
+
+        /// <summary>
+        /// Query code integrity certificate information.
+        /// </summary>
+        /// <param name="image_file">The image file.</param>
+        /// <param name="type">The type of check to make.</param>
+        /// <returns>The NT status code.</returns>
+        public static NtStatus QueryCodeIntegrityCertificateInfo(NtFile image_file, int type)
+        {
+            SystemCodeIntegrityCertificateInformation info = new SystemCodeIntegrityCertificateInformation()
+            {
+                ImageFile = image_file.Handle.DangerousGetHandle(),
+                Type = type
+            };
+
+            return QuerySystemInfo(info, SystemInformationClass.SystemCodeIntegrityCertificateInformation, false).Status;
+        }
+
+        #endregion
+
+        #region Static Properties
         /// <summary>
         /// Get whether the kernel debugger is enabled.
         /// </summary>
@@ -1319,32 +1651,6 @@
         }

         /// <summary>
-        /// Create a kernel dump for current system.
-        /// </summary>
-        /// <param name="path">The path to the output file.</param>
-        /// <param name="flags">Flags</param>
-        /// <param name="page_flags">Page flags</param>
-        public static void CreateKernelDump(string path, SystemDebugKernelDumpControlFlags flags, SystemDebugKernelDumpPageControlFlags page_flags)
-        {
-            NtToken.EnableDebugPrivilege();
-            using (NtFile file = NtFile.Create(path, FileAccessRights.Synchronize | FileAccessRights.GenericWrite | FileAccessRights.GenericRead,
-                    FileShareMode.Read, FileOpenOptions.SynchronousIoNonAlert | FileOpenOptions.WriteThrough | FileOpenOptions.NoIntermediateBuffering, FileDisposition.OverwriteIf,
-                    null))
-            {
-                using (var buffer = new SystemDebugKernelDumpConfig()
-                {
-                    FileHandle = file.Handle.DangerousGetHandle(),
-                    Flags = flags,
-                    PageFlags = page_flags
-                }.ToBuffer())
-                {
-                    NtSystemCalls.NtSystemDebugControl(SystemDebugControlCode.KernelCrashDump, buffer, buffer.Length,
-                        SafeHGlobalBuffer.Null, 0, out int ret_length).ToNtException();
-                }
-            }
-        }
-
-        /// <summary>
         /// Get whether secure boot is enabled.
         /// </summary>
         public static bool SecureBootEnabled
@@ -1388,243 +1694,6 @@
                 }
             }
         }
-
-        /// <summary>
-        /// Query all system environment value names.
-        /// </summary>
-        /// <returns>A list of names of environment values</returns>
-        public static IEnumerable<string> QuerySystemEnvironmentValueNames()
-        {
-            using (var buffer = EnumEnvironmentValues(SystemEnvironmentValueInformationClass.NamesOnly))
-            {
-                int offset = 0;
-                int size_struct = Marshal.SizeOf(typeof(SystemEnvironmentValueName));
-                while (offset <= buffer.Length - size_struct)
-                {
-                    var struct_buffer = buffer.GetStructAtOffset<SystemEnvironmentValueName>(offset);
-                    SystemEnvironmentValueName name = struct_buffer.Result;
-                    yield return struct_buffer.Data.ReadNulTerminatedUnicodeString();
-                    if (name.NextEntryOffset == 0)
-                    {
-                        break;
-                    }
-                    offset = offset + name.NextEntryOffset;
-                }
-            }
-        }
-
-        /// <summary>
-        /// Query all system environment value names and values.
-        /// </summary>
-        /// <returns>A list of names of environment values</returns>
-        public static IEnumerable<SystemEnvironmentValue> QuerySystemEnvironmentValueNamesAndValues()
-        {
-            using (var buffer = EnumEnvironmentValues(SystemEnvironmentValueInformationClass.NamesAndValues))
-            {
-                int offset = 0;
-                int size_struct = Marshal.SizeOf(typeof(SystemEnvironmentValueNameAndValue));
-                while (offset <= buffer.Length - size_struct)
-                {
-                    var struct_buffer = buffer.GetStructAtOffset<SystemEnvironmentValueNameAndValue>(offset);
-                    SystemEnvironmentValueNameAndValue name = struct_buffer.Result;
-                    yield return new SystemEnvironmentValue(struct_buffer);
-                    if (name.NextEntryOffset == 0)
-                    {
-                        break;
-                    }
-                    offset = offset + name.NextEntryOffset;
-                }
-            }
-        }
-
-        /// <summary>
-        /// Query a single system environment value.
-        /// </summary>
-        /// <param name="name">The name of the value.</param>
-        /// <param name="vendor_guid">The associated vendor guid</param>
-        /// <param name="throw_on_error">True to throw on error.</param>
-        /// <returns>The system environment value.</returns>
-        public static NtResult<SystemEnvironmentValue> QuerySystemEnvironmentValue(string name, Guid vendor_guid, bool throw_on_error)
-        {
-            UnicodeString name_string = new UnicodeString(name);
-            int value_length = 0;
-            NtStatus status = NtSystemCalls.NtQuerySystemEnvironmentValueEx(name_string, ref vendor_guid, null, ref value_length, 0);
-            if (status != NtStatus.STATUS_BUFFER_TOO_SMALL)
-            {
-                return status.CreateResultFromError<SystemEnvironmentValue>(throw_on_error);
-            }
-
-            byte[] value = new byte[value_length];
-            OptionalInt32 attributes = new OptionalInt32();
-            return NtSystemCalls.NtQuerySystemEnvironmentValueEx(name_string, ref vendor_guid, value, ref value_length, attributes)
-                .CreateResult(throw_on_error, () => new SystemEnvironmentValue(name, value, attributes, vendor_guid));
-        }
-
-        /// <summary>
-        /// Query a single system environment value.
-        /// </summary>
-        /// <param name="name">The name of the value.</param>
-        /// <param name="vendor_guid">The associated vendor guid</param>
-        /// <returns>The system environment value.</returns>
-        public static SystemEnvironmentValue QuerySystemEnvironmentValue(string name, Guid vendor_guid)
-        {
-            return QuerySystemEnvironmentValue(name, vendor_guid, true).Result;
-        }
-
-        /// <summary>
-        /// Set a system environment variable.
-        /// </summary>
-        /// <param name="name">The name of the variable.</param>
-        /// <param name="vendor_guid">The vendor GUID</param>
-        /// <param name="value">The value to set</param>
-        /// <param name="attributes">Attributes of the value</param>
-        public static void SetSystemEnvironmentValue(string name, Guid vendor_guid, byte[] value, int attributes)
-        {
-            NtSystemCalls.NtSetSystemEnvironmentValueEx(new UnicodeString(name), ref vendor_guid, value, value.Length, attributes).ToNtException();
-        }
-
-        /// <summary>
-        /// Set a system environment variable.
-        /// </summary>
-        /// <param name="name">The name of the variable.</param>
-        /// <param name="vendor_guid">The vendor GUID</param>
-        /// <param name="value">The value to set</param>
-        /// <param name="attributes">Attributes of the value</param>
-        public static void SetSystemEnvironmentValue(string name, Guid vendor_guid, byte[] value, SystemEnvironmentValueAttribute attributes)
-        {
-            SetSystemEnvironmentValue(name, vendor_guid, value, (int)attributes);
-        }
-
-        /// <summary>
-        /// Set a system environment variable.
-        /// </summary>
-        /// <param name="name">The name of the variable.</param>
-        /// <param name="vendor_guid">The vendor GUID</param>
-        /// <param name="value">The value to set</param>
-        /// <param name="attributes">Attributes of the value</param>
-        public static void SetSystemEnvironmentValue(string name, Guid vendor_guid, string value, int attributes)
-        {
-            SetSystemEnvironmentValue(name, vendor_guid, Encoding.Unicode.GetBytes(value), attributes);
-        }
-
-        /// <summary>
-        /// Set a system environment variable.
-        /// </summary>
-        /// <param name="name">The name of the variable.</param>
-        /// <param name="vendor_guid">The vendor GUID</param>
-        /// <param name="value">The value to set</param>
-        /// <param name="attributes">Attributes of the value</param>
-        public static void SetSystemEnvironmentValue(string name, Guid vendor_guid, string value, SystemEnvironmentValueAttribute attributes)
-        {
-            SetSystemEnvironmentValue(name, vendor_guid, value, (int)attributes);
-        }
-
-        /// <summary>
-        /// Allocate a LUID.
-        /// </summary>
-        /// <returns>The allocated LUID.</returns>
-        public static Luid AllocateLocallyUniqueId()
-        {
-            NtSystemCalls.NtAllocateLocallyUniqueId(out Luid luid).ToNtException();
-            return luid;
-        }
-
-        /// <summary>
-        /// Get the addresses of a list of objects from the handle table and initialize the Address property.
-        /// </summary>
-        /// <param name="objects">The list of objects to initialize.</param>
-        public static void ResolveObjectAddress(IEnumerable<NtObject> objects)
-        {
-            var handles = GetHandles(NtProcess.Current.ProcessId, false).ToDictionary(h => h.Handle, h => h.Object);
-            foreach (var obj in objects)
-            {
-                int obj_handle = obj.Handle.DangerousGetHandle().ToInt32();
-                if (handles.ContainsKey(obj_handle))
-                {
-                    obj.Address = handles[obj_handle];
-                }
-            }
-        }
-
-        /// <summary>
-        /// Get the address of an object in kernel memory from the handle table and initialize the Address property.
-        /// </summary>
-        /// <param name="obj">The object.</param>
-        public static void ResolveObjectAddress(NtObject obj)
-        {
-            ResolveObjectAddress(new[] { obj });
-        }
-
-        /// <summary>
-        /// Query whether a file is trusted for dynamic code.
-        /// </summary>
-        /// <param name="handle">The handle to a file to query.</param>
-        /// <param name="image">Pointer to a memory buffer containing the image.</param>
-        /// <param name="image_size">The size of the in-memory buffer.</param>
-        /// <returns>True if the file is trusted.</returns>
-        [SupportedVersion(SupportedVersion.Windows10_RS4)]
-        public static NtStatus QueryDynamicCodeTrust(SafeKernelObjectHandle handle, IntPtr image, int image_size)
-        {
-            SystemCodeIntegrityVerificationInformation info = new SystemCodeIntegrityVerificationInformation()
-            {
-                FileHandle = handle.DangerousGetHandle(),
-                Image = image,
-                ImageSize = image_size
-            };
-
-            using (var buffer = info.ToBuffer())
-            {
-                return NtSystemCalls.NtQuerySystemInformation(SystemInformationClass.SystemCodeIntegrityVerificationInformation, buffer,
-                    buffer.Length, out int ret_length);
-            }
-        }
-
-        /// <summary>
-        /// Query whether a file is trusted for dynamic code.
-        /// </summary>
-        /// <param name="image">Pointer to a memory buffer containing the image.</param>
-        /// <returns>The status code from the operation. Returns STATUS_SUCCESS is valid.</returns>
-        [SupportedVersion(SupportedVersion.Windows10_RS4)]
-        public static NtStatus QueryDynamicCodeTrust(byte[] image)
-        {
-            using (var buffer = image.ToBuffer())
-            {
-                return QueryDynamicCodeTrust(SafeKernelObjectHandle.Null,
-                    buffer.DangerousGetHandle(), buffer.Length);
-            }
-        }
-
-        /// <summary>
-        /// Query whether a file is trusted for dynamic code.
-        /// </summary>
-        /// <param name="handle">The handle to a file to query.</param>
-        /// <returns>The status code from the operation. Returns STATUS_SUCCESS is valid.</returns>
-        [SupportedVersion(SupportedVersion.Windows10_RS4)]
-        public static NtStatus QueryDynamicCodeTrust(SafeKernelObjectHandle handle)
-        {
-            return QueryDynamicCodeTrust(handle, IntPtr.Zero, 0);
-        }
-
-        /// <summary>
-        /// Set a file is trusted for dynamic code.
-        /// </summary>
-        /// <param name="handle">The handle to a file to set.</param>
-        /// <returns>The status code from the operation.</returns>
-        [SupportedVersion(SupportedVersion.Windows10_RS4)]
-        public static NtStatus SetDynamicCodeTrust(SafeKernelObjectHandle handle)
-        {
-            SystemCodeIntegrityVerificationInformation info = new SystemCodeIntegrityVerificationInformation()
-            {
-                FileHandle = handle.DangerousGetHandle()
-            };
-
-            using (var buffer = info.ToBuffer())
-            {
-                return NtSystemCalls.NtSetSystemInformation(SystemInformationClass.SystemCodeIntegrityVerificationInformation, buffer,
-                    buffer.Length);
-            }
-        }
-
         /// <summary>
         /// Get system timer resolution.
         /// </summary>
@@ -1666,19 +1735,6 @@
         /// </summary>
         public static int NumberOfProcessors => _basic_info.Value.NumberOfProcessors;

-        /// <summary>
-        /// Get list of root silos.
-        /// </summary>
-        /// <returns>The list of root silos.</returns>
-        public static IReadOnlyCollection<int> GetRootSilos()
-        {
-            using (var buffer = QuerySystemInfoVariable<SystemRootSiloInformation>(SystemInformationClass.SystemRootSiloInformation))
-            {
-                var result = buffer.Result;
-                int[] silos = new int[result.NumberOfSilos];
-                buffer.Data.ReadArray(0, silos, 0, silos.Length);
-                return silos.ToList().AsReadOnly();
-            }
-        }
+        #endregion
     }
 }


Prepend FDO picture path name for UpdateFdoFromMongoDbAction

FDO expects pictures in a certain directory, so prepend that directory name
when bringing pictures from LF to FDO

--- src/LfMerge/Actions/UpdateFdoFromMongoDbAction.cs
+++ src/LfMerge/Actions/UpdateFdoFromMongoDbAction.cs
@@ -686,7 +686,7 @@
 			return result;
 		}

-		private ICmPicture GetOrCreatePictureByGuid(Guid guid, ILexSense owner, string fileName, string caption, int captionWs)
+		private ICmPicture GetOrCreatePictureByGuid(Guid guid, ILexSense owner, string pictureName, string caption, int captionWs)
 		{
 			ICmPicture result;
 			if (!_pictureRepo.TryGetObject(guid, out result))
@@ -694,10 +694,13 @@
 				if (caption == null)
 					caption = "";
 				ITsString captionTss = TsStringUtils.MakeTss(caption, captionWs);
+				// FDO expects pictures in a certain path
+				const string fdoPicturePath = "Pictures/";
+				string picturePath = pictureName.StartsWith(fdoPicturePath) ? pictureName : string.Format("{0}{1}", fdoPicturePath, pictureName);
 				// NOTE: The CmPictureFactory class doesn't allow us to specify the GUID of the
 				// created Picture object. So we can't rely on GUIDs for round-tripping pictures.
 				// TODO: Look into what we *can* rely on for round-tripping pictures.
-				result = _pictureFactory.Create(fileName, captionTss, CmFolderTags.LocalPictures);
+				result = _pictureFactory.Create(picturePath, captionTss, CmFolderTags.LocalPictures);
 				owner.PicturesOS.Add(result);
 			}
 			return result;


Return lines instead of entire text in correction extent

--- rules/UseSupportsShouldProcess.cs
+++ rules/UseSupportsShouldProcess.cs
@@ -194,6 +194,11 @@
                 correctionExtents.Add(GetCorrectionExtentAddParamBlock(funcDefnAst, parameterAsts));
             }

+            // This is how we handle multiple edits.
+            // create separate edits
+            // apply those edits to the original script extent1
+            // and then give the corrected extent as suggested correction.
+
             // sort in descending order of start position
             correctionExtents.Sort((x, y) =>
             {
@@ -206,7 +211,7 @@
             foreach (var correctionExtent in correctionExtents)
             {
                 var shiftedCorrectionExtent = Normalize(funcDefnAst.Extent, correctionExtent);
-                editableText = editableText.ApplyEdit(shiftedCorrectionExtent);
+                editableText = editableText.ApplyEdit1(shiftedCorrectionExtent);
             }

             var result = new List<CorrectionExtent>();
@@ -219,10 +224,6 @@
                 editableText.ToString(),
                 funcDefnAst.Extent.File));
             return result;
-            // This is how we handle multiple edits.
-            // create separate edits
-            // apply those edits to the original script extent1
-            // and then give the corrected extent as suggested correction.
         }

         private CorrectionExtent GetCorrectionExtentAddParamBlock(
@@ -233,53 +234,47 @@
             var paramBlockText = WriteParamBlock(parameterAsts);
             // TODO replace this hard coding
             var indentation = new string(' ', funcStartScriptPos.ColumnNumber + 3);
-            var sb = new StringBuilder();
-            sb.Append("{");
-            sb.AppendLine();
-            sb.Append(String.Join(
-                Environment.NewLine,
-                paramBlockText.GetLines().Select(line => indentation + line)));
-
+            var lines = new List<String>();
+            lines.Add("{");
+            lines.AddRange(paramBlockText.Select(line => indentation + line));
             return new CorrectionExtent(
                 funcDefnAst.Body.Extent.StartLineNumber,
                 funcDefnAst.Body.Extent.StartLineNumber,
                 funcDefnAst.Body.Extent.StartColumnNumber,
                 funcDefnAst.Body.Extent.StartColumnNumber + 1,
-                sb.ToString(),
-                funcDefnAst.Extent.File);
-        }
-
-        private string WriteParamBlock(ParameterAst[] parameterAsts)
-        {
-            var sb = new StringBuilder();
-            sb.AppendLine("[CmdletBinding(SupportsShouldProcess)]");
-            sb.AppendLine("param(");
+                lines,
+                funcDefnAst.Extent.File,
+                null);
+        }
+
+        private IList<String> WriteParamBlock(ParameterAst[] parameterAsts)
+        {
+            var lines = new List<String>();
+            lines.Add("[CmdletBinding(SupportsShouldProcess)]");
+            lines.Add("param(");
+
             // TODO replace this hard coding
             string indentation = new string(' ', 4);
             int count = 0;
-            foreach (var paramAst in parameterAsts)
+            var usableParamAsts = parameterAsts.Where(p => !IsWhatIf(p) && !IsConfirm(p));
+            var usableCount = usableParamAsts.Count();
+            foreach (var paramAst in usableParamAsts)
             {
                 count++;
-                if (IsWhatIf(paramAst) || IsConfirm(paramAst))
-                {
-                    continue;
+                var suffix = ",";
+                if (count == usableCount)
+                {
+                    suffix = "";
                 }

                 foreach (var line in paramAst.Extent.Text.GetLines())
                 {
-                    sb.Append(indentation);
-                    sb.Append(line);
-                }
-
-                if (count != parameterAsts.Length)
-                {
-                    sb.AppendLine(",");
-                }
-            }
-
-            sb.AppendLine();
-            sb.AppendLine(")");
-            return sb.ToString();
+                    lines.Add(indentation + line + suffix);
+                }
+            }
+
+            lines.Add(")");
+            return lines;
         }

@@ -293,10 +288,10 @@
             var rParenTokenIdx = Array.FindIndex(funcDefnTokens, tok => tok.Kind == TokenKind.RParen);

             return new CorrectionExtent(
-                tokens[lParenTokenIdx - 1].Extent.EndLineNumber,
-                tokens[rParenTokenIdx].Extent.EndLineNumber,
-                tokens[lParenTokenIdx - 1].Extent.EndColumnNumber,
-                tokens[rParenTokenIdx].Extent.EndColumnNumber,
+                funcDefnTokens[lParenTokenIdx - 1].Extent.EndLineNumber,
+                funcDefnTokens[rParenTokenIdx].Extent.EndLineNumber,
+                funcDefnTokens[lParenTokenIdx - 1].Extent.EndColumnNumber,
+                funcDefnTokens[rParenTokenIdx].Extent.EndColumnNumber,
                 "",
                 ast.Extent.File);
         }
@@ -311,13 +306,7 @@
                 referenceExtent.EndLineNumber,
                 referenceExtent.EndColumnNumber);

-            var range = new Range(
-                cextent.StartLineNumber,
-                cextent.StartColumnNumber,
-                cextent.EndLineNumber,
-                cextent.EndColumnNumber);
-
-            var shiftedRange = Range.Normalize(refRange, range);
+            var shiftedRange = Range.Normalize(refRange, cextent);

             // TODO Add a method to TextEdit class that takes in range and text
             // TODO Add a method to CorrectionExtent that takes in range and all other stuff
@@ -344,17 +333,17 @@

         private static CorrectionExtent GetCorrectionExtent(ParamBlockAst paramBlockAst)
         {
-
-            string correctionText = new String(' ', paramBlockAst.Extent.StartColumnNumber - 1)
-                + "[CmdletBinding(SupportsShouldProcess)]"
-                + Environment.NewLine;
-
             return new CorrectionExtent(
                 paramBlockAst.Extent.StartLineNumber,
                 paramBlockAst.Extent.StartLineNumber,
                 1,
                 1,
-                correctionText,
+                new String[] {
+                    new String(' ', paramBlockAst.Extent.StartColumnNumber - 1)
+                        + "[CmdletBinding(SupportsShouldProcess)]",
+                    String.Empty
+                },
+                null,
                 null);
         }
         private static CorrectionExtent GetCorrectionExtent(AttributeAst cmdletBindingAttributeAst)


Enable ETW/EventSource logging of task IDs for boxed state machines (#27115)

* Wrap MoveNext Action for TPL event tracing

Wraps the MoveNext action of the AsyncStateMachineBox in a
continuation wrapper when async causality tracing is on so that the
TPL event source can find the task that is associated with a
continuation. Does not wrap otherwise.

* Clarifying comment

* removing trailing whitespace

* code review feedback.

Makes AsyncMethodBuilderCore.TryFindContinuationTask check to
whether the target of a continuation is itself a task, as a fall-back
to checking to see if the continuation is a ContinuationWrapper

* Got rid of unnecessary null checks

Signed-off-by: dotnet-bot <03c4cb6107ae99956a7681f2c97ff7104809a2bd@microsoft.com>

--- src/Common/src/CoreLib/System/Runtime/CompilerServices/AsyncMethodBuilderCore.cs
+++ src/Common/src/CoreLib/System/Runtime/CompilerServices/AsyncMethodBuilderCore.cs
@@ -123,7 +123,9 @@
         }

         internal static Task? TryGetContinuationTask(Action continuation) =>
-            (continuation?.Target as ContinuationWrapper)?._innerTask;
+            (continuation.Target is ContinuationWrapper wrapper) ?
+                wrapper._innerTask :           // A wrapped continuation, created by an awaiter
+                continuation.Target as Task;   // The continuation targets a task directly, such as with AsyncStateMachineBox

         /// <summary>
         /// Logically we pass just an Action (delegate) to a task for its action to 'ContinueWith' when it completes.


Make DataStoreErrorLogger._log static

Make DataStoreErrorLogger._log static

--- src/Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore/DataStoreErrorLogger.cs
+++ src/Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore/DataStoreErrorLogger.cs
@@ -18,7 +18,7 @@
     public class DataStoreErrorLogger : ILogger
     {
 #if NETSTANDARD1_3
-        private readonly AsyncLocal<DataStoreErrorLog> _log = new AsyncLocal<DataStoreErrorLog>();
+        private static readonly AsyncLocal<DataStoreErrorLog> _log = new AsyncLocal<DataStoreErrorLog>();
 #else
         private static readonly string ContextName = "__DataStoreErrorLog" + AppDomain.CurrentDomain.Id;
 #endif


Shouldn't be protected

Shouldn't be protected

svn path=/trunk/bitsharp/; revision=105621

--- src/MonoTorrent/MonoTorrent.Client/ConnectionListeners/ConnectionListenerBase.cs
+++ src/MonoTorrent/MonoTorrent.Client/ConnectionListeners/ConnectionListenerBase.cs
@@ -40,7 +40,7 @@
         private ClientEngine engine;
         private bool isListening;

-        protected internal ClientEngine Engine
+        internal ClientEngine Engine
         {
             get { return engine; }
             set { engine = value; }


--- source/projects/MyCouch/Contexts/ApiContextBase.cs
+++ source/projects/MyCouch/Contexts/ApiContextBase.cs
@@ -17,22 +17,12 @@
             Connection = connection;
         }

-        protected virtual Task<HttpResponseMessage> SendAsync(HttpRequest httpRequest)
-        {
-            return Connection.SendAsync(httpRequest);
-        }
-
-        protected virtual Task<HttpResponseMessage> SendAsync(HttpRequest httpRequest, CancellationToken cancellationToken)
+        protected virtual Task<HttpResponseMessage> SendAsync(HttpRequest httpRequest, CancellationToken cancellationToken = default)
         {
             return Connection.SendAsync(httpRequest, cancellationToken);
         }

-        protected virtual Task<HttpResponseMessage> SendAsync(HttpRequest httpRequest, HttpCompletionOption completionOption)
-        {
-            return Connection.SendAsync(httpRequest, completionOption);
-        }
-
-        protected virtual Task<HttpResponseMessage> SendAsync(HttpRequest httpRequest, HttpCompletionOption completionOption, CancellationToken cancellationToken)
+        protected virtual Task<HttpResponseMessage> SendAsync(HttpRequest httpRequest, HttpCompletionOption completionOption, CancellationToken cancellationToken = default)
         {
             return Connection.SendAsync(httpRequest, completionOption, cancellationToken);
         }


Completely decoupled BatchedQuery from DocumentQuery

--- src/Marten/Services/BatchQuerying/BatchedQuery.cs
+++ src/Marten/Services/BatchQuerying/BatchedQuery.cs
@@ -102,21 +102,6 @@
             return AddItem(new UserSuppliedQueryHandler<T>(_schema, _serializer, sql, parameters));
         }

-        [Obsolete("This is going to go away, but watch the includes")]
-        private DocumentQuery toDocumentQuery<TDoc>(IMartenQueryable<TDoc> queryable)
-        {
-            var expression = queryable.Expression;
-
-            var model = QueryParser.GetParsedQuery(expression);
-
-            var docQuery = _schema.ToDocumentQuery(model);
-            docQuery.Includes.AddRange(queryable.Includes);
-
-
-            return docQuery;
-        }
-
-
         public Task<bool> Any<TDoc>(IMartenQueryable<TDoc> queryable)
         {
             var expression = queryable.Expression;