Updated Unbalance Adapter to include standard Alarming with Delay and Hysterisis

--- Source/Libraries/Adapters/openHistorian.Adapters/Unbalanced.cs
+++ Source/Libraries/Adapters/openHistorian.Adapters/Unbalanced.cs
@@ -49,6 +49,7 @@
 using GSF.Units.EE;
 using System.Threading.Tasks;
 using GSF;
+using System.Xml.Serialization;

 // ReSharper disable MemberCanBePrivate.Local
 // ReSharper disable NotAccessedField.Local
@@ -66,8 +67,11 @@
         {
             public DateTime Date { get; set; }
             //public double S0S1 { get; set; }
-            public double S2S1 { get; set; }
+            public double S0S1 { get; set; }
             public Guid PositivePhaseSignalID { get; set; }
+            public int Alarm { get; set; }
+            public string SignalType { get; set; }
+
         }

         /// <summary>
@@ -81,10 +85,16 @@
             public Guid S0S1 { get; set; }
             public Guid S2S1 { get; set; }

+            public string SignalType { get; set; }
+
             public double count;
             public double sum;
             public void Reset() => count = sum = 0;

+            public bool activeAlarm;
+            public int countExceeding;
+
+
         }

@@ -136,6 +146,23 @@
         /// Defines the default value for the <see cref="MaxSQLRows"/>.
         /// </summary>
         public const int DefaultWindowSize = 30;
+
+
+        /// <summary>
+        /// Defines the default value for the <see cref="MaxSQLRows"/>.
+        /// </summary>
+        public const double DefaultAlarmThreshhold = 0.03;
+
+        /// <summary>
+        /// Defines the default value for the <see cref="MaxSQLRows"/>.
+        /// </summary>
+        public const int DefaultAlarmDelay = 5;
+
+        /// <summary>
+        /// Defines the default value for the <see cref="MaxSQLRows"/>.
+        /// </summary>
+        public const double DefaultAlarmHysterisis = 0;
+

@@ -143,6 +170,7 @@
         private int m_numberOfFrames;
         private double m_lastS0S1;
         private double m_lastS2S1;
+        private bool m_countAlarms;

         private LongSynchronizedOperation m_sqlWritter;
         private IsolatedQueue<DailySummary> m_summaryQueue;
@@ -186,6 +214,30 @@
         [Description("Defines the maximum number of daily Summary Points inserted at once.")]
         [DefaultValue(DefaultMaxSQLRows)]
         public int MaxSQLRows { get; set; }
+
+        /// <summary>
+        /// Gets or sets the Setpoint for Alarming.
+        /// </summary>
+        [ConnectionStringParameter]
+        [Description("Defines Threshold for alarming on unbalance. If it is 0 there are no Alarms")]
+        [DefaultValue(DefaultAlarmThreshhold)]
+        public double AlarmSetPoint { get; set; }
+
+        /// <summary>
+        /// Gets or sets the Delay for Alarming.
+        /// </summary>
+        [ConnectionStringParameter]
+        [Description("Defines the delay for alarming on unbalance in sec.")]
+        [DefaultValue(DefaultAlarmDelay)]
+        public int AlarmDelay { get; set; }
+
+        /// <summary>
+        /// Gets or sets the Hysterisis for Alarming.
+        /// </summary>
+        [ConnectionStringParameter]
+        [Description("Defines the hysterisis for alarming on unbalance")]
+        [DefaultValue(DefaultAlarmHysterisis)]
+        public double AlarmHysterisis { get; set; }

         /// <summary>
         /// Gets or sets template for the parent device acronym used to group associated output measurements.
@@ -412,10 +464,20 @@
                         // Get output measurement record, creating a new one if needed
                         MeasurementRecord measurement = GetMeasurementRecord(currentDeviceID ?? CurrentDeviceID(i), outputPointTag, outputAlternateTag, signalReference, description, SignalType.CALC, TargetHistorianAcronym);

+                        MeasurementRecord posSeq = new TableOperations<MeasurementRecord>(connection).QueryRecordWhere("SignalId = {0}",input1.SignalID);
+                        string unbalancetype = "X";
+
+                        if (posSeq != null && posSeq.SignalTypeID == (int)SignalType.IPHM)
+                            unbalancetype = "I";
+                        else if (posSeq != null && posSeq.SignalTypeID == (int)SignalType.VPHM)
+                            unbalancetype = "V";

                         output = measurement.SignalID;

                         keys = new ThreePhaseSet() { PositiveSequence = input1.SignalID, NegativeSequence = input2.SignalID, ZeroSequence = input3.SignalID, S0S1 = output, S2S1 = output };
+                        keys.activeAlarm = false;
+                        keys.countExceeding = 0;
+                        keys.SignalType = unbalancetype;
                         new TableOperations<ThreePhaseSet>(connection).AddNewRecord(keys);

@@ -439,6 +501,8 @@
             if (m_threePhaseComponent.Count == 0)
                 OnStatusMessage(MessageLevel.Error, "No case with all 3 sequences was found");

+            m_countAlarms = !(AlarmSetPoint == 0);
+
             m_numberOfFrames = 0;

             m_cancelationTokenSql = new GSF.Threading.CancellationToken();
@@ -501,13 +565,38 @@
                 Measurement s2s1Measurement = new Measurement { Metadata = MeasurementKey.LookUpBySignalID(set.S0S1).Metadata };
                 outputmeasurements.Add(Measurement.Clone(s2s1Measurement, s2s1, frame.Timestamp));

+                // Logic to count Alarms
+                if (m_countAlarms)
+                {
+                    if (set.countExceeding > (AlarmDelay * FramesPerSecond))
+                        set.activeAlarm = true;
+
+                    if (s0s1 > AlarmSetPoint)
+                        set.countExceeding++;
+
+                    if (s0s1 < (AlarmSetPoint - AlarmHysterisis))
+                        set.countExceeding = 0;
+                }
+
                 if (ReportSQL && (!double.IsNaN(s2s1)))
                 {
                     set.sum += s0s1;
                     set.count += 1.0;
                     if (report)
                     {
-                        m_summaryQueue.Enqueue(new DailySummary() { PositivePhaseSignalID = set.PositiveSequence, S2S1 = (set.sum / set.count), Date = ((DateTime)frame.Timestamp).RoundDownToNearestDay() });
+                        DailySummary summary = new DailySummary()
+                        {
+                            PositivePhaseSignalID = set.PositiveSequence,
+                            S0S1 = (set.sum / set.count),
+                            Date = ((DateTime)frame.Timestamp).RoundDownToNearestDay(),
+                            Alarm = 0,
+                            SignalType = set.SignalType
+                        };
+
+                        if (m_countAlarms && !set.activeAlarm && set.countExceeding > (AlarmDelay * FramesPerSecond))
+                            summary.Alarm = 1;
+
+                        m_summaryQueue.Enqueue(summary);
                         set.Reset();
                     }
                 }
@@ -531,10 +620,10 @@
                 int n = m_summaryQueue.Dequeue(data, 0, MaxSQLRows);
                 if (n > 0)
                 {
-                    string sqlCmd = "INSERT INTO Unbalance (Date, S2S1, PositivePhaseSignalID) VALUES";
+                    string sqlCmd = "INSERT INTO Unbalance (Date, S0S1, PositivePhaseSignalID, SignalType, Alarm) VALUES";

                     for (int i = 0; i < n; i++)
-                        sqlCmd = sqlCmd + $"\n ('{data[i].Date}',{data[i].S2S1},'{data[i].PositivePhaseSignalID}'),";
+                        sqlCmd = sqlCmd + $"\n ('{data[i].Date}',{data[i].S0S1},'{data[i].PositivePhaseSignalID}','{data[i].SignalType}',{data[i].Alarm}),";

                     sqlCmd = sqlCmd.Substring(0, sqlCmd.Length - 1);
                     using (AdoDataConnection connection = new AdoDataConnection(ReportSettingsCategory))


Enabling passing test.

Enabling passing test.

***NO_CI***
 (changeset 1363488)

--- Src/Compilers/CSharp/Test/Symbol/Symbols/Source/MethodTests.cs
+++ Src/Compilers/CSharp/Test/Symbol/Symbols/Source/MethodTests.cs
@@ -1625,7 +1625,7 @@
             context.Diagnostics.Verify();
         }

-        [Fact(Skip = "893788")]
+        [Fact()]
         public void TestMetadataVirtual()
         {
             string text = @"


Fixed image source file and bug on and scale

--- tests/tests/classes/tests/Physics/PhysicsTest.cs
+++ tests/tests/classes/tests/Physics/PhysicsTest.cs
@@ -182,13 +182,14 @@

             CCSprite ball = new CCSprite(yellow ? "Images/YellowSquare.png" : "Images/CyanSquare.png");

-            ball.ScaleX = Window.WindowSizeInPixels.Width / 100.0f;
-            ball.ScaleY = Window.WindowSizeInPixels.Height / 100.0f;
-
             var body = CCPhysicsBody.CreateBox(size, material, 0.0f);
             ball.PhysicsBody = body;
             ball.Position = point;// new cpVect(point.X, point.Y);

+            ball.ScaleX = size.Width / 100.0f;
+            ball.ScaleY = size.Height / 100.0f;
+
+
             return ball;
         }

@@ -199,7 +200,7 @@

         public CCSprite MakeBall(CCPoint point, float radius, CCPhysicsMaterial material)
         {
-            CCSprite ball = new CCSprite("ball.png");
+            CCSprite ball = new CCSprite("Images/ball.png");
             ball.Scale = 0.13f * radius;
             var body = CCPhysicsBody.CreateCircle(radius, material, CCPoint.Zero);
             ball.PhysicsBody = body;


(GH-70) Added validation for description maximum length requirement

--- src/Chocolatey.Language.Server/DiagnosticsHandler.cs
+++ src/Chocolatey.Language.Server/DiagnosticsHandler.cs
@@ -92,6 +92,16 @@
                     Range = range
                 };
             }
+            else if (descriptionLength > 4000)
+            {
+                var range = textPositions.GetRange(descriptionElement.StartTag.End, descriptionElement.EndTag.Start);
+
+                yield return new Diagnostic {
+                    Message = "Description should not exceed 4000 characters",
+                    Severity = DiagnosticSeverity.Error,
+                    Range = range
+                };
+            }
         }
     }
 }


added love promo

added love promo

--- src/CollectionsOnline.WebSite/Views/HomeIndex.cshtml
+++ src/CollectionsOnline.WebSite/Views/HomeIndex.cshtml
@@ -15,12 +15,60 @@

-
Then the guns fell silent: the Centenary of the Armistice

-
Exactly 100 years ago, on 11 November 1918, the guns of World War I fell silent. Explore our collections to learn more.

+
LOVE exhibition at the Immigration Museum, Open from 1 December 2018

+
Stories of the heart - friends, family and lovers.  Explore the collection objects on display in Love to find out more.

-
+

-
+
+
+
+
+
+                            item
+
+
+                    HT 36719
+                    Painting - 'A Family', Nickel Mundabi Ngadwa, Shepparton, 2013
+
+
+

+

+
+
+
+
+
+
+
+                            item
+
+
+                    X 102673
+                    Ornament, neck, Locality unrecorded, Cape Province, South Africa
+
+
+

+

+
+
+
+
+
+
+
+                            item
+
+
+                    SH 950520
+                    Sculpture - Young Love, Leopoldine Mimovich, Bronze, circa 1995
+
+
+

+

+
+
+

@@ -28,55 +76,7 @@
                             article

-                    Armistice Day, World War I, 11 Nov 1918
-
-
-

-

-
-
-
-
-
-
-
-                            item
-
-
-                    MM 1409
-                    Children's Armistice Day Parade, Duntroon, Australian Capital Territory, Nov 1918
-
-
-

-

-
-
-
-
-
-
-
-                            item
-
-
-                    MM 7155
-                    Peace Day, Colac, Victoria, Nov 1918
-
-
-

-

-
-
-
-
-
-
-
-                            item
-
-
-                    HT 34787
-                    Telegram - Armistice, World War I, Portland, Victoria, Nov 1918
+                    Objects & Stories from the Love Exhibition


Changed fields into properties

Changed fields into properties

--- src/Discord.Net/API/Gateway/GuildEmojiUpdateEvent.cs
+++ src/Discord.Net/API/Gateway/GuildEmojiUpdateEvent.cs
@@ -5,8 +5,8 @@
     public class GuildEmojiUpdateEvent
     {
         [JsonProperty("guild_id")]
-        public ulong GuildId;
+        public ulong GuildId { get; set; }
         [JsonProperty("emojis")]
-        public Emoji[] Emojis;
+        public Emoji[] Emojis { get; set; }
     }
 }


Adds more verbosity for CronusContext error

--- src/Elders.Cronus/MessageProcessing/CronusContext.cs
+++ src/Elders.Cronus/MessageProcessing/CronusContext.cs
@@ -16,7 +16,7 @@
         {
             get
             {
-                if (string.IsNullOrEmpty(tenant)) throw new ArgumentException($"Unknown tenant. CronusContext is not properly built. Please call `Initialize(...)` and make sure that you properly configured `cronus:tenants`. More info at https://github.com/Elders/Cronus/blob/master/doc/Configuration.md");
+                if (string.IsNullOrEmpty(tenant)) throw new ArgumentException($"Unknown tenant. CronusContext is not properly built. Please call `Initialize(...)` and make sure that you have properly configured `cronus:tenants`. More info at https://github.com/Elders/Cronus/blob/master/doc/Configuration.md. Also, CronustContext does not like singletons due to multitenancy support.");
                 return tenant;
             }
             set


Serialize settings using default serializer

--- src/Exceptionless.Api/Controllers/AdminController.cs
+++ src/Exceptionless.Api/Controllers/AdminController.cs
@@ -17,6 +17,7 @@
 using Foundatio.Storage;
 using Microsoft.AspNetCore.Authorization;
 using Microsoft.AspNetCore.Mvc;
+using Newtonsoft.Json;

 namespace Exceptionless.Api.Controllers {
     [Route(API_PREFIX + "/admin")]
@@ -41,7 +42,7 @@

         [HttpGet("settings")]
         public IActionResult SettingsRequest() {
-            return Ok(Settings.Current);
+            return Ok(JsonConvert.SerializeObject(Settings.Current, Formatting.Indented));
         }

         [HttpGet("assemblies")]


Version up.

Version up.

--- src/ExpressiveAnnotations/Properties/AssemblyInfo.cs
+++ src/ExpressiveAnnotations/Properties/AssemblyInfo.cs
@@ -48,5 +48,5 @@
 // You can specify all the values or you can default the Build and Revision Numbers
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("2.2.10.0")]
-[assembly: AssemblyFileVersion("2.2.10.0")]
+[assembly: AssemblyVersion("2.2.11.0")]
+[assembly: AssemblyFileVersion("2.2.11.0")]


bugfix reduced expressions, we should only reduce once, or parameters are not found in closure

--- src/FastExpressionCompiler/FastExpressionCompiler.cs
+++ src/FastExpressionCompiler/FastExpressionCompiler.cs
@@ -360,6 +360,8 @@
             public NestedLambdaInfo[] NestedLambdas;
             public LambdaExpression[] NestedLambdaExprs;

+            public Dictionary<Expression, Expression> ReducedExpressions;
+
             public int ClosedItemCount => Constants.Length + NonPassedParameters.Length + NestedLambdas.Length;

             // FieldInfos are needed to load field of closure object on stack in emitter.
@@ -387,6 +389,7 @@
                 Labels = null;
                 LabelCount = 0;
                 LastEmitIsAddress = false;
+                ReducedExpressions = null;

                 if (closure == null)
                 {
@@ -1010,7 +1013,11 @@
                         return true;

                     case ExpressionType.Extension:
-                        expr = expr.Reduce();
+                        var reducedExpr = expr.Reduce();
+                        if (closure.ReducedExpressions == null)
+                            closure.ReducedExpressions = new Dictionary<Expression, Expression>();
+                        closure.ReducedExpressions.Add(expr, reducedExpr);
+                        expr = reducedExpr;
                         continue;

                     case ExpressionType.Default:
@@ -1341,7 +1348,7 @@
                             return TryEmitSwitch((SwitchExpression)expr, paramExprs, il, ref closure, parent);

                         case ExpressionType.Extension:
-                            expr = expr.Reduce();
+                            expr = closure.ReducedExpressions[expr];
                             continue;

                         default:


Added `PrintModuleOutputNamespace` option to `CSharpTypePrinter`.

--- src/Generator/Generators/CSharp/CSharpTypePrinter.cs
+++ src/Generator/Generators/CSharp/CSharpTypePrinter.cs
@@ -19,6 +19,8 @@

         public DriverOptions Options => Context.Options;
         public TypeMapDatabase TypeMapDatabase => Context.TypeMaps;
+
+        public bool PrintModuleOutputNamespace = true;

         public CSharpTypePrinter(BindingContext context)
         {
@@ -646,10 +648,13 @@
                 ctx = ctx.Namespace;
             }

-            var unit = ctx.TranslationUnit;
-            if (!unit.IsSystemHeader && unit.IsValid &&
-                !string.IsNullOrWhiteSpace(unit.Module.OutputNamespace))
-                names.Push(unit.Module.OutputNamespace);
+            if (PrintModuleOutputNamespace)
+            {
+                var unit = ctx.TranslationUnit;
+                if (!unit.IsSystemHeader && unit.IsValid &&
+                    !string.IsNullOrWhiteSpace(unit.Module.OutputNamespace))
+                    names.Push(unit.Module.OutputNamespace);
+            }

             return QualifiedType(string.Join(".", names));
         }


Improved caret position binding a bit.

Improved caret position binding a bit.

--- Utilities.Controls/Behaviors/TextEditorContentIndexBehavior.cs
+++ Utilities.Controls/Behaviors/TextEditorContentIndexBehavior.cs
@@ -1,4 +1,5 @@
 using System;
+using System.Windows;
 using ICSharpCode.AvalonEdit;
 using ICSharpCode.AvalonEdit.Editing;

@@ -13,6 +14,7 @@
 		{
 			_editor = editor;
 			editor.TextArea.Caret.PositionChanged += caret_PositionChanged;
+			editor.DataContextChanged += editor_DataContextChanged;
 		}

 		internal void UpdateIndex(int index)
@@ -22,7 +24,7 @@
 			{
 				_indexBindingChanged = true;

-				if (index <= _editor.Text.Length)	 // TODO: Really fix this.
+				if (0 <= index && index <= _editor.Text.Length)	 // TODO: Really fix this.
 					_editor.TextArea.Caret.Offset = index;
 			}
 			else
@@ -37,19 +39,34 @@
 			if (caret == null)
 				return;

-			if (!_indexBindingChanged)
+			if (!_dataContextChanged)
 			{
-				_positionChanged = true;
-				AvalonEditor.SetContentIndex(_editor, caret.Offset);
+				if (!_indexBindingChanged)
+				{
+					_positionChanged = true;
+					AvalonEditor.SetContentIndex(_editor, caret.Offset);
+				}
+				else
+				{
+					_indexBindingChanged = false;
+				}
 			}
 			else
 			{
-				_indexBindingChanged = false;
+				_dataContextChanged = false;
 			}
+		}
+
+		void editor_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
+		{
+			_dataContextChanged = true;
+			_positionChanged = false;
+			_indexBindingChanged = false;
 		}

 		private bool _positionChanged;
 		private bool _indexBindingChanged;
+		private bool _dataContextChanged;

 		private readonly TextEditor _editor;
 	}


Update

Update

--- YourFood.Services/Controllers/OData/ShoppingListsController.cs
+++ YourFood.Services/Controllers/OData/ShoppingListsController.cs
@@ -123,6 +123,7 @@
         [EnableQuery]
         public IQueryable<RecipeProduct> GetProducts([FromODataUri]
                                                      int key)
+
         {
             var products = this.Data.ShoppingLists
                                .All()


Fix wrong comments (#18215)

Fix wrong comments (#18215)


ajustes

ajustes

--- SysCommand.Tests.UnitTests/Console.App/TestApp.cs
+++ SysCommand.Tests.UnitTests/Console.App/TestApp.cs
@@ -3,7 +3,6 @@
 using System;
 using System.Linq;
 using SysCommand.ConsoleApp;
-using SysCommand.Evaluation;
 using System.IO;
 using SysCommand.Test;


tweak to media.cshtml

tweak to media.cshtml

--- TestSite/Views/Partials/Grid/Editors/Media.cshtml
+++ TestSite/Views/Partials/Grid/Editors/Media.cshtml
@@ -4,7 +4,7 @@
 {
     var udi = Model.value.udi.ToString();

-    var item = Umbraco.Media(udi);
+    var item = Umbraco.Media((string)udi);

     if (item != null)
     {


Update IDE.cs

Update IDE.cs

--- source/Cosmos.HAL2/Drivers/PCI/Controllers/IDE.cs
+++ source/Cosmos.HAL2/Drivers/PCI/Controllers/IDE.cs
@@ -1,7 +1,7 @@
 using System;
 using Cosmos.HAL.BlockDevice;

-namespace Cosmos.HAL.Drivers.PCI.SATA
+namespace Cosmos.HAL.Drivers.PCI.Controllers
 {
     public class IDE
     {


Use ResouceUtility in FigletTransform

Use ResouceUtility in FigletTransform

--- source/Nuke.Common/OutputSinks/FigletTransform.cs
+++ source/Nuke.Common/OutputSinks/FigletTransform.cs
@@ -3,27 +3,24 @@
 // https://github.com/nuke-build/nuke/blob/master/LICENSE

 using System;
+using System.Diagnostics;
 using System.Diagnostics.CodeAnalysis;
 using System.IO;
 using System.Linq;
 using System.Reflection;
+using AutoMapper.XpressionMapper;
 using Colorful;
 using Nuke.Common.Utilities;

 namespace Nuke.Common.OutputSinks
 {
     [ExcludeFromCodeCoverage]
-    public static class FigletTransform
+    public class FigletTransform
     {
         public static string GetText(string text, string integratedFontName = null)
         {
-            integratedFontName = integratedFontName ?? "cybermedium";
-
-            var fullResourceName = $"{typeof(IOutputSink).Namespace}.Fonts.{integratedFontName}.flf";
-            var assembly = typeof(FigletTransform).GetTypeInfo().Assembly;
-            var resourceStream = assembly.GetManifestResourceStream(fullResourceName);
-
-            return GetText(text, resourceStream.NotNull("resourceStream != null"));
+            var resource = ResourceUtility.GetResource<FigletTransform>($"Fonts.{integratedFontName ?? "cybermedium"}.flf");
+            return GetText(text, resource);
         }

         public static string GetText(string text, Stream stream)


native locator adjustment

native locator adjustment

--- TestsFinal/TestsFinal.DroidNative/MVVM/Locator.cs
+++ TestsFinal/TestsFinal.DroidNative/MVVM/Locator.cs
@@ -37,19 +37,5 @@
             navigationService.Configure(typeof(T).ToString(), typeof(TK));
             SimpleIoc.Default.Register<T>();
         }
-
-        public CreateGlobalCalculationViewModel GlobalCalculationViewModel
-        {
-            get { return ServiceLocator.Current.GetInstance<CreateGlobalCalculationViewModel>(); }
-        }
-
-        public GlobalCalculationViewModel LocalCalculationViewModel
-        {
-            get { return ServiceLocator.Current.GetInstance<GlobalCalculationViewModel>(); }
-        }
-        public MainViewModel MainViewModel
-        {
-            get { return ServiceLocator.Current.GetInstance<MainViewModel>(); }
-        }
     }
 }


Revise nullability of Extensions.*

Revise nullability of Extensions.*

--- ThScoreFileConverter/Extensions/EnumExtensions.cs
+++ ThScoreFileConverter/Extensions/EnumExtensions.cs
@@ -76,8 +76,7 @@
                         (field, attr) => (enumValue: (TEnum)field.GetValue(null), attr))
                     .ToLookup(pair => pair.attr.GetType());

-                return lookup[typeof(TAttribute)]
-                    .ToDictionary(pair => pair.enumValue, pair => pair.attr as TAttribute);
+                return lookup[typeof(TAttribute)].ToDictionary(pair => pair.enumValue, pair => (TAttribute)pair.attr);
             }
         }
     }


Added controls to MainPage UI

Added controls to MainPage UI

--- 2_IntrToXamForms/Phoneword/Phoneword/Phoneword/MainPage.xaml.cs
+++ 2_IntrToXamForms/Phoneword/Phoneword/Phoneword/MainPage.xaml.cs
@@ -9,9 +9,49 @@
 {
     public partial class MainPage : ContentPage
     {
+        Entry phoneNumberText;
+        Button translateButton;
+        Button callButton;
+
         public MainPage()
         {
             InitializeComponent();
+
+            this.Padding = new Thickness(20, 20, 20, 20);
+
+            StackLayout panel = new StackLayout
+            {
+                Spacing = 15
+            };
+
+            panel.Children.Add(
+                new Label
+                {
+                    Text = "Enter a Phoneword:",
+                    FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label))
+                });
+
+            panel.Children.Add(
+                phoneNumberText = new Entry
+                {
+                    Text = "1-855-XAMARIN"
+                });
+
+            panel.Children.Add(
+                translateButton = new Button
+                {
+                    Text = "Translate"
+                });
+
+            panel.Children.Add(
+                callButton = new Button
+                {
+                    Text = "Call",
+                    IsEnabled = false
+                });
+
+            this.Content = panel;
+
         }
     }
 }


Fix regression in OutOfRange<T>

Fix regression in OutOfRange<T>

--- src/GuardClauses/GuardAgainstOutOfRangeExtensions.cs
+++ src/GuardClauses/GuardAgainstOutOfRangeExtensions.cs
@@ -96,7 +96,10 @@
         /// <param name="message">Optional. Custom error message</param>
         /// <returns><paramref name="input" /> if the value is in the range of valid SqlDateTime values.</returns>
         /// <exception cref="ArgumentOutOfRangeException"></exception>
-        public static DateTime OutOfSQLDateRange([JetBrainsNotNull] this IGuardClause guardClause, DateTime input, [JetBrainsNotNull][JetBrainsInvokerParameterName] string parameterName, string? message = null)
+        public static DateTime OutOfSQLDateRange([JetBrainsNotNull] this IGuardClause guardClause,
+            DateTime input,
+            [JetBrainsNotNull][JetBrainsInvokerParameterName] string parameterName,
+            string? message = null)
         {
             // System.Data is unavailable in .NET Standard so we can't use SqlDateTime.
             const long sqlMinDateTicks = 552877920000000000;
@@ -116,11 +119,15 @@
         /// <param name="message">Optional. Custom error message</param>
         /// <returns><paramref name="input" /> if the value is not out of range.</returns>
         /// <exception cref="ArgumentOutOfRangeException"></exception>
-        public static T OutOfRange<T>(this IGuardClause guardClause, T input, [JetBrainsInvokerParameterName] string parameterName, T rangeFrom, T rangeTo, string? message = null) where T : IComparable, IComparable<T>
+        public static T OutOfRange<T>(this IGuardClause guardClause, T input,
+            [JetBrainsInvokerParameterName] string parameterName,
+            T rangeFrom,
+            T rangeTo,
+            string? message = null) where T : IComparable, IComparable<T>
         {
             if (rangeFrom.CompareTo(rangeTo) > 0)
             {
-                throw new ArgumentException(message ?? $"{nameof(rangeFrom)} should be less or equal than {nameof(rangeTo)}");
+                throw new ArgumentException(message ?? $"{nameof(rangeFrom)} should be less or equal than {nameof(rangeTo)}", parameterName);
             }

             if (input.CompareTo(rangeFrom) < 0 || input.CompareTo(rangeTo) > 0)
@@ -129,7 +136,7 @@
                 {
                     throw new ArgumentOutOfRangeException(parameterName, $"Input {parameterName} was out of range");
                 }
-                throw new ArgumentOutOfRangeException(message, (Exception?)null);
+                throw new ArgumentOutOfRangeException(parameterName, message);
             }

             return input;


Redirect to the correct URL after updating OpenID

--- App/StackExchange.DataExplorer/Controllers/AccountController.cs
+++ App/StackExchange.DataExplorer/Controllers/AccountController.cs
@@ -133,7 +133,7 @@
                           openId = Current.DB.Query<UserOpenId>("select top 1 * from UserOpenIds  where UserId = @Id", new {CurrentUser.Id}).First();
                           Current.DB.UserOpenIds.Update(openId.Id, new { OpenIdClaim = claimedId });
                           user = CurrentUser;
-                          returnUrl = "/user/" + user.Id;
+                          returnUrl = "/users/" + user.Id;
                         }
                         else if (openId == null)
                         {


EnumMaskPropertyDrawer:Sync gist

EnumMaskPropertyDrawer:Sync gist

gist版とバージョンを合わせる

--- Assets/Utility/EnumMaskPropertyDrawer/EnumMaskPropertyDrawer.cs
+++ Assets/Utility/EnumMaskPropertyDrawer/EnumMaskPropertyDrawer.cs
@@ -14,17 +14,44 @@

 	public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
 		if (SerializedPropertyType.Enum == property.propertyType) {
-			var parent_object = property.serializedObject.targetObject;
-			var current = parent_object.GetType().GetField(property.propertyPath).GetValue(parent_object);
-			EditorGUI.BeginChangeCheck();
-			var value = EditorGUI.EnumMaskField(position, label, (System.Enum)current);
-			if (EditorGUI.EndChangeCheck()) {
-				current = value;
-				parent_object.GetType().GetField(property.propertyPath).SetValue(parent_object, current);
+			object current = GetCurrent(property);
+			if (null != current) {
+				EditorGUI.BeginChangeCheck();
+				var value = EditorGUI.EnumMaskField(position, label, (System.Enum)current);
+				if (EditorGUI.EndChangeCheck()) {
+					property.intValue = System.Convert.ToInt32(value);
+				}
 			}
 		} else {
 			EditorGUI.LabelField(position, label, new GUIContent("This type has not supported."));
 		}
+	}
+
+	private static object GetCurrent(SerializedProperty property) {
+		object result = property.serializedObject.targetObject;
+		var property_names = property.propertyPath.Replace(".Array.data", ".").Split('.');
+		foreach (var property_name in property_names) {
+			var parent = result;
+			var indexer_start = property_name.IndexOf('[');
+			if (-1 == indexer_start) {
+				var binding_flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic;
+				result = parent.GetType().GetField(property_name, binding_flags).GetValue(parent);
+			} else if (parent.GetType().IsArray) {
+				var indexer_end = property_name.IndexOf(']');
+				var index_string = property_name.Substring(indexer_start + 1, indexer_end - indexer_start - 1);
+				var index = int.Parse(index_string);
+				var array = (System.Array)parent;
+				if (index < array.Length) {
+					result = array.GetValue(index);
+				} else {
+					result = null;
+					break;
+				}
+			} else {
+				throw new System.MissingFieldException();
+			}
+		}
+		return result;
 	}
 }
 #endif


PXE deploy fix.

PXE deploy fix.

--- source2/VSIP/Cosmos.VS.Package/VsProjectConfig.cs
+++ source2/VSIP/Cosmos.VS.Package/VsProjectConfig.cs
@@ -46,7 +46,7 @@

         } else if (xTarget == BuildTarget.PXE) {
           string xPxePath = Path.Combine(CosmosPaths.Build, "PXE");
-          File.Copy(xBinFile, Path.Combine(xPxePath, "Cosmos.bin"));
+          File.Copy(xBinFile, Path.Combine(xPxePath, "Cosmos.bin"), true);
           Process.Start(Path.Combine(CosmosPaths.Tools, "Cosmos.Deploy.Pixie.GUI.exe"), "192.168.42.1 \"" + xPxePath + "\"");

         } else if (xTarget == BuildTarget.VMware) {


More merge conflicts

More merge conflicts

--- Basic.Azure.Storage.Tests.Integration/BlobServiceClientTests.cs
+++ Basic.Azure.Storage.Tests.Integration/BlobServiceClientTests.cs
@@ -2,7 +2,6 @@
 using Basic.Azure.Storage.Communications.BlobService;
 using Basic.Azure.Storage.Communications.Common;
 using Basic.Azure.Storage.Communications.ServiceExceptions;
-using Microsoft.WindowsAzure.Storage;
 using NUnit.Framework;
 using System;
 using System.Collections.Generic;
@@ -13,7 +12,6 @@
 using System.Threading;
 using System.Threading.Tasks;
 using Basic.Azure.Storage.Communications.Utility;
-using Microsoft.WindowsAzure.Storage.Blob;
 using BlobType = Microsoft.WindowsAzure.Storage.Blob.BlobType;
 using LeaseDuration = Basic.Azure.Storage.Communications.Common.LeaseDuration;
 using LeaseState = Basic.Azure.Storage.Communications.Common.LeaseState;


added another command to friends from the view model

--- relay_commands/RelayCommands/ViewModels/MainViewModel.cs
+++ relay_commands/RelayCommands/ViewModels/MainViewModel.cs
@@ -13,18 +13,25 @@
 {
     class MainViewModel : ViewModelBase
     {
-        private readonly IUserMessageService _userMessageService;
         public MainViewModel(IUserService userService,
-            IUserMessageService userMessageService)
+            IUserMessageService userMessageService,
+            FriendsViewModel friendsViewModel)
         {
-            _userMessageService = userMessageService;
-
             Title = "Relay Commands Demo";

             userService.UserChanged += (s, e) =>
                 {
                     CurrentUser = e.NewUser;
                 };
+
+            friendsViewModel.Commands.Add(new FriendCommand
+                {
+                    Header = "Login with this user",
+                    Command = new RelayCommand<UserData>(user=>
+                    {
+                        userService.SetUser(user);
+                    })
+                });

             GCCommand = new RelayCommand(() =>
             {


Fix links

Fix links


Fix assembly loading name format

Fix assembly loading name format

--- src/serilog-generator/Configuration/CurrentDirectoryAssemblyLoader.cs
+++ src/serilog-generator/Configuration/CurrentDirectoryAssemblyLoader.cs
@@ -10,7 +10,7 @@
         {
             AppDomain.CurrentDomain.AssemblyResolve += (s, e) =>
             {
-                var assemblyPath = Path.Combine(Environment.CurrentDirectory, e.Name + ".dll");
+                var assemblyPath = Path.Combine(Environment.CurrentDirectory, new AssemblyName(e.Name).Name + ".dll");
                 return !File.Exists(assemblyPath) ? null : Assembly.LoadFrom(assemblyPath);
             };
         }


CMS update of rest/messages/sms-conversation-tracking by dprothero@twilio.com

--- rest/messages/sms-conversation-tracking/example-1.4.x.cs
+++ rest/messages/sms-conversation-tracking/example-1.4.x.cs
@@ -1,48 +0,0 @@
-// In Package Manager, run:
-// Install-Package Twilio.Mvc -DependencyVersion HighestMinor
-
-using System.Collections.Generic;
-using System.Web.Mvc;
-using Twilio.Mvc;
-using Twilio.TwiML;
-using Twilio.TwiML.Mvc;
-
-public class SmsController : TwilioController
-{
-    [HttpPost]
-    public ActionResult Index(SmsRequest request)
-    {
-        var counter = 0;
-
-        // get the session varible if it exists
-        if (Session["counter"] != null)
-        {
-            counter = (int) Session["counter"];
-        }
-
-        // increment it
-        counter++;
-
-        // save it
-        Session["counter"] = counter;
-
-        // make an associative array of senders we know, indexed by phone number
-        var people = new Dictionary<string, string>()
-        {
-            {"+14158675309", "Rey"},
-            {"+14158675310", "Finn"},
-            {"+14158675311", "Chewy"}
-        };
-
-        // if the sender is known, then greet them by name
-        var name = "Friend";
-        if (people.ContainsKey(request.From))
-        {
-            name = people[request.From];
-        }
-
-        var response = new TwilioResponse();
-        response.Message($"{name} has messaged {request.To} {counter} times");
-        return TwiML(response);
-    }
-}


fix: New GUID in AssemblyInfo, too

fix: New GUID in AssemblyInfo, too

--- Duplicati/Library/Backend/Tardigrade/Properties/AssemblyInfo.cs
+++ Duplicati/Library/Backend/Tardigrade/Properties/AssemblyInfo.cs
@@ -20,7 +20,7 @@
 [assembly: ComVisible(false)]

 // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
-[assembly: Guid("ae035e01-c917-4f13-f35e-78f21c1a2f17")]
+[assembly: Guid("9A04CB37-DA72-4008-9703-3AC5191974E9")]

 // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
 //


Fixed documentation

Fixed documentation

--- src/Kephas.Core/Application/IAppLifecycleBehavior.cs
+++ src/Kephas.Core/Application/IAppLifecycleBehavior.cs
@@ -38,7 +38,7 @@
         Task BeforeAppInitializeAsync(IAppContext appContext, CancellationToken cancellationToken = default);

         /// <summary>
-        /// Interceptor called after a feature completes its asynchronous initialization.
+        /// Interceptor called after the application completes its asynchronous initialization.
         /// </summary>
         /// <param name="appContext">Context for the application.</param>
         /// <param name="cancellationToken">The cancellation token (optional).</param>
@@ -48,7 +48,7 @@
         Task AfterAppInitializeAsync(IAppContext appContext, CancellationToken cancellationToken = default);

         /// <summary>
-        /// Interceptor called before a feature starts its asynchronous finalization.
+        /// Interceptor called before the application starts its asynchronous finalization.
         /// </summary>
         /// <remarks>
         /// To interrupt finalization, simply throw any appropriate exception.
@@ -62,7 +62,7 @@
         Task BeforeAppFinalizeAsync(IAppContext appContext, CancellationToken cancellationToken = default);

         /// <summary>
-        /// Interceptor called after a feature completes its asynchronous finalization.
+        /// Interceptor called after the application completes its asynchronous finalization.
         /// </summary>
         /// <param name="appContext">Context for the application.</param>
         /// <param name="cancellationToken">The cancellation token (optional).</param>


Code style changes.

Code style changes.

--- src/Magick.NET/Shared/Settings/MagickReadSettings.cs
+++ src/Magick.NET/Shared/Settings/MagickReadSettings.cs
@@ -41,14 +41,10 @@
         /// </summary>
         /// <param name="readDefines">The read defines to set.</param>
         public MagickReadSettings(IReadDefines readDefines)
-        {
-            SetDefines(readDefines);
-        }
+            => SetDefines(readDefines);

         internal MagickReadSettings(MagickSettings settings)
-        {
-            CopyFrom(settings);
-        }
+            => CopyFrom(settings);

         internal MagickReadSettings(IMagickReadSettings<QuantumType> settings)
         {


Add UmbracoProperty to GridContentMediaValue

--- Gibe.DittoProcessors/Processors/Models/GridContentMediaValue.cs
+++ Gibe.DittoProcessors/Processors/Models/GridContentMediaValue.cs
@@ -1,9 +1,14 @@
-namespace Gibe.DittoProcessors.Processors.Models
+using Our.Umbraco.Ditto;
+
+namespace Gibe.DittoProcessors.Processors.Models
 {
 	public class GridContentMediaValue
 	{
 		public int Id { get; set; }
+
+		[UmbracoProperty("umbracoFile")]
 		public string Image { get; set; }
+
 		public string Caption { get; set; }
 	}
 }


Correctly read the end-time of a station program/block.

--- src/Neptunium/Core/Stations/NepAppStationsManager.cs
+++ src/Neptunium/Core/Stations/NepAppStationsManager.cs
@@ -137,7 +137,7 @@

                                             if (listingElement.Attribute("EndTime") != null)
                                             {
-                                                listing.EndTime = DateTime.Parse(listingElement.Attribute("Time").Value);
+                                                listing.EndTime = DateTime.Parse(listingElement.Attribute("EndTime").Value);
                                             }

                                             listings.Add(listing);


Fix Google ClientId

Fix Google ClientId

--- KompetansetorgetXamarin/KompetansetorgetXamarin/AuthProvider.cs
+++ KompetansetorgetXamarin/KompetansetorgetXamarin/AuthProvider.cs
@@ -12,6 +12,7 @@
         // For Google login, configure at https://console.developers.google.com/
         public static string Name = "Google";
         public static string ClientId = "976073814766-kpv0giko30e7s8u3gd15s7238a2hqesl.apps.googleusercontent.com";
+        //public static string ClientId = "232694463747-kvgavlaaekt3jj6vb934koptl6rsv1q2.apps.googleusercontent.com";
         public static string ClientSecret = "";

         // These values do not need changing
@@ -21,7 +22,7 @@
         public static string UserInfoUrl = "https://www.googleapis.com/oauth2/v2/userinfo";

         // Set this property to the location the user will be redirected too after successfully authenticating
-        public static string RedirectUrl = "http://blank.org";
+        public static string RedirectUrl = "https://httpbin.org/get";
         public static string Image = "http://icons.iconarchive.com/icons/graphics-vibe/simple-rounded-social/128/google-icon.png";
         public static string ApiRequests = "https://maps.googleapis.com/maps/api/geocode/json?address=122+Flinders+St,+Darlinghurst,+NSW,+Australia&sensor=false";
     }


More carefully specify how the new process should be started/spawned.

--- LINQToTTree/LINQToTTreeLib/ExecutionCommon/LocalBashExecutor.cs
+++ LINQToTTree/LINQToTTreeLib/ExecutionCommon/LocalBashExecutor.cs
@@ -155,6 +155,12 @@
             proc.StartInfo.RedirectStandardOutput = true;
             proc.StartInfo.WorkingDirectory = tmpDir.FullName;

+            // Get the start info stuff configured properly
+            proc.StartInfo.LoadUserProfile = true;
+            proc.StartInfo.CreateNoWindow = true;
+            proc.StartInfo.UseShellExecute = false;
+            proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
+
             proc.StartInfo.FileName = FindBash();
             proc.StartInfo.Arguments = $"-c {NormalizeFileForTarget(tmpDir)}/{reason}.sh &> {NormalizeFileForTarget(logFile)}";

@@ -220,11 +226,17 @@
             startInfo.FileName = FindBash();

             // We are going to write out a log file
-
-            // Run root with the path as an argument.
             FileInfo macroFile = new FileInfo(rootMacroFilePath);
             var logFile = new FileInfo(macroFile.FullName + "-log");
+
+            // Run root with the path as an argument.
             startInfo.Arguments = $"-c \". {GetROOTBinaryPath()}/thisroot.sh; root -b -q {macroFile.ConvertToBash()} &> {logFile.ConvertToBash()}\"";
+
+            // Get the start info stuff configured properly
+            startInfo.LoadUserProfile = true;
+            startInfo.CreateNoWindow = true;
+            startInfo.UseShellExecute = false;
+            startInfo.WindowStyle = ProcessWindowStyle.Hidden;

             return logFile;
         }


fixed issue  #150 Remote Volume controls do not work with build 3052011654

--- MediaBrowser.Theater.Implementations/Commands/CommandManager.cs
+++ MediaBrowser.Theater.Implementations/Commands/CommandManager.cs
@@ -162,8 +162,6 @@

         public void input_AppCommand(object sender, AppCommandEventArgs appCommandEventArgs)
         {
-            Boolean handled = false;
-
             var appCommand = MapAppCommand(appCommandEventArgs.Cmd);
             _logger.Debug("input_AppCommand: {0} {1}", appCommandEventArgs.Cmd, appCommand == null ? "null" : appCommand.ToString());

@@ -172,19 +170,20 @@
                 if (IsDuplicateMediaKeyEvent(appCommand.Value))
                 {
                     _logger.Debug("input_AppCommand: IsDuplicate - cmd {0} after key {1}", appCommand, _lastKeyDown);
-                    handled = true;
+                    appCommandEventArgs.Handled = false;
                 }
                 else
                 {
                     if (_commandReceived != null)
                     {
                         var command = _inputCommandMaps.GetMappedCommand(appCommand.Value);
-                        _commandReceived.Invoke(null, new CommandEventArgs {Command = command});
-                        handled = true;
+                        var commandEventArgs = new CommandEventArgs { Command = command, Handled = appCommandEventArgs.Handled};
+                        _commandReceived.Invoke(null, commandEventArgs);
+                        appCommandEventArgs.Handled = commandEventArgs.Handled;
                     }
                 }
-
-                if (handled)
+
+                if (appCommandEventArgs.Handled)
                 {
                     _lastCmd = appCommand.Value;
                     _lastCmdTime = DateTime.Now;
@@ -194,8 +193,6 @@
                     _logger.Debug("input_AppCommand {0}, command not handled", appCommand);
                 }
             }
-
-           appCommandEventArgs.Handled = handled;
         }


Optimize content tests. PP9-6352

Optimize content tests. PP9-6352

--- src/Picturepark.SDK.V1.Tests/Clients/ContentTests.cs
+++ src/Picturepark.SDK.V1.Tests/Clients/ContentTests.cs
@@ -61,7 +61,7 @@
         public async Task ShouldGetMany()
         {
             /// Arrange
-            var contentIds = new string[]
+            var contentIds = new[]
             {
                 await _fixture.GetRandomContentIdAsync(".jpg", 50).ConfigureAwait(false),
                 await _fixture.GetRandomContentIdAsync(".jpg", 50).ConfigureAwait(false)
@@ -81,7 +81,7 @@
         public async Task ShouldTransferOwnershipMany()
         {
             /// Arrange
-            var contentIds = new string[]
+            var contentIds = new[]
             {
                 await _fixture.GetRandomContentIdAsync(".jpg", 50).ConfigureAwait(false),
                 await _fixture.GetRandomContentIdAsync(".jpg", 50).ConfigureAwait(false)
@@ -150,7 +150,7 @@
             };

             request.Aggregators.Add(numRangeAggregator);
-            ObjectAggregationResult result = await _client.Contents.AggregateAsync(request);
+            await _client.Contents.AggregateAsync(request);
         }

         [Fact]
@@ -289,7 +289,7 @@
         public async Task ShouldCreateContent()
         {
             /// Arrange
-            await SetupContentItemSchema().ConfigureAwait(false);
+            await SetupSchema(typeof(ContentItem)).ConfigureAwait(false);

             var request = new ContentCreateRequest
             {
@@ -310,7 +310,7 @@
         public async Task ShouldCreateContents()
         {
             /// Arrange
-            await SetupContentItemSchema().ConfigureAwait(false);
+            await SetupSchema(typeof(ContentItem)).ConfigureAwait(false);

             var request1 = new ContentCreateRequest
             {
@@ -369,7 +369,7 @@
         {
             string contentId = await _fixture.GetRandomContentIdAsync(".jpg", 20).ConfigureAwait(false);
             Assert.False(string.IsNullOrEmpty(contentId));
-            ContentDetail contentDetail = await _client.Contents.GetAsync(contentId, new ContentResolveBehaviour[] { ContentResolveBehaviour.Content }).ConfigureAwait(false);
+            ContentDetail contentDetail = await _client.Contents.GetAsync(contentId, new[] { ContentResolveBehaviour.Content }).ConfigureAwait(false);

             var fileMetadata = contentDetail.GetFileMetadata();
             var fileName = new Random().Next(0, 999999) + "-" + fileMetadata.FileName + ".jpg";
@@ -432,7 +432,7 @@
             };

             /// Act
-            var response = await _client.Contents.UpdateMetadataAsync(contentId, request, new ContentResolveBehaviour[] { ContentResolveBehaviour.Metadata }).ConfigureAwait(false);
+            var response = await _client.Contents.UpdateMetadataAsync(contentId, request, new[] { ContentResolveBehaviour.Metadata }).ConfigureAwait(false);

             /// Assert
             Assert.NotNull(response);
@@ -496,11 +496,7 @@
         public async Task ShouldSetLayerAndResolveDisplayValues()
         {
             /// Arrange
-            var schemas = await _client.Schemas.GenerateSchemasAsync(typeof(PersonShot)).ConfigureAwait(false);
-            foreach (var schema in schemas)
-            {
-                await _client.Schemas.CreateOrUpdateAndWaitForCompletionAsync(schema, true).ConfigureAwait(false);
-            }
+            await SetupSchema(typeof(PersonShot)).ConfigureAwait(false);

             var contentId = await _fixture.GetRandomContentIdAsync(".jpg", 20).ConfigureAwait(false);
             var request = new ContentMetadataUpdateRequest
@@ -520,7 +516,7 @@
             };

             /// Act
-            var response = await _client.Contents.UpdateMetadataAsync(contentId, request, new ContentResolveBehaviour[] { ContentResolveBehaviour.Metadata, ContentResolveBehaviour.InnerDisplayValueName }).ConfigureAwait(false);
+            var response = await _client.Contents.UpdateMetadataAsync(contentId, request, new[] { ContentResolveBehaviour.Metadata, ContentResolveBehaviour.InnerDisplayValueName }).ConfigureAwait(false);

             /// Assert
             Assert.Equal("test description", ((JObject)response.Metadata["personShot"])["displayValue"]["name"].ToString());
@@ -531,14 +527,8 @@
         public async Task ShouldMergeLayersOnMetadataUpdate()
         {
             /// Arrange
-            foreach (var type in new[] { typeof(PersonShot), typeof(AllDataTypesContract) })
-            {
-                var schemas = await _client.Schemas.GenerateSchemasAsync(type).ConfigureAwait(false);
-                foreach (var schema in schemas)
-                {
-                    await _client.Schemas.CreateOrUpdateAndWaitForCompletionAsync(schema, true).ConfigureAwait(false);
-                }
-            }
+            await SetupSchema(typeof(PersonShot)).ConfigureAwait(false);
+            await SetupSchema(typeof(AllDataTypesContract)).ConfigureAwait(false);

             var contentId = await _fixture.GetRandomContentIdAsync(".jpg", 20).ConfigureAwait(false);
             var request = new ContentMetadataUpdateRequest
@@ -577,7 +567,7 @@
             };

             /// Act
-            var response = await _client.Contents.UpdateMetadataAsync(contentId, request, new ContentResolveBehaviour[] { ContentResolveBehaviour.Metadata }).ConfigureAwait(false);
+            var response = await _client.Contents.UpdateMetadataAsync(contentId, request, new[] { ContentResolveBehaviour.Metadata }).ConfigureAwait(false);

             /// Assert
             Assert.Equal("test description", ((JObject)response.Metadata["personShot"])["description"].ToString());
@@ -589,26 +579,18 @@
         public async Task ShouldReplaceLayersOnMetadataUpdate()
         {
             /// Arrange
-            var schemaSuffix = new Random().Next(0, 999999);
-            foreach (var type in new[] { typeof(PersonShot), typeof(AllDataTypesContract) })
-            {
-                var schemas = await _client.Schemas.GenerateSchemasAsync(type).ConfigureAwait(false);
-                foreach (var schema in schemas)
-                {
-                    AppendSchemaIdSuffix(schema, schemaSuffix);
-                    await _client.Schemas.CreateOrUpdateAndWaitForCompletionAsync(schema, true).ConfigureAwait(false);
-                }
-            }
+            await SetupSchema(typeof(PersonShot)).ConfigureAwait(false);
+            await SetupSchema(typeof(AllDataTypesContract)).ConfigureAwait(false);

             var contentId = await _fixture.GetRandomContentIdAsync(".jpg", 20).ConfigureAwait(false);
             var request = new ContentMetadataUpdateRequest
             {
                 Id = contentId,
-                LayerSchemaIds = new List<string> { nameof(PersonShot) + schemaSuffix },
+                LayerSchemaIds = new List<string> { nameof(PersonShot) },
                 Metadata = new DataDictionary
                 {
                     {
-                        nameof(PersonShot) + schemaSuffix,
+                        nameof(PersonShot),
                         new Dictionary<string, object>
                         {
                             { "Description", "test description" }
@@ -620,43 +602,6 @@
             await _client.Contents.UpdateMetadataAsync(contentId, request).ConfigureAwait(false);

             request = new ContentMetadataUpdateRequest
-            {
-                Id = contentId,
-                LayerSchemaIds = new List<string> { nameof(AllDataTypesContract) + schemaSuffix },
-                Metadata = new DataDictionary
-                {
-                    {
-                        nameof(AllDataTypesContract) + schemaSuffix,
-                        new Dictionary<string, object>
-                        {
-                            { "IntegerField", 12345 }
-                        }
-                    }
-                },
-                LayerSchemasUpdateOptions = UpdateOption.Replace
-            };
-
-            /// Act
-            var response = await _client.Contents.UpdateMetadataAsync(contentId, request, new ContentResolveBehaviour[] { ContentResolveBehaviour.Metadata }).ConfigureAwait(false);
-
-            /// Assert
-            Assert.DoesNotContain("personShot", response.Metadata.Keys);
-            Assert.Equal(12345, ((JObject)response.Metadata["allDataTypesContract" + schemaSuffix])["integerField"].ToObject<int>());
-        }
-
-        [Fact]
-        [Trait("Stack", "Contents")]
-        public async Task ShouldMergeFieldsOnMetadataUpdate()
-        {
-            /// Arrange
-            var schemas = await _client.Schemas.GenerateSchemasAsync(typeof(AllDataTypesContract)).ConfigureAwait(false);
-            foreach (var schema in schemas)
-            {
-                await _client.Schemas.CreateOrUpdateAndWaitForCompletionAsync(schema, true).ConfigureAwait(false);
-            }
-
-            var contentId = await _fixture.GetRandomContentIdAsync(".jpg", 20).ConfigureAwait(false);
-            var request = new ContentMetadataUpdateRequest
             {
                 Id = contentId,
                 LayerSchemaIds = new List<string> { nameof(AllDataTypesContract) },
@@ -669,12 +614,27 @@
                             { "IntegerField", 12345 }
                         }
                     }
-                }
-            };
-
-            await _client.Contents.UpdateMetadataAsync(contentId, request).ConfigureAwait(false);
-
-            request = new ContentMetadataUpdateRequest
+                },
+                LayerSchemasUpdateOptions = UpdateOption.Replace
+            };
+
+            /// Act
+            var response = await _client.Contents.UpdateMetadataAsync(contentId, request, new[] { ContentResolveBehaviour.Metadata }).ConfigureAwait(false);
+
+            /// Assert
+            Assert.DoesNotContain("personShot", response.Metadata.Keys);
+            Assert.Equal(12345, ((JObject)response.Metadata["allDataTypesContract"])["integerField"].ToObject<int>());
+        }
+
+        [Fact]
+        [Trait("Stack", "Contents")]
+        public async Task ShouldMergeFieldsOnMetadataUpdate()
+        {
+            /// Arrange
+            await SetupSchema(typeof(AllDataTypesContract)).ConfigureAwait(false);
+
+            var contentId = await _fixture.GetRandomContentIdAsync(".jpg", 20).ConfigureAwait(false);
+            var request = new ContentMetadataUpdateRequest
             {
                 Id = contentId,
                 LayerSchemaIds = new List<string> { nameof(AllDataTypesContract) },
@@ -684,34 +644,15 @@
                         nameof(AllDataTypesContract),
                         new Dictionary<string, object>
                         {
-                            { "StringField", "test string" }
-                        }
-                    }
-                },
-                SchemaFieldsUpdateOptions = UpdateOption.Merge
-            };
-
-            /// Act
-            var response = await _client.Contents.UpdateMetadataAsync(contentId, request, new ContentResolveBehaviour[] { ContentResolveBehaviour.Metadata }).ConfigureAwait(false);
-
-            /// Assert
-            Assert.Equal(12345, ((JObject)response.Metadata["allDataTypesContract"])["integerField"].ToObject<int>());
-            Assert.Equal("test string", ((JObject)response.Metadata["allDataTypesContract"])["stringField"].ToString());
-        }
-
-        [Fact]
-        [Trait("Stack", "Contents")]
-        public async Task ShouldReplaceFieldsOnMetadataUpdate()
-        {
-            /// Arrange
-            var schemas = await _client.Schemas.GenerateSchemasAsync(typeof(AllDataTypesContract)).ConfigureAwait(false);
-            foreach (var schema in schemas)
-            {
-                await _client.Schemas.CreateOrUpdateAndWaitForCompletionAsync(schema, true).ConfigureAwait(false);
-            }
-
-            var contentId = await _fixture.GetRandomContentIdAsync(".jpg", 20).ConfigureAwait(false);
-            var request = new ContentMetadataUpdateRequest
+                            { "IntegerField", 12345 }
+                        }
+                    }
+                }
+            };
+
+            await _client.Contents.UpdateMetadataAsync(contentId, request).ConfigureAwait(false);
+
+            request = new ContentMetadataUpdateRequest
             {
                 Id = contentId,
                 LayerSchemaIds = new List<string> { nameof(AllDataTypesContract) },
@@ -721,15 +662,30 @@
                         nameof(AllDataTypesContract),
                         new Dictionary<string, object>
                         {
-                            { "IntegerField", 12345 }
-                        }
-                    }
-                }
-            };
-
-            await _client.Contents.UpdateMetadataAsync(contentId, request).ConfigureAwait(false);
-
-            request = new ContentMetadataUpdateRequest
+                            { "StringField", "test string" }
+                        }
+                    }
+                },
+                SchemaFieldsUpdateOptions = UpdateOption.Merge
+            };
+
+            /// Act
+            var response = await _client.Contents.UpdateMetadataAsync(contentId, request, new[] { ContentResolveBehaviour.Metadata }).ConfigureAwait(false);
+
+            /// Assert
+            Assert.Equal(12345, ((JObject)response.Metadata["allDataTypesContract"])["integerField"].ToObject<int>());
+            Assert.Equal("test string", ((JObject)response.Metadata["allDataTypesContract"])["stringField"].ToString());
+        }
+
+        [Fact]
+        [Trait("Stack", "Contents")]
+        public async Task ShouldReplaceFieldsOnMetadataUpdate()
+        {
+            /// Arrange
+            await SetupSchema(typeof(AllDataTypesContract)).ConfigureAwait(false);
+
+            var contentId = await _fixture.GetRandomContentIdAsync(".jpg", 20).ConfigureAwait(false);
+            var request = new ContentMetadataUpdateRequest
             {
                 Id = contentId,
                 LayerSchemaIds = new List<string> { nameof(AllDataTypesContract) },
@@ -739,6 +695,24 @@
                         nameof(AllDataTypesContract),
                         new Dictionary<string, object>
                         {
+                            { "IntegerField", 12345 }
+                        }
+                    }
+                }
+            };
+
+            await _client.Contents.UpdateMetadataAsync(contentId, request).ConfigureAwait(false);
+
+            request = new ContentMetadataUpdateRequest
+            {
+                Id = contentId,
+                LayerSchemaIds = new List<string> { nameof(AllDataTypesContract) },
+                Metadata = new DataDictionary
+                {
+                    {
+                        nameof(AllDataTypesContract),
+                        new Dictionary<string, object>
+                        {
                             { "StringField", "test string" }
                         }
                     }
@@ -747,7 +721,7 @@
             };

             /// Act
-            var response = await _client.Contents.UpdateMetadataAsync(contentId, request, new ContentResolveBehaviour[] { ContentResolveBehaviour.Metadata }).ConfigureAwait(false);
+            var response = await _client.Contents.UpdateMetadataAsync(contentId, request, new[] { ContentResolveBehaviour.Metadata }).ConfigureAwait(false);

             /// Assert
             Assert.Null(((JObject)response.Metadata["allDataTypesContract"])["integerField"]);
@@ -841,7 +815,7 @@
             var contentId = await _fixture.GetRandomContentIdAsync(".jpg", 20).ConfigureAwait(false);

             Assert.False(string.IsNullOrEmpty(contentId));
-            ContentDetail contentDetail = await _client.Contents.GetAsync(contentId, new ContentResolveBehaviour[] { ContentResolveBehaviour.Content }).ConfigureAwait(false);
+            ContentDetail contentDetail = await _client.Contents.GetAsync(contentId, new[] { ContentResolveBehaviour.Content }).ConfigureAwait(false);

             var fileMetadata = contentDetail.GetFileMetadata();
             var fileName = new Random().Next(0, 999999) + "-" + fileMetadata.FileName + ".jpg";
@@ -887,7 +861,7 @@
             var contentId = await _fixture.GetRandomContentIdAsync(".jpg", 20).ConfigureAwait(false);
             Assert.False(string.IsNullOrEmpty(contentId));

-            ContentDetail result = await _client.Contents.GetAsync(contentId, new ContentResolveBehaviour[] { ContentResolveBehaviour.InnerDisplayValueList }).ConfigureAwait(false);
+            ContentDetail result = await _client.Contents.GetAsync(contentId, new[] { ContentResolveBehaviour.InnerDisplayValueList }).ConfigureAwait(false);
             Assert.NotNull(result.Id);
         }

@@ -902,7 +876,7 @@

             Assert.False(string.IsNullOrEmpty(contentId));

-            ContentDetail result = await _client.Contents.GetAsync(contentId, new ContentResolveBehaviour[] { ContentResolveBehaviour.Content }).ConfigureAwait(false);
+            ContentDetail result = await _client.Contents.GetAsync(contentId, new[] { ContentResolveBehaviour.Content }).ConfigureAwait(false);

             FileMetadata fileMetadata = result.GetFileMetadata();
             Assert.False(string.IsNullOrEmpty(fileMetadata.FileName));
@@ -916,7 +890,7 @@
             var contentId = await _fixture.GetRandomContentIdAsync(".jpg", 20).ConfigureAwait(false);

             /// Act
-            var contentDetail = await _client.Contents.GetAsync(contentId, new ContentResolveBehaviour[] { ContentResolveBehaviour.Metadata, ContentResolveBehaviour.LinkedListItems }).ConfigureAwait(false);
+            var contentDetail = await _client.Contents.GetAsync(contentId, new[] { ContentResolveBehaviour.Metadata, ContentResolveBehaviour.LinkedListItems }).ConfigureAwait(false);

             /// Assert
             Assert.Equal(contentId, contentDetail.Id);
@@ -1000,7 +974,7 @@
         public async Task ShouldDeactivateAndReactivateContent()
         {
             /// Arrange
-            await SetupContentItemSchema().ConfigureAwait(false);
+            await SetupSchema(typeof(ContentItem)).ConfigureAwait(false);

             var request = new ContentCreateRequest
             {
@@ -1028,7 +1002,7 @@
         public async Task ShouldDeactivateAndReactivateContentMany()
         {
             /// Arrange
-            await SetupContentItemSchema().ConfigureAwait(false);
+            await SetupSchema(typeof(ContentItem)).ConfigureAwait(false);

             var content1 = await _client.Contents.CreateAsync(new ContentCreateRequest
             {
@@ -1134,7 +1108,7 @@
             };

             // Act
-            var result = await _client.Contents.UpdatePermissionsAsync(contentDetail.Id, request).ConfigureAwait(false);
+            await _client.Contents.UpdatePermissionsAsync(contentDetail.Id, request).ConfigureAwait(false);

             var currentContentDetail = await _client.Contents.GetAsync(contentId).ConfigureAwait(false);
             var currentContentPermissionSetIds = currentContentDetail.ContentPermissionSetIds.Select(i => i).ToList();
@@ -1315,12 +1289,15 @@
             }
         }

-        private async Task SetupContentItemSchema()
-        {
-            var schemas = await _client.Schemas.GenerateSchemasAsync(typeof(ContentItem)).ConfigureAwait(false);
+        private async Task SetupSchema(Type type)
+        {
+            var schemas = await _client.Schemas.GenerateSchemasAsync(type).ConfigureAwait(false);
             foreach (var schema in schemas)
             {
-                await _client.Schemas.CreateOrUpdateAndWaitForCompletionAsync(schema, false).ConfigureAwait(false);
+                if (await _client.Schemas.ExistsAsync(schema.Id).ConfigureAwait(false) == false)
+                {
+                    await _client.Schemas.CreateAndWaitForCompletionAsync(schema, true).ConfigureAwait(false);
+                }
             }
         }
     }


git-svn-id: svn://localhost/mosa@873 45b04e34-05f1-4d87-a130-40a8491d5c8b

--- Mosa/Runtime/CompilerFramework/IL/CilToIRTransformationStage.cs
+++ Mosa/Runtime/CompilerFramework/IL/CilToIRTransformationStage.cs
@@ -29,24 +29,13 @@
         CodeTransformationStage,
         IILVisitor<CodeTransformationStage.Context>
     {
-        #region Construction
-
-        /// <summary>
-        /// Initializes a new instance of <see cref="CilToIrTransformationStage"/>.
-        /// </summary>
-        public CilToIrTransformationStage()
-        {
-        }
-
-        #endregion // Construction
-
         #region IMethodCompilerStage Members

         /// <summary>
         /// Retrieves the name of the compilation stage.
         /// </summary>
         /// <value>The name of the compilation stage.</value>
-        public sealed override string Name
+        public override string Name
         {
             get { return @"CilToIrTransformationStage"; }
         }
@@ -55,7 +44,7 @@
         /// Adds this stage to the given pipeline.
         /// </summary>
         /// <param name="pipeline">The pipeline to add this stage to.</param>
-		public sealed override void AddToPipeline(CompilerPipeline<IMethodCompilerStage> pipeline)
+		public override void AddToPipeline(CompilerPipeline<IMethodCompilerStage> pipeline)
 		{
 		}

@@ -78,7 +67,7 @@

         void IILVisitor<Context>.Ldarga(LdargaInstruction instruction, Context ctx)
         {
-            Replace(ctx, new IR.AddressOfInstruction(instruction.Results[0], instruction.Operands[0]));
+            Replace(ctx, new AddressOfInstruction(instruction.Results[0], instruction.Operands[0]));
         }

         void IILVisitor<Context>.Ldloc(LdlocInstruction instruction, Context ctx)
@@ -88,7 +77,7 @@

         void IILVisitor<Context>.Ldloca(LdlocaInstruction instruction, Context ctx)
         {
-            Replace(ctx, new IR.AddressOfInstruction(instruction.Results[0], instruction.Operands[0]));
+            Replace(ctx, new AddressOfInstruction(instruction.Results[0], instruction.Operands[0]));
         }

         void IILVisitor<Context>.Ldc(LdcInstruction instruction, Context ctx)
@@ -117,12 +106,12 @@
         void IILVisitor<Context>.Ldsfld(LdsfldInstruction instruction, Context ctx)
         {
             RuntimeField field = instruction.Field;
-            Replace(ctx, new IR.MoveInstruction(instruction.Results[0], new MemberOperand(field)));
+            Replace(ctx, new MoveInstruction(instruction.Results[0], new MemberOperand(field)));
         }

         void IILVisitor<Context>.Ldsflda(LdsfldaInstruction instruction, Context ctx)
         {
-            Replace(ctx, new IR.AddressOfInstruction(instruction.Results[0], instruction.Operands[0]));
+            Replace(ctx, new AddressOfInstruction(instruction.Results[0], instruction.Operands[0]));
         }

         void IILVisitor<Context>.Ldftn(LdftnInstruction instruction, Context ctx)
@@ -153,7 +142,7 @@
         void IILVisitor<Context>.Stobj(StobjInstruction instruction, Context ctx)
         {
             // This is actually stind.* and stobj - the opcodes have the same meanings
-            Replace(ctx, new IR.StoreInstruction(instruction.Operands[0], instruction.Operands[1]));
+            Replace(ctx, new StoreInstruction(instruction.Operands[0], instruction.Operands[1]));
         }

         void IILVisitor<Context>.Stfld(StfldInstruction instruction, Context ctx)
@@ -163,7 +152,7 @@
         void IILVisitor<Context>.Stsfld(StsfldInstruction instruction, Context ctx)
         {
             RuntimeField field = instruction.Field;
-            Replace(ctx, new IR.MoveInstruction(new MemberOperand(field), instruction.Operands[0]));
+            Replace(ctx, new MoveInstruction(new MemberOperand(field), instruction.Operands[0]));
         }

         void IILVisitor<Context>.Dup(DupInstruction instruction, Context ctx)
@@ -220,23 +209,23 @@
             switch (instruction.Code)
             {
                 case OpCode.And:
-                    type = typeof(IR.LogicalAndInstruction);
+                    type = typeof(LogicalAndInstruction);
                     break;

                 case OpCode.Or:
-                    type = typeof(IR.LogicalOrInstruction);
+                    type = typeof(LogicalOrInstruction);
                     break;

                 case OpCode.Xor:
-                    type = typeof(IR.LogicalXorInstruction);
+                    type = typeof(LogicalXorInstruction);
                     break;

                 case OpCode.Div_un:
-                    type = typeof(IR.UDivInstruction);
+                    type = typeof(UDivInstruction);
                     break;

                 case OpCode.Rem_un:
-                    type = typeof(IR.URemInstruction);
+                    type = typeof(URemInstruction);
                     break;

                 default:
@@ -253,15 +242,15 @@
             switch (instruction.Code)
             {
                 case OpCode.Shl:
-                    replType = typeof(IR.ShiftLeftInstruction);
+                    replType = typeof(ShiftLeftInstruction);
                     break;

                 case OpCode.Shr:
-                    replType = typeof(IR.ArithmeticShiftRightInstruction);
+                    replType = typeof(ArithmeticShiftRightInstruction);
                     break;

                 case OpCode.Shr_un:
-                    replType = typeof(IR.ShiftRightInstruction);
+                    replType = typeof(ShiftRightInstruction);
                     break;

                 default:
@@ -274,15 +263,14 @@

         void IILVisitor<Context>.Neg(NegInstruction instruction, Context ctx)
         {
-            Replace(ctx, new Instruction[] {
-                //_architecture.CreateInstruction(typeof(IL.BinaryLogicInstruction), OpCode.Xor, instruction.Results[0], instruction.Results[0]),
-                _architecture.CreateInstruction(typeof(IL.SubInstruction), OpCode.Sub, instruction.Results[0], instruction.Operands[0])
+            Replace(ctx, new[] {
+                _architecture.CreateInstruction(typeof(SubInstruction), OpCode.Sub, instruction.Results[0], instruction.Operands[0])
             });
         }

         void IILVisitor<Context>.Not(NotInstruction instruction, Context ctx)
         {
-            Replace(ctx, _architecture.CreateInstruction(typeof(IR.LogicalNotInstruction), instruction.Results[0], instruction.Operands[0]));
+            Replace(ctx, _architecture.CreateInstruction(typeof(LogicalNotInstruction), instruction.Results[0], instruction.Operands[0]));
         }

         void IILVisitor<Context>.Conversion(ConversionInstruction instruction, Context ctx)
@@ -482,7 +470,7 @@
         /// <param name="dest">The destination operand.</param>
         /// <param name="source">The source operand.</param>
         /// <returns>True if the store is truncating, otherwise false.</returns>
-        private bool IsTruncating(Operand dest, Operand source)
+        private static bool IsTruncating(Operand dest, Operand source)
         {
             CilElementType cetDest = dest.Type.Type;
             CilElementType cetSource = source.Type.Type;
@@ -491,16 +479,16 @@
             {
                 return (cetSource == CilElementType.I8 || cetSource == CilElementType.U8);
             }
-            else if (cetDest == CilElementType.I2 || cetDest == CilElementType.U2 || cetDest == CilElementType.Char)
+            if (cetDest == CilElementType.I2 || cetDest == CilElementType.U2 || cetDest == CilElementType.Char)
             {
                 return (cetSource == CilElementType.I8 || cetSource == CilElementType.U8 || cetSource == CilElementType.I4 || cetSource == CilElementType.U4);
             }
-            else if (cetDest == CilElementType.I1 || cetDest == CilElementType.U1)
+            if (cetDest == CilElementType.I1 || cetDest == CilElementType.U1)
             {
                 return (cetSource == CilElementType.I8 || cetSource == CilElementType.U8 || cetSource == CilElementType.I4 || cetSource == CilElementType.U4 || cetSource == CilElementType.I2 || cetSource == CilElementType.U2 || cetSource == CilElementType.U2);
             }
-            else
-                return false;
+
+            return false;
         }

         /// <summary>
@@ -508,27 +496,11 @@
         /// </summary>
         /// <param name="source">The source operand to determine sign extension for.</param>
         /// <returns>True if the given operand should be loaded with its sign extended.</returns>
-        private bool IsSignExtending(Operand source)
+        private static bool IsSignExtending(Operand source)
         {
             bool result = false;
             CilElementType cet = source.Type.Type;
             if (cet == CilElementType.I1 || cet == CilElementType.I2)
-            {
-                result = true;
-            }
-            return result;
-        }
-
-        /// <summary>
-        /// Determines if the load should zero extend the given source operand.
-        /// </summary>
-        /// <param name="source">The source operand to determine zero extension for.</param>
-        /// <returns>True if the given operand should be loaded zero extended.</returns>
-        private bool IsZeroExtending(Operand source)
-        {
-            bool result = false;
-            CilElementType cet = source.Type.Type;
-            if (cet == CilElementType.U1 || cet == CilElementType.U2 || cet == CilElementType.Char)
             {
                 result = true;
             }
@@ -833,93 +805,6 @@
             CheckAndConvertInstruction(ctx, dest, src);
         }

-        private void ComputeExtensionTypeAndMask(ConvType destinationType, ref Type extensionType, ref uint mask)
-        {
-            switch (destinationType)
-            {
-                case ConvType.I1:
-                    mask = 0xFF;
-                    extensionType = typeof(IR.SignExtendedMoveInstruction);
-                    break;
-
-                case ConvType.I2:
-                    mask = 0xFFFF;
-                    extensionType = typeof(IR.SignExtendedMoveInstruction);
-                    break;
-
-                case ConvType.I4:
-                    mask = 0xFFFFFFFF;
-                    break;
-
-                case ConvType.I8:
-                    break;
-
-                case ConvType.U1:
-                    mask = 0xFF;
-                    extensionType = typeof(IR.ZeroExtendedMoveInstruction);
-                    break;
-
-                case ConvType.U2:
-                    mask = 0xFFFF;
-                    extensionType = typeof(IR.ZeroExtendedMoveInstruction);
-                    break;
-
-                case ConvType.U4:
-                    mask = 0xFFFFFFFF;
-                    break;
-
-                case ConvType.U8:
-                    break;
-
-                case ConvType.R4:
-                    break;
-
-                case ConvType.R8:
-                    break;
-
-                case ConvType.I:
-                    break;
-
-                case ConvType.U:
-                    break;
-
-                case ConvType.Ptr:
-                    break;
-
-                default:
-                    Debug.Assert(false);
-                    throw new NotSupportedException();
-            }
-        }
-
-        private void ProcessMixedTypeConversion(List<Instruction> instructionList, Type type, uint mask, Operand destinationOperand, Operand sourceOperand)
-        {
-            instructionList.AddRange(new Instruction[] {
-                _architecture.CreateInstruction(type, destinationOperand, sourceOperand),
-                _architecture.CreateInstruction(typeof(LogicalAndInstruction), destinationOperand, destinationOperand, new ConstantOperand(new SigType(CilElementType.U4), mask))
-            });
-        }
-
-        private void ProcessSingleTypeTruncation(List<Instruction> instructionList, Type type, uint mask, Operand destinationOperand, Operand sourceOperand)
-        {
-            if (sourceOperand.Type.Type == CilElementType.I8 || sourceOperand.Type.Type == CilElementType.U8)
-            {
-                instructionList.Add(_architecture.CreateInstruction(typeof(IR.MoveInstruction), destinationOperand, sourceOperand));
-                instructionList.Add(_architecture.CreateInstruction(type, destinationOperand, sourceOperand, new ConstantOperand(new SigType(CilElementType.U4), mask)));
-            }
-            else
-                instructionList.Add(_architecture.CreateInstruction(type, destinationOperand, sourceOperand, new ConstantOperand(new SigType(CilElementType.U4), mask)));
-        }
-
-        private void ExtendAndTruncateResult(List<Instruction> instructionList, Type extensionType, Operand destinationOperand)
-        {
-            if (null != extensionType && destinationOperand is RegisterOperand)
-            {
-                RegisterOperand resultOperand = new RegisterOperand(new SigType(CilElementType.I4), ((RegisterOperand)destinationOperand).Register);
-                instructionList.Add(_architecture.CreateInstruction(extensionType, resultOperand, destinationOperand));
-            }
-        }
-
         private void CheckAndConvertInstruction(Context context, Operand destinationOperand, Operand sourceOperand)
         {
             uint mask = 0;
@@ -933,12 +818,12 @@

             ComputeExtensionTypeAndMask(ctDest, ref extension, ref mask);

-            if (type == typeof(IR.LogicalAndInstruction) || 0 != mask)
+            if (type == typeof(LogicalAndInstruction) || 0 != mask)
             {
                 Debug.Assert(0 != mask, @"Conversion is an AND, but no mask given.");

                 List<Instruction> instructions = new List<Instruction>();
-                if (type != typeof(IR.LogicalAndInstruction))
+                if (type != typeof(LogicalAndInstruction))
                 {
                     ProcessMixedTypeConversion(instructions, type, mask, destinationOperand, sourceOperand);
                 }
@@ -956,31 +841,92 @@
                 Replace(context, _architecture.CreateInstruction(type, destinationOperand, sourceOperand));
             }
         }
-        /// <summary>
-        /// Truncates I8 operands to I4 operands, as a conversion down to smaller types is always truncating.
-        /// </summary>
-        /// <param name="op">The operand to truncate.</param>
-        /// <returns>The truncated operand.</returns>
-        private Operand TruncateI8(Operand op)
-        {
-            Operand res = op;
-            if (op.Type.Type == CilElementType.I8 || op.Type.Type == CilElementType.U8)
-            {
-                if (op is RegisterOperand)
-                {
-                    res = new RegisterOperand(new SigType(CilElementType.I4), ((RegisterOperand)op).Register);
-                }
-                else if (op is MemoryOperand)
-                {
-                    MemoryOperand mop = ((MemoryOperand)op);
-                    res = new MemoryOperand(new SigType(CilElementType.I4), mop.Base, new IntPtr(-0x10));
-                }
-                else
-                {
+
+        private void ComputeExtensionTypeAndMask(ConvType destinationType, ref Type extensionType, ref uint mask)
+        {
+            switch (destinationType)
+            {
+                case ConvType.I1:
+                    mask = 0xFF;
+                    extensionType = typeof(SignExtendedMoveInstruction);
+                    break;
+
+                case ConvType.I2:
+                    mask = 0xFFFF;
+                    extensionType = typeof(SignExtendedMoveInstruction);
+                    break;
+
+                case ConvType.I4:
+                    mask = 0xFFFFFFFF;
+                    break;
+
+                case ConvType.I8:
+                    break;
+
+                case ConvType.U1:
+                    mask = 0xFF;
+                    extensionType = typeof(ZeroExtendedMoveInstruction);
+                    break;
+
+                case ConvType.U2:
+                    mask = 0xFFFF;
+                    extensionType = typeof(ZeroExtendedMoveInstruction);
+                    break;
+
+                case ConvType.U4:
+                    mask = 0xFFFFFFFF;
+                    break;
+
+                case ConvType.U8:
+                    break;
+
+                case ConvType.R4:
+                    break;
+
+                case ConvType.R8:
+                    break;
+
+                case ConvType.I:
+                    break;
+
+                case ConvType.U:
+                    break;
+
+                case ConvType.Ptr:
+                    break;
+
+                default:
+                    Debug.Assert(false);
                     throw new NotSupportedException();
-                }
-            }
-            return res;
+            }
+        }
+
+        private void ProcessMixedTypeConversion(List<Instruction> instructionList, Type type, uint mask, Operand destinationOperand, Operand sourceOperand)
+        {
+            instructionList.AddRange(new[] {
+                _architecture.CreateInstruction(type, destinationOperand, sourceOperand),
+                _architecture.CreateInstruction(typeof(LogicalAndInstruction), destinationOperand, destinationOperand, new ConstantOperand(new SigType(CilElementType.U4), mask))
+            });
+        }
+
+        private void ProcessSingleTypeTruncation(List<Instruction> instructionList, Type type, uint mask, Operand destinationOperand, Operand sourceOperand)
+        {
+            if (sourceOperand.Type.Type == CilElementType.I8 || sourceOperand.Type.Type == CilElementType.U8)
+            {
+                instructionList.Add(_architecture.CreateInstruction(typeof(IR.MoveInstruction), destinationOperand, sourceOperand));
+                instructionList.Add(_architecture.CreateInstruction(type, destinationOperand, sourceOperand, new ConstantOperand(new SigType(CilElementType.U4), mask)));
+            }
+            else
+                instructionList.Add(_architecture.CreateInstruction(type, destinationOperand, sourceOperand, new ConstantOperand(new SigType(CilElementType.U4), mask)));
+        }
+
+        private void ExtendAndTruncateResult(List<Instruction> instructionList, Type extensionType, Operand destinationOperand)
+        {
+            if (null != extensionType && destinationOperand is RegisterOperand)
+            {
+                RegisterOperand resultOperand = new RegisterOperand(new SigType(CilElementType.I4), ((RegisterOperand)destinationOperand).Register);
+                instructionList.Add(_architecture.CreateInstruction(extensionType, resultOperand, destinationOperand));
+            }
         }

         /// <summary>
@@ -1061,7 +1007,7 @@
         /// </summary>
         /// <param name="load">The IL load instruction to process.</param>
         /// <param name="ctx">Provides the transformation context.</param>
-        private void ProcessLoadInstruction(IL.ILoadInstruction load, Context ctx)
+        private void ProcessLoadInstruction(ILoadInstruction load, Context ctx)
         {
             // We don't need to rewire the source/destination yet, its already there. :(
             Remove(ctx);
@@ -1106,25 +1052,25 @@
         private void ProcessStoreInstruction(IStoreInstruction store, Context ctx)
         {
             // Do we need to truncate the value?
-            if (true == IsTruncating(store.Destination, store.Source))
+            if (IsTruncating(store.Destination, store.Source))
             {
                 // Replace it with a truncating move...
                 // FIXME: Implement proper truncation as specified in the CIL spec
                 //Debug.Assert(false);
                 if (IsSignExtending(store.Source))
-                    Replace(ctx, _architecture.CreateInstruction(typeof(IR.SignExtendedMoveInstruction), store.Destination, store.Source));
+                    Replace(ctx, _architecture.CreateInstruction(typeof(SignExtendedMoveInstruction), store.Destination, store.Source));
                 else
-                    Replace(ctx, _architecture.CreateInstruction(typeof(IR.ZeroExtendedMoveInstruction), store.Destination, store.Source));
+                    Replace(ctx, _architecture.CreateInstruction(typeof(ZeroExtendedMoveInstruction), store.Destination, store.Source));
                 return;
             }
-            else if (1 == store.Source.Definitions.Count && 1 == store.Source.Uses.Count)
+            if (1 == store.Source.Definitions.Count && 1 == store.Source.Uses.Count)
             {
                 store.Source.Replace(store.Destination);
                 Remove(ctx);
                 return;
             }

-            Replace(ctx, _architecture.CreateInstruction(typeof(IR.MoveInstruction), store.Destination, store.Source));
+            Replace(ctx, _architecture.CreateInstruction(typeof(MoveInstruction), store.Destination, store.Source));
         }

@@ -1162,7 +1108,7 @@
             RuntimeMethod callTarget = FindMethod(rt, internalCallTarget.ToString());

             // Transform the opcode with an internal call
-            IL.CallInstruction call = new CallInstruction(OpCode.Call);
+            CallInstruction call = new CallInstruction(OpCode.Call);
             call.SetInvokeTarget(_compiler, callTarget);

             int i = 0;


Implemented HIFO cost basis

Implemented HIFO cost basis

--- src/Portrack/Portrack/Models/Application/Position.cs
+++ src/Portrack/Portrack/Models/Application/Position.cs
@@ -39,12 +39,25 @@
 			};
 		}

+		// <summary>
+		/// Calculate the cost basis of the position based on selected method
+		/// </summary>
+		/// <param name="transactions">All the transaction on that position.</param>
+		/// <returns>a decimal, the cost basis of the position.</returns>
+		private decimal CalculateCostBasis(IEnumerable<Transaction> transactions)
+		{
+			//todo Give user the ability to choose a method or automatically choose for him
+			return CalculateCostBasisFIFO(transactions);
+			//return CalculateCostBasisHIFO(transactions);
+			//return CalculateCostBasisAverage(transactions);
+		}
+
 		/// <summary>
 		/// Calculate the cost basis of the position using FIFO method.
 		/// </summary>
 		/// <param name="transactions">All the transaction on that position.</param>
 		/// <returns>a decimal, the cost basis of the position.</returns>
-		private decimal CalculateCostBasis(IEnumerable<Transaction> transactions)
+		private decimal CalculateCostBasisFIFO(IEnumerable<Transaction> transactions)
 		{
 			transactions = transactions.OrderBy(t => t.Date);

@@ -65,6 +78,7 @@
 					int transactionQuantity = transaction.Shares;
 					foreach (DatedSharesAndPrice datedSharesAndPrice in datedSharesAndPrices.OrderBy(qd => qd.Date))
 					{
+
 						if (transactionQuantity <= datedSharesAndPrice.Shares)
 						{
 							datedSharesAndPrice.Shares -= transactionQuantity;
@@ -78,13 +92,58 @@
 						}
 					}
 				}
-				else { } // Should never happen for now.
+				else
+				{
+					throw new ArgumentException("Invalid Transaction type. Must be either Buy or Sell");
+				}
 			}

 			decimal costBasis = 0;
 			datedSharesAndPrices.ForEach(qd => costBasis += qd.Shares * qd.PricePerShare);

 			return costBasis;
+		}
+
+		/// <summary>
+		/// Calculate the cost basis of the position using High-Cost First-Out method.
+		/// It sells the more expensive share first
+		/// </summary>
+		/// <param name="transactions">All the transaction on that position.</param>
+		/// <returns>a decimal, the cost basis of the position.</returns>
+		private decimal CalculateCostBasisHIFO(IEnumerable<Transaction> transactions)
+		{
+			IEnumerable<Transaction> transactionsBuy = transactions.Where(t => t.Type == TransactionType.Buy)
+																   .OrderByDescending(t => t.Price);
+			IEnumerable<Transaction> transactionsSell = transactions.Where(t => t.Type == TransactionType.Sell)
+																	.OrderBy(t => t.Date);
+			foreach (Transaction sale in transactionsSell)
+			{
+				int transactionQuantity = sale.Shares;
+				foreach (Transaction purchase in transactionsBuy)
+				{
+					if (transactionQuantity <= purchase.Shares)
+					{
+						purchase.Shares -= transactionQuantity;
+						break;
+					}
+					else
+					{
+						transactionQuantity -= purchase.Shares;
+						purchase.Shares = 0;
+						continue;
+					}
+				}
+			}
+
+			decimal costBasis = 0;
+			transactionsBuy.ToList<Transaction>().ForEach(t => costBasis += t.Shares * t.Price);
+
+			return costBasis;
+		}
+
+		private decimal CalculateCostBasisAverage(IEnumerable<Transaction> transactions)
+		{
+			throw new NotImplementedException();
 		}

 		private class DatedSharesAndPrice


Implementing decryption

Implementing decryption

Forgot to implement the DecryptString method, which was causing a
NotImplementedException to be called every time the method was
invoked.

--- MunkeyIssues.Core/Services/Cryptography/RSAEncryptionService.cs
+++ MunkeyIssues.Core/Services/Cryptography/RSAEncryptionService.cs
@@ -19,16 +19,10 @@

         public string EncryptString(string data, string publicKey)
         {
-            using (var rsa = new RSACryptoServiceProvider())
-            {
-                var key = DecodeString(publicKey);
-                rsa.FromXmlString(key);
+            var bytes = Encoding.UTF8.GetBytes(data);
+            var encrypted = Encrypt(bytes, publicKey);

-                var bytes = Encoding.UTF8.GetBytes(data);
-                var encrypted = rsa.Encrypt(bytes, true);
-
-                return Convert.ToBase64String(encrypted);
-            }
+            return Convert.ToBase64String(encrypted);
         }

         public byte[] Decrypt(byte[] data, string privateKey)
@@ -44,7 +38,8 @@

         public string DecryptString(string data, string privateKey)
         {
-            throw new NotImplementedException();
+            var bytes = Decrypt(Convert.FromBase64String(data), privateKey);
+            return Encoding.UTF8.GetString(bytes);
         }

         private static string EncodeString(byte[] bytes)


Fixed casing

Fixed casing

--- src/SFA.DAS.EAS.Web/Views/EmployerTeam/Remove.cshtml
+++ src/SFA.DAS.EAS.Web/Views/EmployerTeam/Remove.cshtml
@@ -39,7 +39,7 @@

-
Back to Manage Team Members

+
Back to Manage Team Members

 }


Make bit default logger thread safe (Initial phase)

--- src/Server/Bit.Owin/Implementations/DefaultLogger.cs
+++ src/Server/Bit.Owin/Implementations/DefaultLogger.cs
@@ -1,4 +1,5 @@
 using System;
+using System.Collections.Concurrent;
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
 using System.Diagnostics;
@@ -57,7 +58,7 @@
                 throw new AggregateException(logExceptions);
         }

-        public virtual IEnumerable<LogData> LogData { get; protected set; } = new Collection<LogData>();
+        public virtual IEnumerable<LogData> LogData { get; protected set; } = new BlockingCollection<LogData> { };

         public LogPolicy Policy { get; set; } = LogPolicy.InCaseOfScopeFailure;


Fixed the data state to no longer add the newline when populating a header object.

--- src/SmtpPilot.Server/States/DataConversationState.cs
+++ src/SmtpPilot.Server/States/DataConversationState.cs
@@ -39,7 +39,7 @@
                 if (IO.IOHelper.LooksLikeHeader(line))
                 {
                     string[] header = line.Split(new char[] { ':' }, 2);
-                    context.AddHeader(new SmtpHeader(header[0], header[1]));
+                    context.AddHeader(new SmtpHeader(header[0], header[1].Replace(Environment.NewLine, String.Empty)));
                 }
                 else
                 {


Add support for null values in KeyBitmaps again.

--- src/StreamDeckSharp/Internals/KeyBitmapExtensions.cs
+++ src/StreamDeckSharp/Internals/KeyBitmapExtensions.cs
@@ -11,6 +11,9 @@
         public static byte[] GetScaledVersion(this KeyBitmap keyBitmap, int width, int height)
         {
             var keyDataAccess = (IKeyBitmapDataAccess)keyBitmap;
+
+            if (keyDataAccess.IsNull)
+                return null;

             var rawData = new byte[keyDataAccess.DataLength];
             keyDataAccess.CopyData(rawData, 0);


fix broken unit test

fix broken unit test

--- OBeautifulCode.AccountingTime.Test/UnitOfTime/UnitOfTimeTest.cs
+++ OBeautifulCode.AccountingTime.Test/UnitOfTime/UnitOfTimeTest.cs
@@ -306,7 +306,7 @@
             var result = systemUnderTest1.Equals(systemUnderTest2);

             // Assert
-            result.Should().BeTrue();
+            result.Should().BeFalse();
         }

         [Fact]


use IReadOnlyCollection instead of IList

--- PDiffy.Web/Features/ImageDifference/ImageDifferenceViewModel.cs
+++ PDiffy.Web/Features/ImageDifference/ImageDifferenceViewModel.cs
@@ -5,7 +5,7 @@
 {
 	public class ImageDifferenceViewModel
 	{
-		public IList<PageViewModel> Pages { get; set; }
+		public IReadOnlyCollection<PageViewModel> Pages { get; set; }
 		public PageViewModel NewPage { get; set; }
 	}
 }


Fixes copying items and moving them using transparent sync, when the destination item does not exist in the database and is only transparently synced

#116

Thanks to @sbouwmeester for figuring this out and submitting the patch.

--- src/Unicorn/Data/DataProvider/UnicornDataProvider.cs
+++ src/Unicorn/Data/DataProvider/UnicornDataProvider.cs
@@ -223,9 +223,9 @@

 			Assert.IsNotNull(existingItem, "Existing item to copy was not in the database!");

-			var destinationItem = GetSourceFromId(destination.ID);
-
-			Assert.IsNotNull(existingItem, "Copy destination was not in the database!");
+			var destinationItem = GetSourceFromId(destination.ID, true);
+
+			Assert.IsNotNull(destinationItem, "Copy destination was not in the database!");

 			// wrap the existing item in a proxy so we can mutate it into a copy
 			var copyTargetItem = new ProxyItem(existingItem);


Another StructuralComparisons usage

Another StructuralComparisons usage

--- src/WampSharp.Tests/Rpc/WampRpcClientHandlerTests.cs
+++ src/WampSharp.Tests/Rpc/WampRpcClientHandlerTests.cs
@@ -6,6 +6,9 @@
 using WampSharp.Rpc;
 using WampSharp.Tests.Rpc.Helpers;
 using WampSharp.Tests.TestHelpers;
+#if MONO
+using StructuralComparisons = WampSharp.Tests.TestHelpers.StructuralComparisons;
+#endif

 namespace WampSharp.Tests.Rpc
 {


added some missing key support to the UserInputStreamHelper

--- src/shell.me/ShellMe.Testing/LowLevelTestConsole.cs
+++ src/shell.me/ShellMe.Testing/LowLevelTestConsole.cs
@@ -30,6 +30,12 @@
                                            return new ConsoleKeyInfo('+', ConsoleKey.OemPlus, false, false, false);
                                        if (c == '!')
                                            return new ConsoleKeyInfo('!', ConsoleKey.D1, true, false, false);
+                                       if (c == '=')
+                                           return new ConsoleKeyInfo('=', ConsoleKey.D0, true, false, false);
+                                       if (c == '[')
+                                           return new ConsoleKeyInfo('[', ConsoleKey.D8, false, true, false);
+                                       if (c == ']')
+                                           return new ConsoleKeyInfo(']', ConsoleKey.D9, false, true, false);

                                        return (ConsoleKeyInfo?) null;
                                    })


fix(DevSupportManager): Fix up-to-date bundle check (#1499)

Using `IStorageItem.GetBasicPropertiesAsync()` sometimes hangs. Instead using `System.IO.FileInfo`, which doesn't seem to hang (but is blocking). Since this is debug code, it's not a huge deal.

--- ReactWindows/ReactNative.Shared/DevSupport/DevSupportManager.cs
+++ ReactWindows/ReactNative.Shared/DevSupport/DevSupportManager.cs
@@ -162,11 +162,12 @@
 #if WINDOWS_UWP
                 var lastUpdateTime = Windows.ApplicationModel.Package.Current.InstalledDate;
                 var localFolder = ApplicationData.Current.LocalFolder;
-                var bundleItem = await localFolder.TryGetItemAsync(JSBundleFileName).AsTask(token);
+                var bundleItem = await localFolder.TryGetItemAsync(JSBundleFileName);
                 if (bundleItem != null)
                 {
-                    var bundleProperties = await bundleItem.GetBasicPropertiesAsync().AsTask(token);
-                    return bundleProperties.DateModified > lastUpdateTime;
+                    // bundleItem.GetBasicPropertiesAsync() is occasionally hanging
+                    var fileInfo = new FileInfo(bundleItem.Path);
+                    return fileInfo.CreationTimeUtc > lastUpdateTime.UtcDateTime;
                 }
 #else
                 var lastUpdateTime = File.GetCreationTime(Assembly.GetExecutingAssembly().Location);