context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// // SoundMenuService.cs // // Authors: // Bertrand Lorentz <bertrand.lorentz@gmail.com> // // Copyright (C) 2010 Bertrand Lorentz // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Mono.Addins; using Mono.Unix; using Gtk; using Notifications; using Hyena; using Banshee.Base; using Banshee.Collection; using Banshee.Collection.Gui; using Banshee.Configuration; using Banshee.Gui; using Banshee.IO; using Banshee.MediaEngine; using Banshee.ServiceStack; using Banshee.Preferences; namespace Banshee.SoundMenu { public class SoundMenuService : IExtensionService { private bool? actions_supported; private ArtworkManager artwork_manager_service; private Notification current_nf; private TrackInfo current_track; private GtkElementsService elements_service; private InterfaceActionService interface_action_service; private string notify_last_artist; private string notify_last_title; private uint ui_manager_id; private SoundMenuProxy sound_menu; private const int icon_size = 42; public SoundMenuService () { } void IExtensionService.Initialize () { elements_service = ServiceManager.Get<GtkElementsService> (); interface_action_service = ServiceManager.Get<InterfaceActionService> (); var notif_addin = AddinManager.Registry.GetAddin("Banshee.NotificationArea"); var ind_addin = AddinManager.Registry.GetAddin("Banshee.AppIndicator"); if (notif_addin != null && notif_addin.Enabled) { Log.Debug("NotificationArea conflicts with SoundMenu, disabling NotificationArea"); notif_addin.Enabled = false; } else if (ind_addin != null && ind_addin.Enabled) { Log.Debug("AppIndicator conflicts with SoundMenu, disabling AppIndicator"); ind_addin.Enabled = false; } AddinManager.AddinLoaded += OnAddinLoaded; if (!ServiceStartup ()) { ServiceManager.ServiceStarted += OnServiceStarted; } } private void OnServiceStarted (ServiceStartedArgs args) { if (args.Service is Banshee.Gui.InterfaceActionService) { interface_action_service = (InterfaceActionService)args.Service; } else if (args.Service is GtkElementsService) { elements_service = (GtkElementsService)args.Service; } ServiceStartup (); } private bool ServiceStartup () { if (elements_service == null || interface_action_service == null) { return false; } interface_action_service.GlobalActions.Add (new ActionEntry [] { new ActionEntry ("CloseAction", Stock.Close, Catalog.GetString ("_Close"), "<Control>W", Catalog.GetString ("Close"), CloseWindow) }); ui_manager_id = interface_action_service.UIManager.AddUiFromString (@" <ui> <menubar name=""MainMenu""> <menu name=""MediaMenu"" action=""MediaMenuAction""> <placeholder name=""ClosePlaceholder""> <menuitem name=""Close"" action=""CloseAction""/> </placeholder> </menu> </menubar> </ui> "); interface_action_service.GlobalActions.UpdateAction ("QuitAction", false); InstallPreferences (); sound_menu = new SoundMenuProxy (); if (Enabled) { sound_menu.Register (true); } ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.StartOfStream | PlayerEvent.EndOfStream | PlayerEvent.TrackInfoUpdated | PlayerEvent.StateChange); artwork_manager_service = ServiceManager.Get<ArtworkManager> (); artwork_manager_service.AddCachedSize (icon_size); RegisterCloseHandler (); ServiceManager.ServiceStarted -= OnServiceStarted; return true; } public void Dispose () { if (current_nf != null) { try { current_nf.Close (); } catch {} } UninstallPreferences (); ServiceManager.PlayerEngine.DisconnectEvent (OnPlayerEvent); elements_service.PrimaryWindowClose = null; interface_action_service.UIManager.RemoveUi (ui_manager_id); Gtk.Action close_action = interface_action_service.GlobalActions["CloseAction"]; if (close_action != null) { interface_action_service.GlobalActions.Remove (close_action); } interface_action_service.GlobalActions.UpdateAction ("QuitAction", true); AddinManager.AddinLoaded -= OnAddinLoaded; sound_menu = null; elements_service = null; interface_action_service = null; } void OnAddinLoaded (object sender, AddinEventArgs args) { if (args.AddinId == "Banshee.NotificationArea" || args.AddinId == "Banshee.AppIndicator") { Log.Debug("SoundMenu conflicts with " + args.AddinId + ", disabling SoundMenu"); AddinManager.Registry.GetAddin("Banshee.SoundMenu").Enabled = false; } } #region Notifications private bool ActionsSupported { get { if (!actions_supported.HasValue) { actions_supported = Notifications.Global.Capabilities != null && Array.IndexOf (Notifications.Global.Capabilities, "actions") > -1; } return actions_supported.Value; } } private bool OnPrimaryWindowClose () { CloseWindow (null, null); return true; } private void CloseWindow (object o, EventArgs args) { if (ServiceManager.PlayerEngine.CurrentState == PlayerState.Playing) { elements_service.PrimaryWindow.Visible = false; } else { Banshee.ServiceStack.Application.Shutdown (); } } private void OnPlayerEvent (PlayerEventArgs args) { switch (args.Event) { case PlayerEvent.StartOfStream: case PlayerEvent.TrackInfoUpdated: current_track = ServiceManager.PlayerEngine.CurrentTrack; ShowTrackNotification (); break; case PlayerEvent.EndOfStream: current_track = null; break; } } private void OnSongSkipped (object o, ActionArgs args) { if (args.Action == "skip-song") { ServiceManager.PlaybackController.Next (); } } private string GetByFrom (string artist, string display_artist, string album, string display_album) { bool has_artist = !String.IsNullOrEmpty (artist); bool has_album = !String.IsNullOrEmpty (album); string markup = null; if (has_artist && has_album) { // Translators: {0} and {1} are Artist Name and // Album Title, respectively; // e.g. 'by Parkway Drive from Killing with a Smile' markup = String.Format (Catalog.GetString ("by '{0}' from '{1}'"), display_artist, display_album); } else if (has_album) { // Translators: {0} is for Album Title; // e.g. 'from Killing with a Smile' markup = String.Format (Catalog.GetString ("from '{0}'"), display_album); } else { // Translators: {0} is for Artist Name; // e.g. 'by Parkway Drive' markup = String.Format(Catalog.GetString ("by '{0}'"), display_artist); } return markup; } private void ShowTrackNotification () { // This has to happen before the next if, otherwise the last_* members aren't set correctly. if (current_track == null || (notify_last_title == current_track.DisplayTrackTitle && notify_last_artist == current_track.DisplayArtistName)) { return; } notify_last_title = current_track.DisplayTrackTitle; notify_last_artist = current_track.DisplayArtistName; if (!ShowNotificationsSchema.Get ()) { return; } foreach (var window in elements_service.ContentWindows) { if (window.HasToplevelFocus) { return; } } bool is_notification_daemon = false; try { var name = Notifications.Global.ServerInformation.Name; is_notification_daemon = name == "notification-daemon" || name == "Notification Daemon"; } catch { // This will be reached if no notification daemon is running return; } string message = GetByFrom ( current_track.ArtistName, current_track.DisplayArtistName, current_track.AlbumTitle, current_track.DisplayAlbumTitle); string image = null; image = is_notification_daemon ? CoverArtSpec.GetPathForSize (current_track.ArtworkId, icon_size) : CoverArtSpec.GetPath (current_track.ArtworkId); if (!File.Exists (new SafeUri(image))) { if (artwork_manager_service != null) { // artwork does not exist, try looking up the pixbuf to trigger scaling or conversion Gdk.Pixbuf tmp_pixbuf = is_notification_daemon ? artwork_manager_service.LookupScalePixbuf (current_track.ArtworkId, icon_size) : artwork_manager_service.LookupPixbuf (current_track.ArtworkId); if (tmp_pixbuf == null) { image = "audio-x-generic"; } else { tmp_pixbuf.Dispose (); } } } try { if (current_nf == null) { current_nf = new Notification (current_track.DisplayTrackTitle, message, image); } else { current_nf.Summary = current_track.DisplayTrackTitle; current_nf.Body = message; current_nf.IconName = image; } current_nf.Urgency = Urgency.Low; current_nf.Timeout = 4500; if (!current_track.IsLive && ActionsSupported && interface_action_service.PlaybackActions["NextAction"].Sensitive) { current_nf.AddAction ("skip-song", Catalog.GetString ("Skip this item"), OnSongSkipped); } current_nf.Show (); } catch (Exception e) { Log.Exception ("Cannot show notification", e); } } private void RegisterCloseHandler () { if (elements_service.PrimaryWindowClose == null) { elements_service.PrimaryWindowClose = OnPrimaryWindowClose; } } private void UnregisterCloseHandler () { if (elements_service.PrimaryWindowClose != null) { elements_service.PrimaryWindowClose = null; } } #endregion #region Preferences private PreferenceBase enabled_pref; private void InstallPreferences () { PreferenceService service = ServiceManager.Get<PreferenceService> (); if (service == null) { return; } enabled_pref = service["general"]["misc"].Add ( new SchemaPreference<bool> (EnabledSchema, Catalog.GetString ("_Show Banshee in the sound menu"), Catalog.GetString ("Control Banshee through the sound menu"), delegate { Enabled = EnabledSchema.Get (); }) ); } private void UninstallPreferences () { PreferenceService service = ServiceManager.Get<PreferenceService> (); if (service == null) { return; } service["general"]["misc"].Remove (enabled_pref); } public bool Enabled { get { return EnabledSchema.Get (); } set { if (value) { sound_menu.Register (false); RegisterCloseHandler (); } else { sound_menu.Unregister (); UnregisterCloseHandler (); } } } private static readonly SchemaEntry<bool> EnabledSchema = new SchemaEntry<bool> ( "plugins.soundmenu", "enabled", true, "Show Banshee in the sound menu", "Show Banshee in the sound menu" ); public static readonly SchemaEntry<bool> ShowNotificationsSchema = new SchemaEntry<bool> ( "plugins.soundmenu", "show_notifications", true, "Show notifications", "Show information notifications when item starts playing" ); #endregion string IService.ServiceName { get { return "SoundMenuService"; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Test.Utilities; using Xunit; namespace Desktop.Analyzers.UnitTests { public partial class DoNotUseInsecureDtdProcessingAnalyzerTests : DiagnosticAnalyzerTestBase { private static readonly string s_CA3075XmlTextReaderConstructedWithNoSecureResolutionMessage = DesktopAnalyzersResources.XmlTextReaderConstructedWithNoSecureResolutionMessage; private DiagnosticResult GetCA3075XmlTextReaderConstructedWithNoSecureResolutionCSharpResultAt(int line, int column) { return GetCSharpResultAt(line, column, CA3075RuleId, s_CA3075XmlTextReaderConstructedWithNoSecureResolutionMessage); } private DiagnosticResult GetCA3075XmlTextReaderConstructedWithNoSecureResolutionBasicResultAt(int line, int column) { return GetBasicResultAt(line, column, CA3075RuleId, s_CA3075XmlTextReaderConstructedWithNoSecureResolutionMessage); } [WorkItem(998, "https://github.com/dotnet/roslyn-analyzers/issues/998")] [Fact] public void StaticPropertyAssignmentShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System; namespace TestNamespace { public static class SystemContext { public static Func<DateTime> UtcNow { get; set; } static SystemContext() { UtcNow = () => DateTime.UtcNow; } } } " ); VerifyBasic(@" Imports System Namespace TestNamespace Module SystemContext Public Property UtcNow As Func(Of DateTime) Sub New() UtcNow = Function() DateTime.UtcNow End Sub End Module End Namespace " ); } [Fact] public void ConstructXmlTextReaderShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { public class TestClass { public void TestMethod(string path) { XmlTextReader reader = new XmlTextReader(path); } } } ", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionCSharpResultAt(10, 36) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Dim reader As New XmlTextReader(path) End Sub End Class End Namespace", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionBasicResultAt(7, 27) ); } [Fact] public void ConstructXmlTextReaderInTryBlockShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { public class TestClass { public void TestMethod(string path) { try { XmlTextReader reader = new XmlTextReader(path); } catch { throw ; } finally {} } } } ", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionCSharpResultAt(11, 40) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Try Dim reader As New XmlTextReader(path) Catch Throw Finally End Try End Sub End Class End Namespace", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionBasicResultAt(8, 31) ); } [Fact] public void ConstructXmlTextReaderInCatchBlockShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { public class TestClass { public void TestMethod(string path) { try { } catch { XmlTextReader reader = new XmlTextReader(path); } finally {} } } } ", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionCSharpResultAt(12, 40) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Try Catch Dim reader As New XmlTextReader(path) Finally End Try End Sub End Class End Namespace", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionBasicResultAt(9, 31) ); } [Fact] public void ConstructXmlTextReaderInFinallyBlockShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { public class TestClass { public void TestMethod(string path) { try { } catch { throw ; } finally { XmlTextReader reader = new XmlTextReader(path); } } } } ", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionCSharpResultAt(13, 40) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Try Catch Throw Finally Dim reader As New XmlTextReader(path) End Try End Sub End Class End Namespace", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionBasicResultAt(11, 31) ); } [Fact] public void ConstructXmlTextReaderOnlySetResolverToSecureValueShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { public class TestClass { public void TestMethod(string path) { XmlTextReader reader = new XmlTextReader(path); reader.XmlResolver = null; } } } ", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionCSharpResultAt(10, 36) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Dim reader As New XmlTextReader(path) reader.XmlResolver = Nothing End Sub End Class End Namespace", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionBasicResultAt(7, 27) ); } [Fact] public void ConstructXmlTextReaderSetResolverToSecureValueInTryBlockShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { public class TestClass { public void TestMethod(string path) { try { XmlTextReader reader = new XmlTextReader(path); reader.XmlResolver = null; } catch { throw ; } finally {} } } } ", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionCSharpResultAt(11, 40) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Try Dim reader As New XmlTextReader(path) reader.XmlResolver = Nothing Catch Throw Finally End Try End Sub End Class End Namespace", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionBasicResultAt(8, 31) ); } [Fact] public void ConstructXmlTextReaderSetResolverToSecureValueInCatchBlockShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { public class TestClass { public void TestMethod(string path) { try { } catch { XmlTextReader reader = new XmlTextReader(path); reader.XmlResolver = null; } finally {} } } } ", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionCSharpResultAt(12, 40) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Try Catch Dim reader As New XmlTextReader(path) reader.XmlResolver = Nothing Finally End Try End Sub End Class End Namespace", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionBasicResultAt(9, 31) ); } [Fact] public void ConstructXmlTextReaderSetResolverToSecureValueInFinallyBlockShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { public class TestClass { public void TestMethod(string path) { try { } catch { throw ; } finally { XmlTextReader reader = new XmlTextReader(path); reader.XmlResolver = null; } } } } ", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionCSharpResultAt(13, 40) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Try Catch Throw Finally Dim reader As New XmlTextReader(path) reader.XmlResolver = Nothing End Try End Sub End Class End Namespace", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionBasicResultAt(11, 31) ); } [Fact] public void ConstructXmlTextReaderOnlySetDtdProcessingToSecureValueShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { public class TestClass { public void TestMethod(string path) { XmlTextReader reader = new XmlTextReader(path); reader.DtdProcessing = DtdProcessing.Prohibit; } } } " ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Dim reader As New XmlTextReader(path) reader.DtdProcessing = DtdProcessing.Prohibit End Sub End Class End Namespace" ); } [Fact] public void ConstructXmlTextReaderSetDtdProcessingToSecureValueInTryBlockShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { public class TestClass { public void TestMethod(string path) { try { XmlTextReader reader = new XmlTextReader(path); reader.DtdProcessing = DtdProcessing.Prohibit; } catch { throw ; } finally {} } } } " ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Try Dim reader As New XmlTextReader(path) reader.DtdProcessing = DtdProcessing.Prohibit Catch Throw Finally End Try End Sub End Class End Namespace" ); } [Fact] public void ConstructXmlTextReaderSetDtdProcessingToSecureValueInCatchBlockShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { public class TestClass { public void TestMethod(string path) { try { } catch { XmlTextReader reader = new XmlTextReader(path); reader.DtdProcessing = DtdProcessing.Prohibit; } finally {} } } } " ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Try Catch Dim reader As New XmlTextReader(path) reader.DtdProcessing = DtdProcessing.Prohibit Finally End Try End Sub End Class End Namespace" ); } [Fact] public void ConstructXmlTextReaderSetDtdProcessingToSecureValueInFinallyBlockShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { public class TestClass { public void TestMethod(string path) { try { } catch { throw ; } finally { XmlTextReader reader = new XmlTextReader(path); reader.DtdProcessing = DtdProcessing.Prohibit; } } } } " ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Try Catch Throw Finally Dim reader As New XmlTextReader(path) reader.DtdProcessing = DtdProcessing.Prohibit End Try End Sub End Class End Namespace" ); } [Fact] public void ConstructXmlTextReaderSetResolverAndDtdProcessingToSecureValuesShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { public class TestClass { public void TestMethod(string path) { XmlTextReader reader = new XmlTextReader(path); reader.DtdProcessing = DtdProcessing.Prohibit; reader.XmlResolver = null; } } } " ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Dim reader As New XmlTextReader(path) reader.DtdProcessing = DtdProcessing.Prohibit reader.XmlResolver = Nothing End Sub End Class End Namespace"); } [Fact] public void ConstructXmlTextReaderSetSetResolverAndDtdProcessingToSecureValueInTryBlockShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { public class TestClass { public void TestMethod(string path) { try { XmlTextReader reader = new XmlTextReader(path); reader.DtdProcessing = DtdProcessing.Prohibit; reader.XmlResolver = null; } catch { throw ; } finally {} } } } " ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Try Dim reader As New XmlTextReader(path) reader.DtdProcessing = DtdProcessing.Prohibit reader.XmlResolver = Nothing Catch Throw Finally End Try End Sub End Class End Namespace"); } [Fact] public void ConstructXmlTextReaderSetSetResolverAndDtdProcessingToSecureValueInCatchBlockShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { public class TestClass { public void TestMethod(string path) { try { } catch { XmlTextReader reader = new XmlTextReader(path); reader.DtdProcessing = DtdProcessing.Prohibit; reader.XmlResolver = null; } finally {} } } } " ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Try Catch Dim reader As New XmlTextReader(path) reader.DtdProcessing = DtdProcessing.Prohibit reader.XmlResolver = Nothing Finally End Try End Sub End Class End Namespace"); } [Fact] public void ConstructXmlTextReaderSetSetResolverAndDtdProcessingToSecureValueInFinallyBlockShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { public class TestClass { public void TestMethod(string path) { try { } catch { throw ; } finally { XmlTextReader reader = new XmlTextReader(path); reader.DtdProcessing = DtdProcessing.Prohibit; reader.XmlResolver = null; } } } } "); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Try Catch Throw Finally Dim reader As New XmlTextReader(path) reader.DtdProcessing = DtdProcessing.Prohibit reader.XmlResolver = Nothing End Try End Sub End Class End Namespace " ); } [Fact] public void ConstructXmlTextReaderSetResolverAndDtdProcessingToSecureValuesInInitializerShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(string path) { XmlTextReader doc = new XmlTextReader(path) { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }; } } }"); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(path As String) Dim doc As New XmlTextReader(path) With { _ .DtdProcessing = DtdProcessing.Prohibit, _ .XmlResolver = Nothing _ } End Sub End Class End Namespace "); } [Fact] public void ConstructXmlTextReaderOnlySetResolverToSecureValueInInitializerShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(string path) { XmlTextReader doc = new XmlTextReader(path) { XmlResolver = null }; } } }", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionCSharpResultAt(10, 33) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(path As String) Dim doc As New XmlTextReader(path) With { _ .XmlResolver = Nothing _ } End Sub End Class End Namespace", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionBasicResultAt(7, 24) ); } [Fact] public void ConstructXmlTextReaderOnlySetDtdProcessingToSecureValueInInitializerShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(string path) { XmlTextReader doc = new XmlTextReader(path) { DtdProcessing = DtdProcessing.Prohibit }; } } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(path As String) Dim doc As New XmlTextReader(path) With { _ .DtdProcessing = DtdProcessing.Prohibit _ } End Sub End Class End Namespace" ); } [Fact] public void ConstructXmlTextReaderAsFieldShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { public XmlTextReader reader = new XmlTextReader(""file.xml""); } }", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionCSharpResultAt(8, 39) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Public reader As XmlTextReader = New XmlTextReader(""file.xml"") End Class End Namespace", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionBasicResultAt(6, 42) ); } [Fact] public void ConstructXmlTextReaderAsFieldSetBothToSecureValuesInInitializerShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { public XmlTextReader reader = new XmlTextReader(""file.xml"") { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }; } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Public reader As XmlTextReader = New XmlTextReader(""file.xml"") With { _ .DtdProcessing = DtdProcessing.Prohibit, _ .XmlResolver = Nothing _ } End Class End Namespace"); } [Fact] public void ConstructXmlTextReaderAsFieldOnlySetResolverToSecureValuesInInitializerShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { public XmlTextReader reader = new XmlTextReader(""file.xml"") { XmlResolver = null }; } }", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionCSharpResultAt(8, 39) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Public reader As XmlTextReader = New XmlTextReader(""file.xml"") With { _ .XmlResolver = Nothing _ } End Class End Namespace", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionBasicResultAt(7, 42) ); } [Fact] public void ConstructXmlTextReaderAsFieldOnlySetDtdProcessingToSecureValuesInInitializerShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { public XmlTextReader reader = new XmlTextReader(""file.xml"") { DtdProcessing = DtdProcessing.Prohibit }; } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Public reader As XmlTextReader = New XmlTextReader(""file.xml"") With { _ .DtdProcessing = DtdProcessing.Prohibit _ } End Class End Namespace" ); } [Fact] public void ConstructDefaultXmlTextReaderAsFieldSetBothToSecureValuesInMethodShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { public XmlTextReader reader = new XmlTextReader(""file.xml""); public TestClass() { reader.XmlResolver = null; reader.DtdProcessing = DtdProcessing.Ignore; } } }", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionCSharpResultAt(8, 39) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Public reader As XmlTextReader = New XmlTextReader(""file.xml"") Public Sub New() reader.XmlResolver = Nothing reader.DtdProcessing = DtdProcessing.Ignore End Sub End Class End Namespace ", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionBasicResultAt(6, 42) ); } [Fact] public void ConstructXmlTextReaderAsFieldOnlySetResolverToSecureValueInMethodShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { public XmlTextReader reader = new XmlTextReader(""file.xml""); public TestClass() { reader.XmlResolver = null; } } }", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionCSharpResultAt(8, 39) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Public reader As XmlTextReader = New XmlTextReader(""file.xml"") Public Sub New() reader.XmlResolver = Nothing End Sub End Class End Namespace", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionBasicResultAt(6, 42) ); } [Fact] public void ConstructXmlTextReaderAsFieldOnlySetResolverToSecureValueInMethodInTryBlockShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { public XmlTextReader reader = new XmlTextReader(""file.xml""); public void TestMethod() { try { reader.XmlResolver = null; } catch { throw; } finally { } } } }", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionCSharpResultAt(8, 39) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Public reader As XmlTextReader = New XmlTextReader(""file.xml"") Public Sub TestMethod() Try reader.XmlResolver = Nothing Catch Throw Finally End Try End Sub End Class End Namespace", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionBasicResultAt(6, 42) ); } [Fact] public void ConstructXmlTextReaderAsFieldOnlySetResolverToSecureValueInMethodInCatchBlockShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { public XmlTextReader reader = new XmlTextReader(""file.xml""); public void TestMethod() { try { } catch { reader.XmlResolver = null; } finally { } } } }", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionCSharpResultAt(8, 39) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Public reader As XmlTextReader = New XmlTextReader(""file.xml"") Public Sub TestMethod() Try Catch reader.XmlResolver = Nothing Finally End Try End Sub End Class End Namespace", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionBasicResultAt(6, 42) ); } [Fact] public void ConstructXmlTextReaderAsFieldOnlySetResolverToSecureValueInMethodInFinallyBlockShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { public XmlTextReader reader = new XmlTextReader(""file.xml""); public void TestMethod() { try { } catch { throw; } finally { reader.XmlResolver = null; } } } }", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionCSharpResultAt(8, 39) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Public reader As XmlTextReader = New XmlTextReader(""file.xml"") Public Sub TestMethod() Try Catch Throw Finally reader.XmlResolver = Nothing End Try End Sub End Class End Namespace", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionBasicResultAt(6, 42) ); } [Fact] public void ConstructXmlTextReaderAsFieldOnlySetDtdProcessingToSecureValueInMethodShouldGenerateDiagnostic() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { public XmlTextReader reader = new XmlTextReader(""file.xml""); public TestClass() { reader.DtdProcessing = DtdProcessing.Ignore; } } }", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionCSharpResultAt(8, 39) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Public reader As XmlTextReader = New XmlTextReader(""file.xml"") Public Sub New() reader.DtdProcessing = DtdProcessing.Ignore End Sub End Class End Namespace", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionBasicResultAt(6, 42) ); } [Fact] public void XmlTextReaderDerivedTypeWithNoSecureSettingsShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; namespace TestNamespace { class DerivedType : XmlTextReader {} class TestClass { void TestMethod() { var c = new DerivedType(); } } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class DerivedType Inherits XmlTextReader End Class Class TestClass Private Sub TestMethod() Dim c = New DerivedType() End Sub End Class End Namespace"); } [Fact] public void XmlTextReaderCreatedAsTempNoSettingsShouldGenerateDiagnostics() { VerifyCSharp(@" using System.Xml; namespace TestNamespace { class TestClass { public void Method1(string path) { Method2(new XmlTextReader(path)); } public void Method2(XmlTextReader reader){} } }", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionCSharpResultAt(11, 21) ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Public Sub Method1(path As String) Method2(New XmlTextReader(path)) End Sub Public Sub Method2(reader As XmlTextReader) End Sub End Class End Namespace", GetCA3075XmlTextReaderConstructedWithNoSecureResolutionBasicResultAt(8, 21) ); } [Fact] public void ConstructXmlTextReaderOnlySetDtdProcessingProhibitTargetFx46ShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Reflection; using System.Xml; [assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute("".NETFramework,Version=v4.6"", FrameworkDisplayName = "".NET Framework 4.6"")] namespace TestNamespace { public class TestClass { public void TestMethod(string path) { XmlTextReader reader = new XmlTextReader(path); reader.DtdProcessing = DtdProcessing.Prohibit; } } } " ); VerifyBasic(@" Imports System.Reflection Imports System.Xml <Assembly: System.Runtime.Versioning.TargetFrameworkAttribute("".NETFramework, Version = v4.6"", FrameworkDisplayName := "".NET Framework 4.6"")> Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Dim reader As New XmlTextReader(path) reader.DtdProcessing = DtdProcessing.Prohibit End Sub End Class End Namespace"); } [Fact] public void ConstructXmlTextReaderOnlySetDtdProcessingProhibitTargetFx452ShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Reflection; using System.Xml; [assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute("".NETFramework,Version=v4.5.2"", FrameworkDisplayName = "".NET Framework 4.5.2"")] namespace TestNamespace { public class TestClass { public void TestMethod(string path) { XmlTextReader reader = new XmlTextReader(path); reader.DtdProcessing = DtdProcessing.Prohibit; } } } " ); VerifyBasic(@" Imports System.Reflection Imports System.Xml <Assembly: System.Runtime.Versioning.TargetFrameworkAttribute("".NETFramework, Version = v4.5.2"", FrameworkDisplayName := "".NET Framework 4.5.2"")> Namespace TestNamespace Public Class TestClass Public Sub TestMethod(path As String) Dim reader As New XmlTextReader(path) reader.DtdProcessing = DtdProcessing.Prohibit End Sub End Class End Namespace" ); } } }
using System; using System.Collections.Generic; using Microsoft.VisualStudio.Text; namespace NuGetConsole.Implementation.Console { interface IGetSpan<T> { Span GetSpan(T t); } class OrderedSpans<T> { List<T> _items = new List<T>(); IGetSpan<T> _getSpan; public OrderedSpans(IGetSpan<T> getSpan) { UtilityMethods.ThrowIfArgumentNull(getSpan); _getSpan = getSpan; } Span GetSpan(T t) { return _getSpan.GetSpan(t); } public int Count { get { return _items.Count; } } public T this[int i] { get { return _items[i]; } } public void Clear() { _items.Clear(); } public void Add(T t) { if (_items.Count > 0 && GetSpan(t).Start < GetSpan(_items[_items.Count - 1]).End) { throw new InvalidOperationException(); } _items.Add(t); } public void PopLast() { _items.RemoveAt(_items.Count - 1); } public int FindFirstOverlap(T t) { if (_items.Count > 0) { Span span = GetSpan(t); // Check most recently added item first int index = _items.Count - 1; Span lastSpan = GetSpan(_items[index]); if (lastSpan.Start <= span.Start) { return lastSpan.OverlapsWith(span) ? index : -1; } // Otherwise start general search index = _items.BinarySearch(t, new SpanStartComparer(_getSpan)); if (index < 0) { int prior = ~index - 1; // the prior Span whose Start < span.Start index = Math.Max(0, prior); } while (index < _items.Count) { Span curSpan = GetSpan(_items[index]); if (curSpan.OverlapsWith(span)) { return index; } if (curSpan.Start >= span.End) { return -1; } index++; } } return -1; } public IEnumerable<T> Overlap(T t) { int index = FindFirstOverlap(t); if (index >= 0) { Span span = GetSpan(t); while (index < _items.Count && GetSpan(_items[index]).OverlapsWith(span)) { yield return _items[index]; index++; } } } class SpanStartComparer : Comparer<T> { IGetSpan<T> _getSpan; public SpanStartComparer(IGetSpan<T> getSpan) { _getSpan = getSpan; } public override int Compare(T x, T y) { return _getSpan.GetSpan(x).Start.CompareTo( _getSpan.GetSpan(y).Start); } } } class OrderedSpans : OrderedSpans<Span> { public OrderedSpans() : base(new SpanGetSapn()) { } class SpanGetSapn : IGetSpan<Span> { public Span GetSpan(Span t) { return t; } } } class OrderedTupleSpans<T> : OrderedSpans<Tuple<Span, T>> { public OrderedTupleSpans() : base(new TupleGetSpan()) { } public IEnumerable<Tuple<Span, T>> Overlap(Span span) { return base.Overlap(Tuple.Create(span, default(T))); } class TupleGetSpan : IGetSpan<Tuple<Span, T>> { public Span GetSpan(Tuple<Span, T> t) { return t.Item1; } } } class ComplexCommandSpans : OrderedTupleSpans<bool> { public void Add(Span lineSpan, bool endCommand) { base.Add(Tuple.Create(lineSpan, endCommand)); } public int FindCommandStart(int i) { while (i - 1 >= 0 && !this[i - 1].Item2) { i--; } return i; } public new IEnumerable<IList<Span>> Overlap(Span span) { int i = base.FindFirstOverlap(Tuple.Create(span, true)); if (i >= 0) { // Find first line of this complex command i = FindCommandStart(i); while (true) { // Collect and return one complex command List<Span> spans = new List<Span>(); while (i < this.Count) { spans.Add(this[i].Item1); if (this[i++].Item2) { break; } } yield return spans; if (i >= Count || !this[i].Item1.OverlapsWith(span)) { break; // Done } } } } } }
/* ********************************************************************************************************** * The MIT License (MIT) * * * * Copyright (c) 2016 Hypermediasystems Ges. f. Software mbH * * Web: http://www.hypermediasystems.de * * This file is part of hmsspx * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * ************************************************************************************************************ */ using System.Threading.Tasks; namespace hmsspx { partial class SPGet { public static async Task<HMS.SP.AccessRequests> getAccessRequests(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.AccessRequests(ret); } public static async Task<HMS.SP.AlternateUrl> getAlternateUrl(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.AlternateUrl(ret); } public static async Task<HMS.SP.App> getApp(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.App(ret); } public static async Task<HMS.SP.AppCatalog> getAppCatalog(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.AppCatalog(ret); } public static async Task<HMS.SP.Site> getSite(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.Site(ret); } public static async Task<HMS.SP.Web> getWeb(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.Web(ret); } public static async Task<HMS.SP.AppContextSite> getAppContextSite(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.AppContextSite(ret); } public static async Task<HMS.SP.AppInstance> getAppInstance(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.AppInstance(ret); } public static async Task<HMS.SP.AppInstanceErrorDetails> getAppInstanceErrorDetails(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.AppInstanceErrorDetails(ret); } public static async Task<HMS.SP.AppLicense> getAppLicense(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.AppLicense(ret); } public static async Task<HMS.SP.AppPrincipalConfiguration> getAppPrincipalConfiguration(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.AppPrincipalConfiguration(ret); } public static async Task<HMS.SP.AppPrincipalCredentialReference> getAppPrincipalCredentialReference(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.AppPrincipalCredentialReference(ret); } public static async Task<HMS.SP.Attachment> getAttachment(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.Attachment(ret); } public static async Task<HMS.SP.AttachmentCreationInformation> getAttachmentCreationInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.AttachmentCreationInformation(ret); } public static async Task<HMS.SP.BasePermissions> getBasePermissions(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.BasePermissions(ret); } public static async Task<HMS.SP.ListItemCollectionPosition> getListItemCollectionPosition(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ListItemCollectionPosition(ret); } public static async Task<HMS.SP.CamlQuery> getCamlQuery(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.CamlQuery(ret); } public static async Task<HMS.SP.ChangeToken> getChangeToken(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ChangeToken(ret); } public static async Task<HMS.SP.Change> getChange(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.Change(ret); } public static async Task<HMS.SP.ChangeAlert> getChangeAlert(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ChangeAlert(ret); } public static async Task<HMS.SP.ContentTypeId> getContentTypeId(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ContentTypeId(ret); } public static async Task<HMS.SP.ChangeContentType> getChangeContentType(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ChangeContentType(ret); } public static async Task<HMS.SP.ChangeField> getChangeField(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ChangeField(ret); } public static async Task<HMS.SP.ChangeFile> getChangeFile(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ChangeFile(ret); } public static async Task<HMS.SP.ChangeFolder> getChangeFolder(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ChangeFolder(ret); } public static async Task<HMS.SP.ChangeGroup> getChangeGroup(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ChangeGroup(ret); } public static async Task<HMS.SP.ChangeItem> getChangeItem(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ChangeItem(ret); } public static async Task<HMS.SP.ChangeList> getChangeList(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ChangeList(ret); } public static async Task<HMS.SP.ChangeLogItemQuery> getChangeLogItemQuery(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ChangeLogItemQuery(ret); } public static async Task<HMS.SP.ChangeQuery> getChangeQuery(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ChangeQuery(ret); } public static async Task<HMS.SP.ChangeUser> getChangeUser(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ChangeUser(ret); } public static async Task<HMS.SP.ChangeView> getChangeView(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ChangeView(ret); } public static async Task<HMS.SP.ChangeWeb> getChangeWeb(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ChangeWeb(ret); } public static async Task<HMS.SP.ClientContext> getClientContext(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ClientContext(ret); } public static async Task<HMS.SP.ContentType> getContentType(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ContentType(ret); } public static async Task<HMS.SP.ContentTypeCreationInformation> getContentTypeCreationInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ContentTypeCreationInformation(ret); } public static async Task<HMS.SP.ContextWebInformation> getContextWebInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ContextWebInformation(ret); } public static async Task<HMS.SP.DocumentLibraryInformation> getDocumentLibraryInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.DocumentLibraryInformation(ret); } public static async Task<HMS.SP.EventReceiverDefinition> getEventReceiverDefinition(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.EventReceiverDefinition(ret); } public static async Task<HMS.SP.EventReceiverDefinitionCreationInformation> getEventReceiverDefinitionCreationInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.EventReceiverDefinitionCreationInformation(ret); } public static async Task<HMS.SP.ExternalAppPrincipalCreationParameters> getExternalAppPrincipalCreationParameters(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ExternalAppPrincipalCreationParameters(ret); } public static async Task<HMS.SP.Feature> getFeature(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.Feature(ret); } public static async Task<HMS.SP.Field> getField(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.Field(ret); } public static async Task<HMS.SP.FieldCalculated> getFieldCalculated(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldCalculated(ret); } public static async Task<HMS.SP.FieldCalculatedErrorValue> getFieldCalculatedErrorValue(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldCalculatedErrorValue(ret); } public static async Task<HMS.SP.FieldChoice> getFieldChoice(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldChoice(ret); } public static async Task<HMS.SP.FieldComputed> getFieldComputed(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldComputed(ret); } public static async Task<HMS.SP.FieldCreationInformation> getFieldCreationInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldCreationInformation(ret); } public static async Task<HMS.SP.FieldCurrency> getFieldCurrency(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldCurrency(ret); } public static async Task<HMS.SP.FieldDateTime> getFieldDateTime(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldDateTime(ret); } public static async Task<HMS.SP.FieldGeolocationValue> getFieldGeolocationValue(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldGeolocationValue(ret); } public static async Task<HMS.SP.FieldLink> getFieldLink(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldLink(ret); } public static async Task<HMS.SP.FieldLinkCreationInformation> getFieldLinkCreationInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldLinkCreationInformation(ret); } public static async Task<HMS.SP.FieldLookup> getFieldLookup(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldLookup(ret); } public static async Task<HMS.SP.FieldLookupValue> getFieldLookupValue(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldLookupValue(ret); } public static async Task<HMS.SP.FieldMultiChoice> getFieldMultiChoice(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldMultiChoice(ret); } public static async Task<HMS.SP.FieldMultiLineText> getFieldMultiLineText(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldMultiLineText(ret); } public static async Task<HMS.SP.FieldNumber> getFieldNumber(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldNumber(ret); } public static async Task<HMS.SP.FieldRatingScale> getFieldRatingScale(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldRatingScale(ret); } public static async Task<HMS.SP.FieldRatingScaleQuestionAnswer> getFieldRatingScaleQuestionAnswer(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldRatingScaleQuestionAnswer(ret); } public static async Task<HMS.SP.FieldStringValues> getFieldStringValues(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldStringValues(ret); } public static async Task<HMS.SP.FieldText> getFieldText(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldText(ret); } public static async Task<HMS.SP.FieldUrl> getFieldUrl(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldUrl(ret); } public static async Task<HMS.SP.FieldUrlValue> getFieldUrlValue(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldUrlValue(ret); } public static async Task<HMS.SP.FieldUser> getFieldUser(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldUser(ret); } public static async Task<HMS.SP.FieldUserValue> getFieldUserValue(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FieldUserValue(ret); } public static async Task<HMS.SP.User> getUser(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.User(ret); } public static async Task<HMS.SP.ListItem> getListItem(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ListItem(ret); } public static async Task<HMS.SP.File> getFile(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.File(ret); } public static async Task<HMS.SP.FileCreationInformation> getFileCreationInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FileCreationInformation(ret); } public static async Task<HMS.SP.FileSaveBinaryInformation> getFileSaveBinaryInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FileSaveBinaryInformation(ret); } public static async Task<HMS.SP.FileVersion> getFileVersion(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.FileVersion(ret); } public static async Task<HMS.SP.Folder> getFolder(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.Folder(ret); } public static async Task<HMS.SP.PropertyValues> getPropertyValues(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.PropertyValues(ret); } public static async Task<HMS.SP.Form> getForm(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.Form(ret); } public static async Task<HMS.SP.Principal> getPrincipal(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.Principal(ret); } public static async Task<HMS.SP.Group> getGroup(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.Group(ret); } public static async Task<HMS.SP.GroupCreationInformation> getGroupCreationInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.GroupCreationInformation(ret); } public static async Task<HMS.SP.Implementationnotes> getImplementationnotes(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.Implementationnotes(ret); } public static async Task<HMS.SP.InformationRightsManagementSettings> getInformationRightsManagementSettings(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.InformationRightsManagementSettings(ret); } public static async Task<HMS.SP.KeyValue> getKeyValue(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.KeyValue(ret); } public static async Task<HMS.SP.Language> getLanguage(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.Language(ret); } public static async Task<HMS.SP.ListDataSource> getListDataSource(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ListDataSource(ret); } public static async Task<HMS.SP.View> getView(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.View(ret); } public static async Task<HMS.SP.SecurableObject> getSecurableObject(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.SecurableObject(ret); } public static async Task<HMS.SP.List> getList(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.List(ret); } public static async Task<HMS.SP.ListCreationInformation> getListCreationInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ListCreationInformation(ret); } public static async Task<HMS.SP.ListDataValidationFailure> getListDataValidationFailure(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ListDataValidationFailure(ret); } public static async Task<HMS.SP.ListDataValidationExceptionValue> getListDataValidationExceptionValue(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ListDataValidationExceptionValue(ret); } public static async Task<HMS.SP.ListItemCreationInformation> getListItemCreationInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ListItemCreationInformation(ret); } public static async Task<HMS.SP.ListItemFormUpdateValue> getListItemFormUpdateValue(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ListItemFormUpdateValue(ret); } public static async Task<HMS.SP.ListTemplate> getListTemplate(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ListTemplate(ret); } public static async Task<HMS.SP.MenuNode> getMenuNode(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.MenuNode(ret); } public static async Task<HMS.SP.MenuState> getMenuState(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.MenuState(ret); } public static async Task<HMS.SP.Navigation> getNavigation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.Navigation(ret); } public static async Task<HMS.SP.NavigationNode> getNavigationNode(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.NavigationNode(ret); } public static async Task<HMS.SP.NavigationNodeCreationInformation> getNavigationNodeCreationInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.NavigationNodeCreationInformation(ret); } public static async Task<HMS.SP.ObjectSharingInformation> getObjectSharingInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ObjectSharingInformation(ret); } public static async Task<HMS.SP.ObjectSharingInformationUser> getObjectSharingInformationUser(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ObjectSharingInformationUser(ret); } public static async Task<HMS.SP.PushNotificationSubscriber> getPushNotificationSubscriber(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.PushNotificationSubscriber(ret); } public static async Task<HMS.SP.RecycleBinItem> getRecycleBinItem(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.RecycleBinItem(ret); } public static async Task<HMS.SP.TimeZone> getTimeZone(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.TimeZone(ret); } public static async Task<HMS.SP.RegionalSettings> getRegionalSettings(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.RegionalSettings(ret); } public static async Task<HMS.SP.RelatedField> getRelatedField(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.RelatedField(ret); } public static async Task<HMS.SP.RelatedFieldExtendedData> getRelatedFieldExtendedData(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.RelatedFieldExtendedData(ret); } public static async Task<HMS.SP.RelatedItem> getRelatedItem(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.RelatedItem(ret); } public static async Task<HMS.SP.RelatedItemManager> getRelatedItemManager(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.RelatedItemManager(ret); } public static async Task<HMS.SP.RenderListDataParameters> getRenderListDataParameters(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.RenderListDataParameters(ret); } public static async Task<HMS.SP.RequestContext> getRequestContext(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.RequestContext(ret); } public static async Task<HMS.SP.RequestVariable> getRequestVariable(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.RequestVariable(ret); } public static async Task<HMS.SP.RoleAssignment> getRoleAssignment(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.RoleAssignment(ret); } public static async Task<HMS.SP.RoleDefinition> getRoleDefinition(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.RoleDefinition(ret); } public static async Task<HMS.SP.RoleDefinitionCreationInformation> getRoleDefinitionCreationInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.RoleDefinitionCreationInformation(ret); } public static async Task<HMS.SP.ServerSettings> getServerSettings(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ServerSettings(ret); } public static async Task<HMS.SP.SimpleDataRow> getSimpleDataRow(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.SimpleDataRow(ret); } public static async Task<HMS.SP.SimpleDataTable> getSimpleDataTable(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.SimpleDataTable(ret); } public static async Task<HMS.SP.UsageInfo> getUsageInfo(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.UsageInfo(ret); } public static async Task<HMS.SP.SubwebQuery> getSubwebQuery(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.SubwebQuery(ret); } public static async Task<HMS.SP.ThemeInfo> getThemeInfo(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ThemeInfo(ret); } public static async Task<HMS.SP.TimeZoneInformation> getTimeZoneInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.TimeZoneInformation(ret); } public static async Task<HMS.SP.ULS> getULS(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ULS(ret); } public static async Task<HMS.SP.UpgradeInfo> getUpgradeInfo(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.UpgradeInfo(ret); } public static async Task<HMS.SP.UserIdInfo> getUserIdInfo(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.UserIdInfo(ret); } public static async Task<HMS.SP.UserCreationInformation> getUserCreationInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.UserCreationInformation(ret); } public static async Task<HMS.SP.UserCustomAction> getUserCustomAction(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.UserCustomAction(ret); } public static async Task<HMS.SP.ViewCreationInformation> getViewCreationInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.ViewCreationInformation(ret); } public static async Task<HMS.SP.WebInformation> getWebInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.WebInformation(ret); } public static async Task<HMS.SP.WebCreationInformation> getWebCreationInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.WebCreationInformation(ret); } public static async Task<HMS.SP.WebInfoCreationInformation> getWebInfoCreationInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.WebInfoCreationInformation(ret); } public static async Task<HMS.SP.WebProxy> getWebProxy(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.WebProxy(ret); } public static async Task<HMS.SP.WebRequestInfo> getWebRequestInfo(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.WebRequestInfo(ret); } public static async Task<HMS.SP.WebResponseInfo> getWebResponseInfo(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.WebResponseInfo(ret); } public static async Task<HMS.SP.WebTemplate> getWebTemplate(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.WebTemplate(ret); } public static async Task<HMS.SP.XmlSchemaFieldCreationInformation> getXmlSchemaFieldCreationInformation(HMS.Auth.Login myClient,string url) { string ret = await myClient.getJSON(url); return new HMS.SP.XmlSchemaFieldCreationInformation(ret); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; using System.Text.RegularExpressions; using Volte.Data.Json; using Volte.Utils; namespace Volte.Data.Dapper { public class QueryRows { const string ZFILE_NAME = "QueryRows"; public QueryRows() { } public QueryRows(DbContext Trans) { _DbContext = Trans; _dbConnecttion = _DbContext.DbConnection; } public QueryRows(IDbConnection dbConnection) { _dbConnecttion = dbConnection; } public void Open() { if (string.IsNullOrEmpty(_CommandText)) { throw new DapperException("CommandText expected"); } IDbCommand cmd = this.DbConnecttion.CreateCommand(); cmd.CommandText = _CommandText; cmd.CommandTimeout = this.CommandTimeout; if (_DbContext.Transaction) { cmd.Transaction = _DbContext.DbTransaction; } try { foreach (var item in _Parameters) { IDataParameter parameter1 = cmd.CreateParameter(); parameter1.ParameterName = _DbContext.ParamPrefix + item.Key; object obj1 = item.Value; if (obj1 == null) { parameter1.Value = DBNull.Value; } else { parameter1.Value = obj1; } cmd.Parameters.Add(parameter1); } IDataReader _DataReader = cmd.ExecuteReader(); _Fill(_DataReader); } catch (Exception e) { ZZLogger.Error(ZFILE_NAME, e); ZZLogger.Error(ZFILE_NAME, _CommandText); string cMessage = "Message=[" + e.Message + "]" + "\nSource=[" + e.Source + "]\nStackTrace=[" + e.StackTrace + "]\nTargetSite=[" + e.TargetSite + "]"; ZZLogger.Error(ZFILE_NAME, cMessage); throw new Exception(_CommandText+" - "+e.Message); } } public void Open(IDataReader _DataReader) { _Fill(_DataReader); } internal void _Fill(IDataReader _DataReader) { _RecordCount = -1; _fieldCount = _DataReader.FieldCount; _Ordinal = new Dictionary<string , int>(); _Names = new Dictionary<int , string>(); _Type = new Dictionary<string , string>(); _Columns = new List<string>(); Dictionary<string, int> _t_name = new Dictionary<string, int>(); for (int i = 0; i < _fieldCount; i++) { string s = _DataReader.GetName(i).ToLower(); if (_t_name.ContainsKey(s)) { int cc = _t_name[s] + 1; s = s + cc.ToString(); _t_name[s] = cc; } else { _t_name[s] = 0; } _Names[i] = s; _Columns.Add(s); _Type[s] = _DataReader.GetFieldType(i).ToString(); _Ordinal[s] = i; } _Data = new List<object[]>(); while (_DataReader.Read()) { object[] values = new object[_fieldCount]; _DataReader.GetValues(values); _Data.Add(values); } _RecordCount = _Data.Count; _DataReader.Close(); _Pointer = 0; _FillData(); } private void _FillData() { if (_Pointer >= 0 && _Pointer < _Data.Count) { _Row = _Data[_Pointer]; } else { _Row = null; } if (_KeepPrev) { if (_Pointer > 0 && _Pointer < _Data.Count) { _Prev = _Data[_Pointer - 1]; } else { _Prev = null; } } else { _Prev = null; } } public void MovePrev() { _Pointer--; } public void MoveNext() { _Pointer++; _FillData(); } public void MoveFirst() { if (_Data.Count > 0) { _Pointer = 0; } else { _Pointer = 1000000; } _FillData(); } public void Move(int _Absolute) { _Pointer = _Absolute; } public bool HasColumn(string Name) { return GetOrdinal(Name) >= 0; } public int GetOrdinal(string Name) { if (_Ordinal.ContainsKey(Name.ToLower())) { return _Ordinal[Name.ToLower()]; } return -1; } private bool ConvertToBoolean(object obj) { if (DBNull.Value.Equals(obj) || obj==null) { return false; } if (obj is bool) { return (bool)obj; }else if (obj is decimal) { return (decimal)obj==1; } else if (obj.Equals("Y") || obj.Equals("y")) { return true; } else if (obj.ToString()=="1") { return true; } else if (obj.Equals("True") || obj.Equals("true")) { return true; } else if (obj.Equals("N") || obj.Equals("n")) { return false; } else if (obj.ToString()=="0") { return false; } else if (obj.Equals("False") || obj.Equals("false")) { return false; } else { return DapperUtil.ToBoolean(obj); } } public bool GetBoolean(int i) { return ConvertToBoolean(this[i]); } public bool GetBoolean(string Name) { return ConvertToBoolean(this[Name]); } public decimal GetDecimal(string Name) { object _obj = this[Name]; if (DBNull.Value.Equals(_obj)) { return 0; } return Convert.ToDecimal(_obj); } public decimal GetDecimal(int i) { object _obj = this[i]; if (DBNull.Value.Equals(_obj)) { return 0; } return Convert.ToDecimal(_obj); } public double GetDouble(string Name) { object _obj = this[Name]; if (DBNull.Value.Equals(_obj)) { return 0; } return Convert.ToDouble(_obj); } public long GetLong(int i) { object _obj = this[i]; if (_obj==null || DBNull.Value.Equals(_obj)) { return 0; } return Convert.ToInt64(_obj); } public long GetLong(string Name) { object _obj = this[Name]; if (_obj==null || DBNull.Value.Equals(_obj)) { return 0; } return Convert.ToInt64(_obj); } public int GetInteger(int i) { object _obj = this[i]; if (_obj==null || DBNull.Value.Equals(_obj)) { return 0; } return Convert.ToInt32(_obj); } public int GetInteger(string Name) { object _obj = this[Name]; if (_obj==null || DBNull.Value.Equals(_obj)) { return 0; } return Convert.ToInt32(_obj); } public string GetValue(int i) { object _obj = this[i]; if (DBNull.Value.Equals(_obj)) { return ""; } return _obj.ToString(); } public string GetValue(string Name) { object _obj = this[Name]; if (DBNull.Value.Equals(_obj)) { return ""; } return _obj.ToString(); } public DateTime GetDateTime(int i) { object _obj = this[i]; if (DBNull.Value.Equals(_obj)) { return Util.DateTime_MinValue; } return Convert.ToDateTime(_obj); } public DateTime GetDateTime(string Name) { object _obj = this[Name]; if (DBNull.Value.Equals(_obj)) { return Util.DateTime_MinValue; } return Convert.ToDateTime(_obj); } public DateTime? GetDateTime2(int i) { object _obj = this[i]; if (DBNull.Value.Equals(_obj)) { return null; } return Convert.ToDateTime(_obj); } public DateTime? GetDateTime2(string Name) { object _obj = this[Name]; if (DBNull.Value.Equals(_obj)) { return null; } return Convert.ToDateTime(_obj); } public bool IsNull(int i) { object _obj = this[i]; if (DBNull.Value.Equals(_obj)) { return true; }else{ return false; } } public bool IsNull(string Name) { object _obj = this[Name]; if (DBNull.Value.Equals(_obj)) { return true; }else{ return false; } } public string GetType(string Name) { return _Type[Name]; } public string GetName(int i) { return _Names[i]; } public string GetType(int i) { return _Type[_Names[i]]; } public void SetParameter(string name , string value) { _Parameters[name] = value; } public void SetParameter(string name , int value) { _Parameters[name] = value; } public object this[string name] { get { try { return _Row[_Ordinal[name.ToLower()]]; } catch (Exception ex) { if (_Row == null) { ZZLogger.Debug(ZFILE_NAME , "row is null"); } ZZLogger.Debug(ZFILE_NAME , "Exception invalid column name [" + name + "]"); ZZLogger.Debug(ZFILE_NAME , ex); throw new DapperException("Exception invalid column name [" + name + "]"); } } } public object this[int i] { get { return _Row[i]; } } public void Close() { _Data = null; _Row = null; _Prev = null; } public JSONObject Props { get { if (__sProps==null){ string _Props=this.GetValue("sProps"); try{ __sProps = new JSONObject(_Props); } catch (Exception e) { } } return __sProps; } } private readonly StringBuilder _Fields = new StringBuilder(); private List<string> _Columns; private DbContext _DbContext; private JSONObject __sProps = null; private Dictionary<string, int> _Ordinal; private Dictionary<int, string> _Names; private Dictionary<string, string> _Type; private IDbConnection _dbConnecttion; private bool _KeepPrev = false; private int _Pointer = -1; private int _CommandTimeout = 120; private int _RecordCount = -1; private int _fieldCount = -1; private int _Top = 0; private string _CommandText = ""; private object[] _Row = new object[1]; private object[] _Prev = new object[1]; private List<object[]> _Data = new List<object[]>(); private Dictionary<string, object> _Parameters = new Dictionary<string, object>(); public Dictionary<string, object> Parameters { get { return _Parameters; } set { _Parameters = value; } } public int CommandTimeout { get { return _CommandTimeout;} set { _CommandTimeout = value; } } public int Top { get { return _Top; } set { _Top = value; } } public bool KeepPrev { get { return _KeepPrev; } set { _KeepPrev = value; } } public string CommandText { get { return _CommandText; } set { _CommandText = value; } } public IDbConnection DbConnecttion { get { return _dbConnecttion; } } public List<string> Columns { get { return _Columns; } } public bool IsFirst { get { return _Pointer == 0; } } public bool IsLast { get { return _Pointer + 1 == _Data.Count; } } public bool BOF { get { return _Pointer < 0; } } public bool EOF { get { return _Pointer >= _Data.Count; } } public int Absolute_Position { get { return _Pointer; } } public int FieldCount { get { return _fieldCount; } } public int RecordCount { get { return _RecordCount; } } public int RecordsAffected { get { return _Data.Count; } } } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ #endregion using System; using System.Collections.Generic; using NUnit.Framework; using Quartz.Impl; using Quartz.Impl.Calendar; using Quartz.Impl.Matchers; using Quartz.Impl.Triggers; using Quartz.Job; using Quartz.Simpl; using Quartz.Spi; namespace Quartz.Tests.Unit.Simpl { /// <summary> /// Unit test for RAMJobStore. These tests were submitted by Johannes Zillmann /// as part of issue QUARTZ-306. /// </summary> [TestFixture] public class RAMJobStoreTest { private IJobStore fJobStore; private JobDetailImpl fJobDetail; private SampleSignaler fSignaler; [SetUp] public void SetUp() { fJobStore = new RAMJobStore(); fSignaler = new SampleSignaler(); fJobStore.Initialize(null, fSignaler); fJobStore.SchedulerStarted(); fJobDetail = new JobDetailImpl("job1", "jobGroup1", typeof (NoOpJob)); fJobDetail.Durable = true; fJobStore.StoreJob(fJobDetail, false); } [Test] public void TestAcquireNextTrigger() { DateTimeOffset d = DateBuilder.EvenMinuteDateAfterNow(); IOperableTrigger trigger1 = new SimpleTriggerImpl("trigger1", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddSeconds(200), d.AddSeconds(200), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger2 = new SimpleTriggerImpl("trigger2", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddSeconds(50), d.AddSeconds(200), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger3 = new SimpleTriggerImpl("trigger1", "triggerGroup2", fJobDetail.Name, fJobDetail.Group, d.AddSeconds(100), d.AddSeconds(200), 2, TimeSpan.FromSeconds(2)); trigger1.ComputeFirstFireTimeUtc(null); trigger2.ComputeFirstFireTimeUtc(null); trigger3.ComputeFirstFireTimeUtc(null); fJobStore.StoreTrigger(trigger1, false); fJobStore.StoreTrigger(trigger2, false); fJobStore.StoreTrigger(trigger3, false); DateTimeOffset firstFireTime = trigger1.GetNextFireTimeUtc().Value; Assert.AreEqual(0, fJobStore.AcquireNextTriggers(d.AddMilliseconds(10), 1, TimeSpan.Zero).Count); Assert.AreEqual(trigger2, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.Zero)[0]); Assert.AreEqual(trigger3, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.Zero)[0]); Assert.AreEqual(trigger1, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.Zero)[0]); Assert.AreEqual(0, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.Zero).Count); // release trigger3 fJobStore.ReleaseAcquiredTrigger(trigger3); Assert.AreEqual(trigger3, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.FromMilliseconds(1))[0]); } [Test] public void TestAcquireNextTriggerBatch() { DateTimeOffset d = DateBuilder.EvenMinuteDateAfterNow(); IOperableTrigger early = new SimpleTriggerImpl("early", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d, d.AddMilliseconds(5), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger1 = new SimpleTriggerImpl("trigger1", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(200000), d.AddMilliseconds(200005), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger2 = new SimpleTriggerImpl("trigger2", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(200100), d.AddMilliseconds(200105), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger3 = new SimpleTriggerImpl("trigger3", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(200200), d.AddMilliseconds(200205), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger4 = new SimpleTriggerImpl("trigger4", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(200300), d.AddMilliseconds(200305), 2, TimeSpan.FromSeconds(2)); IOperableTrigger trigger10 = new SimpleTriggerImpl("trigger10", "triggerGroup2", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(500000), d.AddMilliseconds(700000), 2, TimeSpan.FromSeconds(2)); early.ComputeFirstFireTimeUtc(null); trigger1.ComputeFirstFireTimeUtc(null); trigger2.ComputeFirstFireTimeUtc(null); trigger3.ComputeFirstFireTimeUtc(null); trigger4.ComputeFirstFireTimeUtc(null); trigger10.ComputeFirstFireTimeUtc(null); fJobStore.StoreTrigger(early, false); fJobStore.StoreTrigger(trigger1, false); fJobStore.StoreTrigger(trigger2, false); fJobStore.StoreTrigger(trigger3, false); fJobStore.StoreTrigger(trigger4, false); fJobStore.StoreTrigger(trigger10, false); DateTimeOffset firstFireTime = trigger1.GetNextFireTimeUtc().Value; IList<IOperableTrigger> acquiredTriggers = fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 4, TimeSpan.FromSeconds(1)); Assert.AreEqual(4, acquiredTriggers.Count); Assert.AreEqual(early.Key, acquiredTriggers[0].Key); Assert.AreEqual(trigger1.Key, acquiredTriggers[1].Key); Assert.AreEqual(trigger2.Key, acquiredTriggers[2].Key); Assert.AreEqual(trigger3.Key, acquiredTriggers[3].Key); fJobStore.ReleaseAcquiredTrigger(early); fJobStore.ReleaseAcquiredTrigger(trigger1); fJobStore.ReleaseAcquiredTrigger(trigger2); fJobStore.ReleaseAcquiredTrigger(trigger3); acquiredTriggers = this.fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 5, TimeSpan.FromMilliseconds(1000)); Assert.AreEqual(5, acquiredTriggers.Count); Assert.AreEqual(early.Key, acquiredTriggers[0].Key); Assert.AreEqual(trigger1.Key, acquiredTriggers[1].Key); Assert.AreEqual(trigger2.Key, acquiredTriggers[2].Key); Assert.AreEqual(trigger3.Key, acquiredTriggers[3].Key); Assert.AreEqual(trigger4.Key, acquiredTriggers[4].Key); fJobStore.ReleaseAcquiredTrigger(early); fJobStore.ReleaseAcquiredTrigger(trigger1); fJobStore.ReleaseAcquiredTrigger(trigger2); fJobStore.ReleaseAcquiredTrigger(trigger3); fJobStore.ReleaseAcquiredTrigger(trigger4); acquiredTriggers = fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 6, TimeSpan.FromSeconds(1)); Assert.AreEqual(5, acquiredTriggers.Count); Assert.AreEqual(early.Key, acquiredTriggers[0].Key); Assert.AreEqual(trigger1.Key, acquiredTriggers[1].Key); Assert.AreEqual(trigger2.Key, acquiredTriggers[2].Key); Assert.AreEqual(trigger3.Key, acquiredTriggers[3].Key); Assert.AreEqual(trigger4.Key, acquiredTriggers[4].Key); fJobStore.ReleaseAcquiredTrigger(early); fJobStore.ReleaseAcquiredTrigger(trigger1); fJobStore.ReleaseAcquiredTrigger(trigger2); fJobStore.ReleaseAcquiredTrigger(trigger3); fJobStore.ReleaseAcquiredTrigger(trigger4); acquiredTriggers = fJobStore.AcquireNextTriggers(firstFireTime.AddMilliseconds(1), 5, TimeSpan.Zero); Assert.AreEqual(2, acquiredTriggers.Count); fJobStore.ReleaseAcquiredTrigger(early); fJobStore.ReleaseAcquiredTrigger(trigger1); acquiredTriggers = fJobStore.AcquireNextTriggers(firstFireTime.AddMilliseconds(250), 5, TimeSpan.FromMilliseconds(199)); Assert.AreEqual(5, acquiredTriggers.Count); fJobStore.ReleaseAcquiredTrigger(early); fJobStore.ReleaseAcquiredTrigger(trigger1); fJobStore.ReleaseAcquiredTrigger(trigger2); fJobStore.ReleaseAcquiredTrigger(trigger3); fJobStore.ReleaseAcquiredTrigger(trigger4); acquiredTriggers = fJobStore.AcquireNextTriggers(firstFireTime.AddMilliseconds(150), 5, TimeSpan.FromMilliseconds(50L)); Assert.AreEqual(4, acquiredTriggers.Count); fJobStore.ReleaseAcquiredTrigger(early); fJobStore.ReleaseAcquiredTrigger(trigger1); fJobStore.ReleaseAcquiredTrigger(trigger2); fJobStore.ReleaseAcquiredTrigger(trigger3); } [Test] public void TestTriggerStates() { IOperableTrigger trigger = new SimpleTriggerImpl("trigger1", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, DateTimeOffset.Now.AddSeconds(100), DateTimeOffset.Now.AddSeconds(200), 2, TimeSpan.FromSeconds(2)); trigger.ComputeFirstFireTimeUtc(null); Assert.AreEqual(TriggerState.None, fJobStore.GetTriggerState(trigger.Key)); fJobStore.StoreTrigger(trigger, false); Assert.AreEqual(TriggerState.Normal, fJobStore.GetTriggerState(trigger.Key)); fJobStore.PauseTrigger(trigger.Key); Assert.AreEqual(TriggerState.Paused, fJobStore.GetTriggerState(trigger.Key)); fJobStore.ResumeTrigger(trigger.Key); Assert.AreEqual(TriggerState.Normal, fJobStore.GetTriggerState(trigger.Key)); trigger = fJobStore.AcquireNextTriggers(trigger.GetNextFireTimeUtc().Value.AddSeconds(10), 1, TimeSpan.FromMilliseconds(1))[0]; Assert.IsNotNull(trigger); fJobStore.ReleaseAcquiredTrigger(trigger); trigger = fJobStore.AcquireNextTriggers(trigger.GetNextFireTimeUtc().Value.AddSeconds(10), 1, TimeSpan.FromMilliseconds(1))[0]; Assert.IsNotNull(trigger); Assert.AreEqual(0, fJobStore.AcquireNextTriggers(trigger.GetNextFireTimeUtc().Value.AddSeconds(10), 1, TimeSpan.FromMilliseconds(1)).Count); } [Test] public void TestRemoveCalendarWhenTriggersPresent() { // QRTZNET-29 IOperableTrigger trigger = new SimpleTriggerImpl("trigger1", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, DateTimeOffset.Now.AddSeconds(100), DateTimeOffset.Now.AddSeconds(200), 2, TimeSpan.FromSeconds(2)); trigger.ComputeFirstFireTimeUtc(null); ICalendar cal = new MonthlyCalendar(); fJobStore.StoreTrigger(trigger, false); fJobStore.StoreCalendar("cal", cal, false, true); fJobStore.RemoveCalendar("cal"); } [Test] public void TestStoreTriggerReplacesTrigger() { string jobName = "StoreTriggerReplacesTrigger"; string jobGroup = "StoreTriggerReplacesTriggerGroup"; JobDetailImpl detail = new JobDetailImpl(jobName, jobGroup, typeof (NoOpJob)); fJobStore.StoreJob(detail, false); string trName = "StoreTriggerReplacesTrigger"; string trGroup = "StoreTriggerReplacesTriggerGroup"; IOperableTrigger tr = new SimpleTriggerImpl(trName, trGroup, DateTimeOffset.Now); tr.JobKey = new JobKey(jobName, jobGroup); tr.CalendarName = null; fJobStore.StoreTrigger(tr, false); Assert.AreEqual(tr, fJobStore.RetrieveTrigger(new TriggerKey(trName, trGroup))); tr.CalendarName = "NonExistingCalendar"; fJobStore.StoreTrigger(tr, true); Assert.AreEqual(tr, fJobStore.RetrieveTrigger(new TriggerKey(trName, trGroup))); Assert.AreEqual(tr.CalendarName, fJobStore.RetrieveTrigger(new TriggerKey(trName, trGroup)).CalendarName, "StoreJob doesn't replace triggers"); bool exeptionRaised = false; try { fJobStore.StoreTrigger(tr, false); } catch (ObjectAlreadyExistsException) { exeptionRaised = true; } Assert.IsTrue(exeptionRaised, "an attempt to store duplicate trigger succeeded"); } [Test] public void PauseJobGroupPausesNewJob() { string jobName1 = "PauseJobGroupPausesNewJob"; string jobName2 = "PauseJobGroupPausesNewJob2"; string jobGroup = "PauseJobGroupPausesNewJobGroup"; JobDetailImpl detail = new JobDetailImpl(jobName1, jobGroup, typeof (NoOpJob)); detail.Durable = true; fJobStore.StoreJob(detail, false); fJobStore.PauseJobs(GroupMatcher<JobKey>.GroupEquals(jobGroup)); detail = new JobDetailImpl(jobName2, jobGroup, typeof (NoOpJob)); detail.Durable = true; fJobStore.StoreJob(detail, false); string trName = "PauseJobGroupPausesNewJobTrigger"; string trGroup = "PauseJobGroupPausesNewJobTriggerGroup"; IOperableTrigger tr = new SimpleTriggerImpl(trName, trGroup, DateTimeOffset.UtcNow); tr.JobKey = new JobKey(jobName2, jobGroup); fJobStore.StoreTrigger(tr, false); Assert.AreEqual(TriggerState.Paused, fJobStore.GetTriggerState(tr.Key)); } [Test] public void TestRetrieveJob_NoJobFound() { RAMJobStore store = new RAMJobStore(); IJobDetail job = store.RetrieveJob(new JobKey("not", "existing")); Assert.IsNull(job); } [Test] public void TestRetrieveTrigger_NoTriggerFound() { RAMJobStore store = new RAMJobStore(); IOperableTrigger trigger = store.RetrieveTrigger(new TriggerKey("not", "existing")); Assert.IsNull(trigger); } [Test] public void testStoreAndRetrieveJobs() { RAMJobStore store = new RAMJobStore(); // Store jobs. for (int i = 0; i < 10; i++) { IJobDetail job = JobBuilder.Create<NoOpJob>().WithIdentity("job" + i).Build(); store.StoreJob(job, false); } // Retrieve jobs. for (int i = 0; i < 10; i++) { JobKey jobKey = JobKey.Create("job" + i); IJobDetail storedJob = store.RetrieveJob(jobKey); Assert.AreEqual(jobKey, storedJob.Key); } } [Test] public void TestStoreAndRetriveTriggers() { RAMJobStore store = new RAMJobStore(); // Store jobs and triggers. for (int i = 0; i < 10; i++) { IJobDetail job = JobBuilder.Create<NoOpJob>().WithIdentity("job" + i).Build(); store.StoreJob(job, true); SimpleScheduleBuilder schedule = SimpleScheduleBuilder.Create(); ITrigger trigger = TriggerBuilder.Create().WithIdentity("job" + i).WithSchedule(schedule).ForJob(job).Build(); store.StoreTrigger((IOperableTrigger) trigger, true); } // Retrieve job and trigger. for (int i = 0; i < 10; i++) { JobKey jobKey = JobKey.Create("job" + i); IJobDetail storedJob = store.RetrieveJob(jobKey); Assert.AreEqual(jobKey, storedJob.Key); TriggerKey triggerKey = new TriggerKey("job" + i); ITrigger storedTrigger = store.RetrieveTrigger(triggerKey); Assert.AreEqual(triggerKey, storedTrigger.Key); } } [Test] public void TestAcquireTriggers() { ISchedulerSignaler schedSignaler = new SampleSignaler(); ITypeLoadHelper loadHelper = new SimpleTypeLoadHelper(); loadHelper.Initialize(); RAMJobStore store = new RAMJobStore(); store.Initialize(loadHelper, schedSignaler); // Setup: Store jobs and triggers. DateTime startTime0 = DateTime.UtcNow.AddMinutes(1).ToUniversalTime(); // a min from now. for (int i = 0; i < 10; i++) { DateTime startTime = startTime0.AddMinutes(i*1); // a min apart IJobDetail job = JobBuilder.Create<NoOpJob>().WithIdentity("job" + i).Build(); SimpleScheduleBuilder schedule = SimpleScheduleBuilder.RepeatMinutelyForever(2); IOperableTrigger trigger = (IOperableTrigger) TriggerBuilder.Create().WithIdentity("job" + i).WithSchedule(schedule).ForJob(job).StartAt(startTime).Build(); // Manually trigger the first fire time computation that scheduler would do. Otherwise // the store.acquireNextTriggers() will not work properly. DateTimeOffset? fireTime = trigger.ComputeFirstFireTimeUtc(null); Assert.AreEqual(true, fireTime != null); store.StoreJobAndTrigger(job, trigger); } // Test acquire one trigger at a time for (int i = 0; i < 10; i++) { DateTimeOffset noLaterThan = startTime0.AddMinutes(i); int maxCount = 1; TimeSpan timeWindow = TimeSpan.Zero; IList<IOperableTrigger> triggers = store.AcquireNextTriggers(noLaterThan, maxCount, timeWindow); Assert.AreEqual(1, triggers.Count); Assert.AreEqual("job" + i, triggers[0].Key.Name); // Let's remove the trigger now. store.RemoveJob(triggers[0].JobKey); } } [Test] public void TestAcquireTriggersInBatch() { ISchedulerSignaler schedSignaler = new SampleSignaler(); ITypeLoadHelper loadHelper = new SimpleTypeLoadHelper(); loadHelper.Initialize(); RAMJobStore store = new RAMJobStore(); store.Initialize(loadHelper, schedSignaler); // Setup: Store jobs and triggers. DateTimeOffset startTime0 = DateTimeOffset.UtcNow.AddMinutes(1); // a min from now. for (int i = 0; i < 10; i++) { DateTimeOffset startTime = startTime0.AddMinutes(i); // a min apart IJobDetail job = JobBuilder.Create<NoOpJob>().WithIdentity("job" + i).Build(); SimpleScheduleBuilder schedule = SimpleScheduleBuilder.RepeatMinutelyForever(2); IOperableTrigger trigger = (IOperableTrigger) TriggerBuilder.Create().WithIdentity("job" + i).WithSchedule(schedule).ForJob(job).StartAt(startTime).Build(); // Manually trigger the first fire time computation that scheduler would do. Otherwise // the store.acquireNextTriggers() will not work properly. DateTimeOffset? fireTime = trigger.ComputeFirstFireTimeUtc(null); Assert.AreEqual(true, fireTime != null); store.StoreJobAndTrigger(job, trigger); } // Test acquire batch of triggers at a time DateTimeOffset noLaterThan = startTime0.AddMinutes(10); int maxCount = 7; TimeSpan timeWindow = TimeSpan.FromMinutes(8); IList<IOperableTrigger> triggers = store.AcquireNextTriggers(noLaterThan, maxCount, timeWindow); Assert.AreEqual(7, triggers.Count); for (int i = 0; i < 7; i++) { Assert.AreEqual("job" + i, triggers[i].Key.Name); } } public class SampleSignaler : ISchedulerSignaler { internal int fMisfireCount = 0; public void NotifyTriggerListenersMisfired(ITrigger trigger) { fMisfireCount++; } public void NotifySchedulerListenersFinalized(ITrigger trigger) { } public void SignalSchedulingChange(DateTimeOffset? candidateNewNextFireTimeUtc) { } public void NotifySchedulerListenersError(string message, SchedulerException jpe) { } public void NotifySchedulerListenersJobDeleted(JobKey jobKey) { } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.WebSitesExtensions; using Microsoft.WindowsAzure.WebSitesExtensions.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.WindowsAzure.WebSitesExtensions { /// <summary> /// Operations for managing the settings. /// </summary> internal partial class SettingsOperations : IServiceOperations<WebSiteExtensionsClient>, Microsoft.WindowsAzure.WebSitesExtensions.ISettingsOperations { /// <summary> /// Initializes a new instance of the SettingsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal SettingsOperations(WebSiteExtensionsClient client) { this._client = client; } private WebSiteExtensionsClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.WebSiteExtensionsClient. /// </summary> public WebSiteExtensionsClient Client { get { return this._client; } } /// <summary> /// Gets a setting. /// </summary> /// <param name='settingId'> /// Required. The setting identifier. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async System.Threading.Tasks.Task<OperationResponse> DeleteAsync(string settingId, CancellationToken cancellationToken) { // Validate if (settingId == null) { throw new ArgumentNullException("settingId"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("settingId", settingId); Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = "/api/settings/" + settingId.Trim(); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets a setting. /// </summary> /// <param name='settingId'> /// Required. The setting identifier. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The get setting operation response. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.WebSitesExtensions.Models.SettingsGetResponse> GetAsync(string settingId, CancellationToken cancellationToken) { // Validate if (settingId == null) { throw new ArgumentNullException("settingId"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("settingId", settingId); Tracing.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = "/api/settings/" + settingId.Trim(); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result SettingsGetResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new SettingsGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { string valueInstance = ((string)responseDoc); result.Value = valueInstance; } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Lists the settings. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The list settings operation response. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.WebSitesExtensions.Models.SettingsListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = "/api/settings"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result SettingsListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new SettingsListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken settingsSequenceElement = ((JToken)responseDoc); if (settingsSequenceElement != null && settingsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in settingsSequenceElement) { string settingsKey = ((string)property.Name); string settingsValue = ((string)property.Value); result.Settings.Add(settingsKey, settingsValue); } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Updates a setting. /// </summary> /// <param name='parameters'> /// Required. The setting value. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async System.Threading.Tasks.Task<OperationResponse> UpdateAsync(SettingsUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "UpdateAsync", tracingParameters); } // Construct URL string url = "/api/settings"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; if (parameters.Settings != null) { if (parameters.Settings is ILazyCollection == false || ((ILazyCollection)parameters.Settings).IsInitialized) { JObject settingsDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Settings) { string settingsKey = pair.Key; string settingsValue = pair.Value; settingsDictionary[settingsKey] = settingsValue; } requestDoc = settingsDictionary; } } requestContent = requestDoc.ToString(Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Threading; using Xunit; namespace System.Diagnostics.ProcessTests { public class ProcessTests : ProcessTestBase { private void SetAndCheckBasePriority(ProcessPriorityClass exPriorityClass, int priority) { _process.PriorityClass = exPriorityClass; _process.Refresh(); Assert.Equal(priority, _process.BasePriority); } private void AssertNonZeroWindowsZeroUnix(long value) { switch (global::Interop.PlatformDetection.OperatingSystem) { case global::Interop.OperatingSystem.Windows: Assert.NotEqual(0, value); break; default: Assert.Equal(0, value); break; } } [Fact, PlatformSpecific(PlatformID.Windows)] public void TestBasePriorityOnWindows() { ProcessPriorityClass originalPriority = _process.PriorityClass; Assert.Equal(ProcessPriorityClass.Normal, originalPriority); try { // We are not checking for RealTime case here, as RealTime priority process can // preempt the threads of all other processes, including operating system processes // performing important tasks, which may cause the machine to be unresponsive. //SetAndCheckBasePriority(ProcessPriorityClass.RealTime, 24); SetAndCheckBasePriority(ProcessPriorityClass.High, 13); SetAndCheckBasePriority(ProcessPriorityClass.Idle, 4); SetAndCheckBasePriority(ProcessPriorityClass.Normal, 8); } finally { _process.PriorityClass = originalPriority; } } [Fact, PlatformSpecific(PlatformID.AnyUnix), OuterLoop] // This test requires admin elevation on Unix public void TestBasePriorityOnUnix() { ProcessPriorityClass originalPriority = _process.PriorityClass; Assert.Equal(ProcessPriorityClass.Normal, originalPriority); try { SetAndCheckBasePriority(ProcessPriorityClass.High, -11); SetAndCheckBasePriority(ProcessPriorityClass.Idle, 19); SetAndCheckBasePriority(ProcessPriorityClass.Normal, 0); } finally { _process.PriorityClass = originalPriority; } } [Fact] public void TestEnableRaiseEvents() { { bool isExitedInvoked = false; // Test behavior when EnableRaisingEvent = true; // Ensure event is called. Process p = CreateProcessInfinite(); p.EnableRaisingEvents = true; p.Exited += delegate { isExitedInvoked = true; }; StartAndKillProcessWithDelay(p); Assert.True(isExitedInvoked, String.Format("TestCanRaiseEvents0001: {0}", "isExited Event not called when EnableRaisingEvent is set to true.")); } { bool isExitedInvoked = false; // Check with the default settings (false, events will not be raised) Process p = CreateProcessInfinite(); p.Exited += delegate { isExitedInvoked = true; }; StartAndKillProcessWithDelay(p); Assert.False(isExitedInvoked, String.Format("TestCanRaiseEvents0002: {0}", "isExited Event called with the default settings for EnableRaiseEvents")); } { bool isExitedInvoked = false; // Same test, this time explicitly set the property to false Process p = CreateProcessInfinite(); p.EnableRaisingEvents = false; p.Exited += delegate { isExitedInvoked = true; }; ; StartAndKillProcessWithDelay(p); Assert.False(isExitedInvoked, String.Format("TestCanRaiseEvents0003: {0}", "isExited Event called with the EnableRaiseEvents = false")); } } [Fact] public void TestExitCode() { { Process p = CreateProcess(); p.Start(); Assert.True(p.WaitForExit(WaitInMS)); Assert.Equal(SuccessExitCode, p.ExitCode); } { Process p = CreateProcessInfinite(); StartAndKillProcessWithDelay(p); Assert.NotEqual(0, p.ExitCode); } } [Fact] public void TestExitTime() { DateTime timeBeforeProcessStart = DateTime.UtcNow; Process p = CreateProcessInfinite(); StartAndKillProcessWithDelay(p); Assert.True(p.ExitTime.ToUniversalTime() > timeBeforeProcessStart, "TestExitTime is incorrect."); } [Fact] public void TestId() { if (global::Interop.IsWindows) { Assert.Equal(_process.Id, Interop.GetProcessId(_process.SafeHandle)); } else { IEnumerable<int> testProcessIds = Process.GetProcessesByName(CoreRunName).Select(p => p.Id); Assert.Contains(_process.Id, testProcessIds); } } [Fact] public void TestHasExited() { { Process p = CreateProcess(); p.Start(); Assert.True(p.WaitForExit(WaitInMS)); Assert.True(p.HasExited, "TestHasExited001 failed"); } { Process p = CreateProcessInfinite(); p.Start(); try { Assert.False(p.HasExited, "TestHasExited002 failed"); } finally { p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); } Assert.True(p.HasExited, "TestHasExited003 failed"); } } [Fact] public void TestMachineName() { // Checking that the MachineName returns some value. Assert.NotNull(_process.MachineName); } [Fact, PlatformSpecific(~PlatformID.OSX)] public void TestMainModuleOnNonOSX() { string fileName = "corerun"; if (global::Interop.IsWindows) fileName = "CoreRun.exe"; Process p = Process.GetCurrentProcess(); Assert.True(p.Modules.Count > 0); Assert.Equal(fileName, p.MainModule.ModuleName); Assert.EndsWith(fileName, p.MainModule.FileName); Assert.Equal(string.Format("System.Diagnostics.ProcessModule ({0})", fileName), p.MainModule.ToString()); } [Fact] public void TestMaxWorkingSet() { using (Process p = Process.GetCurrentProcess()) { Assert.True((long)p.MaxWorkingSet > 0); Assert.True((long)p.MinWorkingSet >= 0); } if (global::Interop.IsOSX) return; // doesn't support getting/setting working set for other processes long curValue = (long)_process.MaxWorkingSet; Assert.True(curValue >= 0); if (global::Interop.IsWindows) { try { _process.MaxWorkingSet = (IntPtr)((int)curValue + 1024); IntPtr min, max; uint flags; Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags); curValue = (int)max; _process.Refresh(); Assert.Equal(curValue, (int)_process.MaxWorkingSet); } finally { _process.MaxWorkingSet = (IntPtr)curValue; } } } [Fact] public void TestMinWorkingSet() { using (Process p = Process.GetCurrentProcess()) { Assert.True((long)p.MaxWorkingSet > 0); Assert.True((long)p.MinWorkingSet >= 0); } if (global::Interop.IsOSX) return; // doesn't support getting/setting working set for other processes long curValue = (long)_process.MinWorkingSet; Assert.True(curValue >= 0); if (global::Interop.IsWindows) { try { _process.MinWorkingSet = (IntPtr)((int)curValue - 1024); IntPtr min, max; uint flags; Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags); curValue = (int)min; _process.Refresh(); Assert.Equal(curValue, (int)_process.MinWorkingSet); } finally { _process.MinWorkingSet = (IntPtr)curValue; } } } [Fact] public void TestModules() { foreach (ProcessModule pModule in _process.Modules) { // Validated that we can get a value for each of the following. Assert.NotNull(pModule); Assert.NotEqual(IntPtr.Zero, pModule.BaseAddress); Assert.NotNull(pModule.FileName); Assert.NotNull(pModule.ModuleName); // Just make sure these don't throw IntPtr addr = pModule.EntryPointAddress; int memSize = pModule.ModuleMemorySize; } } [Fact] public void TestNonpagedSystemMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize64); } [Fact] public void TestPagedMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize64); } [Fact] public void TestPagedSystemMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize64); } [Fact] public void TestPeakPagedMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize64); } [Fact] public void TestPeakVirtualMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize64); } [Fact] public void TestPeakWorkingSet64() { AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet64); } [Fact] public void TestPrivateMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize64); } [Fact] public void TestVirtualMemorySize64() { Assert.True(_process.VirtualMemorySize64 > 0); } [Fact] public void TestWorkingSet64() { Assert.True(_process.WorkingSet64 > 0); } [Fact] public void TestProcessorTime() { Assert.True(_process.UserProcessorTime.TotalSeconds >= 0); Assert.True(_process.PrivilegedProcessorTime.TotalSeconds >= 0); double processorTimeBeforeSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds; double processorTimeAtHalfSpin = 0; // Perform loop to occupy cpu, takes less than a second. int i = int.MaxValue / 16; while (i > 0) { i--; if (i == int.MaxValue / 32) processorTimeAtHalfSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds; } Assert.InRange(processorTimeAtHalfSpin, processorTimeBeforeSpin, Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds); } [Fact] public void TestProcessStartTime() { DateTime timeBeforeCreatingProcess = DateTime.UtcNow; Process p = CreateProcessInfinite(); try { p.Start(); // Time in unix, is measured in jiffies, which is incremented by one for every timer interrupt since the boot time. // Thus, because there are HZ timer interrupts in a second, there are HZ jiffies in a second. Hence 1\HZ, will // be the resolution of system timer. The lowest value of HZ on unix is 100, hence the timer resolution is 10 ms. // Allowing for error in 10 ms. long tenMSTicks = new TimeSpan(0, 0, 0, 0, 10).Ticks; long beforeTicks = timeBeforeCreatingProcess.Ticks - tenMSTicks; long afterTicks = DateTime.UtcNow.Ticks + tenMSTicks; Assert.InRange(p.StartTime.ToUniversalTime().Ticks, beforeTicks, afterTicks); } finally { if (!p.HasExited) p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); } } [Fact] [PlatformSpecific(~PlatformID.OSX)] // getting/setting affinity not supported on OSX public void TestProcessorAffinity() { IntPtr curProcessorAffinity = _process.ProcessorAffinity; try { _process.ProcessorAffinity = new IntPtr(0x1); Assert.Equal(new IntPtr(0x1), _process.ProcessorAffinity); } finally { _process.ProcessorAffinity = curProcessorAffinity; Assert.Equal(curProcessorAffinity, _process.ProcessorAffinity); } } [Fact] public void TestPriorityBoostEnabled() { bool isPriorityBoostEnabled = _process.PriorityBoostEnabled; try { _process.PriorityBoostEnabled = true; Assert.True(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled001 failed"); _process.PriorityBoostEnabled = false; Assert.False(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled002 failed"); } finally { _process.PriorityBoostEnabled = isPriorityBoostEnabled; } } [Fact, PlatformSpecific(PlatformID.AnyUnix), OuterLoop] // This test requires admin elevation on Unix public void TestPriorityClassUnix() { ProcessPriorityClass priorityClass = _process.PriorityClass; try { _process.PriorityClass = ProcessPriorityClass.High; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High); _process.PriorityClass = ProcessPriorityClass.Normal; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal); } finally { _process.PriorityClass = priorityClass; } } [Fact, PlatformSpecific(PlatformID.Windows)] public void TestPriorityClassWindows() { ProcessPriorityClass priorityClass = _process.PriorityClass; try { _process.PriorityClass = ProcessPriorityClass.High; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High); _process.PriorityClass = ProcessPriorityClass.Normal; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal); } finally { _process.PriorityClass = priorityClass; } } [Fact] public void TestInvalidPriorityClass() { Process p = new Process(); Assert.Throws<ArgumentException>(() => { p.PriorityClass = ProcessPriorityClass.Normal | ProcessPriorityClass.Idle; }); } [Fact] public void TestProcessName() { Assert.Equal(_process.ProcessName, CoreRunName, StringComparer.OrdinalIgnoreCase); } [Fact] public void TestSafeHandle() { Assert.False(_process.SafeHandle.IsInvalid); } [Fact] public void TestSessionId() { uint sessionId; if (global::Interop.IsWindows) { Interop.ProcessIdToSessionId((uint)_process.Id, out sessionId); } else { sessionId = (uint)Interop.getsid(_process.Id); } Assert.Equal(sessionId, (uint)_process.SessionId); } [Fact] public void TestGetCurrentProcess() { Process current = Process.GetCurrentProcess(); Assert.NotNull(current); int currentProcessId = global::Interop.IsWindows ? Interop.GetCurrentProcessId() : Interop.getpid(); Assert.Equal(currentProcessId, current.Id); } [Fact] public void TestGetProcessById() { Process p = Process.GetProcessById(_process.Id); Assert.Equal(_process.Id, p.Id); Assert.Equal(_process.ProcessName, p.ProcessName); } [Fact] public void TestGetProcesses() { Process currentProcess = Process.GetCurrentProcess(); // Get all the processes running on the machine, and check if the current process is one of them. var foundCurrentProcess = (from p in Process.GetProcesses() where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName)) select p).Any(); Assert.True(foundCurrentProcess, "TestGetProcesses001 failed"); foundCurrentProcess = (from p in Process.GetProcesses(currentProcess.MachineName) where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName)) select p).Any(); Assert.True(foundCurrentProcess, "TestGetProcesses002 failed"); } [Fact] public void TestGetProcessesByName() { // Get the current process using its name Process currentProcess = Process.GetCurrentProcess(); Assert.True(Process.GetProcessesByName(currentProcess.ProcessName).Count() > 0, "TestGetProcessesByName001 failed"); Assert.True(Process.GetProcessesByName(currentProcess.ProcessName, currentProcess.MachineName).Count() > 0, "TestGetProcessesByName001 failed"); } public static IEnumerable<object[]> GetTestProcess() { Process currentProcess = Process.GetCurrentProcess(); yield return new object[] { currentProcess, Process.GetProcessById(currentProcess.Id, "127.0.0.1") }; yield return new object[] { currentProcess, Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1").Where(p => p.Id == currentProcess.Id).Single() }; } [Theory, PlatformSpecific(PlatformID.Windows)] [MemberData("GetTestProcess")] public void TestProcessOnRemoteMachineWindows(Process currentProcess, Process remoteProcess) { Assert.Equal(currentProcess.Id, remoteProcess.Id); Assert.Equal(currentProcess.BasePriority, remoteProcess.BasePriority); Assert.Equal(currentProcess.EnableRaisingEvents, remoteProcess.EnableRaisingEvents); Assert.Equal("127.0.0.1", remoteProcess.MachineName); // This property throws exception only on remote processes. Assert.Throws<NotSupportedException>(() => remoteProcess.MainModule); } [Fact, PlatformSpecific(PlatformID.AnyUnix)] public void TestProcessOnRemoteMachineUnix() { Process currentProcess = Process.GetCurrentProcess(); Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1")); Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessById(currentProcess.Id, "127.0.0.1")); } [Fact] public void TestStartInfo() { { Process process = CreateProcessInfinite(); process.Start(); Assert.Equal(CoreRunName, process.StartInfo.FileName); process.Kill(); Assert.True(process.WaitForExit(WaitInMS)); } { Process process = CreateProcessInfinite(); process.Start(); Assert.Throws<System.InvalidOperationException>(() => (process.StartInfo = new ProcessStartInfo())); process.Kill(); Assert.True(process.WaitForExit(WaitInMS)); } { Process process = new Process(); process.StartInfo = new ProcessStartInfo(TestExeName); Assert.Equal(TestExeName, process.StartInfo.FileName); } { Process process = new Process(); Assert.Throws<ArgumentNullException>(() => process.StartInfo = null); } { Process process = Process.GetCurrentProcess(); Assert.Throws<System.InvalidOperationException>(() => process.StartInfo); } } // [Fact] // uncomment for diagnostic purposes to list processes to console public void TestDiagnosticsWithConsoleWriteLine() { foreach (var p in Process.GetProcesses().OrderBy(p => p.Id)) { Console.WriteLine("{0} : \"{1}\" (Threads: {2})", p.Id, p.ProcessName, p.Threads.Count); p.Dispose(); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using EnvDTE; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Feedback.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; using Roslyn.VisualStudio.ProjectSystem; using VSLangProj; using VSLangProj140; using OLEServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { /// <summary> /// The Workspace for running inside Visual Studio. /// </summary> internal abstract class VisualStudioWorkspaceImpl : VisualStudioWorkspace { private static readonly IntPtr s_docDataExisting_Unknown = new IntPtr(-1); private const string AppCodeFolderName = "App_Code"; protected readonly IServiceProvider ServiceProvider; private readonly IVsUIShellOpenDocument _shellOpenDocument; private readonly IVsTextManager _textManager; // Not readonly because it needs to be set in the derived class' constructor. private VisualStudioProjectTracker _projectTracker; // document worker coordinator private ISolutionCrawlerRegistrationService _registrationService; private readonly ForegroundThreadAffinitizedObject foregroundObject = new ForegroundThreadAffinitizedObject(); public VisualStudioWorkspaceImpl( SVsServiceProvider serviceProvider, WorkspaceBackgroundWork backgroundWork) : base( CreateHostServices(serviceProvider), backgroundWork) { this.ServiceProvider = serviceProvider; _textManager = serviceProvider.GetService(typeof(SVsTextManager)) as IVsTextManager; _shellOpenDocument = serviceProvider.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; // Ensure the options factory services are initialized on the UI thread this.Services.GetService<IOptionService>(); var session = serviceProvider.GetService(typeof(SVsLog)) as IVsSqmMulti; var profileService = serviceProvider.GetService(typeof(SVsFeedbackProfile)) as IVsFeedbackProfile; // We have Watson hits where this came back null, so guard against it if (profileService != null) { Sqm.LogSession(session, profileService.IsMicrosoftInternal); } } internal static HostServices CreateHostServices(SVsServiceProvider serviceProvider) { var composition = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); return MefV1HostServices.Create(composition.DefaultExportProvider); } protected void InitializeStandardVisualStudioWorkspace(SVsServiceProvider serviceProvider, SaveEventsService saveEventsService) { var projectTracker = new VisualStudioProjectTracker(serviceProvider); // Ensure the document tracking service is initialized on the UI thread var documentTrackingService = this.Services.GetService<IDocumentTrackingService>(); var documentProvider = new RoslynDocumentProvider(projectTracker, serviceProvider, documentTrackingService); projectTracker.DocumentProvider = documentProvider; projectTracker.MetadataReferenceProvider = this.Services.GetService<VisualStudioMetadataReferenceManager>(); projectTracker.RuleSetFileProvider = this.Services.GetService<VisualStudioRuleSetManager>(); this.SetProjectTracker(projectTracker); var workspaceHost = new VisualStudioWorkspaceHost(this); projectTracker.RegisterWorkspaceHost(workspaceHost); projectTracker.StartSendingEventsToWorkspaceHost(workspaceHost); saveEventsService.StartSendingSaveEvents(); // Ensure the options factory services are initialized on the UI thread this.Services.GetService<IOptionService>(); } /// <summary>NOTE: Call only from derived class constructor</summary> protected void SetProjectTracker(VisualStudioProjectTracker projectTracker) { _projectTracker = projectTracker; } internal VisualStudioProjectTracker ProjectTracker { get { return _projectTracker; } } internal void ClearReferenceCache() { _projectTracker.MetadataReferenceProvider.ClearCache(); } internal IVisualStudioHostDocument GetHostDocument(DocumentId documentId) { var project = GetHostProject(documentId.ProjectId); if (project != null) { return project.GetDocumentOrAdditionalDocument(documentId); } return null; } internal IVisualStudioHostProject GetHostProject(ProjectId projectId) { return this.ProjectTracker.GetProject(projectId); } private bool TryGetHostProject(ProjectId projectId, out IVisualStudioHostProject project) { project = GetHostProject(projectId); return project != null; } public override bool TryApplyChanges(Microsoft.CodeAnalysis.Solution newSolution) { // first make sure we can edit the document we will be updating (check them out from source control, etc) var changedDocs = newSolution.GetChanges(this.CurrentSolution).GetProjectChanges().SelectMany(pd => pd.GetChangedDocuments()).ToList(); if (changedDocs.Count > 0) { this.EnsureEditableDocuments(changedDocs); } return base.TryApplyChanges(newSolution); } public override bool CanOpenDocuments { get { return true; } } internal override bool CanChangeActiveContextDocument { get { return true; } } public override bool CanApplyChange(ApplyChangesKind feature) { switch (feature) { case ApplyChangesKind.AddDocument: case ApplyChangesKind.RemoveDocument: case ApplyChangesKind.ChangeDocument: case ApplyChangesKind.AddMetadataReference: case ApplyChangesKind.RemoveMetadataReference: case ApplyChangesKind.AddProjectReference: case ApplyChangesKind.RemoveProjectReference: case ApplyChangesKind.AddAnalyzerReference: case ApplyChangesKind.RemoveAnalyzerReference: case ApplyChangesKind.AddAdditionalDocument: case ApplyChangesKind.RemoveAdditionalDocument: case ApplyChangesKind.ChangeAdditionalDocument: return true; default: return false; } } private bool TryGetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project) { hierarchy = null; project = null; return this.TryGetHostProject(projectId, out hostProject) && this.TryGetHierarchy(projectId, out hierarchy) && hierarchy.TryGetProject(out project); } internal void GetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project) { if (!TryGetProjectData(projectId, out hostProject, out hierarchy, out project)) { throw new ArgumentException(string.Format(ServicesVSResources.CouldNotFindProject, projectId)); } } internal bool TryAddReferenceToProject(ProjectId projectId, string assemblyName) { IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; try { GetProjectData(projectId, out hostProject, out hierarchy, out project); } catch (ArgumentException) { return false; } var vsProject = (VSProject)project.Object; try { vsProject.References.Add(assemblyName); } catch (Exception) { return false; } return true; } private string GetAnalyzerPath(AnalyzerReference analyzerReference) { return analyzerReference.FullPath; } protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (analyzerReference == null) { throw new ArgumentNullException(nameof(analyzerReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetAnalyzerPath(analyzerReference); if (filePath != null) { VSProject3 vsProject = (VSProject3)project.Object; vsProject.AnalyzerReferences.Add(filePath); } } protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (analyzerReference == null) { throw new ArgumentNullException(nameof(analyzerReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetAnalyzerPath(analyzerReference); if (filePath != null) { VSProject3 vsProject = (VSProject3)project.Object; vsProject.AnalyzerReferences.Remove(filePath); } } private string GetMetadataPath(MetadataReference metadataReference) { var fileMetadata = metadataReference as PortableExecutableReference; if (fileMetadata != null) { return fileMetadata.FilePath; } return null; } protected override void ApplyMetadataReferenceAdded(ProjectId projectId, MetadataReference metadataReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (metadataReference == null) { throw new ArgumentNullException(nameof(metadataReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetMetadataPath(metadataReference); if (filePath != null) { VSProject vsProject = (VSProject)project.Object; vsProject.References.Add(filePath); } } protected override void ApplyMetadataReferenceRemoved(ProjectId projectId, MetadataReference metadataReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (metadataReference == null) { throw new ArgumentNullException(nameof(metadataReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetMetadataPath(metadataReference); if (filePath != null) { VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object; VSLangProj.Reference reference = vsProject.References.Find(filePath); if (reference != null) { reference.Remove(); } } } protected override void ApplyProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); IVisualStudioHostProject refHostProject; IVsHierarchy refHierarchy; EnvDTE.Project refProject; GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject); VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object; vsProject.References.AddProject(refProject); } protected override void ApplyProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); IVisualStudioHostProject refHostProject; IVsHierarchy refHierarchy; EnvDTE.Project refProject; GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject); VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object; foreach (VSLangProj.Reference reference in vsProject.References) { if (reference.SourceProject == refProject) { reference.Remove(); } } } protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text) { AddDocumentCore(info, text, isAdditionalDocument: false); } protected override void ApplyAdditionalDocumentAdded(DocumentInfo info, SourceText text) { AddDocumentCore(info, text, isAdditionalDocument: true); } private void AddDocumentCore(DocumentInfo info, SourceText initialText, bool isAdditionalDocument) { IVsHierarchy hierarchy; EnvDTE.Project project; IVisualStudioHostProject hostProject; GetProjectData(info.Id.ProjectId, out hostProject, out hierarchy, out project); // If the first namespace name matches the name of the project, then we don't want to // generate a folder for that. The project is implicitly a folder with that name. var folders = info.Folders.AsEnumerable(); if (folders.FirstOrDefault() == project.Name) { folders = folders.Skip(1); } folders = FilterFolderForProjectType(project, folders); if (IsWebsite(project)) { AddDocumentToFolder(hostProject, project, info.Id, SpecializedCollections.SingletonEnumerable(AppCodeFolderName), info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } else if (folders.Any()) { AddDocumentToFolder(hostProject, project, info.Id, folders, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } else { AddDocumentToProject(hostProject, project, info.Id, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } } private bool IsWebsite(EnvDTE.Project project) { return project.Kind == VsWebSite.PrjKind.prjKindVenusProject; } private IEnumerable<string> FilterFolderForProjectType(EnvDTE.Project project, IEnumerable<string> folders) { foreach (var folder in folders) { var items = GetAllItems(project.ProjectItems); var folderItem = items.FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Compare(p.Name, folder) == 0); if (folderItem == null || folderItem.Kind != EnvDTE.Constants.vsProjectItemKindPhysicalFile) { yield return folder; } } } private IEnumerable<ProjectItem> GetAllItems(ProjectItems projectItems) { if (projectItems == null) { return SpecializedCollections.EmptyEnumerable<ProjectItem>(); } var items = projectItems.OfType<ProjectItem>(); return items.Concat(items.SelectMany(i => GetAllItems(i.ProjectItems))); } #if false protected override void AddExistingDocument(DocumentId documentId, string filePath, IEnumerable<string> folders) { IVsHierarchy hierarchy; EnvDTE.Project project; IVisualStudioHostProject hostProject; GetProjectData(documentId.ProjectId, out hostProject, out hierarchy, out project); // If the first namespace name matches the name of the project, then we don't want to // generate a folder for that. The project is implicitly a folder with that name. if (folders.FirstOrDefault() == project.Name) { folders = folders.Skip(1); } var name = Path.GetFileName(filePath); if (folders.Any()) { AddDocumentToFolder(hostProject, project, documentId, folders, name, SourceCodeKind.Regular, initialText: null, filePath: filePath); } else { AddDocumentToProject(hostProject, project, documentId, name, SourceCodeKind.Regular, initialText: null, filePath: filePath); } } #endif private ProjectItem AddDocumentToProject( IVisualStudioHostProject hostProject, EnvDTE.Project project, DocumentId documentId, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText = null, string filePath = null, bool isAdditionalDocument = false) { string folderPath; if (!project.TryGetFullPath(out folderPath)) { // TODO(cyrusn): Throw an appropriate exception here. throw new Exception(ServicesVSResources.CouldNotFindLocationOfFol); } return AddDocumentToProjectItems(hostProject, project.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument); } private ProjectItem AddDocumentToFolder( IVisualStudioHostProject hostProject, EnvDTE.Project project, DocumentId documentId, IEnumerable<string> folders, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText = null, string filePath = null, bool isAdditionalDocument = false) { var folder = project.FindOrCreateFolder(folders); string folderPath; if (!folder.TryGetFullPath(out folderPath)) { // TODO(cyrusn): Throw an appropriate exception here. throw new Exception(ServicesVSResources.CouldNotFindLocationOfFol); } return AddDocumentToProjectItems(hostProject, folder.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument); } private ProjectItem AddDocumentToProjectItems( IVisualStudioHostProject hostProject, ProjectItems projectItems, DocumentId documentId, string folderPath, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText, string filePath, bool isAdditionalDocument) { if (filePath == null) { var baseName = Path.GetFileNameWithoutExtension(documentName); var extension = isAdditionalDocument ? Path.GetExtension(documentName) : GetPreferredExtension(hostProject, sourceCodeKind); var uniqueName = projectItems.GetUniqueName(baseName, extension); filePath = Path.Combine(folderPath, uniqueName); } if (initialText != null) { using (var writer = new StreamWriter(filePath, append: false, encoding: initialText.Encoding ?? Encoding.UTF8)) { initialText.Write(writer); } } using (var documentIdHint = _projectTracker.DocumentProvider.ProvideDocumentIdHint(filePath, documentId)) { return projectItems.AddFromFile(filePath); } } protected void RemoveDocumentCore(DocumentId documentId) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } var document = this.GetHostDocument(documentId); if (document != null) { var project = document.Project.Hierarchy as IVsProject3; var itemId = document.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // it is no longer part of the solution return; } int result; project.RemoveItem(0, itemId, out result); } } protected override void ApplyDocumentRemoved(DocumentId documentId) { RemoveDocumentCore(documentId); } protected override void ApplyAdditionalDocumentRemoved(DocumentId documentId) { RemoveDocumentCore(documentId); } public override void OpenDocument(DocumentId documentId, bool activate = true) { OpenDocumentCore(documentId, activate); } public override void OpenAdditionalDocument(DocumentId documentId, bool activate = true) { OpenDocumentCore(documentId, activate); } public override void CloseDocument(DocumentId documentId) { CloseDocumentCore(documentId); } public override void CloseAdditionalDocument(DocumentId documentId) { CloseDocumentCore(documentId); } public bool TryGetInfoBarData(out IVsWindowFrame frame, out IVsInfoBarUIFactory factory) { frame = null; factory = null; var monitorSelectionService = ServiceProvider.GetService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection; object value = null; // We want to get whichever window is currently in focus (including toolbars) as we could have had an exception thrown from the error list or interactive window if (monitorSelectionService != null && ErrorHandler.Succeeded(monitorSelectionService.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_WindowFrame, out value))) { frame = value as IVsWindowFrame; } else { return false; } factory = ServiceProvider.GetService(typeof(SVsInfoBarUIFactory)) as IVsInfoBarUIFactory; return frame != null && factory != null; } public void OpenDocumentCore(DocumentId documentId, bool activate = true) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (!foregroundObject.IsForeground()) { throw new InvalidOperationException(ServicesVSResources.ThisWorkspaceOnlySupportsOpeningDocumentsOnTheUIThread); } var document = this.GetHostDocument(documentId); if (document != null && document.Project != null) { IVsWindowFrame frame; if (TryGetFrame(document, out frame)) { if (activate) { frame.Show(); } else { frame.ShowNoActivate(); } } } } private bool TryGetFrame(IVisualStudioHostDocument document, out IVsWindowFrame frame) { frame = null; var itemId = document.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // If the ItemId is Nil, then then IVsProject would not be able to open the // document using its ItemId. Thus, we must use OpenDocumentViaProject, which only // depends on the file path. uint itemid; IVsUIHierarchy uiHierarchy; OLEServiceProvider oleServiceProvider; return ErrorHandler.Succeeded(_shellOpenDocument.OpenDocumentViaProject( document.FilePath, VSConstants.LOGVIEWID.TextView_guid, out oleServiceProvider, out uiHierarchy, out itemid, out frame)); } else { // If the ItemId is not Nil, then we should not call IVsUIShellDocument // .OpenDocumentViaProject here because that simply takes a file path and opens the // file within the context of the first project it finds. That would cause problems // if the document we're trying to open is actually a linked file in another // project. So, we get the project's hierarchy and open the document using its item // ID. // It's conceivable that IVsHierarchy might not implement IVsProject. However, // OpenDocumentViaProject itself relies upon this QI working, so it should be OK to // use here. var vsProject = document.Project.Hierarchy as IVsProject; return vsProject != null && ErrorHandler.Succeeded(vsProject.OpenItem(itemId, VSConstants.LOGVIEWID.TextView_guid, s_docDataExisting_Unknown, out frame)); } } public void CloseDocumentCore(DocumentId documentId) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (this.IsDocumentOpen(documentId)) { var document = this.GetHostDocument(documentId); if (document != null) { IVsUIHierarchy uiHierarchy; IVsWindowFrame frame; int isOpen; if (ErrorHandler.Succeeded(_shellOpenDocument.IsDocumentOpen(null, 0, document.FilePath, Guid.Empty, 0, out uiHierarchy, null, out frame, out isOpen))) { // TODO: do we need save argument for CloseDocument? frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave); } } } } protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText) { EnsureEditableDocuments(documentId); var hostDocument = GetHostDocument(documentId); hostDocument.UpdateText(newText); } protected override void ApplyAdditionalDocumentTextChanged(DocumentId documentId, SourceText newText) { EnsureEditableDocuments(documentId); var hostDocument = GetHostDocument(documentId); hostDocument.UpdateText(newText); } private static string GetPreferredExtension(IVisualStudioHostProject hostProject, SourceCodeKind sourceCodeKind) { // No extension was provided. Pick a good one based on the type of host project. switch (hostProject.Language) { case LanguageNames.CSharp: // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325 //return sourceCodeKind == SourceCodeKind.Regular ? ".cs" : ".csx"; return ".cs"; case LanguageNames.VisualBasic: // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325 //return sourceCodeKind == SourceCodeKind.Regular ? ".vb" : ".vbx"; return ".vb"; default: throw new InvalidOperationException(); } } public override IVsHierarchy GetHierarchy(ProjectId projectId) { var project = this.GetHostProject(projectId); if (project == null) { return null; } return project.Hierarchy; } internal override void SetDocumentContext(DocumentId documentId) { var hostDocument = GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var hierarchy = hostDocument.Project.Hierarchy; var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId); if (sharedHierarchy != null) { if (sharedHierarchy.SetProperty( (uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext, ProjectTracker.GetProject(documentId.ProjectId).ProjectSystemName) == VSConstants.S_OK) { // The ASP.NET 5 intellisense project is now updated. return; } else { // Universal Project shared files // Change the SharedItemContextHierarchy of the project's parent hierarchy, then // hierarchy events will trigger the workspace to update. var hr = sharedHierarchy.SetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy, hierarchy); } } else { // Regular linked files // Transfer the item (open buffer) to the new hierarchy, and then hierarchy events // will trigger the workspace to update. var vsproj = hierarchy as IVsProject3; var hr = vsproj.TransferItem(hostDocument.FilePath, hostDocument.FilePath, punkWindowFrame: null); } } internal void UpdateDocumentContextIfContainsDocument(IVsHierarchy sharedHierarchy, DocumentId documentId) { // TODO: This is a very roundabout way to update the context // The sharedHierarchy passed in has a new context, but we don't know what it is. // The documentId passed in is associated with this sharedHierarchy, and this method // will be called once for each such documentId. During this process, one of these // documentIds will actually belong to the new SharedItemContextHierarchy. Once we // find that one, we can map back to the open buffer and set its active context to // the appropriate project. var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker); if (hostProject.Hierarchy == sharedHierarchy) { // How? return; } if (hostProject.Id != documentId.ProjectId) { // While this documentId is associated with one of the head projects for this // sharedHierarchy, it is not associated with the new context hierarchy. Another // documentId will be passed to this method and update the context. return; } // This documentId belongs to the new SharedItemContextHierarchy. Update the associated // buffer. OnDocumentContextUpdated(documentId); } /// <summary> /// Finds the <see cref="DocumentId"/> related to the given <see cref="DocumentId"/> that /// is in the current context. For regular files (non-shared and non-linked) and closed /// linked files, this is always the provided <see cref="DocumentId"/>. For open linked /// files and open shared files, the active context is already tracked by the /// <see cref="Workspace"/> and can be looked up directly. For closed shared files, the /// document in the shared project's <see cref="__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy"/> /// is preferred. /// </summary> internal override DocumentId GetDocumentIdInCurrentContext(DocumentId documentId) { // If the document is open, then the Workspace knows the current context for both // linked and shared files if (IsDocumentOpen(documentId)) { return base.GetDocumentIdInCurrentContext(documentId); } var hostDocument = GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // An itemid is required to determine whether the file belongs to a Shared Project return base.GetDocumentIdInCurrentContext(documentId); } // If this is a regular document or a closed linked (non-shared) document, then use the // default logic for determining current context. var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId); if (sharedHierarchy == null) { return base.GetDocumentIdInCurrentContext(documentId); } // This is a closed shared document, so we must determine the correct context. var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker); var matchingProject = CurrentSolution.GetProject(hostProject.Id); if (matchingProject == null || hostProject.Hierarchy == sharedHierarchy) { return base.GetDocumentIdInCurrentContext(documentId); } if (matchingProject.ContainsDocument(documentId)) { // The provided documentId is in the current context project return documentId; } // The current context document is from another project. var linkedDocumentIds = CurrentSolution.GetDocument(documentId).GetLinkedDocumentIds(); var matchingDocumentId = linkedDocumentIds.FirstOrDefault(id => id.ProjectId == matchingProject.Id); return matchingDocumentId ?? base.GetDocumentIdInCurrentContext(documentId); } private bool TryGetHierarchy(ProjectId projectId, out IVsHierarchy hierarchy) { hierarchy = this.GetHierarchy(projectId); return hierarchy != null; } public override string GetFilePath(DocumentId documentId) { var document = this.GetHostDocument(documentId); if (document == null) { return null; } else { return document.FilePath; } } internal void StartSolutionCrawler() { if (_registrationService == null) { lock (this) { if (_registrationService == null) { _registrationService = this.Services.GetService<ISolutionCrawlerRegistrationService>(); _registrationService.Register(this); } } } } internal void StopSolutionCrawler() { if (_registrationService != null) { lock (this) { if (_registrationService != null) { _registrationService.Unregister(this, blockingShutdown: true); _registrationService = null; } } } } protected override void Dispose(bool finalize) { // workspace is going away. unregister this workspace from work coordinator StopSolutionCrawler(); base.Dispose(finalize); } public void EnsureEditableDocuments(IEnumerable<DocumentId> documents) { var queryEdit = (IVsQueryEditQuerySave2)ServiceProvider.GetService(typeof(SVsQueryEditQuerySave)); var fileNames = documents.Select(GetFilePath).ToArray(); uint editVerdict; uint editResultFlags; // TODO: meditate about the flags we can pass to this and decide what is most appropriate for Roslyn int result = queryEdit.QueryEditFiles( rgfQueryEdit: 0, cFiles: fileNames.Length, rgpszMkDocuments: fileNames, rgrgf: new uint[fileNames.Length], rgFileInfo: new VSQEQS_FILE_ATTRIBUTE_DATA[fileNames.Length], pfEditVerdict: out editVerdict, prgfMoreInfo: out editResultFlags); if (ErrorHandler.Failed(result) || editVerdict != (uint)tagVSQueryEditResult.QER_EditOK) { throw new Exception("Unable to check out the files from source control."); } if ((editResultFlags & (uint)(tagVSQueryEditResultFlags2.QER_Changed | tagVSQueryEditResultFlags2.QER_Reloaded)) != 0) { throw new Exception("A file was reloaded during the source control checkout."); } } public void EnsureEditableDocuments(params DocumentId[] documents) { this.EnsureEditableDocuments((IEnumerable<DocumentId>)documents); } internal void OnDocumentTextUpdatedOnDisk(DocumentId documentId) { var vsDoc = this.GetHostDocument(documentId); this.OnDocumentTextLoaderChanged(documentId, vsDoc.Loader); } internal void OnAdditionalDocumentTextUpdatedOnDisk(DocumentId documentId) { var vsDoc = this.GetHostDocument(documentId); this.OnAdditionalDocumentTextLoaderChanged(documentId, vsDoc.Loader); } public TInterface GetVsService<TService, TInterface>() where TService : class where TInterface : class { return this.ServiceProvider.GetService(typeof(TService)) as TInterface; } /// <summary> /// A trivial implementation of <see cref="IVisualStudioWorkspaceHost" /> that just /// forwards the calls down to the underlying Workspace. /// </summary> protected class VisualStudioWorkspaceHost : IVisualStudioWorkspaceHost, IVisualStudioWorkingFolder { private readonly VisualStudioWorkspaceImpl _workspace; private Dictionary<DocumentId, uint> _documentIdToHierarchyEventsCookieMap = new Dictionary<DocumentId, uint>(); public VisualStudioWorkspaceHost(VisualStudioWorkspaceImpl workspace) { _workspace = workspace; } void IVisualStudioWorkspaceHost.OnOptionsChanged(ProjectId projectId, CompilationOptions compilationOptions, ParseOptions parseOptions) { _workspace.OnCompilationOptionsChanged(projectId, compilationOptions); _workspace.OnParseOptionsChanged(projectId, parseOptions); } void IVisualStudioWorkspaceHost.OnDocumentAdded(DocumentInfo documentInfo) { _workspace.OnDocumentAdded(documentInfo); } void IVisualStudioWorkspaceHost.OnDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader, bool updateActiveContext) { // TODO: Move this out to DocumentProvider. As is, this depends on being able to // access the host document which will already be deleted in some cases, causing // a crash. Until this is fixed, we will leak a HierarchyEventsSink every time a // Mercury shared document is closed. // UnsubscribeFromSharedHierarchyEvents(documentId); using (_workspace.Services.GetService<IGlobalOperationNotificationService>().Start("Document Closed")) { _workspace.OnDocumentClosed(documentId, loader, updateActiveContext); } } void IVisualStudioWorkspaceHost.OnDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool currentContext) { SubscribeToSharedHierarchyEvents(documentId); _workspace.OnDocumentOpened(documentId, textBuffer.AsTextContainer(), currentContext); } private void SubscribeToSharedHierarchyEvents(DocumentId documentId) { // Todo: maybe avoid double alerts. var hostDocument = _workspace.GetHostDocument(documentId); if (hostDocument == null) { return; } var hierarchy = hostDocument.Project.Hierarchy; var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId); if (sharedHierarchy != null) { uint cookie; var eventSink = new HierarchyEventsSink(_workspace, sharedHierarchy, documentId); var hr = sharedHierarchy.AdviseHierarchyEvents(eventSink, out cookie); if (hr == VSConstants.S_OK && !_documentIdToHierarchyEventsCookieMap.ContainsKey(documentId)) { _documentIdToHierarchyEventsCookieMap.Add(documentId, cookie); } } } private void UnsubscribeFromSharedHierarchyEvents(DocumentId documentId) { var hostDocument = _workspace.GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId); if (sharedHierarchy != null) { uint cookie; if (_documentIdToHierarchyEventsCookieMap.TryGetValue(documentId, out cookie)) { var hr = sharedHierarchy.UnadviseHierarchyEvents(cookie); _documentIdToHierarchyEventsCookieMap.Remove(documentId); } } } private void RegisterPrimarySolutionForPersistentStorage(SolutionId solutionId) { var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService; if (service == null) { return; } service.RegisterPrimarySolution(solutionId); } private void UnregisterPrimarySolutionForPersistentStorage(SolutionId solutionId, bool synchronousShutdown) { var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService; if (service == null) { return; } service.UnregisterPrimarySolution(solutionId, synchronousShutdown); } void IVisualStudioWorkspaceHost.OnDocumentRemoved(DocumentId documentId) { _workspace.OnDocumentRemoved(documentId); } void IVisualStudioWorkspaceHost.OnMetadataReferenceAdded(ProjectId projectId, PortableExecutableReference metadataReference) { _workspace.OnMetadataReferenceAdded(projectId, metadataReference); } void IVisualStudioWorkspaceHost.OnMetadataReferenceRemoved(ProjectId projectId, PortableExecutableReference metadataReference) { _workspace.OnMetadataReferenceRemoved(projectId, metadataReference); } void IVisualStudioWorkspaceHost.OnProjectAdded(ProjectInfo projectInfo) { using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Add Project")) { _workspace.OnProjectAdded(projectInfo); } } void IVisualStudioWorkspaceHost.OnProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { _workspace.OnProjectReferenceAdded(projectId, projectReference); } void IVisualStudioWorkspaceHost.OnProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { _workspace.OnProjectReferenceRemoved(projectId, projectReference); } void IVisualStudioWorkspaceHost.OnProjectRemoved(ProjectId projectId) { using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Remove Project")) { _workspace.OnProjectRemoved(projectId); } } void IVisualStudioWorkspaceHost.OnSolutionAdded(SolutionInfo solutionInfo) { RegisterPrimarySolutionForPersistentStorage(solutionInfo.Id); _workspace.OnSolutionAdded(solutionInfo); } void IVisualStudioWorkspaceHost.OnSolutionRemoved() { var solutionId = _workspace.CurrentSolution.Id; _workspace.OnSolutionRemoved(); _workspace.ClearReferenceCache(); UnregisterPrimarySolutionForPersistentStorage(solutionId, synchronousShutdown: false); } void IVisualStudioWorkspaceHost.ClearSolution() { _workspace.ClearSolution(); _workspace.ClearReferenceCache(); } void IVisualStudioWorkspaceHost.OnDocumentTextUpdatedOnDisk(DocumentId id) { _workspace.OnDocumentTextUpdatedOnDisk(id); } void IVisualStudioWorkspaceHost.OnAssemblyNameChanged(ProjectId id, string assemblyName) { _workspace.OnAssemblyNameChanged(id, assemblyName); } void IVisualStudioWorkspaceHost.OnOutputFilePathChanged(ProjectId id, string outputFilePath) { _workspace.OnOutputFilePathChanged(id, outputFilePath); } void IVisualStudioWorkspaceHost.OnProjectNameChanged(ProjectId projectId, string name, string filePath) { _workspace.OnProjectNameChanged(projectId, name, filePath); } void IVisualStudioWorkspaceHost.OnAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { _workspace.OnAnalyzerReferenceAdded(projectId, analyzerReference); } void IVisualStudioWorkspaceHost.OnAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { _workspace.OnAnalyzerReferenceRemoved(projectId, analyzerReference); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentAdded(DocumentInfo additionalDocumentInfo) { _workspace.OnAdditionalDocumentAdded(additionalDocumentInfo); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentRemoved(DocumentId additionalDocumentId) { _workspace.OnAdditionalDocumentRemoved(additionalDocumentId); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool isCurrentContext) { _workspace.OnAdditionalDocumentOpened(documentId, textBuffer.AsTextContainer(), isCurrentContext); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader) { _workspace.OnAdditionalDocumentClosed(documentId, loader); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentTextUpdatedOnDisk(DocumentId id) { _workspace.OnAdditionalDocumentTextUpdatedOnDisk(id); } void IVisualStudioWorkingFolder.OnBeforeWorkingFolderChange() { UnregisterPrimarySolutionForPersistentStorage(_workspace.CurrentSolution.Id, synchronousShutdown: true); } void IVisualStudioWorkingFolder.OnAfterWorkingFolderChange() { var solutionId = _workspace.CurrentSolution.Id; _workspace.ProjectTracker.UpdateSolutionProperties(solutionId); RegisterPrimarySolutionForPersistentStorage(solutionId); } } } }
// // MonoTests.System.Runtime.Remoting.SoapServicesTest.cs // // Author: Lluis Sanchez Gual (lluis@ximian.com) // // 2003 (C) Copyright, Novell, Inc. // using System; using System.Reflection; using System.Runtime.Remoting; using System.Runtime.Remoting.Metadata; using NUnit.Framework; namespace MonoTests.System.Runtime.Remoting { [SoapTypeAttribute (XmlElementName="ename", XmlNamespace="ens", XmlTypeName="tname", XmlTypeNamespace="tns")] public class SoapTest { [SoapField(XmlElementName="atrib",XmlNamespace="ns1",UseAttribute=true)] public string atribut; [SoapField(XmlElementName="elem",XmlNamespace="ns1")] public int element; [SoapField(XmlElementName="elem2")] public int element2; [SoapMethod (SoapAction="myaction")] public void FesAlgo () { } public void FesAlgoMes () { } public void FesAlgoMesEspecial () { } } public class SoapTest1 { } [SoapTypeAttribute (XmlElementName="ename", XmlTypeName="tname")] public class SoapTest2 { } [SoapTypeAttribute (XmlNamespace="ens", XmlTypeNamespace="tns")] public class SoapTest3 { } [TestFixture] public class SoapServicesTest: Assertion { public string ThisNamespace { get { string tn = "http://schemas.microsoft.com/clr/nsassem/"; tn += GetType ().Namespace + "/" + GetType ().Assembly.GetName().Name; return tn; } } public string GetClassNs (Type t) { string tn = "http://schemas.microsoft.com/clr/nsassem/"; tn += t.FullName + "/" + t.Assembly.GetName().Name; return tn; } public string GetSimpleTypeName (Type t) { return t.FullName + ", " + t.Assembly.GetName().Name; } [Test] public void TestGetXmlType () { bool res; string name, ns; // XmlType res = SoapServices.GetXmlElementForInteropType (typeof(SoapTest), out name, out ns); Assert ("E1",res); AssertEquals ("E2", "ename", name); AssertEquals ("E3", "ens", ns); res = SoapServices.GetXmlElementForInteropType (typeof(SoapTest1), out name, out ns); Assert ("E4",!res); res = SoapServices.GetXmlElementForInteropType (typeof(SoapTest2), out name, out ns); Assert ("E5",res); AssertEquals ("E6", "ename", name); AssertEquals ("E7", ThisNamespace, ns); res = SoapServices.GetXmlElementForInteropType (typeof(SoapTest3), out name, out ns); Assert ("E8",res); AssertEquals ("E9", "SoapTest3", name); AssertEquals ("E10", "ens", ns); // XmlElement res = SoapServices.GetXmlTypeForInteropType (typeof(SoapTest), out name, out ns); Assert ("T1",res); AssertEquals ("T2", "tname", name); AssertEquals ("T3", "tns", ns); res = SoapServices.GetXmlTypeForInteropType (typeof(SoapTest1), out name, out ns); Assert ("T4",!res); res = SoapServices.GetXmlTypeForInteropType (typeof(SoapTest2), out name, out ns); Assert ("T5",res); AssertEquals ("T6", "tname", name); AssertEquals ("T7", ThisNamespace, ns); res = SoapServices.GetXmlTypeForInteropType (typeof(SoapTest3), out name, out ns); Assert ("T8",res); AssertEquals ("T9", "SoapTest3", name); AssertEquals ("T10", "tns", ns); } [Test] public void TestGetInteropType () { Type t; // Manual registration t = SoapServices.GetInteropTypeFromXmlElement ("aa","bb"); AssertEquals ("M1", t, null); SoapServices.RegisterInteropXmlElement ("aa","bb",typeof(SoapTest)); t = SoapServices.GetInteropTypeFromXmlElement ("aa","bb"); AssertEquals ("M2", typeof (SoapTest), t); t = SoapServices.GetInteropTypeFromXmlType ("aa","bb"); AssertEquals ("M3", null, t); SoapServices.RegisterInteropXmlType ("aa","bb",typeof(SoapTest)); t = SoapServices.GetInteropTypeFromXmlType ("aa","bb"); AssertEquals ("M4", typeof (SoapTest), t); // Preload type SoapServices.PreLoad (typeof(SoapTest2)); t = SoapServices.GetInteropTypeFromXmlElement ("ename",ThisNamespace); AssertEquals ("T1", typeof (SoapTest2), t); t = SoapServices.GetInteropTypeFromXmlType ("tname",ThisNamespace); AssertEquals ("T2", typeof (SoapTest2), t); // Preload assembly SoapServices.PreLoad (typeof(SoapTest).Assembly); t = SoapServices.GetInteropTypeFromXmlElement ("SoapTest3","ens"); AssertEquals ("A1", typeof (SoapTest3), t); t = SoapServices.GetInteropTypeFromXmlType ("SoapTest3","tns"); AssertEquals ("A2", typeof (SoapTest3), t); } [Test] public void TestSoapFields () { string name; Type t; SoapServices.GetInteropFieldTypeAndNameFromXmlAttribute (typeof(SoapTest), "atrib", "ns1", out t, out name); AssertEquals ("#1", "atribut", name); AssertEquals ("#2", typeof(string), t); SoapServices.GetInteropFieldTypeAndNameFromXmlElement (typeof(SoapTest), "elem", "ns1", out t, out name); AssertEquals ("#3", "element", name); AssertEquals ("#4", typeof(int), t); SoapServices.GetInteropFieldTypeAndNameFromXmlElement (typeof(SoapTest), "elem2", null, out t, out name); AssertEquals ("#5", "element2", name); AssertEquals ("#6", typeof(int), t); } [Test] [Category("NotWorking")] public void TestSoapActions () { string act; MethodBase mb; mb = typeof(SoapTest).GetMethod ("FesAlgo"); act = SoapServices.GetSoapActionFromMethodBase (mb); AssertEquals ("S1", "myaction", act); mb = typeof(SoapTest).GetMethod ("FesAlgoMes"); SoapServices.RegisterSoapActionForMethodBase (mb, "anotheraction"); act = SoapServices.GetSoapActionFromMethodBase (mb); AssertEquals ("S2", "anotheraction", act); mb = typeof(SoapTest).GetMethod ("FesAlgoMesEspecial"); act = SoapServices.GetSoapActionFromMethodBase (mb); AssertEquals ("S3", GetClassNs (typeof(SoapTest))+ "#FesAlgoMesEspecial", act); string typeName, methodName; bool res; res = SoapServices.GetTypeAndMethodNameFromSoapAction ("myaction", out typeName, out methodName); Assert ("M1", res); AssertEquals ("M2", GetSimpleTypeName (typeof(SoapTest)), typeName); AssertEquals ("M3", "FesAlgo", methodName); res = SoapServices.GetTypeAndMethodNameFromSoapAction ("anotheraction", out typeName, out methodName); Assert ("M4", res); AssertEquals ("M5", GetSimpleTypeName (typeof(SoapTest)), typeName); AssertEquals ("M6", "FesAlgoMes", methodName); res = SoapServices.GetTypeAndMethodNameFromSoapAction (GetClassNs (typeof(SoapTest))+ "#FesAlgoMesEspecial", out typeName, out methodName); Assert ("M7", res); AssertEquals ("M8", GetSimpleTypeName (typeof(SoapTest)), typeName); AssertEquals ("M9", "FesAlgoMesEspecial", methodName); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Collections.Tests { public static class QueueTests { [Fact] public static void Ctor_Empty() { const int DefaultCapactiy = 32; var queue = new Queue(); Assert.Equal(0, queue.Count); for (int i = 0; i <= DefaultCapactiy; i++) { queue.Enqueue(i); } Assert.Equal(DefaultCapactiy + 1, queue.Count); } [Theory] [InlineData(1)] [InlineData(32)] [InlineData(77)] public static void Ctor_Int(int capacity) { var queue = new Queue(capacity); for (int i = 0; i <= capacity; i++) { queue.Enqueue(i); } Assert.Equal(capacity + 1, queue.Count); } [Fact] public static void Ctor_Int_NegativeCapacity_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Queue(-1)); // Capacity < 0 } [Theory] [InlineData(1, 2.0)] [InlineData(32, 1.0)] [InlineData(77, 5.0)] public static void Ctor_Int_Int(int capacity, float growFactor) { var queue = new Queue(capacity, growFactor); for (int i = 0; i <= capacity; i++) { queue.Enqueue(i); } Assert.Equal(capacity + 1, queue.Count); } [Fact] public static void Ctor_Int_Int_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Queue(-1, 1)); // Capacity < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("growFactor", () => new Queue(1, (float)0.99)); // Grow factor < 1 AssertExtensions.Throws<ArgumentOutOfRangeException>("growFactor", () => new Queue(1, (float)10.01)); // Grow factor > 10 } [Fact] public static void Ctor_ICollection() { ArrayList arrList = Helpers.CreateIntArrayList(100); var queue = new Queue(arrList); Assert.Equal(arrList.Count, queue.Count); for (int i = 0; i < queue.Count; i++) { Assert.Equal(i, queue.Dequeue()); } } [Fact] public static void Ctor_ICollection_NullCollection_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("col", () => new Queue(null)); // Collection is null } [Fact] public static void DebuggerAttribute() { DebuggerAttributes.ValidateDebuggerDisplayReferences(new Queue()); var testQueue = new Queue(); testQueue.Enqueue("a"); testQueue.Enqueue(1); testQueue.Enqueue("b"); testQueue.Enqueue(2); DebuggerAttributeInfo debuggerAttribute = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(testQueue); PropertyInfo infoProperty = debuggerAttribute.Properties.Single(property => property.Name == "Items"); object[] items = (object[])infoProperty.GetValue(debuggerAttribute.Instance); Assert.Equal(testQueue.ToArray(), items); } [Fact] public static void DebuggerAttribute_NullQueue_ThrowsArgumentNullException() { bool threwNull = false; try { DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Queue), null); } catch (TargetInvocationException ex) { threwNull = ex.InnerException is ArgumentNullException; } Assert.True(threwNull); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(32)] public static void Clear(int capacity) { var queue1 = new Queue(capacity); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.Enqueue(1); queue2.Clear(); Assert.Equal(0, queue2.Count); }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(32)] public static void Clear_Empty(int capacity) { var queue1 = new Queue(capacity); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.Clear(); Assert.Equal(0, queue2.Count); queue2.Clear(); Assert.Equal(0, queue2.Count); }); } [Fact] public static void Clone() { Queue queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Queue clone = (Queue)queue2.Clone(); Assert.Equal(queue2.IsSynchronized, clone.IsSynchronized); Assert.Equal(queue2.Count, clone.Count); for (int i = 0; i < queue2.Count; i++) { Assert.True(clone.Contains(i)); } }); } [Fact] public static void Clone_IsShallowCopy() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.Enqueue(new Foo(10)); Queue clone = (Queue)queue2.Clone(); var foo = (Foo)queue2.Dequeue(); foo.IntValue = 50; var fooClone = (Foo)clone.Dequeue(); Assert.Equal(50, fooClone.IntValue); }); } [Fact] public static void Clone_Empty() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Queue clone = (Queue)queue2.Clone(); Assert.Equal(0, clone.Count); // Can change the clone queue clone.Enqueue(500); Assert.Equal(500, clone.Dequeue()); }); } [Fact] public static void Clone_Clear() { Queue queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.Clear(); Queue clone = (Queue)queue2.Clone(); Assert.Equal(0, clone.Count); // Can change clone queue clone.Enqueue(500); Assert.Equal(500, clone.Dequeue()); }); } [Fact] public static void Clone_DequeueUntilEmpty() { Queue queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { for (int i = 0; i < 100; i++) { queue2.Dequeue(); } Queue clone = (Queue)queue2.Clone(); Assert.Equal(0, queue2.Count); // Can change clone the queue clone.Enqueue(500); Assert.Equal(500, clone.Dequeue()); }); } [Fact] public static void Clone_DequeueThenEnqueue() { var queue1 = new Queue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { // Insert 50 items in the Queue for (int i = 0; i < 50; i++) { queue2.Enqueue(i); } // Insert and Remove 75 items in the Queue. This should wrap the queue // where there is 25 at the end of the array and 25 at the beginning for (int i = 0; i < 75; i++) { queue2.Enqueue(i + 50); queue2.Dequeue(); } Queue queClone = (Queue)queue2.Clone(); Assert.Equal(50, queClone.Count); Assert.Equal(75, queClone.Dequeue()); // Add an item to the Queue queClone.Enqueue(100); Assert.Equal(50, queClone.Count); Assert.Equal(76, queClone.Dequeue()); }); } [Fact] public static void Contains() { Queue queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { for (int i = 0; i < queue2.Count; i++) { Assert.True(queue2.Contains(i)); } queue2.Enqueue(null); Assert.True(queue2.Contains(null)); }); } [Fact] public static void Contains_NonExistentObject() { Queue queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Assert.False(queue2.Contains(101)); Assert.False(queue2.Contains("hello world")); Assert.False(queue2.Contains(null)); queue2.Enqueue(null); Assert.False(queue2.Contains(-1)); // We have a null item in the list, so the algorithm may use a different branch }); } [Fact] public static void Contains_EmptyQueue() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Assert.False(queue2.Contains(101)); Assert.False(queue2.Contains("hello world")); Assert.False(queue2.Contains(null)); }); } [Theory] [InlineData(0, 0)] [InlineData(1, 0)] [InlineData(10, 0)] [InlineData(100, 0)] [InlineData(1000, 0)] [InlineData(1, 50)] [InlineData(10, 50)] [InlineData(100, 50)] [InlineData(1000, 50)] public static void CopyTo(int count, int index) { Queue queue1 = Helpers.CreateIntQueue(count); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { var array = new object[count + index]; queue2.CopyTo(array, index); Assert.Equal(count + index, array.Length); for (int i = index; i < index + count; i++) { Assert.Equal(queue2.Dequeue(), array[i]); } }); } [Fact] public static void CopyTo_DequeueThenEnqueue() { var queue1 = new Queue(100); // Insert 50 items in the Queue for (int i = 0; i < 50; i++) { queue1.Enqueue(i); } // Insert and Remove 75 items in the Queue. This should wrap the queue // where there is 25 at the end of the array and 25 at the beginning for (int i = 0; i < 75; i++) { queue1.Enqueue(i + 50); queue1.Dequeue(); } var array = new object[queue1.Count]; queue1.CopyTo(array, 0); Assert.Equal(queue1.Count, array.Length); for (int i = 0; i < queue1.Count; i++) { Assert.Equal(queue1.Dequeue(), array[i]); } } [Fact] public static void CopyTo_Invalid() { Queue queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { AssertExtensions.Throws<ArgumentNullException>("array", () => queue2.CopyTo(null, 0)); // Array is null Assert.Throws<ArgumentException>(() => queue2.CopyTo(new object[150, 150], 0)); // Array is multidimensional AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => queue2.CopyTo(new object[150], -1)); // Index < 0 Assert.Throws<ArgumentException>(null, () => queue2.CopyTo(new object[150], 51)); // Index + queue.Count > array.Length }); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void Dequeue(int count) { Queue queue1 = Helpers.CreateIntQueue(count); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { for (int i = 1; i <= count; i++) { int obj = (int)queue2.Dequeue(); Assert.Equal(i - 1, obj); Assert.Equal(count - i, queue2.Count); } }); } [Fact] public static void Dequeue_EmptyQueue_ThrowsInvalidOperationException() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Assert.Throws<InvalidOperationException>(() => queue2.Dequeue()); // Queue is empty }); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void Dequeue_UntilEmpty(int count) { Queue queue1 = Helpers.CreateIntQueue(count); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { for (int i = 0; i < count; i++) { queue2.Dequeue(); } Assert.Throws<InvalidOperationException>(() => queue2.Dequeue()); }); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(10000)] public static void Enqueue(int count) { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { for (int i = 1; i <= count; i++) { queue2.Enqueue(i); Assert.Equal(i, queue2.Count); } Assert.Equal(count, queue2.Count); }); } [Fact] public static void Enqueue_Null() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.Enqueue(null); Assert.Equal(1, queue2.Count); }); } [Theory] [InlineData(0)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void GetEnumerator(int count) { var queue1 = Helpers.CreateIntQueue(count); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Assert.NotSame(queue2.GetEnumerator(), queue2.GetEnumerator()); IEnumerator enumerator = queue2.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { Assert.Equal(counter, enumerator.Current); counter++; } Assert.Equal(count, counter); enumerator.Reset(); } }); } [Fact] public static void GetEnumerator_StartOfEnumeration_Clone() { Queue queue = Helpers.CreateIntQueue(10); IEnumerator enumerator = queue.GetEnumerator(); ICloneable cloneableEnumerator = (ICloneable)enumerator; IEnumerator clonedEnumerator = (IEnumerator)cloneableEnumerator.Clone(); Assert.NotSame(enumerator, clonedEnumerator); // Cloned and original enumerators should enumerate separately. Assert.True(enumerator.MoveNext()); Assert.Equal(0, enumerator.Current); Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Current); Assert.True(clonedEnumerator.MoveNext()); Assert.Equal(0, enumerator.Current); Assert.Equal(0, clonedEnumerator.Current); // Cloned and original enumerators should enumerate in the same sequence. for (int i = 1; i < queue.Count; i++) { Assert.True(enumerator.MoveNext()); Assert.NotEqual(enumerator.Current, clonedEnumerator.Current); Assert.True(clonedEnumerator.MoveNext()); Assert.Equal(enumerator.Current, clonedEnumerator.Current); } Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Equal(queue.Count - 1, clonedEnumerator.Current); Assert.False(clonedEnumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Current); } [Fact] public static void GetEnumerator_InMiddleOfEnumeration_Clone() { Queue queue = Helpers.CreateIntQueue(10); IEnumerator enumerator = queue.GetEnumerator(); enumerator.MoveNext(); ICloneable cloneableEnumerator = (ICloneable)enumerator; // Cloned and original enumerators should start at the same spot, even // if the original is in the middle of enumeration. IEnumerator clonedEnumerator = (IEnumerator)cloneableEnumerator.Clone(); Assert.Equal(enumerator.Current, clonedEnumerator.Current); for (int i = 0; i < queue.Count - 1; i++) { Assert.True(clonedEnumerator.MoveNext()); } Assert.False(clonedEnumerator.MoveNext()); } [Fact] public static void GetEnumerator_Invalid() { var queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { IEnumerator enumerator = queue2.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // If the underlying collection is modified, MoveNext and Reset throw, but Current doesn't enumerator.MoveNext(); object dequeued = queue2.Dequeue(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); Assert.Equal(dequeued, enumerator.Current); // Current throws if the current index is < 0 or >= count enumerator = queue2.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.False(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current throws after resetting enumerator = queue2.GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.True(enumerator.MoveNext()); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); }); } [Fact] public static void Peek() { string s1 = "hello"; string s2 = "world"; char c = '\0'; bool b = false; byte i8 = 0; short i16 = 0; int i32 = 0; long i64 = 0L; float f = (float)0.0; double d = 0.0; var queue1 = new Queue(); queue1.Enqueue(s1); queue1.Enqueue(s2); queue1.Enqueue(c); queue1.Enqueue(b); queue1.Enqueue(i8); queue1.Enqueue(i16); queue1.Enqueue(i32); queue1.Enqueue(i64); queue1.Enqueue(f); queue1.Enqueue(d); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Assert.Same(s1, queue2.Peek()); queue2.Dequeue(); Assert.Same(s2, queue2.Peek()); queue2.Dequeue(); Assert.Equal(c, queue2.Peek()); queue2.Dequeue(); Assert.Equal(b, queue2.Peek()); queue2.Dequeue(); Assert.Equal(i8, queue2.Peek()); queue2.Dequeue(); Assert.Equal(i16, queue2.Peek()); queue2.Dequeue(); Assert.Equal(i32, queue2.Peek()); queue2.Dequeue(); Assert.Equal(i64, queue2.Peek()); queue2.Dequeue(); Assert.Equal(f, queue2.Peek()); queue2.Dequeue(); Assert.Equal(d, queue2.Peek()); queue2.Dequeue(); }); } [Fact] public static void Peek_EmptyQueue_ThrowsInvalidOperationException() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Assert.Throws<InvalidOperationException>(() => queue2.Peek()); // Queue is empty }); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void ToArray(int count) { Queue queue1 = Helpers.CreateIntQueue(count); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { object[] arr = queue2.ToArray(); Assert.Equal(count, arr.Length); for (int i = 0; i < count; i++) { Assert.Equal(queue2.Dequeue(), arr[i]); } }); } [Fact] public static void ToArray_Wrapped() { var queue1 = new Queue(1); queue1.Enqueue(1); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { object[] arr = queue2.ToArray(); Assert.Equal(1, arr.Length); Assert.Equal(1, arr[0]); }); } [Fact] public static void ToArrayDiffentObjectTypes() { string s1 = "hello"; string s2 = "world"; char c = '\0'; bool b = false; byte i8 = 0; short i16 = 0; int i32 = 0; long i64 = 0L; float f = (float)0.0; double d = 0.0; var queue1 = new Queue(); queue1.Enqueue(s1); queue1.Enqueue(s2); queue1.Enqueue(c); queue1.Enqueue(b); queue1.Enqueue(i8); queue1.Enqueue(i16); queue1.Enqueue(i32); queue1.Enqueue(i64); queue1.Enqueue(f); queue1.Enqueue(d); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { object[] arr = queue2.ToArray(); Assert.Same(s1, arr[0]); Assert.Same(s2, arr[1]); Assert.Equal(c, arr[2]); Assert.Equal(b, arr[3]); Assert.Equal(i8, arr[4]); Assert.Equal(i16, arr[5]); Assert.Equal(i32, arr[6]); Assert.Equal(i64, arr[7]); Assert.Equal(f, arr[8]); Assert.Equal(d, arr[9]); }); } [Fact] public static void ToArray_EmptyQueue() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { object[] arr = queue2.ToArray(); Assert.Equal(0, arr.Length); }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void TrimToSize(int count) { Queue queue1 = Helpers.CreateIntQueue(count); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.TrimToSize(); Assert.Equal(count, queue2.Count); // Can change the queue after trimming queue2.Enqueue(100); Assert.Equal(count + 1, queue2.Count); if (count == 0) { Assert.Equal(100, queue2.Dequeue()); } else { Assert.Equal(0, queue2.Dequeue()); } }); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void TrimToSize_DequeueAll(int count) { Queue queue1 = Helpers.CreateIntQueue(count); for (int i = 0; i < count; i++) { queue1.Dequeue(); } Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.TrimToSize(); Assert.Equal(0, queue2.Count); // Can change the queue after trimming queue2.Enqueue(1); Assert.Equal(1, queue2.Dequeue()); }); } [Fact] public static void TrimToSize_Wrapped() { var queue = new Queue(100); // Insert 50 items in the Queue for (int i = 0; i < 50; i++) { queue.Enqueue(i); } // Insert and Remove 75 items in the Queue. This should wrap the queue // where there is 25 at the end of the array and 25 at the beginning for (int i = 0; i < 75; i++) { queue.Enqueue(i + 50); queue.Dequeue(); } queue.TrimToSize(); Assert.Equal(50, queue.Count); Assert.Equal(75, queue.Dequeue()); queue.Enqueue(100); Assert.Equal(50, queue.Count); Assert.Equal(76, queue.Dequeue()); } private class Foo { public Foo(int intValue) { IntValue = intValue; } public int IntValue { get; set; } } } public class Queue_SyncRootTests { private const int NumberOfElements = 1000; private const int NumberOfWorkers = 1000; private Queue _queueDaughter; private Queue _queueGrandDaughter; [Fact] public void SyncRoot() { var queueMother = new Queue(); for (int i = 0; i < NumberOfElements; i++) { queueMother.Enqueue(i); } Assert.Equal(queueMother.SyncRoot.GetType(), typeof(object)); var queueSon = Queue.Synchronized(queueMother); _queueGrandDaughter = Queue.Synchronized(queueSon); _queueDaughter = Queue.Synchronized(queueMother); Assert.Equal(queueMother.SyncRoot, queueSon.SyncRoot); Assert.Equal(queueSon.SyncRoot, queueMother.SyncRoot); Assert.Equal(queueMother.SyncRoot, _queueGrandDaughter.SyncRoot); Assert.Equal(queueMother.SyncRoot, _queueDaughter.SyncRoot); Task[] workers = new Task[NumberOfWorkers]; Action action1 = SortElements; Action action2 = ReverseElements; for (int i = 0; i < NumberOfWorkers; i += 2) { workers[i] = Task.Run(action1); workers[i + 1] = Task.Run(action2); } Task.WaitAll(workers); } private void SortElements() { _queueGrandDaughter.Clear(); for (int i = 0; i < NumberOfElements; i++) { _queueGrandDaughter.Enqueue(i); } } private void ReverseElements() { _queueDaughter.Clear(); for (int i = 0; i < NumberOfElements; i++) { _queueDaughter.Enqueue(i); } } } public class Queue_SynchronizedTests { public Queue _queue; public int _threadsToUse = 8; public int _threadAge = 5; // 5000; public int _threadCount; [Fact] public static void Synchronized() { Queue queue = Helpers.CreateIntQueue(100); Queue syncQueue = Queue.Synchronized(queue); Assert.True(syncQueue.IsSynchronized); Assert.Equal(queue.Count, syncQueue.Count); for (int i = 0; i < queue.Count; i++) { Assert.True(syncQueue.Contains(i)); } } [Fact] public void SynchronizedEnqueue() { // Enqueue _queue = Queue.Synchronized(new Queue()); PerformTest(StartEnqueueThread, 40); // Dequeue Queue queue = Helpers.CreateIntQueue(_threadAge); _queue = Queue.Synchronized(queue); PerformTest(StartDequeueThread, 0); // Enqueue, dequeue _queue = Queue.Synchronized(new Queue()); PerformTest(StartEnqueueDequeueThread, 0); // Dequeue, enqueue queue = Helpers.CreateIntQueue(_threadsToUse); _queue = Queue.Synchronized(queue); PerformTest(StartDequeueEnqueueThread, _threadsToUse); } private void PerformTest(Action action, int expected) { var tasks = new Task[_threadsToUse]; for (int i = 0; i < _threadsToUse; i++) { tasks[i] = Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } _threadCount = _threadsToUse; Task.WaitAll(tasks); Assert.Equal(expected, _queue.Count); } [Fact] public static void Synchronized_NullQueue_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("queue", () => Queue.Synchronized(null)); // Queue is null } public void StartEnqueueThread() { int t_age = _threadAge; while (t_age > 0) { _queue.Enqueue(t_age); Interlocked.Decrement(ref t_age); } Interlocked.Decrement(ref _threadCount); } private void StartDequeueThread() { int t_age = _threadAge; while (t_age > 0) { try { _queue.Dequeue(); } catch { } Interlocked.Decrement(ref t_age); } Interlocked.Decrement(ref _threadCount); } private void StartEnqueueDequeueThread() { int t_age = _threadAge; while (t_age > 0) { _queue.Enqueue(2); _queue.Dequeue(); Interlocked.Decrement(ref t_age); } Interlocked.Decrement(ref _threadCount); } private void StartDequeueEnqueueThread() { int t_age = _threadAge; while (t_age > 0) { _queue.Dequeue(); _queue.Enqueue(2); Interlocked.Decrement(ref t_age); } Interlocked.Decrement(ref _threadCount); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ExpressRouteServiceProvidersOperations operations. /// </summary> internal partial class ExpressRouteServiceProvidersOperations : IServiceOperations<NetworkManagementClient>, IExpressRouteServiceProvidersOperations { /// <summary> /// Initializes a new instance of the ExpressRouteServiceProvidersOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ExpressRouteServiceProvidersOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Gets all the available express route service providers. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ExpressRouteServiceProvider>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteServiceProviders").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ExpressRouteServiceProvider>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteServiceProvider>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the available express route service providers. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ExpressRouteServiceProvider>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ExpressRouteServiceProvider>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteServiceProvider>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Layouts { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using NLog.Layouts; using Xunit; public class CsvLayoutTests : NLogTestBase { #if !SILVERLIGHT [Fact] public void EndToEndTest() { try { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='f' type='File' fileName='CSVLayoutEndToEnd1.txt'> <layout type='CSVLayout'> <column name='level' layout='${level}' /> <column name='message' layout='${message}' /> <column name='counter' layout='${counter}' /> <delimiter>Comma</delimiter> </layout> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='f' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); logger.Info("msg2"); logger.Warn("Message with, a comma"); using (StreamReader sr = File.OpenText("CSVLayoutEndToEnd1.txt")) { Assert.Equal("level,message,counter", sr.ReadLine()); Assert.Equal("Debug,msg,1", sr.ReadLine()); Assert.Equal("Info,msg2,2", sr.ReadLine()); Assert.Equal("Warn,\"Message with, a comma\",3", sr.ReadLine()); } } finally { if (File.Exists("CSVLayoutEndToEnd1.txt")) { File.Delete("CSVLayoutEndToEnd1.txt"); } } } /// <summary> /// Custom header overwrites file headers /// /// Note: maybe changed with an option in the future /// </summary> [Fact] public void CustomHeaderTest() { try { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='f' type='File' fileName='CSVLayoutEndToEnd1.txt'> <layout type='CSVLayout'> <header>headertest</header> <column name='level' layout='${level}' /> <column name='message' layout='${message}' /> <column name='counter' layout='${counter}' /> <delimiter>Comma</delimiter> </layout> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='f' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); logger.Info("msg2"); logger.Warn("Message with, a comma"); using (StreamReader sr = File.OpenText("CSVLayoutEndToEnd1.txt")) { Assert.Equal("headertest", sr.ReadLine()); // Assert.Equal("level,message,counter", sr.ReadLine()); Assert.Equal("Debug,msg,1", sr.ReadLine()); Assert.Equal("Info,msg2,2", sr.ReadLine()); Assert.Equal("Warn,\"Message with, a comma\",3", sr.ReadLine()); } } finally { if (File.Exists("CSVLayoutEndToEnd1.txt")) { File.Delete("CSVLayoutEndToEnd1.txt"); } } } [Fact] public void NoHeadersTest() { try { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='f' type='File' fileName='CSVLayoutEndToEnd2.txt'> <layout type='CSVLayout' withHeader='false'> <delimiter>Comma</delimiter> <column name='level' layout='${level}' /> <column name='message' layout='${message}' /> <column name='counter' layout='${counter}' /> </layout> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='f' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); logger.Info("msg2"); logger.Warn("Message with, a comma"); using (StreamReader sr = File.OpenText("CSVLayoutEndToEnd2.txt")) { Assert.Equal("Debug,msg,1", sr.ReadLine()); Assert.Equal("Info,msg2,2", sr.ReadLine()); Assert.Equal("Warn,\"Message with, a comma\",3", sr.ReadLine()); } } finally { if (File.Exists("CSVLayoutEndToEnd2.txt")) { File.Delete("CSVLayoutEndToEnd2.txt"); } } } #endif [Fact] public void CsvLayoutRenderingNoQuoting() { var delimiters = new Dictionary<CsvColumnDelimiterMode, string> { { CsvColumnDelimiterMode.Auto, CultureInfo.CurrentCulture.TextInfo.ListSeparator }, { CsvColumnDelimiterMode.Comma, "," }, { CsvColumnDelimiterMode.Semicolon, ";" }, { CsvColumnDelimiterMode.Space, " " }, { CsvColumnDelimiterMode.Tab, "\t" }, { CsvColumnDelimiterMode.Pipe, "|" }, { CsvColumnDelimiterMode.Custom, "zzz" }, }; foreach (var delim in delimiters) { var csvLayout = new CsvLayout() { Quoting = CsvQuotingMode.Nothing, Columns = { new CsvColumn("date", "${longdate}"), new CsvColumn("level", "${level}"), new CsvColumn("message;text", "${message}"), }, Delimiter = delim.Key, CustomColumnDelimiter = "zzz", }; var ev = new LogEventInfo(); ev.TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56); ev.Level = LogLevel.Info; ev.Message = "hello, world"; string sep = delim.Value; Assert.Equal("2010-01-01 12:34:56.0000" + sep + "Info" + sep + "hello, world", csvLayout.Render(ev)); Assert.Equal("date" + sep + "level" + sep + "message;text", csvLayout.Header.Render(ev)); } } [Fact] public void CsvLayoutRenderingFullQuoting() { var delimiters = new Dictionary<CsvColumnDelimiterMode, string> { { CsvColumnDelimiterMode.Auto, CultureInfo.CurrentCulture.TextInfo.ListSeparator }, { CsvColumnDelimiterMode.Comma, "," }, { CsvColumnDelimiterMode.Semicolon, ";" }, { CsvColumnDelimiterMode.Space, " " }, { CsvColumnDelimiterMode.Tab, "\t" }, { CsvColumnDelimiterMode.Pipe, "|" }, { CsvColumnDelimiterMode.Custom, "zzz" }, }; foreach (var delim in delimiters) { var csvLayout = new CsvLayout() { Quoting = CsvQuotingMode.All, Columns = { new CsvColumn("date", "${longdate}"), new CsvColumn("level", "${level}"), new CsvColumn("message;text", "${message}"), }, QuoteChar = "'", Delimiter = delim.Key, CustomColumnDelimiter = "zzz", }; var ev = new LogEventInfo(); ev.TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56); ev.Level = LogLevel.Info; ev.Message = "hello, world"; string sep = delim.Value; Assert.Equal("'2010-01-01 12:34:56.0000'" + sep + "'Info'" + sep + "'hello, world'", csvLayout.Render(ev)); Assert.Equal("'date'" + sep + "'level'" + sep + "'message;text'", csvLayout.Header.Render(ev)); } } [Fact] public void CsvLayoutRenderingAutoQuoting() { var csvLayout = new CsvLayout() { Quoting = CsvQuotingMode.Auto, Columns = { new CsvColumn("date", "${longdate}"), new CsvColumn("level", "${level}"), new CsvColumn("message;text", "${message}"), }, QuoteChar = "'", Delimiter = CsvColumnDelimiterMode.Semicolon, }; // no quoting Assert.Equal( "2010-01-01 12:34:56.0000;Info;hello, world", csvLayout.Render(new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello, world" })); // multi-line string - requires quoting Assert.Equal( "2010-01-01 12:34:56.0000;Info;'hello\rworld'", csvLayout.Render(new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello\rworld" })); // multi-line string - requires quoting Assert.Equal( "2010-01-01 12:34:56.0000;Info;'hello\nworld'", csvLayout.Render(new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello\nworld" })); // quote character used in string, will be quoted and doubled Assert.Equal( "2010-01-01 12:34:56.0000;Info;'hello''world'", csvLayout.Render(new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello'world" })); Assert.Equal("date;level;'message;text'", csvLayout.Header.Render(LogEventInfo.CreateNullEvent())); } [Fact] public void CsvLayoutCachingTest() { var csvLayout = new CsvLayout() { Quoting = CsvQuotingMode.Auto, Columns = { new CsvColumn("date", "${longdate}"), new CsvColumn("level", "${level}"), new CsvColumn("message", "${message}"), }, QuoteChar = "'", Delimiter = CsvColumnDelimiterMode.Semicolon, }; var e1 = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello, world" }; var e2 = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 57), Level = LogLevel.Info, Message = "hello, world" }; var r11 = csvLayout.Render(e1); var r12 = csvLayout.Render(e1); var r21 = csvLayout.Render(e2); var r22 = csvLayout.Render(e2); var h11 = csvLayout.Header.Render(e1); var h12 = csvLayout.Header.Render(e1); var h21 = csvLayout.Header.Render(e2); var h22 = csvLayout.Header.Render(e2); Assert.Same(r11, r12); Assert.Same(r21, r22); Assert.NotSame(r11, r21); Assert.NotSame(r12, r22); Assert.Same(h11, h12); Assert.Same(h21, h22); Assert.NotSame(h11, h21); Assert.NotSame(h12, h22); } } }
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; namespace Elasticsearch.Net.Integration.Yaml.IndicesGetAlias1 { public partial class IndicesGetAlias1YamlTests { public class IndicesGetAlias110BasicYamlBase : YamlTestsBase { public IndicesGetAlias110BasicYamlBase() : base() { //do indices.create _body = new { aliases= new { test_alias= new {}, test_blias= new {} } }; this.Do(()=> _client.IndicesCreate("test_index", _body)); //do indices.create _body = new { aliases= new { test_alias= new {}, test_blias= new {} } }; this.Do(()=> _client.IndicesCreate("test_index_2", _body)); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAllAliasesViaAlias2Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAllAliasesViaAlias2Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll()); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index.aliases.test_blias: this.IsMatch(_response.test_index.aliases.test_blias, new {}); //match _response.test_index_2.aliases.test_alias: this.IsMatch(_response.test_index_2.aliases.test_alias, new {}); //match _response.test_index_2.aliases.test_blias: this.IsMatch(_response.test_index_2.aliases.test_blias, new {}); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAllAliasesViaIndexAlias3Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAllAliasesViaIndexAlias3Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index.aliases.test_blias: this.IsMatch(_response.test_index.aliases.test_blias, new {}); //is_false _response.test_index_2; this.IsFalse(_response.test_index_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetSpecificAliasViaIndexAliasName4Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetSpecificAliasViaIndexAliasName4Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index", "test_alias")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //is_false _response.test_index.aliases.test_blias; this.IsFalse(_response.test_index.aliases.test_blias); //is_false _response.test_index_2; this.IsFalse(_response.test_index_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasesViaIndexAliasAll5Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasesViaIndexAliasAll5Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index", "_all")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index.aliases.test_blias: this.IsMatch(_response.test_index.aliases.test_blias, new {}); //is_false _response.test_index_2; this.IsFalse(_response.test_index_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasesViaIndexAlias6Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasesViaIndexAlias6Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index", "*")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index.aliases.test_blias: this.IsMatch(_response.test_index.aliases.test_blias, new {}); //is_false _response.test_index_2; this.IsFalse(_response.test_index_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasesViaIndexAliasPrefix7Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasesViaIndexAliasPrefix7Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index", "test_a*")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //is_false _response.test_index.aliases.test_blias; this.IsFalse(_response.test_index.aliases.test_blias); //is_false _response.test_index_2; this.IsFalse(_response.test_index_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasesViaIndexAliasNameName8Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasesViaIndexAliasNameName8Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index", "test_alias,test_blias")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index.aliases.test_blias: this.IsMatch(_response.test_index.aliases.test_blias, new {}); //is_false _response.test_index_2; this.IsFalse(_response.test_index_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasesViaAliasName9Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasesViaAliasName9Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll("test_alias")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index_2.aliases.test_alias: this.IsMatch(_response.test_index_2.aliases.test_alias, new {}); //is_false _response.test_index.aliases.test_blias; this.IsFalse(_response.test_index.aliases.test_blias); //is_false _response.test_index_2.aliases.test_blias; this.IsFalse(_response.test_index_2.aliases.test_blias); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasesViaAllAliasName10Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasesViaAllAliasName10Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("_all", "test_alias")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index_2.aliases.test_alias: this.IsMatch(_response.test_index_2.aliases.test_alias, new {}); //is_false _response.test_index.aliases.test_blias; this.IsFalse(_response.test_index.aliases.test_blias); //is_false _response.test_index_2.aliases.test_blias; this.IsFalse(_response.test_index_2.aliases.test_blias); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasesViaAliasName11Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasesViaAliasName11Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("*", "test_alias")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index_2.aliases.test_alias: this.IsMatch(_response.test_index_2.aliases.test_alias, new {}); //is_false _response.test_index.aliases.test_blias; this.IsFalse(_response.test_index.aliases.test_blias); //is_false _response.test_index_2.aliases.test_blias; this.IsFalse(_response.test_index_2.aliases.test_blias); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasesViaPrefAliasName12Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasesViaPrefAliasName12Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("*2", "test_alias")); //match _response.test_index_2.aliases.test_alias: this.IsMatch(_response.test_index_2.aliases.test_alias, new {}); //is_false _response.test_index.aliases.test_alias; this.IsFalse(_response.test_index.aliases.test_alias); //is_false _response.test_index.aliases.test_blias; this.IsFalse(_response.test_index.aliases.test_blias); //is_false _response.test_index_2.aliases.test_blias; this.IsFalse(_response.test_index_2.aliases.test_blias); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasesViaNameNameAliasName13Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasesViaNameNameAliasName13Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index,test_index_2", "test_alias")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index_2.aliases.test_alias: this.IsMatch(_response.test_index_2.aliases.test_alias, new {}); //is_false _response.test_index.aliases.test_blias; this.IsFalse(_response.test_index.aliases.test_blias); //is_false _response.test_index_2.aliases.test_blias; this.IsFalse(_response.test_index_2.aliases.test_blias); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class NonExistentAliasOnAnExistingIndexReturnsAnEmptyBody14Tests : IndicesGetAlias110BasicYamlBase { [Test] public void NonExistentAliasOnAnExistingIndexReturnsAnEmptyBody14Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index", "non-existent")); //match this._status: this.IsMatch(this._status, new {}); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class ExistentAndNonExistentAliasReturnsJustTheExisting15Tests : IndicesGetAlias110BasicYamlBase { [Test] public void ExistentAndNonExistentAliasReturnsJustTheExisting15Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index", "test_alias,non-existent")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //is_false _response[@"test_index"][@"aliases"][@"non-existent"]; this.IsFalse(_response[@"test_index"][@"aliases"][@"non-existent"]); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GettingAliasOnAnNonExistentIndexShouldReturn40416Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GettingAliasOnAnNonExistentIndexShouldReturn40416Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("non-existent", "foo"), shouldCatch: @"missing"); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasWithLocalFlag17Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasWithLocalFlag17Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll(nv=>nv .AddQueryString("local", @"true") )); //is_true _response.test_index; this.IsTrue(_response.test_index); //is_true _response.test_index_2; this.IsTrue(_response.test_index_2); } } } }
/* * Unity VSCode Support * * Seamless support for Microsoft Visual Studio Code in Unity * * Version: * 2.45 * * Authors: * Matthew Davey <matthew.davey@dotbunny.com> */ // REQUIRES: VSCode 0.8.0 - Settings directory moved to .vscode // TODO: Currently VSCode will not debug mono on Windows -- need a solution. namespace dotBunny.Unity { using System; using System.IO; using System.Text.RegularExpressions; using UnityEditor; using UnityEngine; [InitializeOnLoad] public static class VSCode { /// <summary> /// Current Version Number /// </summary> public const float Version = 2.45f; /// <summary> /// Current Version Code /// </summary> public const string VersionCode = "-RELEASE"; /// <summary> /// Download URL for Unity Debbuger /// </summary> public const string UnityDebuggerURL = "https://raw.githubusercontent.com/dotBunny/VSCode-Test/master/Downloads/unity-debug-101.vsix"; #region Properties /// <summary> /// Should debug information be displayed in the Unity terminal? /// </summary> public static bool Debug { get { return EditorPrefs.GetBool("VSCode_Debug", false); } set { EditorPrefs.SetBool("VSCode_Debug", value); } } /// <summary> /// Is the Visual Studio Code Integration Enabled? /// </summary> /// <remarks> /// We do not want to automatically turn it on, for in larger projects not everyone is using VSCode /// </remarks> public static bool Enabled { get { return EditorPrefs.GetBool("VSCode_Enabled", false); } set { // When turning the plugin on, we should remove all the previous project files if (!Enabled && value) { ClearProjectFiles(); } EditorPrefs.SetBool("VSCode_Enabled", value); } } public static bool UseUnityDebugger { get { return EditorPrefs.GetBool("VSCode_UseUnityDebugger", false); } set { if ( value != UseUnityDebugger ) { // Set value EditorPrefs.SetBool("VSCode_UseUnityDebugger", value); // Do not write the launch JSON file because the debugger uses its own if ( value ) { WriteLaunchFile = false; } // Update launch file UpdateLaunchFile(); } } } /// <summary> /// Should the launch.json file be written? /// </summary> /// <remarks> /// Useful to disable if someone has their own custom one rigged up /// </remarks> public static bool WriteLaunchFile { get { return EditorPrefs.GetBool("VSCode_WriteLaunchFile", true); } set { EditorPrefs.SetBool("VSCode_WriteLaunchFile", value); } } /// <summary> /// Should the plugin automatically update itself. /// </summary> static bool AutomaticUpdates { get { return EditorPrefs.GetBool("VSCode_AutomaticUpdates", false); } set { EditorPrefs.SetBool("VSCode_AutomaticUpdates", value); } } static float GitHubVersion { get { return EditorPrefs.GetFloat("VSCode_GitHubVersion", Version); } set { EditorPrefs.SetFloat("VSCode_GitHubVersion", value); } } /// <summary> /// When was the last time that the plugin was updated? /// </summary> static DateTime LastUpdate { get { // Feature creation date. DateTime lastTime = new DateTime(2015, 10, 8); if (EditorPrefs.HasKey("VSCode_LastUpdate")) { DateTime.TryParse(EditorPrefs.GetString("VSCode_LastUpdate"), out lastTime); } return lastTime; } set { EditorPrefs.SetString("VSCode_LastUpdate", value.ToString()); } } /// <summary> /// Quick reference to the VSCode launch settings file /// </summary> static string LaunchPath { get { return SettingsFolder + System.IO.Path.DirectorySeparatorChar + "launch.json"; } } /// <summary> /// The full path to the project /// </summary> static string ProjectPath { get { return System.IO.Path.GetDirectoryName(UnityEngine.Application.dataPath); } } /// <summary> /// Should the script editor be reverted when quiting Unity. /// </summary> /// <remarks> /// Useful for environments where you do not use VSCode for everything. /// </remarks> static bool RevertExternalScriptEditorOnExit { get { return EditorPrefs.GetBool("VSCode_RevertScriptEditorOnExit", true); } set { EditorPrefs.SetBool("VSCode_RevertScriptEditorOnExit", value); } } /// <summary> /// Quick reference to the VSCode settings folder /// </summary> static string SettingsFolder { get { return ProjectPath + System.IO.Path.DirectorySeparatorChar + ".vscode"; } } static string SettingsPath { get { return SettingsFolder + System.IO.Path.DirectorySeparatorChar + "settings.json"; } } static int UpdateTime { get { return EditorPrefs.GetInt("VSCode_UpdateTime", 7); } set { EditorPrefs.SetInt("VSCode_UpdateTime", value); } } #endregion /// <summary> /// Integration Constructor /// </summary> static VSCode() { if (Enabled) { UpdateUnityPreferences(true); UpdateLaunchFile(); // Add Update Check DateTime targetDate = LastUpdate.AddDays(UpdateTime); if (DateTime.Now >= targetDate && AutomaticUpdates) { CheckForUpdate(); } } // Event for when script is reloaded System.AppDomain.CurrentDomain.DomainUnload += System_AppDomain_CurrentDomain_DomainUnload; } static void System_AppDomain_CurrentDomain_DomainUnload(object sender, System.EventArgs e) { if (Enabled && RevertExternalScriptEditorOnExit) { UpdateUnityPreferences(false); } } #region Public Members /// <summary> /// Force Unity To Write Project File /// </summary> /// <remarks> /// Reflection! /// </remarks> public static void SyncSolution() { System.Type T = System.Type.GetType("UnityEditor.SyncVS,UnityEditor"); System.Reflection.MethodInfo SyncSolution = T.GetMethod("SyncSolution", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); SyncSolution.Invoke(null, null); } /// <summary> /// Update the solution files so that they work with VS Code /// </summary> public static void UpdateSolution() { // No need to process if we are not enabled if (!VSCode.Enabled) { return; } if (VSCode.Debug) { UnityEngine.Debug.Log("[VSCode] Updating Solution & Project Files"); } var currentDirectory = Directory.GetCurrentDirectory(); var solutionFiles = Directory.GetFiles(currentDirectory, "*.sln"); var projectFiles = Directory.GetFiles(currentDirectory, "*.csproj"); foreach (var filePath in solutionFiles) { string content = File.ReadAllText(filePath); content = ScrubSolutionContent(content); File.WriteAllText(filePath, content); ScrubFile(filePath); } foreach (var filePath in projectFiles) { string content = File.ReadAllText(filePath); content = ScrubProjectContent(content); File.WriteAllText(filePath, content); ScrubFile(filePath); } } #endregion #region Private Members /// <summary> /// Call VSCode with arguements /// </summary> static void CallVSCode(string args) { System.Diagnostics.Process proc = new System.Diagnostics.Process(); #if UNITY_EDITOR_OSX proc.StartInfo.FileName = "open"; proc.StartInfo.Arguments = " -n -b \"com.microsoft.VSCode\" --args " + args; proc.StartInfo.UseShellExecute = false; #elif UNITY_EDITOR_WIN proc.StartInfo.FileName = "code"; proc.StartInfo.Arguments = args; proc.StartInfo.UseShellExecute = false; #else //TODO: Allow for manual path to code? proc.StartInfo.FileName = "code"; proc.StartInfo.Arguments = args; proc.StartInfo.UseShellExecute = false; #endif proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.RedirectStandardOutput = true; proc.Start(); } /// <summary> /// Check for Updates with GitHub /// </summary> static void CheckForUpdate() { var fileContent = string.Empty; EditorUtility.DisplayProgressBar("VSCode", "Checking for updates ...", 0.5f); // Because were not a runtime framework, lets just use the simplest way of doing this try { using (var webClient = new System.Net.WebClient()) { fileContent = webClient.DownloadString("https://raw.githubusercontent.com/dotBunny/VSCode/master/Plugins/Editor/VSCode.cs"); } } catch (Exception e) { if (Debug) { UnityEngine.Debug.Log("[VSCode] " + e.Message); } // Don't go any further if there is an error return; } finally { EditorUtility.ClearProgressBar(); } // Set the last update time LastUpdate = DateTime.Now; // Fix for oddity in downlo if (fileContent.Substring(0, 2) != "/*") { int startPosition = fileContent.IndexOf("/*", StringComparison.CurrentCultureIgnoreCase); // Jump over junk characters fileContent = fileContent.Substring(startPosition); } string[] fileExploded = fileContent.Split('\n'); if (fileExploded.Length > 7) { float github = Version; if (float.TryParse(fileExploded[6].Replace("*", "").Trim(), out github)) { GitHubVersion = github; } if (github > Version) { var GUIDs = AssetDatabase.FindAssets("t:Script VSCode"); var path = Application.dataPath.Substring(0, Application.dataPath.Length - "/Assets".Length) + System.IO.Path.DirectorySeparatorChar + AssetDatabase.GUIDToAssetPath(GUIDs[0]).Replace('/', System.IO.Path.DirectorySeparatorChar); if (EditorUtility.DisplayDialog("VSCode Update", "A newer version of the VSCode plugin is available, would you like to update your version?", "Yes", "No")) { // Always make sure the file is writable System.IO.FileInfo fileInfo = new System.IO.FileInfo(path); fileInfo.IsReadOnly = false; // Write update file File.WriteAllText(path, fileContent); // Force update on text file AssetDatabase.ImportAsset(AssetDatabase.GUIDToAssetPath(GUIDs[0]), ImportAssetOptions.ForceUpdate); } } } } /// <summary> /// Clear out any existing project files and lingering stuff that might cause problems /// </summary> static void ClearProjectFiles() { var currentDirectory = Directory.GetCurrentDirectory(); var solutionFiles = Directory.GetFiles(currentDirectory, "*.sln"); var projectFiles = Directory.GetFiles(currentDirectory, "*.csproj"); var unityProjectFiles = Directory.GetFiles(currentDirectory, "*.unityproj"); foreach (string solutionFile in solutionFiles) { File.Delete(solutionFile); } foreach (string projectFile in projectFiles) { File.Delete(projectFile); } foreach (string unityProjectFile in unityProjectFiles) { File.Delete(unityProjectFile); } // Replace with our clean files (only in Unity 5) #if !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2 && !UNITY_4_3 && !UNITY_4_5 && !UNITY_4_6 && !UNITY_4_7 SyncSolution(); #endif } /// <summary> /// Force Unity Preferences Window To Read From Settings /// </summary> static void FixUnityPreferences() { // I want that window, please and thank you System.Type T = System.Type.GetType("UnityEditor.PreferencesWindow,UnityEditor"); if (EditorWindow.focusedWindow == null) return; // Only run this when the editor window is visible (cause its what screwed us up) if (EditorWindow.focusedWindow.GetType() == T) { var window = EditorWindow.GetWindow(T, true, "Unity Preferences"); if (window == null) { if (Debug) { UnityEngine.Debug.Log("[VSCode] No Preferences Window Found (really?)"); } return; } var invokerType = window.GetType(); var invokerMethod = invokerType.GetMethod("ReadPreferences", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); if (invokerMethod != null) { invokerMethod.Invoke(window, null); } else if (Debug) { UnityEngine.Debug.Log("[VSCode] No Reflection Method Found For Preferences"); } } // // Get internal integration class // System.Type iT = System.Type.GetType("UnityEditor.VisualStudioIntegration.UnityVSSupport,UnityEditor.VisualStudioIntegration"); // var iinvokerMethod = iT.GetMethod("ScriptEditorChanged", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); // var temp = EditorPrefs.GetString("kScriptsDefaultApp"); // iinvokerMethod.Invoke(null,new object[] { temp } ); } /// <summary> /// Determine what port Unity is listening for on Windows /// </summary> static int GetDebugPort() { #if UNITY_EDITOR_WIN System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = "netstat"; process.StartInfo.Arguments = "-a -n -o -p TCP"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.Start(); string output = process.StandardOutput.ReadToEnd(); string[] lines = output.Split('\n'); process.WaitForExit(); foreach (string line in lines) { string[] tokens = Regex.Split(line, "\\s+"); if (tokens.Length > 4) { int test = -1; int.TryParse(tokens[5], out test); if (test > 1023) { try { var p = System.Diagnostics.Process.GetProcessById(test); if (p.ProcessName == "Unity") { return test; } } catch { } } } } #else System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = "lsof"; process.StartInfo.Arguments = "-c /^Unity$/ -i 4tcp -a"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.Start(); // Not thread safe (yet!) string output = process.StandardOutput.ReadToEnd(); string[] lines = output.Split('\n'); process.WaitForExit(); foreach (string line in lines) { int port = -1; if (line.StartsWith("Unity")) { string[] portions = line.Split(new string[] { "TCP *:" }, System.StringSplitOptions.None); if (portions.Length >= 2) { Regex digitsOnly = new Regex(@"[^\d]"); string cleanPort = digitsOnly.Replace(portions[1], ""); if (int.TryParse(cleanPort, out port)) { if (port > -1) { return port; } } } } } #endif return -1; } static void InstallUnityDebugger() { EditorUtility.DisplayProgressBar("VSCode", "Downloading Unity Debugger ...", 0.1f); byte[] fileContent; try { using (var webClient = new System.Net.WebClient()) { fileContent = webClient.DownloadData(UnityDebuggerURL); } } catch (Exception e) { if (Debug) { UnityEngine.Debug.Log("[VSCode] " + e.Message); } // Don't go any further if there is an error return; } finally { EditorUtility.ClearProgressBar(); } // Do we have a file to install? if ( fileContent != null ) { string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".vsix"; File.WriteAllBytes(fileName, fileContent); CallVSCode(fileName); } } // HACK: This is in until Unity can figure out why MD keeps opening even though a different program is selected. [MenuItem("Assets/Open C# Project In Code", false, 1000)] static void MenuOpenProject() { // Force the project files to be sync SyncSolution(); // Load Project CallVSCode("\"" + ProjectPath + "\" -r"); } [MenuItem("Assets/Open C# Project In Code", true, 1000)] static bool ValidateMenuOpenProject() { return Enabled; } /// <summary> /// VS Code Integration Preferences Item /// </summary> /// <remarks> /// Contains all 3 toggles: Enable/Disable; Debug On/Off; Writing Launch File On/Off /// </remarks> [PreferenceItem("VSCode")] static void VSCodePreferencesItem() { if (EditorApplication.isCompiling) { EditorGUILayout.HelpBox("Please wait for Unity to finish compiling. \nIf the window doesn't refresh, simply click on the window or move it around to cause a repaint to happen.", MessageType.Warning); return; } EditorGUILayout.BeginVertical(); EditorGUILayout.HelpBox("Support development of this plugin, follow @reapazor and @dotbunny on Twitter.", MessageType.Info); EditorGUI.BeginChangeCheck(); Enabled = EditorGUILayout.Toggle(new GUIContent("Enable Integration", "Should the integration work its magic for you?"), Enabled); UseUnityDebugger = EditorGUILayout.Toggle(new GUIContent("Use Unity Debugger", "Should the integration integrate with Unity's VSCode Extension (must be installed)."), UseUnityDebugger); EditorGUILayout.Space(); RevertExternalScriptEditorOnExit = EditorGUILayout.Toggle(new GUIContent("Revert Script Editor On Unload", "Should the external script editor setting be reverted to its previous setting on project unload? This is useful if you do not use Code with all your projects."),RevertExternalScriptEditorOnExit); Debug = EditorGUILayout.Toggle(new GUIContent("Output Messages To Console", "Should informational messages be sent to Unity's Console?"), Debug); WriteLaunchFile = EditorGUILayout.Toggle(new GUIContent("Always Write Launch File", "Always write the launch.json settings when entering play mode?"), WriteLaunchFile); EditorGUILayout.Space(); AutomaticUpdates = EditorGUILayout.Toggle(new GUIContent("Automatic Updates", "Should the plugin automatically update itself?"), AutomaticUpdates); UpdateTime = EditorGUILayout.IntSlider(new GUIContent("Update Timer (Days)", "After how many days should updates be checked for?"), UpdateTime, 1, 31); EditorGUILayout.Space(); EditorGUILayout.Space(); if (EditorGUI.EndChangeCheck()) { UpdateUnityPreferences(Enabled); //UnityEditor.PreferencesWindow.Read // TODO: Force Unity To Reload Preferences // This seems to be a hick up / issue if (VSCode.Debug) { if (Enabled) { UnityEngine.Debug.Log("[VSCode] Integration Enabled"); } else { UnityEngine.Debug.Log("[VSCode] Integration Disabled"); } } } if (GUILayout.Button(new GUIContent("Force Update", "Check for updates to the plugin, right NOW!"))) { CheckForUpdate(); EditorGUILayout.EndVertical(); return; } if (GUILayout.Button(new GUIContent("Write Workspace Settings", "Output a default set of workspace settings for VSCode to use, ignoring many different types of files."))) { WriteWorkspaceSettings(); EditorGUILayout.EndVertical(); return; } EditorGUILayout.Space(); EditorGUILayout.Space(); if (UseUnityDebugger) { EditorGUILayout.HelpBox("In order for the \"Use Unity Debuggger\" option to function above, you need to have installed the Unity Debugger Extension for Visual Studio Code. You can do this by simply clicking the button below and it will take care of the rest.", MessageType.Warning); if (GUILayout.Button(new GUIContent("Install Unity Debugger", "Install the Unity Debugger Extension into Code"))) { InstallUnityDebugger(); EditorGUILayout.EndVertical(); return; } } GUILayout.FlexibleSpace(); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Label( new GUIContent( string.Format("{0:0.00}", Version) + VersionCode, "GitHub's Version @ " + string.Format("{0:0.00}", GitHubVersion))); EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); } /// <summary> /// Asset Open Callback (from Unity) /// </summary> /// <remarks> /// Called when Unity is about to open an asset. /// </remarks> [UnityEditor.Callbacks.OnOpenAssetAttribute()] static bool OnOpenedAsset(int instanceID, int line) { // bail out if we are not using VSCode if (!Enabled) { return false; } // current path without the asset folder string appPath = ProjectPath; // determine asset that has been double clicked in the project view UnityEngine.Object selected = EditorUtility.InstanceIDToObject(instanceID); if (selected.GetType().ToString() == "UnityEditor.MonoScript") { string completeFilepath = appPath + Path.DirectorySeparatorChar + AssetDatabase.GetAssetPath(selected); string args = null; if (line == -1) { args = "\"" + ProjectPath + "\" \"" + completeFilepath + "\" -r"; } else { args = "\"" + ProjectPath + "\" -g \"" + completeFilepath + ":" + line.ToString() + "\" -r"; } // call 'open' CallVSCode(args); return true; } // Didnt find a code file? let Unity figure it out return false; } /// <summary> /// Executed when the Editor's playmode changes allowing for capture of required data /// </summary> static void OnPlaymodeStateChanged() { if (UnityEngine.Application.isPlaying && EditorApplication.isPlayingOrWillChangePlaymode) { UpdateLaunchFile(); } } /// <summary> /// Detect when scripts are reloaded and relink playmode detection /// </summary> [UnityEditor.Callbacks.DidReloadScripts()] static void OnScriptReload() { EditorApplication.playmodeStateChanged -= OnPlaymodeStateChanged; EditorApplication.playmodeStateChanged += OnPlaymodeStateChanged; } /// <summary> /// Remove extra/erroneous lines from a file. static void ScrubFile(string path) { string[] lines = File.ReadAllLines(path); System.Collections.Generic.List<string> newLines = new System.Collections.Generic.List<string>(); for (int i = 0; i < lines.Length; i++) { // Check Empty if (string.IsNullOrEmpty(lines[i].Trim()) || lines[i].Trim() == "\t" || lines[i].Trim() == "\t\t") { } else { newLines.Add(lines[i]); } } File.WriteAllLines(path, newLines.ToArray()); } /// <summary> /// Remove extra/erroneous data from project file (content). /// </summary> static string ScrubProjectContent(string content) { if (content.Length == 0) return ""; // Note: it causes OmniSharp faults on Windows, such as "not seeing UnityEngine.UI". 3.5 target works fine #if !UNITY_EDITOR_WIN // Make sure our reference framework is 2.0, still the base for Unity if (content.IndexOf("<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>") != -1) { content = Regex.Replace(content, "<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>", "<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>"); } #endif string targetPath = "";// "<TargetPath>Temp" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "Debug" + Path.DirectorySeparatorChar + "</TargetPath>"; //OutputPath string langVersion = "<LangVersion>default</LangVersion>"; bool found = true; int location = 0; string addedOptions = ""; int startLocation = -1; int endLocation = -1; int endLength = 0; while (found) { startLocation = -1; endLocation = -1; endLength = 0; addedOptions = ""; startLocation = content.IndexOf("<PropertyGroup", location); if (startLocation != -1) { endLocation = content.IndexOf("</PropertyGroup>", startLocation); endLength = (endLocation - startLocation); if (endLocation == -1) { found = false; continue; } else { found = true; location = endLocation; } if (content.Substring(startLocation, endLength).IndexOf("<TargetPath>") == -1) { addedOptions += "\n\r\t" + targetPath + "\n\r"; } if (content.Substring(startLocation, endLength).IndexOf("<LangVersion>") == -1) { addedOptions += "\n\r\t" + langVersion + "\n\r"; } if (!string.IsNullOrEmpty(addedOptions)) { content = content.Substring(0, endLocation) + addedOptions + content.Substring(endLocation); } } else { found = false; } } return content; } /// <summary> /// Remove extra/erroneous data from solution file (content). /// </summary> static string ScrubSolutionContent(string content) { // Replace Solution Version content = content.Replace( "Microsoft Visual Studio Solution File, Format Version 11.00\r\n# Visual Studio 2008\r\n", "\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio 2012"); // Remove Solution Properties (Unity Junk) int startIndex = content.IndexOf("GlobalSection(SolutionProperties) = preSolution"); if (startIndex != -1) { int endIndex = content.IndexOf("EndGlobalSection", startIndex); content = content.Substring(0, startIndex) + content.Substring(endIndex + 16); } return content; } /// <summary> /// Update Visual Studio Code Launch file /// </summary> static void UpdateLaunchFile() { if ( !VSCode.Enabled ) return; else if ( VSCode.UseUnityDebugger ) { if (!Directory.Exists(VSCode.SettingsFolder)) System.IO.Directory.CreateDirectory(VSCode.SettingsFolder); // Write out proper formatted JSON (hence no more SimpleJSON here) string fileContent = "{\n\t\"version\": \"0.2.0\",\n\t\"configurations\": [\n\t\t{\n\t\t\t\"name\": \"Unity Editor\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"Windows Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"OSX Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"Linux Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"iOS Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"Android Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\n\t\t}\n\t]\n}"; File.WriteAllText(VSCode.LaunchPath, fileContent); } else if (VSCode.WriteLaunchFile) { int port = GetDebugPort(); if (port > -1) { if (!Directory.Exists(VSCode.SettingsFolder)) System.IO.Directory.CreateDirectory(VSCode.SettingsFolder); // Write out proper formatted JSON (hence no more SimpleJSON here) string fileContent = "{\n\t\"version\":\"0.2.0\",\n\t\"configurations\":[ \n\t\t{\n\t\t\t\"name\":\"Unity\",\n\t\t\t\"type\":\"mono\",\n\t\t\t\"request\":\"attach\",\n\t\t\t\"address\":\"localhost\",\n\t\t\t\"port\":" + port + "\n\t\t}\n\t]\n}"; File.WriteAllText(VSCode.LaunchPath, fileContent); if (VSCode.Debug) { UnityEngine.Debug.Log("[VSCode] Debug Port Found (" + port + ")"); } } else { if (VSCode.Debug) { UnityEngine.Debug.LogWarning("[VSCode] Unable to determine debug port."); } } } } /// <summary> /// Update Unity Editor Preferences static void UpdateUnityPreferences(bool enabled) { if (enabled) { #if UNITY_EDITOR_OSX var newPath = "/Applications/Visual Studio Code.app"; #elif UNITY_EDITOR_WIN var newPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData) + Path.DirectorySeparatorChar + "Code" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "code.cmd"; #else var newPath = "/usr/local/bin/code"; #endif // App if (EditorPrefs.GetString("kScriptsDefaultApp") != newPath) { EditorPrefs.SetString("VSCode_PreviousApp", EditorPrefs.GetString("kScriptsDefaultApp")); } EditorPrefs.SetString("kScriptsDefaultApp", newPath); // Arguments if (EditorPrefs.GetString("kScriptEditorArgs") != "-r -g \"$(File):$(Line)\"") { EditorPrefs.SetString("VSCode_PreviousArgs", EditorPrefs.GetString("kScriptEditorArgs")); } EditorPrefs.SetString("kScriptEditorArgs", "-r -g \"$(File):$(Line)\""); EditorPrefs.SetString("kScriptEditorArgs" + newPath, "-r -g \"$(File):$(Line)\""); // MonoDevelop Solution if (EditorPrefs.GetBool("kMonoDevelopSolutionProperties", false)) { EditorPrefs.SetBool("VSCode_PreviousMD", true); } EditorPrefs.SetBool("kMonoDevelopSolutionProperties", false); // Support Unity Proj (JS) if (EditorPrefs.GetBool("kExternalEditorSupportsUnityProj", false)) { EditorPrefs.SetBool("VSCode_PreviousUnityProj", true); } EditorPrefs.SetBool("kExternalEditorSupportsUnityProj", false); // Attach to Editor if (!EditorPrefs.GetBool("AllowAttachedDebuggingOfEditor", false)) { EditorPrefs.SetBool("VSCode_PreviousAttach", false); } EditorPrefs.SetBool("AllowAttachedDebuggingOfEditor", true); } else { // Restore previous app if (!string.IsNullOrEmpty(EditorPrefs.GetString("VSCode_PreviousApp"))) { EditorPrefs.SetString("kScriptsDefaultApp", EditorPrefs.GetString("VSCode_PreviousApp")); } // Restore previous args if (!string.IsNullOrEmpty(EditorPrefs.GetString("VSCode_PreviousArgs"))) { EditorPrefs.SetString("kScriptEditorArgs", EditorPrefs.GetString("VSCode_PreviousArgs")); } // Restore MD setting if (EditorPrefs.GetBool("VSCode_PreviousMD", false)) { EditorPrefs.SetBool("kMonoDevelopSolutionProperties", true); } // Restore MD setting if (EditorPrefs.GetBool("VSCode_PreviousUnityProj", false)) { EditorPrefs.SetBool("kExternalEditorSupportsUnityProj", true); } // Restore previous attach if (!EditorPrefs.GetBool("VSCode_PreviousAttach", true)) { EditorPrefs.SetBool("AllowAttachedDebuggingOfEditor", false); } } FixUnityPreferences(); } /// <summary> /// Write Default Workspace Settings /// </summary> static void WriteWorkspaceSettings() { if (Debug) { UnityEngine.Debug.Log("[VSCode] Workspace Settings Written"); } if (!Directory.Exists(VSCode.SettingsFolder)) { System.IO.Directory.CreateDirectory(VSCode.SettingsFolder); } string exclusions = "{\n" + "\t\"files.exclude\":\n" + "\t{\n" + // Hidden Files "\t\t\"**/.DS_Store\":true,\n" + "\t\t\"**/.git\":true,\n" + "\t\t\"**/.gitignore\":true,\n" + "\t\t\"**/.gitattributes\":true,\n" + "\t\t\"**/.gitmodules\":true,\n" + "\t\t\"**/.svn\":true,\n" + // Project Files "\t\t\"**/*.booproj\":true,\n" + "\t\t\"**/*.pidb\":true,\n" + "\t\t\"**/*.suo\":true,\n" + "\t\t\"**/*.user\":true,\n" + "\t\t\"**/*.userprefs\":true,\n" + "\t\t\"**/*.unityproj\":true,\n" + "\t\t\"**/*.dll\":true,\n" + "\t\t\"**/*.exe\":true,\n" + // Media Files "\t\t\"**/*.pdf\":true,\n" + // Audio "\t\t\"**/*.mid\":true,\n" + "\t\t\"**/*.midi\":true,\n" + "\t\t\"**/*.wav\":true,\n" + // Textures "\t\t\"**/*.gif\":true,\n" + "\t\t\"**/*.ico\":true,\n" + "\t\t\"**/*.jpg\":true,\n" + "\t\t\"**/*.jpeg\":true,\n" + "\t\t\"**/*.png\":true,\n" + "\t\t\"**/*.psd\":true,\n" + "\t\t\"**/*.tga\":true,\n" + "\t\t\"**/*.tif\":true,\n" + "\t\t\"**/*.tiff\":true,\n" + // Models "\t\t\"**/*.3ds\":true,\n" + "\t\t\"**/*.3DS\":true,\n" + "\t\t\"**/*.fbx\":true,\n" + "\t\t\"**/*.FBX\":true,\n" + "\t\t\"**/*.lxo\":true,\n" + "\t\t\"**/*.LXO\":true,\n" + "\t\t\"**/*.ma\":true,\n" + "\t\t\"**/*.MA\":true,\n" + "\t\t\"**/*.obj\":true,\n" + "\t\t\"**/*.OBJ\":true,\n" + // Unity File Types "\t\t\"**/*.asset\":true,\n" + "\t\t\"**/*.cubemap\":true,\n" + "\t\t\"**/*.flare\":true,\n" + "\t\t\"**/*.mat\":true,\n" + "\t\t\"**/*.meta\":true,\n" + "\t\t\"**/*.prefab\":true,\n" + "\t\t\"**/*.unity\":true,\n" + // Folders "\t\t\"build/\":true,\n" + "\t\t\"Build/\":true,\n" + "\t\t\"Library/\":true,\n" + "\t\t\"library/\":true,\n" + "\t\t\"obj/\":true,\n" + "\t\t\"Obj/\":true,\n" + "\t\t\"ProjectSettings/\":true,\r" + "\t\t\"temp/\":true,\n" + "\t\t\"Temp/\":true\n" + "\t}\n" + "}"; // Dont like the replace but it fixes the issue with the JSON File.WriteAllText(VSCode.SettingsPath, exclusions); } #endregion } /// <summary> /// VSCode Asset AssetPostprocessor /// <para>This will ensure any time that the project files are generated the VSCode versions will be made</para> /// </summary> /// <remarks>Undocumented Event</remarks> public class VSCodeAssetPostprocessor : AssetPostprocessor { /// <summary> /// On documented, project generation event callback /// </summary> private static void OnGeneratedCSProjectFiles() { // Force execution of VSCode update VSCode.UpdateSolution(); } } }
using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Dynamic; using System.Linq; using System.Linq.Expressions; using System.Reflection; //using System.Web.Script.Serialization; namespace System { public static class ObjectExtensions { // public static string ToJSON(this object @this) // { // return new JavaScriptSerializer().Serialize(@this); //} /// <summary> /// Checks if any of given objects is equal to this instance. /// </summary> public static bool IsAnyOf<T>(this T @this, params T[] objects) { return Array.IndexOf(objects, @this) >= 0; } /// <summary> /// Checks if all of given objects are different than this instance. /// </summary> public static bool IsNoneOf<T>(this T @this, params T[] objects) { return !IsAnyOf(@this, objects); } public static void MustNotBeNull<T>(this T param, string paramName = null) where T : class { if ((object) param == null) throw new ArgumentNullException(paramName ?? string.Empty); } public static PropertyInfo[] GetProperties(this object @this) { return @this.GetType().GetProperties(); } public static PropertyInfo[] GetProperties<T>(this object @this) { return @this.GetType().GetProperties().Where(x => x.IsDefined(typeof (T), false)).ToArray(); } } //FROM http://blogs.msdn.com/b/davidebb/archive/2010/01/18/use-c-4-0-dynamic-to-drastically-simplify-your-private-reflection-code.aspx //doesnt count to line counts :) public static class PrivateReflectionDynamicObjectExtensions { public static dynamic AsDynamic(this object o) { return PrivateReflectionDynamicObject.WrapObjectIfNeeded(o); } } internal class PrivateReflectionDynamicObject : DynamicObject { private const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; private static readonly IDictionary<Type, IDictionary<string, IProperty>> _propertiesOnType = new ConcurrentDictionary<Type, IDictionary<string, IProperty>>(); // Simple abstraction to make field and property access consistent private object RealObject { get; set; } internal static object WrapObjectIfNeeded(object o) { // Don't wrap primitive types, which don't have many interesting internal APIs if (o == null || o.GetType().IsPrimitive || o is string) return o; return new PrivateReflectionDynamicObject {RealObject = o}; } public override bool TryGetMember(GetMemberBinder binder, out object result) { IProperty prop = GetProperty(binder.Name); // Get the property value result = prop.GetValue(RealObject, index: null); // Wrap the sub object if necessary. This allows nested anonymous objects to work. result = WrapObjectIfNeeded(result); return true; } public override bool TrySetMember(SetMemberBinder binder, object value) { IProperty prop = GetProperty(binder.Name); // Set the property value prop.SetValue(RealObject, value, index: null); return true; } public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) { // The indexed property is always named "Item" in C# IProperty prop = GetIndexProperty(); result = prop.GetValue(RealObject, indexes); // Wrap the sub object if necessary. This allows nested anonymous objects to work. result = WrapObjectIfNeeded(result); return true; } public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value) { // The indexed property is always named "Item" in C# IProperty prop = GetIndexProperty(); prop.SetValue(RealObject, value, indexes); return true; } // Called when a method is called public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { result = InvokeMemberOnType(RealObject.GetType(), RealObject, binder.Name, args); // Wrap the sub object if necessary. This allows nested anonymous objects to work. result = WrapObjectIfNeeded(result); return true; } public override bool TryConvert(ConvertBinder binder, out object result) { result = Convert.ChangeType(RealObject, binder.Type); return true; } public override string ToString() { return RealObject.ToString(); } private IProperty GetIndexProperty() { // The index property is always named "Item" in C# return GetProperty("Item"); } private IProperty GetProperty(string propertyName) { // Get the list of properties and fields for this type IDictionary<string, IProperty> typeProperties = GetTypeProperties(RealObject.GetType()); // Look for the one we want IProperty property; if (typeProperties.TryGetValue(propertyName, out property)) { return property; } // The property doesn't exist // Get a list of supported properties and fields and show them as part of the exception message // For fields, skip the auto property backing fields (which name start with <) IOrderedEnumerable<string> propNames = typeProperties.Keys.Where(name => name[0] != '<').OrderBy(name => name); throw new ArgumentException( String.Format( "The property {0} doesn't exist on type {1}. Supported properties are: {2}", propertyName, RealObject.GetType(), String.Join(", ", propNames))); } private static IDictionary<string, IProperty> GetTypeProperties(Type type) { // First, check if we already have it cached IDictionary<string, IProperty> typeProperties; if (_propertiesOnType.TryGetValue(type, out typeProperties)) { return typeProperties; } // Not cache, so we need to build it typeProperties = new ConcurrentDictionary<string, IProperty>(); // First, add all the properties foreach (PropertyInfo prop in type.GetProperties(bindingFlags).Where(p => p.DeclaringType == type)) { typeProperties[prop.Name] = new Property {PropertyInfo = prop}; } // Now, add all the fields foreach (FieldInfo field in type.GetFields(bindingFlags).Where(p => p.DeclaringType == type)) { typeProperties[field.Name] = new Field {FieldInfo = field}; } // Finally, recurse on the base class to add its fields if (type.BaseType != null) { foreach (IProperty prop in GetTypeProperties(type.BaseType).Values) { typeProperties[prop.Name] = prop; } } // Cache it for next time _propertiesOnType[type] = typeProperties; return typeProperties; } private static object InvokeMemberOnType(Type type, object target, string name, object[] args) { try { // Try to incoke the method return type.InvokeMember( name, BindingFlags.InvokeMethod | bindingFlags, null, target, args); } catch (MissingMethodException) { // If we couldn't find the method, try on the base class if (type.BaseType != null) { return InvokeMemberOnType(type.BaseType, target, name, args); } //quick greg hack to allow methods to not exist! return null; } } private class Field : IProperty { internal FieldInfo FieldInfo { get; set; } string IProperty.Name { get { return FieldInfo.Name; } } object IProperty.GetValue(object obj, object[] index) { return FieldInfo.GetValue(obj); } void IProperty.SetValue(object obj, object val, object[] index) { FieldInfo.SetValue(obj, val); } } private interface IProperty { string Name { get; } object GetValue(object obj, object[] index); void SetValue(object obj, object val, object[] index); } // IProperty implementation over a PropertyInfo private class Property : IProperty { internal PropertyInfo PropertyInfo { get; set; } string IProperty.Name { get { return PropertyInfo.Name; } } object IProperty.GetValue(object obj, object[] index) { return PropertyInfo.GetValue(obj, index); } void IProperty.SetValue(object obj, object val, object[] index) { PropertyInfo.SetValue(obj, val, index); } } } public class DelegateAdjuster { public static Action<BaseT> CastArgument<BaseT, DerivedT>(Expression<Action<DerivedT>> source) where DerivedT : BaseT { if (typeof (DerivedT) == typeof (BaseT)) { return (Action<BaseT>) ((Delegate) source.Compile()); } ParameterExpression sourceParameter = Expression.Parameter(typeof (BaseT), "source"); var result = Expression.Lambda<Action<BaseT>>( Expression.Invoke( source, Expression.Convert(sourceParameter, typeof (DerivedT))), sourceParameter); return result.Compile(); } } public static class NullObjectExtensions { public static TResult With<TInput, TResult>(this TInput o, Func<TInput, TResult> evaluator) where TResult : class where TInput : class { if (o == null) return null; return evaluator(o); } public static TResult Return<TInput, TResult>(this TInput o, Func<TInput, TResult> evaluator, TResult failureValue) where TInput : class { if (o == null) return failureValue; return evaluator(o); } public static TInput If<TInput>(this TInput o, Func<TInput, bool> evaluator) where TInput : class { if (o == null) return null; return evaluator(o) ? o : null; } public static TInput Unless<TInput>(this TInput o, Func<TInput, bool> evaluator) where TInput : class { if (o == null) return null; return evaluator(o) ? null : o; } public static TInput Do<TInput>(this TInput o, Action<TInput> action) where TInput : class { if (o == null) return null; action(o); return o; } } }
// Copyright Bastian Eicher // Licensed under the MIT License #if !NET20 && !NET40 using System.Threading.Tasks; #endif namespace NanoByte.Common.Collections { /// <summary> /// Provides extension methods for <see cref="Dictionary{TKey,TValue}"/>s. /// </summary> public static class DictionaryExtensions { /// <summary> /// Adds multiple pairs to the dictionary in one go. /// </summary> public static void AddRange<TSourceKey, TSourceValue, TTargetKey, TTargetValue>(this IDictionary<TTargetKey, TTargetValue> target, [InstantHandle] IEnumerable<KeyValuePair<TSourceKey, TSourceValue>> source) where TSourceKey : TTargetKey where TSourceValue : TTargetValue { #region Sanity checks if (target == null) throw new ArgumentNullException(nameof(target)); if (source == null) throw new ArgumentNullException(nameof(source)); #endregion foreach (var (key, value) in source) target.Add(key, value); } /// <summary> /// Returns an existing element with a specific key from a dictionary or the value type's default value if it is missing. /// </summary> /// <param name="dictionary">The dictionary to get an element from.</param> /// <param name="key">The key to look for in the <paramref name="dictionary"/>.</param> /// <returns>The existing element or the default value of <typeparamref name="TValue"/>.</returns> [Pure] [return: MaybeNull] public static TValue GetOrDefault<TKey, TValue>([InstantHandle] this IDictionary<TKey, TValue> dictionary, TKey key) { #region Sanity checks if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); if (key == null) throw new ArgumentNullException(nameof(key)); #endregion dictionary.TryGetValue(key, out var value); return value; } /// <summary> /// Returns an existing element with a specific key from a dictionary or creates and adds a new element using a callback if it is missing. /// </summary> /// <param name="dictionary">The dictionary to get an element from or to add an element to.</param> /// <param name="key">The key to look for in the <paramref name="dictionary"/>.</param> /// <param name="valueFactory">A callback that provides the value to add to the <paramref name="dictionary"/> if the <paramref name="key"/> is not found.</param> /// <returns>The existing element or the newly created element.</returns> /// <remarks>No superfluous calls to <paramref name="valueFactory"/> occur. Not thread-safe!</remarks> public static TValue GetOrAdd<TKey, TValue>([InstantHandle] this IDictionary<TKey, TValue> dictionary, TKey key, [InstantHandle] Func<TValue> valueFactory) { #region Sanity checks if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); if (key == null) throw new ArgumentNullException(nameof(key)); if (valueFactory == null) throw new ArgumentNullException(nameof(valueFactory)); #endregion if (!dictionary.TryGetValue(key, out var value)) dictionary.Add(key, value = valueFactory()); return value; } /// <summary> /// Returns an existing element with a specific key from a dictionary or creates and adds a new element using the default constructor if it is missing. /// </summary> /// <param name="dictionary">The dictionary to get an element from or to add an element to.</param> /// <param name="key">The key to look for in the <paramref name="dictionary"/>.</param> /// <returns>The existing element or the newly created element.</returns> public static TValue GetOrAdd<TKey, TValue>([InstantHandle] this IDictionary<TKey, TValue> dictionary, TKey key) where TValue : new() { #region Sanity checks if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); if (key == null) throw new ArgumentNullException(nameof(key)); #endregion return dictionary.GetOrAdd(key, () => new TValue()); } #if !NET20 && !NET40 /// <summary> /// Returns an existing element with a specific key from a dictionary or creates and adds a new element using a callback if it is missing. /// </summary> /// <param name="dictionary">The dictionary to get an element from or to add an element to.</param> /// <param name="key">The key to look for in the <paramref name="dictionary"/>.</param> /// <param name="valueFactory">A callback that provides a task that provides the value to add to the <paramref name="dictionary"/> if the <paramref name="key"/> is not found.</param> /// <returns>The existing element or the newly created element.</returns> /// <remarks>Superfluous calls to <paramref name="valueFactory"/> may occur in case of read races. <see cref="IDisposable.Dispose"/> is called on superfluously created objects if implemented.</remarks> public static async Task<TValue> GetOrAddAsync<TKey, TValue>([InstantHandle] this IDictionary<TKey, TValue> dictionary, TKey key, Func<Task<TValue>> valueFactory) { if (dictionary.TryGetValue(key, out var existingValue)) return existingValue; var newValue = await valueFactory().ConfigureAwait(false); // Detect and handle races if (dictionary.TryGetValue(key, out existingValue)) { (newValue as IDisposable)?.Dispose(); return existingValue; } dictionary.Add(key, newValue); return newValue; } #endif /// <summary> /// Builds a <see cref="MultiDictionary{TKey,TValue}"/> from an enumerable. /// </summary> /// <param name="elements">The elements to build the dictionary from.</param> /// <param name="keySelector">Selects the dictionary key from an input element.</param> /// <param name="valueSelector">Selects a dictionary value from an input element.</param> [Pure] public static MultiDictionary<TKey, TValue> ToMultiDictionary<TSource, TKey, TValue>([InstantHandle] this IEnumerable<TSource> elements, [InstantHandle] Func<TSource, TKey> keySelector, [InstantHandle] Func<TSource, TValue> valueSelector) where TKey : notnull { #region Sanity checks if (elements == null) throw new ArgumentNullException(nameof(elements)); if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); if (valueSelector == null) throw new ArgumentNullException(nameof(valueSelector)); #endregion var result = new MultiDictionary<TKey, TValue>(); foreach (TSource item in elements) result.Add(keySelector(item), valueSelector(item)); return result; } /// <summary> /// Determines whether two dictionaries contain the same key-value pairs. /// </summary> /// <param name="first">The first of the two dictionaries to compare.</param> /// <param name="second">The first of the two dictionaries to compare.</param> /// <param name="valueComparer">Controls how to compare values; leave <c>null</c> for default comparer.</param> [Pure] public static bool UnsequencedEquals<TKey, TValue>([InstantHandle] this IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second, IEqualityComparer<TValue>? valueComparer = null) { #region Sanity checks if (first == null) throw new ArgumentNullException(nameof(first)); if (second == null) throw new ArgumentNullException(nameof(second)); #endregion if (first == second) return true; if (first.Count != second.Count) return false; var keySet = new HashSet<TKey>(first.Keys); if (!second.Keys.All(keySet.Contains)) return false; valueComparer ??= EqualityComparer<TValue>.Default; foreach (var (key, value) in first) { if (!valueComparer.Equals(value, second[key])) return false; } return true; } /// <summary> /// Generates a hash code for the contents of the dictionary. /// </summary> /// <param name="dictionary">The dictionary to generate the hash for.</param> /// <param name="valueComparer">Controls how to compare values; leave <c>null</c> for default comparer.</param> /// <seealso cref="UnsequencedEquals{TKey,TValue}"/> [Pure] public static int GetUnsequencedHashCode<TKey, TValue>([InstantHandle] this IDictionary<TKey, TValue> dictionary, IEqualityComparer<TValue>? valueComparer = null) { #region Sanity checks if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); #endregion var hash = new HashCode(); foreach (var (key, value) in dictionary) { hash.Add(key); hash.Add(value, valueComparer); } return hash.ToHashCode(); } /// <summary> /// Deconstructs a <see cref="KeyValuePair{TKey,TValue}"/> like a tuple. /// </summary> /// <example> /// foreach (var (key, value) in dictionary) /// {/*...*/} /// </example> [Pure] public static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> pair, out TKey key, out TValue value) { key = pair.Key; value = pair.Value; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: src/proto/grpc/testing/services.proto // Original file comments: // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // An integration test service that covers all the method signature permutations // of unary/streaming requests/responses. #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core; namespace Grpc.Testing { public static class BenchmarkService { static readonly string __ServiceName = "grpc.testing.BenchmarkService"; static readonly Marshaller<global::Grpc.Testing.SimpleRequest> __Marshaller_SimpleRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleRequest.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.SimpleResponse> __Marshaller_SimpleResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleResponse.Parser.ParseFrom); static readonly Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> __Method_UnaryCall = new Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse>( MethodType.Unary, __ServiceName, "UnaryCall", __Marshaller_SimpleRequest, __Marshaller_SimpleResponse); static readonly Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> __Method_StreamingCall = new Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse>( MethodType.DuplexStreaming, __ServiceName, "StreamingCall", __Marshaller_SimpleRequest, __Marshaller_SimpleResponse); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Grpc.Testing.ServicesReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of BenchmarkService</summary> public abstract class BenchmarkServiceBase { /// <summary> /// One request followed by one response. /// The server returns the client payload as-is. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.SimpleResponse> UnaryCall(global::Grpc.Testing.SimpleRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// One request followed by one response. /// The server returns the client payload as-is. /// </summary> public virtual global::System.Threading.Tasks.Task StreamingCall(IAsyncStreamReader<global::Grpc.Testing.SimpleRequest> requestStream, IServerStreamWriter<global::Grpc.Testing.SimpleResponse> responseStream, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } } /// <summary>Client for BenchmarkService</summary> public class BenchmarkServiceClient : ClientBase<BenchmarkServiceClient> { /// <summary>Creates a new client for BenchmarkService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public BenchmarkServiceClient(Channel channel) : base(channel) { } /// <summary>Creates a new client for BenchmarkService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public BenchmarkServiceClient(CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected BenchmarkServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected BenchmarkServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// One request followed by one response. /// The server returns the client payload as-is. /// </summary> public virtual global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UnaryCall(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// One request followed by one response. /// The server returns the client payload as-is. /// </summary> public virtual global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UnaryCall, null, options, request); } /// <summary> /// One request followed by one response. /// The server returns the client payload as-is. /// </summary> public virtual AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UnaryCallAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// One request followed by one response. /// The server returns the client payload as-is. /// </summary> public virtual AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UnaryCall, null, options, request); } /// <summary> /// One request followed by one response. /// The server returns the client payload as-is. /// </summary> public virtual AsyncDuplexStreamingCall<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> StreamingCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return StreamingCall(new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// One request followed by one response. /// The server returns the client payload as-is. /// </summary> public virtual AsyncDuplexStreamingCall<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> StreamingCall(CallOptions options) { return CallInvoker.AsyncDuplexStreamingCall(__Method_StreamingCall, null, options); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override BenchmarkServiceClient NewInstance(ClientBaseConfiguration configuration) { return new BenchmarkServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> public static ServerServiceDefinition BindService(BenchmarkServiceBase serviceImpl) { return ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_UnaryCall, serviceImpl.UnaryCall) .AddMethod(__Method_StreamingCall, serviceImpl.StreamingCall).Build(); } } public static class WorkerService { static readonly string __ServiceName = "grpc.testing.WorkerService"; static readonly Marshaller<global::Grpc.Testing.ServerArgs> __Marshaller_ServerArgs = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ServerArgs.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.ServerStatus> __Marshaller_ServerStatus = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ServerStatus.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.ClientArgs> __Marshaller_ClientArgs = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ClientArgs.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.ClientStatus> __Marshaller_ClientStatus = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ClientStatus.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.CoreRequest> __Marshaller_CoreRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.CoreRequest.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.CoreResponse> __Marshaller_CoreResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.CoreResponse.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.Void> __Marshaller_Void = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Void.Parser.ParseFrom); static readonly Method<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus> __Method_RunServer = new Method<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus>( MethodType.DuplexStreaming, __ServiceName, "RunServer", __Marshaller_ServerArgs, __Marshaller_ServerStatus); static readonly Method<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus> __Method_RunClient = new Method<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus>( MethodType.DuplexStreaming, __ServiceName, "RunClient", __Marshaller_ClientArgs, __Marshaller_ClientStatus); static readonly Method<global::Grpc.Testing.CoreRequest, global::Grpc.Testing.CoreResponse> __Method_CoreCount = new Method<global::Grpc.Testing.CoreRequest, global::Grpc.Testing.CoreResponse>( MethodType.Unary, __ServiceName, "CoreCount", __Marshaller_CoreRequest, __Marshaller_CoreResponse); static readonly Method<global::Grpc.Testing.Void, global::Grpc.Testing.Void> __Method_QuitWorker = new Method<global::Grpc.Testing.Void, global::Grpc.Testing.Void>( MethodType.Unary, __ServiceName, "QuitWorker", __Marshaller_Void, __Marshaller_Void); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Grpc.Testing.ServicesReflection.Descriptor.Services[1]; } } /// <summary>Base class for server-side implementations of WorkerService</summary> public abstract class WorkerServiceBase { /// <summary> /// Start server with specified workload. /// First request sent specifies the ServerConfig followed by ServerStatus /// response. After that, a "Mark" can be sent anytime to request the latest /// stats. Closing the stream will initiate shutdown of the test server /// and once the shutdown has finished, the OK status is sent to terminate /// this RPC. /// </summary> public virtual global::System.Threading.Tasks.Task RunServer(IAsyncStreamReader<global::Grpc.Testing.ServerArgs> requestStream, IServerStreamWriter<global::Grpc.Testing.ServerStatus> responseStream, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Start client with specified workload. /// First request sent specifies the ClientConfig followed by ClientStatus /// response. After that, a "Mark" can be sent anytime to request the latest /// stats. Closing the stream will initiate shutdown of the test client /// and once the shutdown has finished, the OK status is sent to terminate /// this RPC. /// </summary> public virtual global::System.Threading.Tasks.Task RunClient(IAsyncStreamReader<global::Grpc.Testing.ClientArgs> requestStream, IServerStreamWriter<global::Grpc.Testing.ClientStatus> responseStream, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Just return the core count - unary call /// </summary> public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.CoreResponse> CoreCount(global::Grpc.Testing.CoreRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Quit this worker /// </summary> public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.Void> QuitWorker(global::Grpc.Testing.Void request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } } /// <summary>Client for WorkerService</summary> public class WorkerServiceClient : ClientBase<WorkerServiceClient> { /// <summary>Creates a new client for WorkerService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public WorkerServiceClient(Channel channel) : base(channel) { } /// <summary>Creates a new client for WorkerService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public WorkerServiceClient(CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected WorkerServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected WorkerServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Start server with specified workload. /// First request sent specifies the ServerConfig followed by ServerStatus /// response. After that, a "Mark" can be sent anytime to request the latest /// stats. Closing the stream will initiate shutdown of the test server /// and once the shutdown has finished, the OK status is sent to terminate /// this RPC. /// </summary> public virtual AsyncDuplexStreamingCall<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus> RunServer(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return RunServer(new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Start server with specified workload. /// First request sent specifies the ServerConfig followed by ServerStatus /// response. After that, a "Mark" can be sent anytime to request the latest /// stats. Closing the stream will initiate shutdown of the test server /// and once the shutdown has finished, the OK status is sent to terminate /// this RPC. /// </summary> public virtual AsyncDuplexStreamingCall<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus> RunServer(CallOptions options) { return CallInvoker.AsyncDuplexStreamingCall(__Method_RunServer, null, options); } /// <summary> /// Start client with specified workload. /// First request sent specifies the ClientConfig followed by ClientStatus /// response. After that, a "Mark" can be sent anytime to request the latest /// stats. Closing the stream will initiate shutdown of the test client /// and once the shutdown has finished, the OK status is sent to terminate /// this RPC. /// </summary> public virtual AsyncDuplexStreamingCall<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus> RunClient(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return RunClient(new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Start client with specified workload. /// First request sent specifies the ClientConfig followed by ClientStatus /// response. After that, a "Mark" can be sent anytime to request the latest /// stats. Closing the stream will initiate shutdown of the test client /// and once the shutdown has finished, the OK status is sent to terminate /// this RPC. /// </summary> public virtual AsyncDuplexStreamingCall<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus> RunClient(CallOptions options) { return CallInvoker.AsyncDuplexStreamingCall(__Method_RunClient, null, options); } /// <summary> /// Just return the core count - unary call /// </summary> public virtual global::Grpc.Testing.CoreResponse CoreCount(global::Grpc.Testing.CoreRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CoreCount(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Just return the core count - unary call /// </summary> public virtual global::Grpc.Testing.CoreResponse CoreCount(global::Grpc.Testing.CoreRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CoreCount, null, options, request); } /// <summary> /// Just return the core count - unary call /// </summary> public virtual AsyncUnaryCall<global::Grpc.Testing.CoreResponse> CoreCountAsync(global::Grpc.Testing.CoreRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CoreCountAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Just return the core count - unary call /// </summary> public virtual AsyncUnaryCall<global::Grpc.Testing.CoreResponse> CoreCountAsync(global::Grpc.Testing.CoreRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CoreCount, null, options, request); } /// <summary> /// Quit this worker /// </summary> public virtual global::Grpc.Testing.Void QuitWorker(global::Grpc.Testing.Void request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return QuitWorker(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Quit this worker /// </summary> public virtual global::Grpc.Testing.Void QuitWorker(global::Grpc.Testing.Void request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_QuitWorker, null, options, request); } /// <summary> /// Quit this worker /// </summary> public virtual AsyncUnaryCall<global::Grpc.Testing.Void> QuitWorkerAsync(global::Grpc.Testing.Void request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return QuitWorkerAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Quit this worker /// </summary> public virtual AsyncUnaryCall<global::Grpc.Testing.Void> QuitWorkerAsync(global::Grpc.Testing.Void request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_QuitWorker, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override WorkerServiceClient NewInstance(ClientBaseConfiguration configuration) { return new WorkerServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> public static ServerServiceDefinition BindService(WorkerServiceBase serviceImpl) { return ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_RunServer, serviceImpl.RunServer) .AddMethod(__Method_RunClient, serviceImpl.RunClient) .AddMethod(__Method_CoreCount, serviceImpl.CoreCount) .AddMethod(__Method_QuitWorker, serviceImpl.QuitWorker).Build(); } } } #endregion
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** Classes: Security Descriptor family of classes ** ** ===========================================================*/ using Microsoft.Win32; using System; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Security.Principal; using System.ComponentModel; namespace System.Security.AccessControl { [Flags] public enum ControlFlags { None = 0x0000, OwnerDefaulted = 0x0001, // set by RM only GroupDefaulted = 0x0002, // set by RM only DiscretionaryAclPresent = 0x0004, // set by RM or user, 'off' means DACL is null DiscretionaryAclDefaulted = 0x0008, // set by RM only SystemAclPresent = 0x0010, // same as DiscretionaryAclPresent SystemAclDefaulted = 0x0020, // sams as DiscretionaryAclDefaulted DiscretionaryAclUntrusted = 0x0040, // ignore this one ServerSecurity = 0x0080, // ignore this one DiscretionaryAclAutoInheritRequired = 0x0100, // ignore this one SystemAclAutoInheritRequired = 0x0200, // ignore this one DiscretionaryAclAutoInherited = 0x0400, // set by RM only SystemAclAutoInherited = 0x0800, // set by RM only DiscretionaryAclProtected = 0x1000, // when set, RM will stop inheriting SystemAclProtected = 0x2000, // when set, RM will stop inheriting RMControlValid = 0x4000, // the reserved 8 bits have some meaning SelfRelative = 0x8000, // must always be on } public abstract class GenericSecurityDescriptor { #region Protected Members // // Pictorially the structure of a security descriptor is as follows: // // 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 // 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 // +---------------------------------------------------------------+ // | Control |Reserved1 (SBZ)| Revision | // +---------------------------------------------------------------+ // | Owner | // +---------------------------------------------------------------+ // | Group | // +---------------------------------------------------------------+ // | Sacl | // +---------------------------------------------------------------+ // | Dacl | // +---------------------------------------------------------------+ // internal const int HeaderLength = 20; internal const int OwnerFoundAt = 4; internal const int GroupFoundAt = 8; internal const int SaclFoundAt = 12; internal const int DaclFoundAt = 16; #endregion #region Private Methods // // Stores an integer in big-endian format into an array at a given offset // private static void MarshalInt(byte[] binaryForm, int offset, int number) { binaryForm[offset + 0] = (byte)(number >> 0); binaryForm[offset + 1] = (byte)(number >> 8); binaryForm[offset + 2] = (byte)(number >> 16); binaryForm[offset + 3] = (byte)(number >> 24); } // // Retrieves an integer stored in big-endian format at a given offset in an array // internal static int UnmarshalInt(byte[] binaryForm, int offset) { return (int)( (binaryForm[offset + 0] << 0) + (binaryForm[offset + 1] << 8) + (binaryForm[offset + 2] << 16) + (binaryForm[offset + 3] << 24)); } #endregion #region Constructors internal GenericSecurityDescriptor() { } #endregion #region Protected Properties // // Marshaling logic requires calling into the derived // class to obtain pointers to SACL and DACL // internal abstract GenericAcl GenericSacl { get; } internal abstract GenericAcl GenericDacl { get; } private bool IsCraftedAefaDacl { get { return (GenericDacl is DiscretionaryAcl) && (GenericDacl as DiscretionaryAcl).EveryOneFullAccessForNullDacl; } } #endregion #region Public Properties public static bool IsSddlConversionSupported() { return true; // SDDL to binary conversions are supported on Windows 2000 and higher } public static byte Revision { get { return 1; } } // // Allows retrieving and setting the control bits for this security descriptor // public abstract ControlFlags ControlFlags { get; } // // Allows retrieving and setting the owner SID for this security descriptor // public abstract SecurityIdentifier Owner { get; set; } // // Allows retrieving and setting the group SID for this security descriptor // public abstract SecurityIdentifier Group { get; set; } // // Retrieves the length of the binary representation // of the security descriptor // public int BinaryLength { get { int result = HeaderLength; if (Owner != null) { result += Owner.BinaryLength; } if (Group != null) { result += Group.BinaryLength; } if ((ControlFlags & ControlFlags.SystemAclPresent) != 0 && GenericSacl != null) { result += GenericSacl.BinaryLength; } if ((ControlFlags & ControlFlags.DiscretionaryAclPresent) != 0 && GenericDacl != null && !IsCraftedAefaDacl) { result += GenericDacl.BinaryLength; } return result; } } #endregion #region Public Methods // // Converts the security descriptor to its SDDL form // public string GetSddlForm(AccessControlSections includeSections) { byte[] binaryForm = new byte[BinaryLength]; string resultSddl; int error; GetBinaryForm(binaryForm, 0); SecurityInfos flags = 0; if ((includeSections & AccessControlSections.Owner) != 0) { flags |= SecurityInfos.Owner; } if ((includeSections & AccessControlSections.Group) != 0) { flags |= SecurityInfos.Group; } if ((includeSections & AccessControlSections.Audit) != 0) { flags |= SecurityInfos.SystemAcl; } if ((includeSections & AccessControlSections.Access) != 0) { flags |= SecurityInfos.DiscretionaryAcl; } error = Win32.ConvertSdToSddl(binaryForm, 1, flags, out resultSddl); if (error == Interop.Errors.ERROR_INVALID_PARAMETER || error == Interop.Errors.ERROR_UNKNOWN_REVISION) { // // Indicates that the marshaling logic in GetBinaryForm is busted // Debug.Fail("binaryForm produced invalid output"); throw new InvalidOperationException(); } else if (error != Interop.Errors.ERROR_SUCCESS) { Debug.Fail($"Win32.ConvertSdToSddl returned {error}"); throw new InvalidOperationException(); } return resultSddl; } // // Converts the security descriptor to its binary form // public void GetBinaryForm(byte[] binaryForm, int offset) { if (binaryForm == null) { throw new ArgumentNullException(nameof(binaryForm)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (binaryForm.Length - offset < BinaryLength) { throw new ArgumentOutOfRangeException( nameof(binaryForm), SR.ArgumentOutOfRange_ArrayTooSmall); } // // the offset will grow as we go for each additional field (owner, group, // acl, etc) being written. But for each of such fields, we must use the // original offset as passed in, not the growing offset // int originalOffset = offset; // // Populate the header // int length = BinaryLength; byte rmControl = ((this is RawSecurityDescriptor) && ((ControlFlags & ControlFlags.RMControlValid) != 0)) ? ((this as RawSecurityDescriptor).ResourceManagerControl) : (byte)0; // if the DACL is our internally crafted NULL replacement, then let us turn off this control int materializedControlFlags = (int)ControlFlags; if (IsCraftedAefaDacl) { unchecked { materializedControlFlags &= ~((int)ControlFlags.DiscretionaryAclPresent); } } binaryForm[offset + 0] = Revision; binaryForm[offset + 1] = rmControl; binaryForm[offset + 2] = unchecked((byte)((int)materializedControlFlags >> 0)); binaryForm[offset + 3] = (byte)((int)materializedControlFlags >> 8); // // Compute offsets at which owner, group, SACL and DACL are stored // int ownerOffset, groupOffset, saclOffset, daclOffset; ownerOffset = offset + OwnerFoundAt; groupOffset = offset + GroupFoundAt; saclOffset = offset + SaclFoundAt; daclOffset = offset + DaclFoundAt; offset += HeaderLength; // // Marhsal the Owner SID into place // if (Owner != null) { MarshalInt(binaryForm, ownerOffset, offset - originalOffset); Owner.GetBinaryForm(binaryForm, offset); offset += Owner.BinaryLength; } else { // // If Owner SID is null, store 0 in the offset field // MarshalInt(binaryForm, ownerOffset, 0); } // // Marshal the Group SID into place // if (Group != null) { MarshalInt(binaryForm, groupOffset, offset - originalOffset); Group.GetBinaryForm(binaryForm, offset); offset += Group.BinaryLength; } else { // // If Group SID is null, store 0 in the offset field // MarshalInt(binaryForm, groupOffset, 0); } // // Marshal the SACL into place, if present // if ((ControlFlags & ControlFlags.SystemAclPresent) != 0 && GenericSacl != null) { MarshalInt(binaryForm, saclOffset, offset - originalOffset); GenericSacl.GetBinaryForm(binaryForm, offset); offset += GenericSacl.BinaryLength; } else { // // If SACL is null or not present, store 0 in the offset field // MarshalInt(binaryForm, saclOffset, 0); } // // Marshal the DACL into place, if present // if ((ControlFlags & ControlFlags.DiscretionaryAclPresent) != 0 && GenericDacl != null && !IsCraftedAefaDacl) { MarshalInt(binaryForm, daclOffset, offset - originalOffset); GenericDacl.GetBinaryForm(binaryForm, offset); offset += GenericDacl.BinaryLength; } else { // // If DACL is null or not present, store 0 in the offset field // MarshalInt(binaryForm, daclOffset, 0); } } #endregion } public sealed class RawSecurityDescriptor : GenericSecurityDescriptor { #region Private Members private SecurityIdentifier _owner; private SecurityIdentifier _group; private ControlFlags _flags; private RawAcl _sacl; private RawAcl _dacl; private byte _rmControl; // the not-so-reserved SBZ1 field #endregion #region Protected Properties internal override GenericAcl GenericSacl { get { return _sacl; } } internal override GenericAcl GenericDacl { get { return _dacl; } } #endregion #region Private methods private void CreateFromParts(ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, RawAcl systemAcl, RawAcl discretionaryAcl) { SetFlags(flags); Owner = owner; Group = group; SystemAcl = systemAcl; DiscretionaryAcl = discretionaryAcl; ResourceManagerControl = 0; } #endregion #region Constructors // // Creates a security descriptor explicitly // public RawSecurityDescriptor(ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, RawAcl systemAcl, RawAcl discretionaryAcl) : base() { CreateFromParts(flags, owner, group, systemAcl, discretionaryAcl); } // // Creates a security descriptor from an SDDL string // public RawSecurityDescriptor(string sddlForm) : this(BinaryFormFromSddlForm(sddlForm), 0) { } // // Creates a security descriptor from its binary representation // Important: the representation must be in self-relative format // public RawSecurityDescriptor(byte[] binaryForm, int offset) : base() { // // The array passed in must be valid // if (binaryForm == null) { throw new ArgumentNullException(nameof(binaryForm)); } if (offset < 0) { // // Offset must not be negative // throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } // // At least make sure the header is in place // if (binaryForm.Length - offset < HeaderLength) { throw new ArgumentOutOfRangeException( nameof(binaryForm), SR.ArgumentOutOfRange_ArrayTooSmall); } // // We only understand revision-1 security descriptors // if (binaryForm[offset + 0] != Revision) { throw new ArgumentOutOfRangeException(nameof(binaryForm), SR.AccessControl_InvalidSecurityDescriptorRevision); } ControlFlags flags; SecurityIdentifier owner, group; RawAcl sacl, dacl; byte rmControl; // // Extract the ResourceManagerControl field // rmControl = binaryForm[offset + 1]; // // Extract the control flags // flags = (ControlFlags)((binaryForm[offset + 2] << 0) + (binaryForm[offset + 3] << 8)); // // Make sure that the input is in self-relative format // if ((flags & ControlFlags.SelfRelative) == 0) { throw new ArgumentException( SR.AccessControl_InvalidSecurityDescriptorSelfRelativeForm, nameof(binaryForm)); } // // Extract the owner SID // int ownerOffset = UnmarshalInt(binaryForm, offset + OwnerFoundAt); if (ownerOffset != 0) { owner = new SecurityIdentifier(binaryForm, offset + ownerOffset); } else { owner = null; } // // Extract the group SID // int groupOffset = UnmarshalInt(binaryForm, offset + GroupFoundAt); if (groupOffset != 0) { group = new SecurityIdentifier(binaryForm, offset + groupOffset); } else { group = null; } // // Extract the SACL // int saclOffset = UnmarshalInt(binaryForm, offset + SaclFoundAt); if (((flags & ControlFlags.SystemAclPresent) != 0) && saclOffset != 0) { sacl = new RawAcl(binaryForm, offset + saclOffset); } else { sacl = null; } // // Extract the DACL // int daclOffset = UnmarshalInt(binaryForm, offset + DaclFoundAt); if (((flags & ControlFlags.DiscretionaryAclPresent) != 0) && daclOffset != 0) { dacl = new RawAcl(binaryForm, offset + daclOffset); } else { dacl = null; } // // Create the resulting security descriptor // CreateFromParts(flags, owner, group, sacl, dacl); // // In the offchance that the flags indicate that the rmControl // field is meaningful, remember what was there. // if ((flags & ControlFlags.RMControlValid) != 0) { ResourceManagerControl = rmControl; } } #endregion #region Static Methods private static byte[] BinaryFormFromSddlForm(string sddlForm) { if (sddlForm == null) { throw new ArgumentNullException(nameof(sddlForm)); } int error; IntPtr byteArray = IntPtr.Zero; uint byteArraySize = 0; byte[] binaryForm = null; try { if (!Interop.Advapi32.ConvertStringSdToSd( sddlForm, GenericSecurityDescriptor.Revision, out byteArray, ref byteArraySize)) { error = Marshal.GetLastWin32Error(); if (error == Interop.Errors.ERROR_INVALID_PARAMETER || error == Interop.Errors.ERROR_INVALID_ACL || error == Interop.Errors.ERROR_INVALID_SECURITY_DESCR || error == Interop.Errors.ERROR_UNKNOWN_REVISION) { throw new ArgumentException( SR.ArgumentException_InvalidSDSddlForm, nameof(sddlForm)); } else if (error == Interop.Errors.ERROR_NOT_ENOUGH_MEMORY) { throw new OutOfMemoryException(); } else if (error == Interop.Errors.ERROR_INVALID_SID) { throw new ArgumentException( SR.AccessControl_InvalidSidInSDDLString, nameof(sddlForm)); } else if (error != Interop.Errors.ERROR_SUCCESS) { Debug.Fail($"Unexpected error out of Win32.ConvertStringSdToSd: {error}"); throw new Win32Exception(error, SR.Format(SR.AccessControl_UnexpectedError, error)); } } binaryForm = new byte[byteArraySize]; // // Extract the data from the returned pointer // Marshal.Copy(byteArray, binaryForm, 0, (int)byteArraySize); } finally { // // Now is a good time to get rid of the returned pointer // if (byteArray != IntPtr.Zero) { Interop.Kernel32.LocalFree(byteArray); } } return binaryForm; } #endregion #region Public Properties // // Allows retrieving the control bits for this security descriptor // Important: Special checks must be applied when setting flags and not // all flags can be set (for instance, we only deal with self-relative // security descriptors), thus flags can be set through other methods. // public override ControlFlags ControlFlags { get { return _flags; } } // // Allows retrieving and setting the owner SID for this security descriptor // public override SecurityIdentifier Owner { get { return _owner; } set { _owner = value; } } // // Allows retrieving and setting the group SID for this security descriptor // public override SecurityIdentifier Group { get { return _group; } set { _group = value; } } // // Allows retrieving and setting the SACL for this security descriptor // public RawAcl SystemAcl { get { return _sacl; } set { _sacl = value; } } // // Allows retrieving and setting the DACL for this security descriptor // public RawAcl DiscretionaryAcl { get { return _dacl; } set { _dacl = value; } } // // CORNER CASE (LEGACY) // The ostensibly "reserved" field in the Security Descriptor header // can in fact be used by obscure resource managers which in this // case must set the RMControlValid flag. // public byte ResourceManagerControl { get { return _rmControl; } set { _rmControl = value; } } #endregion #region Public Methods public void SetFlags(ControlFlags flags) { // // We can not deal with non-self-relative descriptors // so just forget about it // _flags = (flags | ControlFlags.SelfRelative); } #endregion } public sealed class CommonSecurityDescriptor : GenericSecurityDescriptor { #region Private Members private bool _isContainer; private bool _isDS; private RawSecurityDescriptor _rawSd; private SystemAcl _sacl; private DiscretionaryAcl _dacl; #endregion #region Private Methods private void CreateFromParts(bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, SystemAcl systemAcl, DiscretionaryAcl discretionaryAcl) { if (systemAcl != null && systemAcl.IsContainer != isContainer) { throw new ArgumentException( isContainer ? SR.AccessControl_MustSpecifyContainerAcl : SR.AccessControl_MustSpecifyLeafObjectAcl, nameof(systemAcl)); } if (discretionaryAcl != null && discretionaryAcl.IsContainer != isContainer) { throw new ArgumentException( isContainer ? SR.AccessControl_MustSpecifyContainerAcl : SR.AccessControl_MustSpecifyLeafObjectAcl, nameof(discretionaryAcl)); } _isContainer = isContainer; if (systemAcl != null && systemAcl.IsDS != isDS) { throw new ArgumentException( isDS ? SR.AccessControl_MustSpecifyDirectoryObjectAcl : SR.AccessControl_MustSpecifyNonDirectoryObjectAcl, nameof(systemAcl)); } if (discretionaryAcl != null && discretionaryAcl.IsDS != isDS) { throw new ArgumentException( isDS ? SR.AccessControl_MustSpecifyDirectoryObjectAcl : SR.AccessControl_MustSpecifyNonDirectoryObjectAcl, nameof(discretionaryAcl)); } _isDS = isDS; _sacl = systemAcl; // // Replace null DACL with an allow-all for everyone DACL // if (discretionaryAcl == null) { // // to conform to native behavior, we will add allow everyone ace for DACL // discretionaryAcl = DiscretionaryAcl.CreateAllowEveryoneFullAccess(_isDS, _isContainer); } _dacl = discretionaryAcl; // // DACL is never null. So always set the flag bit on // ControlFlags actualFlags = flags | ControlFlags.DiscretionaryAclPresent; // // Keep SACL and the flag bit in sync. // if (systemAcl == null) { unchecked { actualFlags &= ~(ControlFlags.SystemAclPresent); } } else { actualFlags |= (ControlFlags.SystemAclPresent); } _rawSd = new RawSecurityDescriptor(actualFlags, owner, group, systemAcl == null ? null : systemAcl.RawAcl, discretionaryAcl.RawAcl); } #endregion #region Constructors // // Creates a security descriptor explicitly // public CommonSecurityDescriptor(bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, SystemAcl systemAcl, DiscretionaryAcl discretionaryAcl) { CreateFromParts(isContainer, isDS, flags, owner, group, systemAcl, discretionaryAcl); } private CommonSecurityDescriptor(bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, RawAcl systemAcl, RawAcl discretionaryAcl) : this(isContainer, isDS, flags, owner, group, systemAcl == null ? null : new SystemAcl(isContainer, isDS, systemAcl), discretionaryAcl == null ? null : new DiscretionaryAcl(isContainer, isDS, discretionaryAcl)) { } public CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor) : this(isContainer, isDS, rawSecurityDescriptor, false) { } internal CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor, bool trusted) { if (rawSecurityDescriptor == null) { throw new ArgumentNullException(nameof(rawSecurityDescriptor)); } CreateFromParts( isContainer, isDS, rawSecurityDescriptor.ControlFlags, rawSecurityDescriptor.Owner, rawSecurityDescriptor.Group, rawSecurityDescriptor.SystemAcl == null ? null : new SystemAcl(isContainer, isDS, rawSecurityDescriptor.SystemAcl, trusted), rawSecurityDescriptor.DiscretionaryAcl == null ? null : new DiscretionaryAcl(isContainer, isDS, rawSecurityDescriptor.DiscretionaryAcl, trusted)); } // // Create a security descriptor from an SDDL string // public CommonSecurityDescriptor(bool isContainer, bool isDS, string sddlForm) : this(isContainer, isDS, new RawSecurityDescriptor(sddlForm), true) { } // // Create a security descriptor from its binary representation // public CommonSecurityDescriptor(bool isContainer, bool isDS, byte[] binaryForm, int offset) : this(isContainer, isDS, new RawSecurityDescriptor(binaryForm, offset), true) { } #endregion #region Protected Properties internal sealed override GenericAcl GenericSacl { get { return _sacl; } } internal sealed override GenericAcl GenericDacl { get { return _dacl; } } #endregion #region Public Properties public bool IsContainer { get { return _isContainer; } } public bool IsDS { get { return _isDS; } } // // Allows retrieving the control bits for this security descriptor // public override ControlFlags ControlFlags { get { return _rawSd.ControlFlags; } } // // Allows retrieving and setting the owner SID for this security descriptor // public override SecurityIdentifier Owner { get { return _rawSd.Owner; } set { _rawSd.Owner = value; } } // // Allows retrieving and setting the group SID for this security descriptor // public override SecurityIdentifier Group { get { return _rawSd.Group; } set { _rawSd.Group = value; } } public SystemAcl SystemAcl { get { return _sacl; } set { if (value != null) { if (value.IsContainer != this.IsContainer) { throw new ArgumentException( this.IsContainer ? SR.AccessControl_MustSpecifyContainerAcl : SR.AccessControl_MustSpecifyLeafObjectAcl, nameof(value)); } if (value.IsDS != this.IsDS) { throw new ArgumentException( this.IsDS ? SR.AccessControl_MustSpecifyDirectoryObjectAcl : SR.AccessControl_MustSpecifyNonDirectoryObjectAcl, nameof(value)); } } _sacl = value; if (_sacl != null) { _rawSd.SystemAcl = _sacl.RawAcl; AddControlFlags(ControlFlags.SystemAclPresent); } else { _rawSd.SystemAcl = null; RemoveControlFlags(ControlFlags.SystemAclPresent); } } } // // Allows retrieving and setting the DACL for this security descriptor // public DiscretionaryAcl DiscretionaryAcl { get { return _dacl; } set { if (value != null) { if (value.IsContainer != this.IsContainer) { throw new ArgumentException( this.IsContainer ? SR.AccessControl_MustSpecifyContainerAcl : SR.AccessControl_MustSpecifyLeafObjectAcl, nameof(value)); } if (value.IsDS != this.IsDS) { throw new ArgumentException( this.IsDS ? SR.AccessControl_MustSpecifyDirectoryObjectAcl : SR.AccessControl_MustSpecifyNonDirectoryObjectAcl, nameof(value)); } } // // NULL DACLs are replaced with allow everyone full access DACLs. // if (value == null) { _dacl = DiscretionaryAcl.CreateAllowEveryoneFullAccess(IsDS, IsContainer); } else { _dacl = value; } _rawSd.DiscretionaryAcl = _dacl.RawAcl; AddControlFlags(ControlFlags.DiscretionaryAclPresent); } } public bool IsSystemAclCanonical { get { return (SystemAcl == null || SystemAcl.IsCanonical); } } public bool IsDiscretionaryAclCanonical { get { return (DiscretionaryAcl == null || DiscretionaryAcl.IsCanonical); } } #endregion #region Public Methods public void SetSystemAclProtection(bool isProtected, bool preserveInheritance) { if (!isProtected) { RemoveControlFlags(ControlFlags.SystemAclProtected); } else { if (!preserveInheritance && SystemAcl != null) { SystemAcl.RemoveInheritedAces(); } AddControlFlags(ControlFlags.SystemAclProtected); } } public void SetDiscretionaryAclProtection(bool isProtected, bool preserveInheritance) { if (!isProtected) { RemoveControlFlags(ControlFlags.DiscretionaryAclProtected); } else { if (!preserveInheritance && DiscretionaryAcl != null) { DiscretionaryAcl.RemoveInheritedAces(); } AddControlFlags(ControlFlags.DiscretionaryAclProtected); } if (DiscretionaryAcl != null && DiscretionaryAcl.EveryOneFullAccessForNullDacl) { DiscretionaryAcl.EveryOneFullAccessForNullDacl = false; } } public void PurgeAccessControl(SecurityIdentifier sid) { if (sid == null) { throw new ArgumentNullException(nameof(sid)); } if (DiscretionaryAcl != null) { DiscretionaryAcl.Purge(sid); } } public void PurgeAudit(SecurityIdentifier sid) { if (sid == null) { throw new ArgumentNullException(nameof(sid)); } if (SystemAcl != null) { SystemAcl.Purge(sid); } } public void AddDiscretionaryAcl(byte revision, int trusted) { this.DiscretionaryAcl = new DiscretionaryAcl(this.IsContainer, this.IsDS, revision, trusted); this.AddControlFlags(ControlFlags.DiscretionaryAclPresent); } public void AddSystemAcl(byte revision, int trusted) { this.SystemAcl = new SystemAcl(this.IsContainer, this.IsDS, revision, trusted); this.AddControlFlags(ControlFlags.SystemAclPresent); } #endregion #region internal Methods internal void UpdateControlFlags(ControlFlags flagsToUpdate, ControlFlags newFlags) { ControlFlags finalFlags = newFlags | (_rawSd.ControlFlags & (~flagsToUpdate)); _rawSd.SetFlags(finalFlags); } // // These two add/remove method must be called with great care (and thus it is internal) // The caller is responsible for keeping the SaclPresent and DaclPresent bits in sync // with the actual SACL and DACL. // internal void AddControlFlags(ControlFlags flags) { _rawSd.SetFlags(_rawSd.ControlFlags | flags); } internal void RemoveControlFlags(ControlFlags flags) { unchecked { _rawSd.SetFlags(_rawSd.ControlFlags & ~flags); } } internal bool IsSystemAclPresent { get { return (_rawSd.ControlFlags & ControlFlags.SystemAclPresent) != 0; } } internal bool IsDiscretionaryAclPresent { get { return (_rawSd.ControlFlags & ControlFlags.DiscretionaryAclPresent) != 0; } } #endregion } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.BitStamp.Native.BitStamp File: PusherClient.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.BitStamp.Native { using System; using System.Linq; using System.Net.WebSockets; using System.Text; using System.Threading; using Ecng.Common; using Newtonsoft.Json; using StockSharp.Logging; using StockSharp.Localization; class PusherClient : BaseLogReceiver { private class ChannelData { [JsonProperty("event")] public string Event { get; set; } [JsonProperty("data")] public string Data { get; set; } [JsonProperty("channel")] public string Channel { get; set; } } public event Action<Trade> NewTrade; public event Action<OrderBook> NewOrderBook; public event Action<Exception> PusherError; public event Action PusherConnected; public event Action PusherDisconnected; public event Action TradesSubscribed; public event Action OrderBooksSubscribed; private ClientWebSocket _ws; private CancellationTokenSource _source = new CancellationTokenSource(); private bool _connected; public void ConnectPusher() { _ws = new ClientWebSocket(); _ws.ConnectAsync(new Uri("wss://ws.pusherapp.com/app/de504dc5763aeef9ff52?client=PC-Orbit&version=1.0&protocol=7"), _source.Token).Wait(); _connected = true; ThreadingHelper.Thread(OnReceive).Launch(); } public void DisconnectPusher() { _connected = false; _source.Cancel(); _source = new CancellationTokenSource(); } private void OnReceive() { try { var buf = new byte[1024 * 1024]; var pos = 0; var errorCount = 0; const int maxErrorCount = 10; while (!IsDisposed && _connected) { try { var task = _ws.ReceiveAsync(new ArraySegment<byte>(buf, pos, buf.Length - pos), _source.Token); task.Wait(); var result = task.Result; if (result.CloseStatus != null) { if (task.Exception != null) PusherError.SafeInvoke(task.Exception); break; } pos += result.Count; if (!result.EndOfMessage) continue; var recv = Encoding.UTF8.GetString(buf, 0, pos); this.AddDebugLog(recv); pos = 0; var obj = JsonConvert.DeserializeObject<ChannelData>(recv); switch (obj.Event) { case "pusher:connection_established": PusherConnected.SafeInvoke(); break; case "pusher_internal:subscription_succeeded": { switch (obj.Channel) { case "live_trades": TradesSubscribed.SafeInvoke(); break; case "order_book": OrderBooksSubscribed.SafeInvoke(); break; default: this.AddErrorLog(LocalizedStrings.Str3311Params, obj.Event); break; } break; } case "trade": NewTrade.SafeInvoke(JsonConvert.DeserializeObject<Trade>(obj.Data)); break; case "data": NewOrderBook.SafeInvoke(JsonConvert.DeserializeObject<OrderBook>(obj.Data)); break; default: this.AddErrorLog(LocalizedStrings.Str3312Params, obj.Event); break; } errorCount = 0; } catch (AggregateException ex) { PusherError.SafeInvoke(ex); var socketError = ex.InnerExceptions.FirstOrDefault() as WebSocketException; if (socketError != null) break; if (++errorCount >= maxErrorCount) { this.AddErrorLog("Max error {0} limit reached.", maxErrorCount); break; } } catch (Exception ex) { PusherError.SafeInvoke(ex); } } _ws.CloseAsync(WebSocketCloseStatus.Empty, string.Empty, _source.Token).Wait(); _ws.Dispose(); PusherDisconnected.SafeInvoke(); } catch (Exception ex) { PusherError.SafeInvoke(ex); } } private void Send(string command) { var sendBuf = Encoding.UTF8.GetBytes(command); _ws.SendAsync(new ArraySegment<byte>(sendBuf), WebSocketMessageType.Text, true, _source.Token).Wait(); } public void SubscribeTrades() { Send("{\"event\":\"pusher:subscribe\",\"data\":{\"channel\":\"live_trades\"}}"); } public void UnSubscribeTrades() { Send("{\"event\":\"pusher:unsubscribe\",\"data\":{\"channel\":\"live_trades\"}}"); } public void SubscribeDepths() { Send("{\"event\":\"pusher:subscribe\",\"data\":{\"channel\":\"order_book\"}}"); } public void UnSubscribeDepths() { Send("{\"event\":\"pusher:unsubscribe\",\"data\":{\"channel\":\"order_book\"}}"); } /// <summary> /// Release resources. /// </summary> protected override void DisposeManaged() { DisconnectPusher(); base.DisposeManaged(); } } }
#pragma warning disable 0168 using System; using System.Linq; using nHydrate.Generator.Common.Util; namespace nHydrate.Dsl { partial class nHydrateDiagram { ///Determine if this diagram is loading from disk public bool IsLoading { get; set; } = false; #region Constructors //Constructors were not generated for this class because it had HasCustomConstructor //set to true. Please provide the constructors below in a partial class. public nHydrateDiagram(Microsoft.VisualStudio.Modeling.Store store, params Microsoft.VisualStudio.Modeling.PropertyAssignment[] propertyAssignments) : this(store != null ? store.DefaultPartitionForClass(DomainClassId) : null, propertyAssignments) { } public nHydrateDiagram(Microsoft.VisualStudio.Modeling.Partition partition, params Microsoft.VisualStudio.Modeling.PropertyAssignment[] propertyAssignments) : base(partition, propertyAssignments) { this.Store.UndoManager.AddCanUndoRedoCallback(CanUndoRedoCallback); this.Store.TransactionManager.AddCanCommitCallback(CanCommitCallback); //Custom code so need to override the constructor this.ShowGrid = false; this.DisplayType = true; this.IsLoading = true; this.DiagramAdded += new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(nHydrateDiagram_DiagramAdded); TextManagerEvents.RegisterForTextManagerEvents(); } private bool CanUndoRedoCallback(bool isUndo, Microsoft.VisualStudio.Modeling.TransactionItem transactionItem) { return true; } public Microsoft.VisualStudio.Modeling.CanCommitResult CanCommitCallback(Microsoft.VisualStudio.Modeling.Transaction transaction) { return Microsoft.VisualStudio.Modeling.CanCommitResult.Commit; } #endregion #region Events protected override void OnElementAdded(Microsoft.VisualStudio.Modeling.ElementAddedEventArgs e) { var model = this.ModelElement as nHydrate.Dsl.nHydrateModel; if (!model.IsLoading) { } base.OnElementAdded(e); } public event EventHandler<ModelElementEventArgs> ShapeDoubleClick; protected void OnShapeDoubleClick(ModelElementEventArgs e) { if (this.ShapeDoubleClick != null) ShapeDoubleClick(this, e); } public event EventHandler<ModelElementEventArgs> ShapeConfiguring; protected void OnShapeConfiguring(ModelElementEventArgs e) { if (this.ShapeConfiguring != null) ShapeConfiguring(this, e); } #endregion #region Event Handlers private void FieldAdded(object sender, Microsoft.VisualStudio.Modeling.ElementAddedEventArgs e) { var field = e.ModelElement as Field; if (field.Entity == null) return; if (field.Entity.nHydrateModel == null) return; if (!field.Entity.nHydrateModel.IsLoading && field.SortOrder == 0) { var maxSortOrder = 1; if (field.Entity.Fields.Count > 0) maxSortOrder = field.Entity.Fields.Max(x => x.SortOrder); using (var transaction = this.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString())) { field.SortOrder = ++maxSortOrder; transaction.Commit(); } } } private void IndexColumnAdded(object sender, Microsoft.VisualStudio.Modeling.ElementAddedEventArgs e) { var ic = e.ModelElement as IndexColumn; if (ic.Index == null) return; if (ic.Index.Entity == null) return; if (ic.Index.Entity.nHydrateModel == null) return; if (!ic.IsInternal && !ic.Index.Entity.nHydrateModel.IsLoading && !this.Store.InUndo) { if (!ic.Index.Entity.nHydrateModel.IsLoading) { if (ic.Index.IndexType != IndexTypeConstants.User) throw new Exception("This is a managed index and cannot be modified."); } } if (!ic.Index.Entity.nHydrateModel.IsLoading) { if (ic.SortOrder == 0) { using (var transaction = this.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString())) { var max = 0; if (ic.Index.IndexColumns.Count > 0) max = ic.Index.IndexColumns.Max(x => x.SortOrder); ic.SortOrder = max + 1; transaction.Commit(); } } } } private void FieldPropertyChanged(object sender, Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs e) { var f = e.ModelElement as Field; f.CachedImage = null; } private void ViewFieldPropertyChanged(object sender, Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs e) { var f = e.ModelElement as ViewField; f.CachedImage = null; } private bool _isLoaded = false; protected void nHydrateDiagram_DiagramAdded(object sender, Microsoft.VisualStudio.Modeling.ElementAddedEventArgs e) { if (_isLoaded) return; _isLoaded = true; var model = this.Diagram.ModelElement as nHydrateModel; //Notify when field is changed so we can refresh icon this.Store.EventManagerDirectory.ElementPropertyChanged.Add( this.Store.DomainDataDirectory.FindDomainClass(typeof(Field)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(FieldPropertyChanged)); this.Store.EventManagerDirectory.ElementPropertyChanged.Add( this.Store.DomainDataDirectory.FindDomainClass(typeof(ViewField)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ViewFieldPropertyChanged)); //Notify when an index column is added this.Store.EventManagerDirectory.ElementAdded.Add( this.Store.DomainDataDirectory.FindDomainClass(typeof(IndexColumn)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(IndexColumnAdded)); //Notify when a Field is added this.Store.EventManagerDirectory.ElementAdded.Add( this.Store.DomainDataDirectory.FindDomainClass(typeof(Field)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(FieldAdded)); this.IsLoading = false; model.IsDirty = true; } #endregion protected override void OnChildConfiguring(Microsoft.VisualStudio.Modeling.Diagrams.ShapeElement child, bool createdDuringViewFixup) { base.OnChildConfiguring(child, createdDuringViewFixup); try { if (!this.IsLoading) { //Add a default field to entities if (child.ModelElement is Entity) { var item = child.ModelElement as Entity; var model = item.nHydrateModel; if (item.Fields.Count == 0) { var field = new Field(item.Partition) { DataType = DataTypeConstants.Int, Identity = IdentityTypeConstants.Database, Name = "ID", }; item.Fields.Add(field); //Add then set PK so it will trigger index code field.IsPrimaryKey = true; } #region Pasting //If there are invalid indexes then try to remap them foreach (var index in item.Indexes.Where(x => x.FieldList.Any(z => z == null))) { foreach (var c in index.IndexColumns.Where(x => x.Field == null && x.FieldID != Guid.Empty)) { var f = model.Entities.SelectMany(x => x.Fields).FirstOrDefault(x => x.Id == c.FieldID); if (f != null) { var f2 = item.Fields.FirstOrDefault(x => x.Name == f.Name); if (f2 != null) c.FieldID = f2.Id; } } } //Add a PK index if not one if (!item.Indexes.Any(x => x.IndexType == IndexTypeConstants.PrimaryKey) && item.PrimaryKeyFields.Count > 0) { var index = new Index(item.Partition) { IndexType = IndexTypeConstants.PrimaryKey }; item.Indexes.Add(index); var loop = 0; foreach (var field in item.PrimaryKeyFields) { var newIndexColumn = new IndexColumn(item.Partition); index.IndexColumns.Add(newIndexColumn); newIndexColumn.FieldID = field.Id; newIndexColumn.SortOrder = loop; loop++; } } #endregion } else if (child.ModelElement is View) { var item = child.ModelElement as View; if (item.Fields.Count == 0) { var field = new ViewField(item.Partition) { DataType = DataTypeConstants.Int, Name = "Field1", }; item.Fields.Add(field); } } this.OnShapeConfiguring(new ModelElementEventArgs() { Shape = child }); } } catch (Exception ex) { throw; } } internal void NotifyShapeDoubleClick(Microsoft.VisualStudio.Modeling.Diagrams.ShapeElement shape) { this.OnShapeDoubleClick(new ModelElementEventArgs() { Shape = shape }); } protected override void InitializeResources(Microsoft.VisualStudio.Modeling.Diagrams.StyleSet classStyleSet) { var dte = GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE; nHydrate.Generator.Common.Util.EnvDTEHelper.Instance.SetDTE(dte); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using ReactNative.Reflection; using ReactNative.UIManager; using ReactNative.UIManager.Annotations; using System; using System.Collections; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; namespace ReactNative.Views.Text { /// <summary> /// The view manager for text views. /// </summary> public class ReactTextViewManager : ViewParentManager<TextBlock, ReactTextShadowNode> { private static readonly IReactCompoundView s_compoundView = new ReactTextCompoundView(); /// <summary> /// The name of the view manager. /// </summary> public override string Name { get { return "RCTText"; } } /// <summary> /// Sets the font color for the node. /// </summary> /// <param name="view">The view.</param> /// <param name="color">The masked color value.</param> [ReactProp(ViewProps.Color, CustomType = "Color")] public void SetColor(TextBlock view, uint? color) { view.Foreground = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : null; } /// <summary> /// Sets the TextDecorationLine for the node. /// </summary> /// <param name="view">The view.</param> /// <param name="textDecorationLineValue">The TextDecorationLine value.</param> [ReactProp(ViewProps.TextDecorationLine)] public void SetTextDecorationLine(TextBlock view, string textDecorationLineValue) { var textDecorationLine = EnumHelpers.ParseNullable<TextDecorationLine>(textDecorationLineValue) ?? TextDecorationLine.None; switch (textDecorationLine) { case TextDecorationLine.Underline: view.TextDecorations = TextDecorations.Underline; break; case TextDecorationLine.LineThrough: view.TextDecorations = TextDecorations.Strikethrough; break; case TextDecorationLine.UnderlineLineThrough: view.TextDecorations = new TextDecorationCollection(TextDecorations.Underline.Concat(TextDecorations.Strikethrough)); break; case TextDecorationLine.None: default: view.TextDecorations = null; break; } } /// <summary> /// Sets whether or not the text is selectable. /// </summary> /// <param name="view">The view.</param> /// <param name="selectable">A flag indicating whether or not the text is selectable.</param> [ReactProp("selectable")] public void SetSelectable(TextBlock view, bool selectable) { view.Focusable = selectable; } /// <summary> /// Adds a child at the given index. /// </summary> /// <param name="parent">The parent view.</param> /// <param name="child">The child view.</param> /// <param name="index">The index.</param> public override void AddView(TextBlock parent, DependencyObject child, int index) { var inlineChild = child as Inline; if (inlineChild == null) { inlineChild = new InlineUIContainer { Child = (UIElement)child, }; } ((IList)parent.Inlines).Insert(index, inlineChild); } /// <summary> /// Creates the shadow node instance. /// </summary> /// <returns>The shadow node instance.</returns> public override ReactTextShadowNode CreateShadowNodeInstance() { return new ReactTextShadowNode(); } /// <summary> /// Gets the child at the given index. /// </summary> /// <param name="parent">The parent view.</param> /// <param name="index">The index.</param> /// <returns>The child view.</returns> public override DependencyObject GetChildAt(TextBlock parent, int index) { var child = ((IList)parent.Inlines)[index]; var childInlineContainer = child as InlineUIContainer; if (childInlineContainer != null) { return childInlineContainer.Child; } else { return (DependencyObject)child; } } /// <summary> /// Gets the number of children in the view parent. /// </summary> /// <param name="parent">The view parent.</param> /// <returns>The number of children.</returns> public override int GetChildCount(TextBlock parent) { return ((IList)parent.Inlines).Count; } /// <summary> /// Removes all children from the view parent. /// </summary> /// <param name="parent">The view parent.</param> public override void RemoveAllChildren(TextBlock parent) { var inlines = parent.Inlines; inlines.Clear(); } /// <summary> /// Removes the child at the given index. /// </summary> /// <param name="parent">The view parent.</param> /// <param name="index">The index.</param> public override void RemoveChildAt(TextBlock parent, int index) { var inlines = (IList)parent.Inlines; inlines.RemoveAt(index); } /// <summary> /// Receive extra updates from the shadow node. /// </summary> /// <param name="root">The root view.</param> /// <param name="extraData">The extra data.</param> public override void UpdateExtraData(TextBlock root, object extraData) { base.UpdateExtraData(root, extraData); var textNode = extraData as ReactTextShadowNode; if (textNode != null) { textNode.UpdateTextBlock(root); } } /// <summary> /// Creates the view instance. /// </summary> /// <param name="reactContext">The React context.</param> /// <returns>The view instance.</returns> protected override TextBlock CreateViewInstance(ThemedReactContext reactContext) { var textBlock = new TextBlock { TextAlignment = TextAlignment.Left, TextWrapping = TextWrapping.Wrap, TextTrimming = TextTrimming.CharacterEllipsis, }; textBlock.SetReactCompoundView(s_compoundView); return textBlock; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Net.Sockets; using System.Net.Test.Common; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.WebSockets.Client.Tests { public sealed class ArraySegmentSendReceiveTest : SendReceiveTest { public ArraySegmentSendReceiveTest(ITestOutputHelper output) : base(output) { } protected override Task<WebSocketReceiveResult> ReceiveAsync(WebSocket ws, ArraySegment<byte> arraySegment, CancellationToken cancellationToken) => ws.ReceiveAsync(arraySegment, cancellationToken); protected override Task SendAsync(WebSocket ws, ArraySegment<byte> arraySegment, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) => ws.SendAsync(arraySegment, messageType, endOfMessage, cancellationToken); } public abstract class SendReceiveTest : ClientWebSocketTestBase { protected abstract Task SendAsync(WebSocket ws, ArraySegment<byte> arraySegment, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken); protected abstract Task<WebSocketReceiveResult> ReceiveAsync(WebSocket ws, ArraySegment<byte> arraySegment, CancellationToken cancellationToken); public SendReceiveTest(ITestOutputHelper output) : base(output) { } [OuterLoop("Uses external servers")] [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task SendReceive_PartialMessageDueToSmallReceiveBuffer_Success(Uri server) { const int SendBufferSize = 10; var sendBuffer = new byte[SendBufferSize]; var sendSegment = new ArraySegment<byte>(sendBuffer); var receiveBuffer = new byte[SendBufferSize / 2]; var receiveSegment = new ArraySegment<byte>(receiveBuffer); using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds); // The server will read buffers and aggregate it before echoing back a complete message. // But since this test uses a receive buffer that is smaller than the complete message, we will get // back partial message fragments as we read them until we read the complete message payload. for (int i = 0; i < SendBufferSize * 5; i++) { await SendAsync(cws, sendSegment, WebSocketMessageType.Binary, false, ctsDefault.Token); } await SendAsync(cws, sendSegment, WebSocketMessageType.Binary, true, ctsDefault.Token); WebSocketReceiveResult recvResult = await ReceiveAsync(cws, receiveSegment, ctsDefault.Token); Assert.False(recvResult.EndOfMessage); while (recvResult.EndOfMessage == false) { recvResult = await ReceiveAsync(cws, receiveSegment, ctsDefault.Token); } await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "PartialMessageDueToSmallReceiveBufferTest", ctsDefault.Token); } } [OuterLoop("Uses external servers")] [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task SendReceive_PartialMessageBeforeCompleteMessageArrives_Success(Uri server) { var rand = new Random(); var sendBuffer = new byte[ushort.MaxValue + 1]; rand.NextBytes(sendBuffer); var sendSegment = new ArraySegment<byte>(sendBuffer); // Ask the remote server to echo back received messages without ever signaling "end of message". var ub = new UriBuilder(server); ub.Query = "replyWithPartialMessages"; using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(ub.Uri, TimeOutMilliseconds, _output)) { var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds); // Send data to the server; the server will reply back with one or more partial messages. We should be // able to consume that data as it arrives, without having to wait for "end of message" to be signaled. await SendAsync(cws, sendSegment, WebSocketMessageType.Binary, true, ctsDefault.Token); int totalBytesReceived = 0; var receiveBuffer = new byte[sendBuffer.Length]; while (totalBytesReceived < receiveBuffer.Length) { WebSocketReceiveResult recvResult = await ReceiveAsync( cws, new ArraySegment<byte>(receiveBuffer, totalBytesReceived, receiveBuffer.Length - totalBytesReceived), ctsDefault.Token); Assert.False(recvResult.EndOfMessage); Assert.InRange(recvResult.Count, 0, receiveBuffer.Length - totalBytesReceived); totalBytesReceived += recvResult.Count; } Assert.Equal(receiveBuffer.Length, totalBytesReceived); Assert.Equal<byte>(sendBuffer, receiveBuffer); await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "PartialMessageBeforeCompleteMessageArrives", ctsDefault.Token); } } [OuterLoop("Uses external servers")] [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task SendAsync_SendCloseMessageType_ThrowsArgumentExceptionWithMessage(Uri server) { using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); string expectedInnerMessage = ResourceHelper.GetExceptionMessage( "net_WebSockets_Argument_InvalidMessageType", "Close", "SendAsync", "Binary", "Text", "CloseOutputAsync"); var expectedException = new ArgumentException(expectedInnerMessage, "messageType"); string expectedMessage = expectedException.Message; AssertExtensions.Throws<ArgumentException>("messageType", () => { Task t = SendAsync(cws, new ArraySegment<byte>(), WebSocketMessageType.Close, true, cts.Token); }); Assert.Equal(WebSocketState.Open, cws.State); } } [OuterLoop("Uses external servers")] [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task SendAsync_MultipleOutstandingSendOperations_Throws(Uri server) { using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); Task[] tasks = new Task[10]; try { for (int i = 0; i < tasks.Length; i++) { tasks[i] = SendAsync( cws, WebSocketData.GetBufferFromText("hello"), WebSocketMessageType.Text, true, cts.Token); } await Task.WhenAll(tasks); Assert.Equal(WebSocketState.Open, cws.State); } catch (AggregateException ag) { foreach (var ex in ag.InnerExceptions) { if (ex is InvalidOperationException) { Assert.Equal( ResourceHelper.GetExceptionMessage( "net_Websockets_AlreadyOneOutstandingOperation", "SendAsync"), ex.Message); Assert.Equal(WebSocketState.Aborted, cws.State); } else if (ex is WebSocketException) { // Multiple cases. Assert.Equal(WebSocketState.Aborted, cws.State); WebSocketError errCode = (ex as WebSocketException).WebSocketErrorCode; Assert.True( (errCode == WebSocketError.InvalidState) || (errCode == WebSocketError.Success), "WebSocketErrorCode"); } else { Assert.IsAssignableFrom<OperationCanceledException>(ex); } } } } } [OuterLoop("Uses external servers")] [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task ReceiveAsync_MultipleOutstandingReceiveOperations_Throws(Uri server) { using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); Task[] tasks = new Task[2]; await SendAsync( cws, WebSocketData.GetBufferFromText(".delay5sec"), WebSocketMessageType.Text, true, cts.Token); var recvBuffer = new byte[100]; var recvSegment = new ArraySegment<byte>(recvBuffer); try { for (int i = 0; i < tasks.Length; i++) { tasks[i] = ReceiveAsync(cws, recvSegment, cts.Token); } await Task.WhenAll(tasks); Assert.Equal(WebSocketState.Open, cws.State); } catch (Exception ex) { if (ex is InvalidOperationException) { Assert.Equal( ResourceHelper.GetExceptionMessage( "net_Websockets_AlreadyOneOutstandingOperation", "ReceiveAsync"), ex.Message); Assert.Equal(WebSocketState.Aborted, cws.State); } else if (ex is WebSocketException) { // Multiple cases. Assert.Equal(WebSocketState.Aborted, cws.State); WebSocketError errCode = (ex as WebSocketException).WebSocketErrorCode; Assert.True( (errCode == WebSocketError.InvalidState) || (errCode == WebSocketError.Success), "WebSocketErrorCode"); } else if (ex is OperationCanceledException) { Assert.Equal(WebSocketState.Aborted, cws.State); } else { Assert.True(false, "Unexpected exception: " + ex.Message); } } } } [OuterLoop("Uses external servers")] [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task SendAsync_SendZeroLengthPayloadAsEndOfMessage_Success(Uri server) { using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); string message = "hello"; await SendAsync( cws, WebSocketData.GetBufferFromText(message), WebSocketMessageType.Text, false, cts.Token); Assert.Equal(WebSocketState.Open, cws.State); await SendAsync( cws, new ArraySegment<byte>(new byte[0]), WebSocketMessageType.Text, true, cts.Token); Assert.Equal(WebSocketState.Open, cws.State); var recvBuffer = new byte[100]; var receiveSegment = new ArraySegment<byte>(recvBuffer); WebSocketReceiveResult recvRet = await ReceiveAsync(cws, receiveSegment, cts.Token); Assert.Equal(WebSocketState.Open, cws.State); Assert.Equal(message.Length, recvRet.Count); Assert.Equal(WebSocketMessageType.Text, recvRet.MessageType); Assert.True(recvRet.EndOfMessage); Assert.Null(recvRet.CloseStatus); Assert.Null(recvRet.CloseStatusDescription); var recvSegment = new ArraySegment<byte>(receiveSegment.Array, receiveSegment.Offset, recvRet.Count); Assert.Equal(message, WebSocketData.GetTextFromBuffer(recvSegment)); } } [OuterLoop("Uses external servers")] [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task SendReceive_VaryingLengthBuffers_Success(Uri server) { using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var rand = new Random(); var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds); // Values chosen close to boundaries in websockets message length handling as well // as in vectors used in mask application. foreach (int bufferSize in new int[] { 1, 3, 4, 5, 31, 32, 33, 125, 126, 127, 128, ushort.MaxValue - 1, ushort.MaxValue, ushort.MaxValue + 1, ushort.MaxValue * 2 }) { byte[] sendBuffer = new byte[bufferSize]; rand.NextBytes(sendBuffer); await SendAsync(cws, new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Binary, true, ctsDefault.Token); byte[] receiveBuffer = new byte[bufferSize]; int totalReceived = 0; while (true) { WebSocketReceiveResult recvResult = await ReceiveAsync( cws, new ArraySegment<byte>(receiveBuffer, totalReceived, receiveBuffer.Length - totalReceived), ctsDefault.Token); Assert.InRange(recvResult.Count, 0, receiveBuffer.Length - totalReceived); totalReceived += recvResult.Count; if (recvResult.EndOfMessage) break; } Assert.Equal(receiveBuffer.Length, totalReceived); Assert.Equal<byte>(sendBuffer, receiveBuffer); } await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "SendReceive_VaryingLengthBuffers_Success", ctsDefault.Token); } } [OuterLoop("Uses external servers")] [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task SendReceive_Concurrent_Success(Uri server) { using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds); byte[] receiveBuffer = new byte[10]; byte[] sendBuffer = new byte[10]; for (int i = 0; i < sendBuffer.Length; i++) { sendBuffer[i] = (byte)i; } for (int i = 0; i < sendBuffer.Length; i++) { Task<WebSocketReceiveResult> receive = ReceiveAsync(cws, new ArraySegment<byte>(receiveBuffer, receiveBuffer.Length - i - 1, 1), ctsDefault.Token); Task send = SendAsync(cws, new ArraySegment<byte>(sendBuffer, i, 1), WebSocketMessageType.Binary, true, ctsDefault.Token); await Task.WhenAll(receive, send); Assert.Equal(1, receive.Result.Count); } await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "SendReceive_VaryingLengthBuffers_Success", ctsDefault.Token); Array.Reverse(receiveBuffer); Assert.Equal<byte>(sendBuffer, receiveBuffer); } } [OuterLoop("Uses external servers")] [ConditionalFact(nameof(WebSocketsSupported))] public async Task SendReceive_ConnectionClosedPrematurely_ReceiveAsyncFailsAndWebSocketStateUpdated() { var options = new LoopbackServer.Options { WebSocketEndpoint = true }; Func<ClientWebSocket, LoopbackServer, Uri, Task> connectToServerThatAbortsConnection = async (clientSocket, server, url) => { var pendingReceiveAsyncPosted = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); // Start listening for incoming connections on the server side. Task acceptTask = server.AcceptConnectionAsync(async connection => { // Complete the WebSocket upgrade. After this is done, the client-side ConnectAsync should complete. Assert.NotNull(await LoopbackHelper.WebSocketHandshakeAsync(connection)); // Wait for client-side ConnectAsync to complete and for a pending ReceiveAsync to be posted. await pendingReceiveAsyncPosted.Task.TimeoutAfter(TimeOutMilliseconds); // Close the underlying connection prematurely (without sending a WebSocket Close frame). connection.Socket.Shutdown(SocketShutdown.Both); connection.Socket.Close(); }); // Initiate a connection attempt. var cts = new CancellationTokenSource(TimeOutMilliseconds); await clientSocket.ConnectAsync(url, cts.Token); // Post a pending ReceiveAsync before the TCP connection is torn down. var recvBuffer = new byte[100]; var recvSegment = new ArraySegment<byte>(recvBuffer); Task pendingReceiveAsync = ReceiveAsync(clientSocket, recvSegment, cts.Token); pendingReceiveAsyncPosted.SetResult(true); // Wait for the server to close the underlying connection. await acceptTask.WithCancellation(cts.Token); WebSocketException pendingReceiveException = await Assert.ThrowsAsync<WebSocketException>(() => pendingReceiveAsync); Assert.Equal(WebSocketError.ConnectionClosedPrematurely, pendingReceiveException.WebSocketErrorCode); if (PlatformDetection.IsInAppContainer) { const uint WININET_E_CONNECTION_ABORTED = 0x80072EFE; Assert.NotNull(pendingReceiveException.InnerException); Assert.Equal(WININET_E_CONNECTION_ABORTED, (uint)pendingReceiveException.InnerException.HResult); } WebSocketException newReceiveException = await Assert.ThrowsAsync<WebSocketException>(() => ReceiveAsync(clientSocket, recvSegment, cts.Token)); Assert.Equal( ResourceHelper.GetExceptionMessage("net_WebSockets_InvalidState", "Aborted", "Open, CloseSent"), newReceiveException.Message); Assert.Equal(WebSocketState.Aborted, clientSocket.State); Assert.Null(clientSocket.CloseStatus); }; await LoopbackServer.CreateServerAsync(async (server, url) => { using (ClientWebSocket clientSocket = new ClientWebSocket()) { await connectToServerThatAbortsConnection(clientSocket, server, url); } }, options); } [OuterLoop("Uses external servers")] [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task ZeroByteReceive_CompletesWhenDataAvailable(Uri server) { using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var rand = new Random(); var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds); // Do a 0-byte receive. It shouldn't complete yet. Task<WebSocketReceiveResult> t = ReceiveAsync(cws, new ArraySegment<byte>(Array.Empty<byte>()), ctsDefault.Token); Assert.False(t.IsCompleted); // Send a packet to the echo server. await SendAsync(cws, new ArraySegment<byte>(new byte[1] { 42 }), WebSocketMessageType.Binary, true, ctsDefault.Token); // Now the 0-byte receive should complete, but without reading any data. WebSocketReceiveResult r = await t; Assert.Equal(WebSocketMessageType.Binary, r.MessageType); Assert.Equal(0, r.Count); Assert.False(r.EndOfMessage); // Now do a receive to get the payload. var receiveBuffer = new byte[1]; t = ReceiveAsync(cws, new ArraySegment<byte>(receiveBuffer), ctsDefault.Token); Assert.Equal(TaskStatus.RanToCompletion, t.Status); r = await t; Assert.Equal(WebSocketMessageType.Binary, r.MessageType); Assert.Equal(1, r.Count); Assert.True(r.EndOfMessage); Assert.Equal(42, receiveBuffer[0]); // Clean up. await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, nameof(ZeroByteReceive_CompletesWhenDataAvailable), ctsDefault.Token); } } } }
// Copyright 2017, Google LLC All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using Google.Api; using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Cloud.Logging.V2; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.Logging.V2.Snippets { /// <summary>Generated snippets</summary> public class GeneratedLoggingServiceV2ClientSnippets { /// <summary>Snippet for DeleteLogAsync</summary> public async Task DeleteLogAsync() { // Snippet: DeleteLogAsync(LogNameOneof,CallSettings) // Additional: DeleteLogAsync(LogNameOneof,CancellationToken) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) LogNameOneof logName = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")); // Make the request await loggingServiceV2Client.DeleteLogAsync(logName); // End snippet } /// <summary>Snippet for DeleteLog</summary> public void DeleteLog() { // Snippet: DeleteLog(LogNameOneof,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) LogNameOneof logName = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")); // Make the request loggingServiceV2Client.DeleteLog(logName); // End snippet } /// <summary>Snippet for DeleteLogAsync</summary> public async Task DeleteLogAsync_RequestObject() { // Snippet: DeleteLogAsync(DeleteLogRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) DeleteLogRequest request = new DeleteLogRequest { LogNameAsLogNameOneof = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")), }; // Make the request await loggingServiceV2Client.DeleteLogAsync(request); // End snippet } /// <summary>Snippet for DeleteLog</summary> public void DeleteLog_RequestObject() { // Snippet: DeleteLog(DeleteLogRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) DeleteLogRequest request = new DeleteLogRequest { LogNameAsLogNameOneof = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")), }; // Make the request loggingServiceV2Client.DeleteLog(request); // End snippet } /// <summary>Snippet for WriteLogEntriesAsync</summary> public async Task WriteLogEntriesAsync() { // Snippet: WriteLogEntriesAsync(LogNameOneof,MonitoredResource,IDictionary<string, string>,IEnumerable<LogEntry>,CallSettings) // Additional: WriteLogEntriesAsync(LogNameOneof,MonitoredResource,IDictionary<string, string>,IEnumerable<LogEntry>,CancellationToken) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) LogNameOneof logName = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")); MonitoredResource resource = new MonitoredResource(); IDictionary<string, string> labels = new Dictionary<string, string>(); IEnumerable<LogEntry> entries = new List<LogEntry>(); // Make the request WriteLogEntriesResponse response = await loggingServiceV2Client.WriteLogEntriesAsync(logName, resource, labels, entries); // End snippet } /// <summary>Snippet for WriteLogEntries</summary> public void WriteLogEntries() { // Snippet: WriteLogEntries(LogNameOneof,MonitoredResource,IDictionary<string, string>,IEnumerable<LogEntry>,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) LogNameOneof logName = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")); MonitoredResource resource = new MonitoredResource(); IDictionary<string, string> labels = new Dictionary<string, string>(); IEnumerable<LogEntry> entries = new List<LogEntry>(); // Make the request WriteLogEntriesResponse response = loggingServiceV2Client.WriteLogEntries(logName, resource, labels, entries); // End snippet } /// <summary>Snippet for WriteLogEntriesAsync</summary> public async Task WriteLogEntriesAsync_RequestObject() { // Snippet: WriteLogEntriesAsync(WriteLogEntriesRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) WriteLogEntriesRequest request = new WriteLogEntriesRequest { Entries = { }, }; // Make the request WriteLogEntriesResponse response = await loggingServiceV2Client.WriteLogEntriesAsync(request); // End snippet } /// <summary>Snippet for WriteLogEntries</summary> public void WriteLogEntries_RequestObject() { // Snippet: WriteLogEntries(WriteLogEntriesRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) WriteLogEntriesRequest request = new WriteLogEntriesRequest { Entries = { }, }; // Make the request WriteLogEntriesResponse response = loggingServiceV2Client.WriteLogEntries(request); // End snippet } /// <summary>Snippet for ListLogEntriesAsync</summary> public async Task ListLogEntriesAsync() { // Snippet: ListLogEntriesAsync(IEnumerable<string>,string,string,string,int?,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) IEnumerable<string> resourceNames = new List<string>(); string filter = ""; string orderBy = ""; // Make the request PagedAsyncEnumerable<ListLogEntriesResponse, LogEntry> response = loggingServiceV2Client.ListLogEntriesAsync(resourceNames, filter, orderBy); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((LogEntry item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListLogEntriesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (LogEntry item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<LogEntry> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (LogEntry item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListLogEntries</summary> public void ListLogEntries() { // Snippet: ListLogEntries(IEnumerable<string>,string,string,string,int?,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) IEnumerable<string> resourceNames = new List<string>(); string filter = ""; string orderBy = ""; // Make the request PagedEnumerable<ListLogEntriesResponse, LogEntry> response = loggingServiceV2Client.ListLogEntries(resourceNames, filter, orderBy); // Iterate over all response items, lazily performing RPCs as required foreach (LogEntry item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListLogEntriesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (LogEntry item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<LogEntry> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (LogEntry item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListLogEntriesAsync</summary> public async Task ListLogEntriesAsync_RequestObject() { // Snippet: ListLogEntriesAsync(ListLogEntriesRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) ListLogEntriesRequest request = new ListLogEntriesRequest { ResourceNames = { }, }; // Make the request PagedAsyncEnumerable<ListLogEntriesResponse, LogEntry> response = loggingServiceV2Client.ListLogEntriesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((LogEntry item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListLogEntriesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (LogEntry item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<LogEntry> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (LogEntry item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListLogEntries</summary> public void ListLogEntries_RequestObject() { // Snippet: ListLogEntries(ListLogEntriesRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) ListLogEntriesRequest request = new ListLogEntriesRequest { ResourceNames = { }, }; // Make the request PagedEnumerable<ListLogEntriesResponse, LogEntry> response = loggingServiceV2Client.ListLogEntries(request); // Iterate over all response items, lazily performing RPCs as required foreach (LogEntry item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListLogEntriesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (LogEntry item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<LogEntry> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (LogEntry item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListMonitoredResourceDescriptorsAsync</summary> public async Task ListMonitoredResourceDescriptorsAsync_RequestObject() { // Snippet: ListMonitoredResourceDescriptorsAsync(ListMonitoredResourceDescriptorsRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) ListMonitoredResourceDescriptorsRequest request = new ListMonitoredResourceDescriptorsRequest(); // Make the request PagedAsyncEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> response = loggingServiceV2Client.ListMonitoredResourceDescriptorsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((MonitoredResourceDescriptor item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListMonitoredResourceDescriptorsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (MonitoredResourceDescriptor item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<MonitoredResourceDescriptor> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (MonitoredResourceDescriptor item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListMonitoredResourceDescriptors</summary> public void ListMonitoredResourceDescriptors_RequestObject() { // Snippet: ListMonitoredResourceDescriptors(ListMonitoredResourceDescriptorsRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) ListMonitoredResourceDescriptorsRequest request = new ListMonitoredResourceDescriptorsRequest(); // Make the request PagedEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> response = loggingServiceV2Client.ListMonitoredResourceDescriptors(request); // Iterate over all response items, lazily performing RPCs as required foreach (MonitoredResourceDescriptor item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListMonitoredResourceDescriptorsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (MonitoredResourceDescriptor item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<MonitoredResourceDescriptor> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (MonitoredResourceDescriptor item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListLogsAsync</summary> public async Task ListLogsAsync() { // Snippet: ListLogsAsync(ParentNameOneof,string,int?,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) ParentNameOneof parent = ParentNameOneof.From(new ProjectName("[PROJECT]")); // Make the request PagedAsyncEnumerable<ListLogsResponse, string> response = loggingServiceV2Client.ListLogsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((string item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListLogsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (string item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<string> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (string item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListLogs</summary> public void ListLogs() { // Snippet: ListLogs(ParentNameOneof,string,int?,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) ParentNameOneof parent = ParentNameOneof.From(new ProjectName("[PROJECT]")); // Make the request PagedEnumerable<ListLogsResponse, string> response = loggingServiceV2Client.ListLogs(parent); // Iterate over all response items, lazily performing RPCs as required foreach (string item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListLogsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (string item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<string> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (string item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListLogsAsync</summary> public async Task ListLogsAsync_RequestObject() { // Snippet: ListLogsAsync(ListLogsRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) ListLogsRequest request = new ListLogsRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), }; // Make the request PagedAsyncEnumerable<ListLogsResponse, string> response = loggingServiceV2Client.ListLogsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((string item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListLogsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (string item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<string> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (string item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListLogs</summary> public void ListLogs_RequestObject() { // Snippet: ListLogs(ListLogsRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) ListLogsRequest request = new ListLogsRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), }; // Make the request PagedEnumerable<ListLogsResponse, string> response = loggingServiceV2Client.ListLogs(request); // Iterate over all response items, lazily performing RPCs as required foreach (string item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListLogsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (string item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<string> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (string item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Collections; using System.Text; using System.Diagnostics; using System.Xml.Schema; using System.Xml.XPath; using MS.Internal.Xml.XPath; using System.Globalization; namespace System.Xml { // Represents a single node in the document. [DebuggerDisplay("{debuggerDisplayProxy}")] public abstract class XmlNode : ICloneable, IEnumerable, IXPathNavigable { internal XmlNode parentNode; //this pointer is reused to save the userdata information, need to prevent internal user access the pointer directly. internal XmlNode() { } internal XmlNode(XmlDocument doc) { if (doc == null) throw new ArgumentException(SR.Xdom_Node_Null_Doc); this.parentNode = doc; } public virtual XPathNavigator CreateNavigator() { XmlDocument thisAsDoc = this as XmlDocument; if (thisAsDoc != null) { return thisAsDoc.CreateNavigator(this); } XmlDocument doc = OwnerDocument; Debug.Assert(doc != null); return doc.CreateNavigator(this); } // Selects the first node that matches the xpath expression public XmlNode SelectSingleNode(string xpath) { XmlNodeList list = SelectNodes(xpath); // SelectNodes returns null for certain node types return list != null ? list[0] : null; } // Selects the first node that matches the xpath expression and given namespace context. public XmlNode SelectSingleNode(string xpath, XmlNamespaceManager nsmgr) { XPathNavigator xn = (this).CreateNavigator(); //if the method is called on node types like DocType, Entity, XmlDeclaration, //the navigator returned is null. So just return null from here for those node types. if (xn == null) return null; XPathExpression exp = xn.Compile(xpath); exp.SetContext(nsmgr); return new XPathNodeList(xn.Select(exp))[0]; } // Selects all nodes that match the xpath expression public XmlNodeList SelectNodes(string xpath) { XPathNavigator n = (this).CreateNavigator(); //if the method is called on node types like DocType, Entity, XmlDeclaration, //the navigator returned is null. So just return null from here for those node types. if (n == null) return null; return new XPathNodeList(n.Select(xpath)); } // Selects all nodes that match the xpath expression and given namespace context. public XmlNodeList SelectNodes(string xpath, XmlNamespaceManager nsmgr) { XPathNavigator xn = (this).CreateNavigator(); //if the method is called on node types like DocType, Entity, XmlDeclaration, //the navigator returned is null. So just return null from here for those node types. if (xn == null) return null; XPathExpression exp = xn.Compile(xpath); exp.SetContext(nsmgr); return new XPathNodeList(xn.Select(exp)); } // Gets the name of the node. public abstract string Name { get; } // Gets or sets the value of the node. public virtual string Value { get { return null; } set { throw new InvalidOperationException(SR.Format(CultureInfo.InvariantCulture, SR.Xdom_Node_SetVal, NodeType.ToString())); } } // Gets the type of the current node. public abstract XmlNodeType NodeType { get; } // Gets the parent of this node (for nodes that can have parents). public virtual XmlNode ParentNode { get { Debug.Assert(parentNode != null); if (parentNode.NodeType != XmlNodeType.Document) { return parentNode; } // Linear lookup through the children of the document XmlLinkedNode firstChild = parentNode.FirstChild as XmlLinkedNode; if (firstChild != null) { XmlLinkedNode node = firstChild; do { if (node == this) { return parentNode; } node = node.next; } while (node != null && node != firstChild); } return null; } } // Gets all children of this node. public virtual XmlNodeList ChildNodes { get { return new XmlChildNodes(this); } } // Gets the node immediately preceding this node. public virtual XmlNode PreviousSibling { get { return null; } } // Gets the node immediately following this node. public virtual XmlNode NextSibling { get { return null; } } // Gets a XmlAttributeCollection containing the attributes // of this node. public virtual XmlAttributeCollection Attributes { get { return null; } } // Gets the XmlDocument that contains this node. public virtual XmlDocument OwnerDocument { get { Debug.Assert(parentNode != null); if (parentNode.NodeType == XmlNodeType.Document) return (XmlDocument)parentNode; return parentNode.OwnerDocument; } } // Gets the first child of this node. public virtual XmlNode FirstChild { get { XmlLinkedNode linkedNode = LastNode; if (linkedNode != null) return linkedNode.next; return null; } } // Gets the last child of this node. public virtual XmlNode LastChild { get { return LastNode; } } internal virtual bool IsContainer { get { return false; } } internal virtual XmlLinkedNode LastNode { get { return null; } set { } } internal bool AncestorNode(XmlNode node) { XmlNode n = this.ParentNode; while (n != null && n != this) { if (n == node) return true; n = n.ParentNode; } return false; } //trace to the top to find out its parent node. internal bool IsConnected() { XmlNode parent = ParentNode; while (parent != null && !(parent.NodeType == XmlNodeType.Document)) parent = parent.ParentNode; return parent != null; } // Inserts the specified node immediately before the specified reference node. public virtual XmlNode InsertBefore(XmlNode newChild, XmlNode refChild) { if (this == newChild || AncestorNode(newChild)) throw new ArgumentException(SR.Xdom_Node_Insert_Child); if (refChild == null) return AppendChild(newChild); if (!IsContainer) throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain); if (refChild.ParentNode != this) throw new ArgumentException(SR.Xdom_Node_Insert_Path); if (newChild == refChild) return newChild; XmlDocument childDoc = newChild.OwnerDocument; XmlDocument thisDoc = OwnerDocument; if (childDoc != null && childDoc != thisDoc && childDoc != this) throw new ArgumentException(SR.Xdom_Node_Insert_Context); if (!CanInsertBefore(newChild, refChild)) throw new InvalidOperationException(SR.Xdom_Node_Insert_Location); if (newChild.ParentNode != null) newChild.ParentNode.RemoveChild(newChild); // special case for doc-fragment. if (newChild.NodeType == XmlNodeType.DocumentFragment) { XmlNode first = newChild.FirstChild; XmlNode node = first; if (node != null) { newChild.RemoveChild(node); InsertBefore(node, refChild); // insert the rest of the children after this one. InsertAfter(newChild, node); } return first; } if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType)) throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict); XmlLinkedNode newNode = (XmlLinkedNode)newChild; XmlLinkedNode refNode = (XmlLinkedNode)refChild; string newChildValue = newChild.Value; XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert); if (args != null) BeforeEvent(args); if (refNode == FirstChild) { newNode.next = refNode; LastNode.next = newNode; newNode.SetParent(this); if (newNode.IsText) { if (refNode.IsText) { NestTextNodes(newNode, refNode); } } } else { XmlLinkedNode prevNode = (XmlLinkedNode)refNode.PreviousSibling; newNode.next = refNode; prevNode.next = newNode; newNode.SetParent(this); if (prevNode.IsText) { if (newNode.IsText) { NestTextNodes(prevNode, newNode); if (refNode.IsText) { NestTextNodes(newNode, refNode); } } else { if (refNode.IsText) { UnnestTextNodes(prevNode, refNode); } } } else { if (newNode.IsText) { if (refNode.IsText) { NestTextNodes(newNode, refNode); } } } } if (args != null) AfterEvent(args); return newNode; } // Inserts the specified node immediately after the specified reference node. public virtual XmlNode InsertAfter(XmlNode newChild, XmlNode refChild) { if (this == newChild || AncestorNode(newChild)) throw new ArgumentException(SR.Xdom_Node_Insert_Child); if (refChild == null) return PrependChild(newChild); if (!IsContainer) throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain); if (refChild.ParentNode != this) throw new ArgumentException(SR.Xdom_Node_Insert_Path); if (newChild == refChild) return newChild; XmlDocument childDoc = newChild.OwnerDocument; XmlDocument thisDoc = OwnerDocument; if (childDoc != null && childDoc != thisDoc && childDoc != this) throw new ArgumentException(SR.Xdom_Node_Insert_Context); if (!CanInsertAfter(newChild, refChild)) throw new InvalidOperationException(SR.Xdom_Node_Insert_Location); if (newChild.ParentNode != null) newChild.ParentNode.RemoveChild(newChild); // special case for doc-fragment. if (newChild.NodeType == XmlNodeType.DocumentFragment) { XmlNode last = refChild; XmlNode first = newChild.FirstChild; XmlNode node = first; while (node != null) { XmlNode next = node.NextSibling; newChild.RemoveChild(node); InsertAfter(node, last); last = node; node = next; } return first; } if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType)) throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict); XmlLinkedNode newNode = (XmlLinkedNode)newChild; XmlLinkedNode refNode = (XmlLinkedNode)refChild; string newChildValue = newChild.Value; XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert); if (args != null) BeforeEvent(args); if (refNode == LastNode) { newNode.next = refNode.next; refNode.next = newNode; LastNode = newNode; newNode.SetParent(this); if (refNode.IsText) { if (newNode.IsText) { NestTextNodes(refNode, newNode); } } } else { XmlLinkedNode nextNode = refNode.next; newNode.next = nextNode; refNode.next = newNode; newNode.SetParent(this); if (refNode.IsText) { if (newNode.IsText) { NestTextNodes(refNode, newNode); if (nextNode.IsText) { NestTextNodes(newNode, nextNode); } } else { if (nextNode.IsText) { UnnestTextNodes(refNode, nextNode); } } } else { if (newNode.IsText) { if (nextNode.IsText) { NestTextNodes(newNode, nextNode); } } } } if (args != null) AfterEvent(args); return newNode; } // Replaces the child node oldChild with newChild node. public virtual XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild) { XmlNode nextNode = oldChild.NextSibling; RemoveChild(oldChild); XmlNode node = InsertBefore(newChild, nextNode); return oldChild; } // Removes specified child node. public virtual XmlNode RemoveChild(XmlNode oldChild) { if (!IsContainer) throw new InvalidOperationException(SR.Xdom_Node_Remove_Contain); if (oldChild.ParentNode != this) throw new ArgumentException(SR.Xdom_Node_Remove_Child); XmlLinkedNode oldNode = (XmlLinkedNode)oldChild; string oldNodeValue = oldNode.Value; XmlNodeChangedEventArgs args = GetEventArgs(oldNode, this, null, oldNodeValue, oldNodeValue, XmlNodeChangedAction.Remove); if (args != null) BeforeEvent(args); XmlLinkedNode lastNode = LastNode; if (oldNode == FirstChild) { if (oldNode == lastNode) { LastNode = null; oldNode.next = null; oldNode.SetParent(null); } else { XmlLinkedNode nextNode = oldNode.next; if (nextNode.IsText) { if (oldNode.IsText) { UnnestTextNodes(oldNode, nextNode); } } lastNode.next = nextNode; oldNode.next = null; oldNode.SetParent(null); } } else { if (oldNode == lastNode) { XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling; prevNode.next = oldNode.next; LastNode = prevNode; oldNode.next = null; oldNode.SetParent(null); } else { XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling; XmlLinkedNode nextNode = oldNode.next; if (nextNode.IsText) { if (prevNode.IsText) { NestTextNodes(prevNode, nextNode); } else { if (oldNode.IsText) { UnnestTextNodes(oldNode, nextNode); } } } prevNode.next = nextNode; oldNode.next = null; oldNode.SetParent(null); } } if (args != null) AfterEvent(args); return oldChild; } // Adds the specified node to the beginning of the list of children of this node. public virtual XmlNode PrependChild(XmlNode newChild) { return InsertBefore(newChild, FirstChild); } // Adds the specified node to the end of the list of children of this node. public virtual XmlNode AppendChild(XmlNode newChild) { XmlDocument thisDoc = OwnerDocument; if (thisDoc == null) { thisDoc = this as XmlDocument; } if (!IsContainer) throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain); if (this == newChild || AncestorNode(newChild)) throw new ArgumentException(SR.Xdom_Node_Insert_Child); if (newChild.ParentNode != null) newChild.ParentNode.RemoveChild(newChild); XmlDocument childDoc = newChild.OwnerDocument; if (childDoc != null && childDoc != thisDoc && childDoc != this) throw new ArgumentException(SR.Xdom_Node_Insert_Context); // special case for doc-fragment. if (newChild.NodeType == XmlNodeType.DocumentFragment) { XmlNode first = newChild.FirstChild; XmlNode node = first; while (node != null) { XmlNode next = node.NextSibling; newChild.RemoveChild(node); AppendChild(node); node = next; } return first; } if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType)) throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict); if (!CanInsertAfter(newChild, LastChild)) throw new InvalidOperationException(SR.Xdom_Node_Insert_Location); string newChildValue = newChild.Value; XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert); if (args != null) BeforeEvent(args); XmlLinkedNode refNode = LastNode; XmlLinkedNode newNode = (XmlLinkedNode)newChild; if (refNode == null) { newNode.next = newNode; LastNode = newNode; newNode.SetParent(this); } else { newNode.next = refNode.next; refNode.next = newNode; LastNode = newNode; newNode.SetParent(this); if (refNode.IsText) { if (newNode.IsText) { NestTextNodes(refNode, newNode); } } } if (args != null) AfterEvent(args); return newNode; } //the function is provided only at Load time to speed up Load process internal virtual XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) { XmlNodeChangedEventArgs args = doc.GetInsertEventArgsForLoad(newChild, this); if (args != null) doc.BeforeEvent(args); XmlLinkedNode refNode = LastNode; XmlLinkedNode newNode = (XmlLinkedNode)newChild; if (refNode == null) { newNode.next = newNode; LastNode = newNode; newNode.SetParentForLoad(this); } else { newNode.next = refNode.next; refNode.next = newNode; LastNode = newNode; if (refNode.IsText && newNode.IsText) { NestTextNodes(refNode, newNode); } else { newNode.SetParentForLoad(this); } } if (args != null) doc.AfterEvent(args); return newNode; } internal virtual bool IsValidChildType(XmlNodeType type) { return false; } internal virtual bool CanInsertBefore(XmlNode newChild, XmlNode refChild) { return true; } internal virtual bool CanInsertAfter(XmlNode newChild, XmlNode refChild) { return true; } // Gets a value indicating whether this node has any child nodes. public virtual bool HasChildNodes { get { return LastNode != null; } } // Creates a duplicate of this node. public abstract XmlNode CloneNode(bool deep); internal virtual void CopyChildren(XmlDocument doc, XmlNode container, bool deep) { for (XmlNode child = container.FirstChild; child != null; child = child.NextSibling) { AppendChildForLoad(child.CloneNode(deep), doc); } } // DOM Level 2 // Puts all XmlText nodes in the full depth of the sub-tree // underneath this XmlNode into a "normal" form where only // markup (e.g., tags, comments, processing instructions, CDATA sections, // and entity references) separates XmlText nodes, that is, there // are no adjacent XmlText nodes. public virtual void Normalize() { XmlNode firstChildTextLikeNode = null; StringBuilder sb = StringBuilderCache.Acquire(); for (XmlNode crtChild = this.FirstChild; crtChild != null;) { XmlNode nextChild = crtChild.NextSibling; switch (crtChild.NodeType) { case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: { sb.Append(crtChild.Value); XmlNode winner = NormalizeWinner(firstChildTextLikeNode, crtChild); if (winner == firstChildTextLikeNode) { this.RemoveChild(crtChild); } else { if (firstChildTextLikeNode != null) this.RemoveChild(firstChildTextLikeNode); firstChildTextLikeNode = crtChild; } break; } case XmlNodeType.Element: { crtChild.Normalize(); goto default; } default: { if (firstChildTextLikeNode != null) { firstChildTextLikeNode.Value = sb.ToString(); firstChildTextLikeNode = null; } sb.Remove(0, sb.Length); break; } } crtChild = nextChild; } if (firstChildTextLikeNode != null && sb.Length > 0) firstChildTextLikeNode.Value = sb.ToString(); StringBuilderCache.Release(sb); } private XmlNode NormalizeWinner(XmlNode firstNode, XmlNode secondNode) { //first node has the priority if (firstNode == null) return secondNode; Debug.Assert(firstNode.NodeType == XmlNodeType.Text || firstNode.NodeType == XmlNodeType.SignificantWhitespace || firstNode.NodeType == XmlNodeType.Whitespace || secondNode.NodeType == XmlNodeType.Text || secondNode.NodeType == XmlNodeType.SignificantWhitespace || secondNode.NodeType == XmlNodeType.Whitespace); if (firstNode.NodeType == XmlNodeType.Text) return firstNode; if (secondNode.NodeType == XmlNodeType.Text) return secondNode; if (firstNode.NodeType == XmlNodeType.SignificantWhitespace) return firstNode; if (secondNode.NodeType == XmlNodeType.SignificantWhitespace) return secondNode; if (firstNode.NodeType == XmlNodeType.Whitespace) return firstNode; if (secondNode.NodeType == XmlNodeType.Whitespace) return secondNode; Debug.Assert(true, "shouldn't have fall through here."); return null; } // Test if the DOM implementation implements a specific feature. public virtual bool Supports(string feature, string version) { if (string.Equals("XML", feature, StringComparison.OrdinalIgnoreCase)) { if (version == null || version == "1.0" || version == "2.0") return true; } return false; } // Gets the namespace URI of this node. public virtual string NamespaceURI { get { return string.Empty; } } // Gets or sets the namespace prefix of this node. public virtual string Prefix { get { return string.Empty; } set { } } // Gets the name of the node without the namespace prefix. public abstract string LocalName { get; } // Microsoft extensions // Gets a value indicating whether the node is read-only. public virtual bool IsReadOnly { get { XmlDocument doc = OwnerDocument; return HasReadOnlyParent(this); } } internal static bool HasReadOnlyParent(XmlNode n) { while (n != null) { switch (n.NodeType) { case XmlNodeType.EntityReference: case XmlNodeType.Entity: return true; case XmlNodeType.Attribute: n = ((XmlAttribute)n).OwnerElement; break; default: n = n.ParentNode; break; } } return false; } // Creates a duplicate of this node. public virtual XmlNode Clone() { return this.CloneNode(true); } object ICloneable.Clone() { return this.CloneNode(true); } // Provides a simple ForEach-style iteration over the // collection of nodes in this XmlNamedNodeMap. IEnumerator IEnumerable.GetEnumerator() { return new XmlChildEnumerator(this); } public IEnumerator GetEnumerator() { return new XmlChildEnumerator(this); } private void AppendChildText(StringBuilder builder) { for (XmlNode child = FirstChild; child != null; child = child.NextSibling) { if (child.FirstChild == null) { if (child.NodeType == XmlNodeType.Text || child.NodeType == XmlNodeType.CDATA || child.NodeType == XmlNodeType.Whitespace || child.NodeType == XmlNodeType.SignificantWhitespace) builder.Append(child.InnerText); } else { child.AppendChildText(builder); } } } // Gets or sets the concatenated values of the node and // all its children. public virtual string InnerText { get { XmlNode fc = FirstChild; if (fc == null) { return string.Empty; } if (fc.NextSibling == null) { XmlNodeType nodeType = fc.NodeType; switch (nodeType) { case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: return fc.Value; } } StringBuilder builder = StringBuilderCache.Acquire(); AppendChildText(builder); return StringBuilderCache.GetStringAndRelease(builder); } set { XmlNode firstChild = FirstChild; if (firstChild != null //there is one child && firstChild.NextSibling == null // and exactly one && firstChild.NodeType == XmlNodeType.Text)//which is a text node { //this branch is for perf reason and event fired when TextNode.Value is changed firstChild.Value = value; } else { RemoveAll(); AppendChild(OwnerDocument.CreateTextNode(value)); } } } // Gets the markup representing this node and all its children. public virtual string OuterXml { get { StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); XmlDOMTextWriter xw = new XmlDOMTextWriter(sw); try { WriteTo(xw); } finally { xw.Close(); } return sw.ToString(); } } // Gets or sets the markup representing just the children of this node. public virtual string InnerXml { get { StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); XmlDOMTextWriter xw = new XmlDOMTextWriter(sw); try { WriteContentTo(xw); } finally { xw.Close(); } return sw.ToString(); } set { throw new InvalidOperationException(SR.Xdom_Set_InnerXml); } } public virtual IXmlSchemaInfo SchemaInfo { get { return XmlDocument.NotKnownSchemaInfo; } } public virtual string BaseURI { get { XmlNode curNode = this.ParentNode; //save one while loop since if going to here, the nodetype of this node can't be document, entity and entityref while (curNode != null) { XmlNodeType nt = curNode.NodeType; //EntityReference's children come from the dtd where they are defined. //we need to investigate the same thing for entity's children if they are defined in an external dtd file. if (nt == XmlNodeType.EntityReference) return ((XmlEntityReference)curNode).ChildBaseURI; if (nt == XmlNodeType.Document || nt == XmlNodeType.Entity || nt == XmlNodeType.Attribute) return curNode.BaseURI; curNode = curNode.ParentNode; } return string.Empty; } } // Saves the current node to the specified XmlWriter. public abstract void WriteTo(XmlWriter w); // Saves all the children of the node to the specified XmlWriter. public abstract void WriteContentTo(XmlWriter w); // Removes all the children and/or attributes // of the current node. public virtual void RemoveAll() { XmlNode child = FirstChild; XmlNode sibling = null; while (child != null) { sibling = child.NextSibling; RemoveChild(child); child = sibling; } } internal XmlDocument Document { get { if (NodeType == XmlNodeType.Document) return (XmlDocument)this; return OwnerDocument; } } // Looks up the closest xmlns declaration for the given // prefix that is in scope for the current node and returns // the namespace URI in the declaration. public virtual string GetNamespaceOfPrefix(string prefix) { string namespaceName = GetNamespaceOfPrefixStrict(prefix); return namespaceName != null ? namespaceName : string.Empty; } internal string GetNamespaceOfPrefixStrict(string prefix) { XmlDocument doc = Document; if (doc != null) { prefix = doc.NameTable.Get(prefix); if (prefix == null) return null; XmlNode node = this; while (node != null) { if (node.NodeType == XmlNodeType.Element) { XmlElement elem = (XmlElement)node; if (elem.HasAttributes) { XmlAttributeCollection attrs = elem.Attributes; if (prefix.Length == 0) { for (int iAttr = 0; iAttr < attrs.Count; iAttr++) { XmlAttribute attr = attrs[iAttr]; if (attr.Prefix.Length == 0) { if (Ref.Equal(attr.LocalName, doc.strXmlns)) { return attr.Value; // found xmlns } } } } else { for (int iAttr = 0; iAttr < attrs.Count; iAttr++) { XmlAttribute attr = attrs[iAttr]; if (Ref.Equal(attr.Prefix, doc.strXmlns)) { if (Ref.Equal(attr.LocalName, prefix)) { return attr.Value; // found xmlns:prefix } } else if (Ref.Equal(attr.Prefix, prefix)) { return attr.NamespaceURI; // found prefix:attr } } } } if (Ref.Equal(node.Prefix, prefix)) { return node.NamespaceURI; } node = node.ParentNode; } else if (node.NodeType == XmlNodeType.Attribute) { node = ((XmlAttribute)node).OwnerElement; } else { node = node.ParentNode; } } if (Ref.Equal(doc.strXml, prefix)) { // xmlns:xml return doc.strReservedXml; } else if (Ref.Equal(doc.strXmlns, prefix)) { // xmlns:xmlns return doc.strReservedXmlns; } } return null; } // Looks up the closest xmlns declaration for the given namespace // URI that is in scope for the current node and returns // the prefix defined in that declaration. public virtual string GetPrefixOfNamespace(string namespaceURI) { string prefix = GetPrefixOfNamespaceStrict(namespaceURI); return prefix != null ? prefix : string.Empty; } internal string GetPrefixOfNamespaceStrict(string namespaceURI) { XmlDocument doc = Document; if (doc != null) { namespaceURI = doc.NameTable.Add(namespaceURI); XmlNode node = this; while (node != null) { if (node.NodeType == XmlNodeType.Element) { XmlElement elem = (XmlElement)node; if (elem.HasAttributes) { XmlAttributeCollection attrs = elem.Attributes; for (int iAttr = 0; iAttr < attrs.Count; iAttr++) { XmlAttribute attr = attrs[iAttr]; if (attr.Prefix.Length == 0) { if (Ref.Equal(attr.LocalName, doc.strXmlns)) { if (attr.Value == namespaceURI) { return string.Empty; // found xmlns="namespaceURI" } } } else if (Ref.Equal(attr.Prefix, doc.strXmlns)) { if (attr.Value == namespaceURI) { return attr.LocalName; // found xmlns:prefix="namespaceURI" } } else if (Ref.Equal(attr.NamespaceURI, namespaceURI)) { return attr.Prefix; // found prefix:attr // with prefix bound to namespaceURI } } } if (Ref.Equal(node.NamespaceURI, namespaceURI)) { return node.Prefix; } node = node.ParentNode; } else if (node.NodeType == XmlNodeType.Attribute) { node = ((XmlAttribute)node).OwnerElement; } else { node = node.ParentNode; } } if (Ref.Equal(doc.strReservedXml, namespaceURI)) { // xmlns:xml return doc.strXml; } else if (Ref.Equal(doc.strReservedXmlns, namespaceURI)) { // xmlns:xmlns return doc.strXmlns; } } return null; } // Retrieves the first child element with the specified name. public virtual XmlElement this[string name] { get { for (XmlNode n = FirstChild; n != null; n = n.NextSibling) { if (n.NodeType == XmlNodeType.Element && n.Name == name) return (XmlElement)n; } return null; } } // Retrieves the first child element with the specified LocalName and // NamespaceURI. public virtual XmlElement this[string localname, string ns] { get { for (XmlNode n = FirstChild; n != null; n = n.NextSibling) { if (n.NodeType == XmlNodeType.Element && n.LocalName == localname && n.NamespaceURI == ns) return (XmlElement)n; } return null; } } internal virtual void SetParent(XmlNode node) { if (node == null) { this.parentNode = OwnerDocument; } else { this.parentNode = node; } } internal virtual void SetParentForLoad(XmlNode node) { this.parentNode = node; } internal static void SplitName(string name, out string prefix, out string localName) { int colonPos = name.IndexOf(':'); // ordinal compare if (-1 == colonPos || 0 == colonPos || name.Length - 1 == colonPos) { prefix = string.Empty; localName = name; } else { prefix = name.Substring(0, colonPos); localName = name.Substring(colonPos + 1); } } internal virtual XmlNode FindChild(XmlNodeType type) { for (XmlNode child = FirstChild; child != null; child = child.NextSibling) { if (child.NodeType == type) { return child; } } return null; } internal virtual XmlNodeChangedEventArgs GetEventArgs(XmlNode node, XmlNode oldParent, XmlNode newParent, string oldValue, string newValue, XmlNodeChangedAction action) { XmlDocument doc = OwnerDocument; if (doc != null) { if (!doc.IsLoading) { if (((newParent != null && newParent.IsReadOnly) || (oldParent != null && oldParent.IsReadOnly))) throw new InvalidOperationException(SR.Xdom_Node_Modify_ReadOnly); } return doc.GetEventArgs(node, oldParent, newParent, oldValue, newValue, action); } return null; } internal virtual void BeforeEvent(XmlNodeChangedEventArgs args) { if (args != null) OwnerDocument.BeforeEvent(args); } internal virtual void AfterEvent(XmlNodeChangedEventArgs args) { if (args != null) OwnerDocument.AfterEvent(args); } internal virtual XmlSpace XmlSpace { get { XmlNode node = this; XmlElement elem = null; do { elem = node as XmlElement; if (elem != null && elem.HasAttribute("xml:space")) { switch (XmlConvert.TrimString(elem.GetAttribute("xml:space"))) { case "default": return XmlSpace.Default; case "preserve": return XmlSpace.Preserve; default: //should we throw exception if value is otherwise? break; } } node = node.ParentNode; } while (node != null); return XmlSpace.None; } } internal virtual string XmlLang { get { XmlNode node = this; XmlElement elem = null; do { elem = node as XmlElement; if (elem != null) { if (elem.HasAttribute("xml:lang")) return elem.GetAttribute("xml:lang"); } node = node.ParentNode; } while (node != null); return string.Empty; } } internal virtual XPathNodeType XPNodeType { get { return (XPathNodeType)(-1); } } internal virtual string XPLocalName { get { return string.Empty; } } internal virtual string GetXPAttribute(string localName, string namespaceURI) { return string.Empty; } internal virtual bool IsText { get { return false; } } public virtual XmlNode PreviousText { get { return null; } } internal static void NestTextNodes(XmlNode prevNode, XmlNode nextNode) { Debug.Assert(prevNode.IsText); Debug.Assert(nextNode.IsText); nextNode.parentNode = prevNode; } internal static void UnnestTextNodes(XmlNode prevNode, XmlNode nextNode) { Debug.Assert(prevNode.IsText); Debug.Assert(nextNode.IsText); nextNode.parentNode = prevNode.ParentNode; } private object debuggerDisplayProxy { get { return new DebuggerDisplayXmlNodeProxy(this); } } [DebuggerDisplay("{ToString()}")] internal readonly struct DebuggerDisplayXmlNodeProxy { private readonly XmlNode _node; public DebuggerDisplayXmlNodeProxy(XmlNode node) { _node = node; } public override string ToString() { XmlNodeType nodeType = _node.NodeType; string result = nodeType.ToString(); switch (nodeType) { case XmlNodeType.Element: case XmlNodeType.EntityReference: result += ", Name=\"" + _node.Name + "\""; break; case XmlNodeType.Attribute: case XmlNodeType.ProcessingInstruction: result += ", Name=\"" + _node.Name + "\", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay(_node.Value) + "\""; break; case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.Comment: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.XmlDeclaration: result += ", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay(_node.Value) + "\""; break; case XmlNodeType.DocumentType: XmlDocumentType documentType = (XmlDocumentType)_node; result += ", Name=\"" + documentType.Name + "\", SYSTEM=\"" + documentType.SystemId + "\", PUBLIC=\"" + documentType.PublicId + "\", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay(documentType.InternalSubset) + "\""; break; default: break; } return result; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal abstract partial class AbstractAsynchronousTaggerProvider<TTag> { /// <summary> /// Handles the job of batching up change notifications so that don't spam the editor with too /// many update requests at a time. Updating the editor can even be paused and resumed at a /// later point if some feature doesn't want the editor changing while it performs some bit of /// work. /// </summary> private class BatchChangeNotifier : ForegroundThreadAffinitizedObject { private readonly ITextBuffer _subjectBuffer; /// <summary> /// If we get more than this many differences, then we just issue it as a single change /// notification. The number has been completely made up without any data to support it. /// /// Internal for testing purposes. /// </summary> internal const int CoalesceDifferenceCount = 10; /// <summary> /// The worker we use to do work on the appropriate background or foreground thread. /// </summary> private readonly IAsynchronousOperationListener _listener; private readonly IForegroundNotificationService _notificationService; /// <summary> /// We keep track of the last time we reported a span, so that if things have been idle for /// a while, we don't unnecessarily delay the reporting, but if things are busy, we'll start /// to throttle the notifications. /// </summary> private long _lastReportTick; // In general, we want IDE services to avoid reporting changes to the editor too rapidly. // When we do, we diminish performance by choking the UI thread with lots of update // operations. To help alleviate that, we don't immediately report changes to the UI. We // instead create a timer that will report the changes and we enqueue any pending updates to // a list that will be updated all at once once the timer actually runs. private bool _notificationRequestEnqueued; private readonly SortedDictionary<int, NormalizedSnapshotSpanCollection> _snapshotVersionToSpansMap = new SortedDictionary<int, NormalizedSnapshotSpanCollection>(); /// <summary> /// True if we are currently suppressing UI updates. While suppressed we still continue /// doing everything as normal, except we do not update the UI. Then, when we are no longer /// suppressed we will issue all pending UI notifications to the editor. During the time /// that we're suppressed we will respond to all GetTags requests with the tags we had /// before we were paused. /// </summary> public bool IsPaused { get; private set; } private int _lastPausedTime; private readonly Action<SnapshotSpan> _reportChangedSpan; public BatchChangeNotifier( ITextBuffer subjectBuffer, IAsynchronousOperationListener listener, IForegroundNotificationService notificationService, Action<SnapshotSpan> reportChangedSpan) { Contract.ThrowIfNull(reportChangedSpan); _subjectBuffer = subjectBuffer; _listener = listener; _notificationService = notificationService; _reportChangedSpan = reportChangedSpan; } public void Pause() { AssertIsForeground(); _lastPausedTime = Environment.TickCount; this.IsPaused = true; } public void Resume() { AssertIsForeground(); _lastPausedTime = Environment.TickCount; this.IsPaused = false; } private static readonly Func<int, NormalizedSnapshotSpanCollection> s_addFunction = _ => new NormalizedSnapshotSpanCollection(); internal void EnqueueChanges( NormalizedSnapshotSpanCollection changedSpans) { AssertIsForeground(); if (changedSpans.Count == 0) { return; } var snapshot = changedSpans.First().Snapshot; var version = snapshot.Version.VersionNumber; var currentSpans = _snapshotVersionToSpansMap.GetOrAdd(version, s_addFunction); var allSpans = NormalizedSnapshotSpanCollection.Union(currentSpans, changedSpans); _snapshotVersionToSpansMap[version] = allSpans; EnqueueNotificationRequest(TaggerDelay.NearImmediate); } // We may get a flurry of 'Notify' calls if we've enqueued a lot of work and it's now just // completed. Batch up all the notifications so we can tell the editor about them at the // same time. private void EnqueueNotificationRequest( TaggerDelay delay) { AssertIsForeground(); if (_notificationRequestEnqueued) { // we already have a pending task to update the UI. No need to do anything at this // point. return; } var currentTick = Environment.TickCount; if (Math.Abs(currentTick - _lastReportTick) > TaggerDelay.NearImmediate.ComputeTimeDelay(_subjectBuffer).TotalMilliseconds) { _lastReportTick = currentTick; this.NotifyEditor(); } else { // enqueue a task to update the UI with all the changed spans at some time in the // future. _notificationRequestEnqueued = true; // Note: this operation is uncancellable. We already updated our internal state in // RecomputeTags. We must eventually notify the editor about these changes so that the // UI reaches parity with our internal model. Also, if we cancel it, then // 'reportTagsScheduled' will stay 'true' forever and we'll never notify the UI. _notificationService.RegisterNotification(() => { AssertIsForeground(); // First, clear the flag. That way any new changes we hear about will enqueue a task // to run at a later point. _notificationRequestEnqueued = false; this.NotifyEditor(); }, (int)delay.ComputeTimeDelay(_subjectBuffer).TotalMilliseconds, _listener.BeginAsyncOperation("EnqueueNotificationRequest")); } } private void NotifyEditor() { AssertIsForeground(); // If we're currently suppressed, then just re-enqueue a request to update in the // future. if (this.IsPaused) { // TODO(cyrusn): Do we need to make this delay customizable? I don't think we do. // Pausing is only used for features we don't want to spam the user with (like // squiggles while the completion list is up. It's ok to have them appear 1.5 // seconds later once we become un-paused. if ((Environment.TickCount - _lastPausedTime) < TaggerConstants.IdleDelay) { EnqueueNotificationRequest(TaggerDelay.OnIdle); return; } } using (Logger.LogBlock(FunctionId.Tagger_BatchChangeNotifier_NotifyEditor, CancellationToken.None)) { // Go through and report the snapshots from oldest to newest. foreach (var snapshotAndSpans in _snapshotVersionToSpansMap) { var snapshot = snapshotAndSpans.Key; var normalizedSpans = snapshotAndSpans.Value; this.NotifyEditorNow(normalizedSpans); } } // Finally, clear out the collection so that we don't re-report spans. _snapshotVersionToSpansMap.Clear(); _lastReportTick = Environment.TickCount; // reset paused time _lastPausedTime = Environment.TickCount; } private void NotifyEditorNow(NormalizedSnapshotSpanCollection normalizedSpans) { this.AssertIsForeground(); using (Logger.LogBlock(FunctionId.Tagger_BatchChangeNotifier_NotifyEditorNow, CancellationToken.None)) { if (normalizedSpans.Count == 0) { return; } normalizedSpans = CoalesceSpans(normalizedSpans); // Don't use linq here. It's a hotspot. foreach (var span in normalizedSpans) { _reportChangedSpan(span); } } } internal static NormalizedSnapshotSpanCollection CoalesceSpans(NormalizedSnapshotSpanCollection normalizedSpans) { var snapshot = normalizedSpans.First().Snapshot; // Coalesce the spans if there are a lot of them. if (normalizedSpans.Count > CoalesceDifferenceCount) { // Spans are normalized. So to find the whole span we just go from the // start of the first span to the end of the last span. normalizedSpans = new NormalizedSnapshotSpanCollection(snapshot.GetSpanFromBounds( normalizedSpans.First().Start, normalizedSpans.Last().End)); } return normalizedSpans; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Versioning; using Moq; using NuGet.Test.Mocks; using Xunit; namespace NuGet.Test { public class PackageRepositoryTest { [Fact] public void FindByIdReturnsPackage() { // Arrange var repo = GetLocalRepository(); // Act var package = repo.FindPackage(packageId: "A"); // Assert Assert.NotNull(package); Assert.Equal("A", package.Id); } [Fact] public void FindByIdReturnsNullWhenPackageNotFound() { // Arrange var repo = GetLocalRepository(); // Act var package = repo.FindPackage(packageId: "X"); // Assert Assert.Null(package); } [Fact] public void FindByIdAndVersionReturnsPackage() { // Arrange var repo = GetRemoteRepository(); // Act var package = repo.FindPackage(packageId: "A", version: SemanticVersion.Parse("1.0")); // Assert Assert.NotNull(package); Assert.Equal("A", package.Id); Assert.Equal(SemanticVersion.Parse("1.0"), package.Version); } [Fact] public void FindByIdAndVersionReturnsNullWhenPackageNotFound() { // Arrange var repo = GetLocalRepository(); // Act var package1 = repo.FindPackage(packageId: "X", version: SemanticVersion.Parse("1.0")); var package2 = repo.FindPackage(packageId: "A", version: SemanticVersion.Parse("1.1")); // Assert Assert.Null(package1 ?? package2); } [Fact] public void FindByIdAndVersionRangeReturnsPackage() { // Arrange var repo = GetRemoteRepository(); var versionSpec = VersionUtility.ParseVersionSpec("[0.9, 1.1]"); // Act var package = repo.FindPackage("A", versionSpec, allowPrereleaseVersions: false, allowUnlisted: true); // Assert Assert.NotNull(package); Assert.Equal("A", package.Id); Assert.Equal(SemanticVersion.Parse("1.0"), package.Version); } [Fact] public void FindByIdAndVersionRangeReturnsNullWhenPackageNotFound() { // Arrange var repo = GetLocalRepository(); var versionSpec = VersionUtility.ParseVersionSpec("[0.9, 1.1]"); // Act var package1 = repo.FindPackage("X", VersionUtility.ParseVersionSpec("[0.9, 1.1]"), allowPrereleaseVersions: false, allowUnlisted: true); var package2 = repo.FindPackage("A", VersionUtility.ParseVersionSpec("[1.4, 1.5]"), allowPrereleaseVersions: false, allowUnlisted: true); // Assert Assert.Null(package1 ?? package2); } [Fact] public void FindPackageByIdVersionAndVersionRangesUsesRangeIfExactVersionIsNull() { // Arrange var repo = GetRemoteRepository(); // Act var package = repo.FindPackage("A", VersionUtility.ParseVersionSpec("[0.6, 1.1.5]"), allowPrereleaseVersions: false, allowUnlisted: true); // Assert Assert.NotNull(package); Assert.Equal("A", package.Id); Assert.Equal(SemanticVersion.Parse("1.0"), package.Version); } [Fact] public void FindPackagesReturnsPackagesWithTermInPackageTagOrDescriptionOrId() { // Arrange var term = "TAG"; var repo = new MockPackageRepository(); repo.Add(CreateMockPackage("A", "1.0", "Description", " TAG ")); repo.Add(CreateMockPackage("B", "2.0", "Description", "Tags")); repo.Add(CreateMockPackage("C", "1.0", "This description has tags in it")); repo.Add(CreateMockPackage("D", "1.0", "Description")); repo.Add(CreateMockPackage("TagCloud", "1.0", "Description")); // Act var packages = repo.GetPackages().Find(term).ToList(); // Assert Assert.Equal(3, packages.Count); Assert.Equal("A", packages[0].Id); Assert.Equal("C", packages[1].Id); Assert.Equal("TagCloud", packages[2].Id); } [Fact] public void FindPackagesReturnsPrereleasePackagesIfTheFlagIsSetToTrue() { // Arrange var term = "B"; var repo = GetRemoteRepository(includePrerelease: true); // Act var packages = repo.GetPackages().Find(term); // Assert Assert.Equal(packages.Count(), 2); packages = packages.OrderBy(p => p.Id); Assert.Equal(packages.ElementAt(0).Id, "B"); Assert.Equal(packages.ElementAt(0).Version, new SemanticVersion("1.0")); Assert.Equal(packages.ElementAt(1).Id, "B"); Assert.Equal(packages.ElementAt(1).Version, new SemanticVersion("1.0-beta")); } [Fact] public void FindPackagesReturnsPackagesWithTerm() { // Arrange var term = "B xaml"; var repo = GetRemoteRepository(); // Act var packages = repo.GetPackages().Find(term); // Assert Assert.Equal(packages.Count(), 2); packages = packages.OrderBy(p => p.Id); Assert.Equal(packages.ElementAt(0).Id, "B"); Assert.Equal(packages.ElementAt(1).Id, "C"); } [Fact] public void FindPackagesReturnsEmptyCollectionWhenNoPackageContainsTerm() { // Arrange var term = "does-not-exist"; var repo = GetRemoteRepository(); // Act var packages = repo.GetPackages().Find(term); // Assert Assert.False(packages.Any()); } [Fact] public void FindPackagesReturnsAllPackagesWhenSearchTermIsNullOrEmpty() { // Arrange var repo = GetLocalRepository(); // Act var packages1 = repo.GetPackages().Find(String.Empty); var packages2 = repo.GetPackages().Find(null); var packages3 = repo.GetPackages(); // Assert Assert.Equal(packages1.ToList(), packages2.ToList()); Assert.Equal(packages2.ToList(), packages3.ToList()); } [Fact] public void SearchUsesInterfaceIfImplementedByRepository() { // Arrange var repo = new Mock<MockPackageRepository>(MockBehavior.Strict); repo.Setup(m => m.GetPackages()).Returns(Enumerable.Empty<IPackage>().AsQueryable()); repo.As<IServiceBasedRepository>().Setup(m => m.Search(It.IsAny<string>(), It.IsAny<IEnumerable<string>>(), false)) .Returns(new[] { PackageUtility.CreatePackage("A") }.AsQueryable()); // Act var packages = repo.Object.Search("Hello", new[] { ".NETFramework" }, allowPrereleaseVersions: false).ToList(); // Assert Assert.Equal(1, packages.Count); Assert.Equal("A", packages[0].Id); } [Fact] public void GetUpdatesReturnsPackagesWithUpdates() { // Arrange var localRepo = GetLocalRepository(); var remoteRepo = GetRemoteRepository(); // Act var packages = remoteRepo.GetUpdates(localRepo.GetPackages(), includePrerelease: false, includeAllVersions: false); // Assert Assert.True(packages.Any()); Assert.Equal(packages.First().Id, "A"); Assert.Equal(packages.First().Version, SemanticVersion.Parse("1.2")); } [Fact] public void GetUpdatesDoesNotInvokeServiceMethodIfLocalRepositoryDoesNotHaveAnyPackages() { // Arrange var localRepo = new MockPackageRepository(); var serviceRepository = new Mock<IServiceBasedRepository>(MockBehavior.Strict); var remoteRepo = serviceRepository.As<IPackageRepository>().Object; // Act var packages = remoteRepo.GetUpdates(localRepo.GetPackages(), includePrerelease: false, includeAllVersions: false); // Assert serviceRepository.Verify(s => s.GetUpdates(It.IsAny<IEnumerable<IPackage>>(), false, false, It.IsAny<IEnumerable<FrameworkName>>()), Times.Never()); } [Fact] public void GetUpdatesReturnsEmptyCollectionWhenSourceRepositoryIsEmpty() { // Arrange var localRepo = GetLocalRepository(); var remoteRepo = GetEmptyRepository(); // Act var packages = remoteRepo.GetUpdates(localRepo.GetPackages(), includePrerelease: false, includeAllVersions: false); // Assert Assert.False(packages.Any()); } [Fact] public void FindDependencyPicksHighestVersionIfNotSpecified() { // Arrange var repository = new MockPackageRepository() { PackageUtility.CreatePackage("B", "2.0"), PackageUtility.CreatePackage("B", "1.0"), PackageUtility.CreatePackage("B", "1.0.1"), PackageUtility.CreatePackage("B", "1.0.9"), PackageUtility.CreatePackage("B", "1.1") }; var dependency = new PackageDependency("B"); // Act IPackage package = repository.ResolveDependency(dependency, allowPrereleaseVersions: false, preferListedPackages: false); // Assert Assert.Equal("B", package.Id); Assert.Equal(new SemanticVersion("2.0"), package.Version); } [Fact] public void FindPackageNormalizesVersionBeforeComparing() { // Arrange var repository = new MockPackageRepository() { PackageUtility.CreatePackage("B", "1.0.0"), PackageUtility.CreatePackage("B", "1.0.0.1") }; // Act IPackage package = repository.FindPackage("B", new SemanticVersion("1.0")); // Assert Assert.Equal("B", package.Id); Assert.Equal(new SemanticVersion("1.0.0"), package.Version); } [Fact] public void FindDependencyPicksLowestMajorAndMinorVersionButHighestBuildAndRevision() { // Arrange var repository = new MockPackageRepository() { PackageUtility.CreatePackage("B", "2.0"), PackageUtility.CreatePackage("B", "1.0"), PackageUtility.CreatePackage("B", "1.0.1"), PackageUtility.CreatePackage("B", "1.0.9"), PackageUtility.CreatePackage("B", "1.1") }; // B >= 1.0 PackageDependency dependency1 = PackageDependency.CreateDependency("B", "1.0"); // B >= 1.0.0 PackageDependency dependency2 = PackageDependency.CreateDependency("B", "1.0.0"); // B >= 1.0.0.0 PackageDependency dependency3 = PackageDependency.CreateDependency("B", "1.0.0.0"); // B = 1.0 PackageDependency dependency4 = PackageDependency.CreateDependency("B", "[1.0]"); // B >= 1.0.0 && <= 1.0.8 PackageDependency dependency5 = PackageDependency.CreateDependency("B", "[1.0.0, 1.0.8]"); // Act IPackage package1 = repository.ResolveDependency(dependency1, allowPrereleaseVersions: false, preferListedPackages: false); IPackage package2 = repository.ResolveDependency(dependency2, allowPrereleaseVersions: false, preferListedPackages: false); IPackage package3 = repository.ResolveDependency(dependency3, allowPrereleaseVersions: false, preferListedPackages: false); IPackage package4 = repository.ResolveDependency(dependency4, allowPrereleaseVersions: false, preferListedPackages: false); IPackage package5 = repository.ResolveDependency(dependency5, allowPrereleaseVersions: false, preferListedPackages: false); // Assert Assert.Equal("B", package1.Id); Assert.Equal(new SemanticVersion("1.0.9"), package1.Version); Assert.Equal("B", package2.Id); Assert.Equal(new SemanticVersion("1.0.9"), package2.Version); Assert.Equal("B", package3.Id); Assert.Equal(new SemanticVersion("1.0.9"), package3.Version); Assert.Equal("B", package4.Id); Assert.Equal(new SemanticVersion("1.0"), package4.Version); Assert.Equal("B", package5.Id); Assert.Equal(new SemanticVersion("1.0.1"), package5.Version); } [Fact] public void ResolveSafeVersionReturnsNullIfPackagesNull() { // Act var package = PackageRepositoryExtensions.ResolveSafeVersion(null); // Assert Assert.Null(package); } [Fact] public void ResolveSafeVersionReturnsNullIfEmptyPackages() { // Act var package = PackageRepositoryExtensions.ResolveSafeVersion(Enumerable.Empty<IPackage>()); // Assert Assert.Null(package); } [Fact] public void ResolveSafeVersionReturnsHighestBuildAndRevisionWithLowestMajorAndMinor() { var packages = new[] { PackageUtility.CreatePackage("A", "0.9"), PackageUtility.CreatePackage("A", "0.9.3"), PackageUtility.CreatePackage("A", "1.0"), PackageUtility.CreatePackage("A", "1.0.2"), PackageUtility.CreatePackage("A", "1.0.12"), PackageUtility.CreatePackage("A", "1.0.13"), }; // Act var package = PackageRepositoryExtensions.ResolveSafeVersion(packages); // Assert Assert.NotNull(package); Assert.Equal("A", package.Id); Assert.Equal(new SemanticVersion("0.9.3"), package.Version); } private static IPackageRepository GetEmptyRepository() { Mock<IPackageRepository> repository = new Mock<IPackageRepository>(); repository.Setup(c => c.GetPackages()).Returns(() => Enumerable.Empty<IPackage>().AsQueryable()); return repository.Object; } private static IPackageRepository GetRemoteRepository(bool includePrerelease = false) { Mock<IPackageRepository> repository = new Mock<IPackageRepository>(); var packages = new List<IPackage> { CreateMockPackage("A", "1.0", "scripts style"), CreateMockPackage("B", "1.0", "testing"), CreateMockPackage("C", "2.0", "xaml"), CreateMockPackage("A", "1.2", "a updated desc") }; if (includePrerelease) { packages.Add(CreateMockPackage("A", "2.0-alpha", "a prerelease package")); packages.Add(CreateMockPackage("B", "1.0-beta", "another prerelease package")); } repository.Setup(c => c.GetPackages()).Returns(() => packages.AsQueryable()); return repository.Object; } private static IPackageRepository GetLocalRepository() { Mock<IPackageRepository> repository = new Mock<IPackageRepository>(); var packages = new[] { CreateMockPackage("A", "1.0"), CreateMockPackage("B", "1.0") }; repository.Setup(c => c.GetPackages()).Returns(() => packages.AsQueryable()); return repository.Object; } private static IPackage CreateMockPackage(string name, string version, string desc = null, string tags = null) { Mock<IPackage> package = new Mock<IPackage>(); package.SetupGet(p => p.Id).Returns(name); package.SetupGet(p => p.Version).Returns(SemanticVersion.Parse(version)); package.SetupGet(p => p.Description).Returns(desc); package.SetupGet(p => p.Tags).Returns(tags); package.SetupGet(p => p.Listed).Returns(true); return package.Object; } } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using UnityEngine.EventSystems; using System; using System.Linq; using System.Collections; using System.Collections.Generic; using PlayFab; using PlayFab.ClientModels; public class LeaderboardPaneController : MonoBehaviour { public Button CategoryFilter; public Button StatisticFilter; public Button QuestFilter; public RectTransform CategoryContainer; public RectTransform QuestContainer; public RectTransform StatsContainer; public List<string> Quests = new List<string>(); public List<string> StandAloneStatistics = new List<string>(); public List<string> QuestStatistics = new List<string>(); public List<string> ActiveOptions = new List<string>(); public List<string> PlayerLevelStats = new List<string>(); public LeaderboardController Top10LB; public LeaderboardController FriendsLB; public FriendListController FriendListController; public FriendDetailsController detailsController; public Transform friendItemPrefab; public Transform friendListView; public Text myPosition; //private string _blank = "_____________"; public void Init() { //select default stat, // get top10 for stat // get mypos for stat // get friends // get other leaderboard? // CategoryFilter.GetComponentInChildren<Text>().text = "Standalone"; // this.ActiveOptions = this.StandAloneStatistics; // // this.QuestContainer.gameObject.SetActive(false); // this.StatsContainer.anchoredPosition = new Vector2(this.QuestContainer.anchoredPosition.x + 5, this.QuestContainer.anchoredPosition.y); // this.StatisticFilter.GetComponentInChildren<Text>().text = this.StandAloneStatistics[0]; // // this is all fairly hacky, and should be smoothed over. var adStat = this.PlayerLevelStats.Find((val) => { return val == "Total_AdsWatched"; }); if(!string.IsNullOrEmpty(adStat)) { UpdateTop10LB(adStat); UpdateFriendsLB(adStat); this.StatisticFilter.GetComponentInChildren<Text>().text = adStat; } else { UpdateTop10LB(this.PlayerLevelStats[0]); UpdateFriendsLB(this.PlayerLevelStats[0]); this.StatisticFilter.GetComponentInChildren<Text>().text = this.PlayerLevelStats[0]; } UpdateFriendList(); } public void CategoryFilterClicked() { UnityAction<int> afterSelect = (int response)=> { if( response == 0) // stand alone { CategoryFilter.GetComponentInChildren<Text>().text = "Standalone"; this.ActiveOptions = this.StandAloneStatistics; this.QuestContainer.gameObject.SetActive(false); this.StatsContainer.anchoredPosition = new Vector2(this.QuestContainer.anchoredPosition.x + 5, this.QuestContainer.anchoredPosition.y); } else if( response == 1) // per quest { CategoryFilter.GetComponentInChildren<Text>().text = "Per Quest"; this.ActiveOptions = this.QuestStatistics; this.StatsContainer.anchoredPosition = new Vector2(this.StatsContainer.anchoredPosition.x + this.StatsContainer.rect.width, this.StatsContainer.anchoredPosition.y); this.QuestContainer.gameObject.SetActive(true); } }; List<string> categories = new List<string>() {"Standalone", "Per Quest" }; DialogCanvasController.RequestSelectorPrompt(GlobalStrings.CATEGORY_SELECTOR_PROMPT, categories, afterSelect); } public void StatisticFilterClicked() { UnityAction<int> afterSelect = (int response)=> { this.StatisticFilter.GetComponentInChildren<Text>().text = this.PlayerLevelStats[response]; UpdateFriendsLB(this.PlayerLevelStats[response]); UpdateTop10LB(this.PlayerLevelStats[response]); //UpdateMyRank(this.PlayerLevelStats[response]); }; DialogCanvasController.RequestSelectorPrompt(GlobalStrings.STAT_SELECTOR_PROMPT, this.PlayerLevelStats, afterSelect); } public void QuestFilterClicked() { UnityAction<int> afterSelect = (int response)=> { }; List<string> quests = new List<string>(); if(PF_GameData.Levels.Count > 0) { foreach(var quest in PF_GameData.Levels) { this.Quests.Add(quest.Key); } } else { Debug.Log("No quests found..."); return; } DialogCanvasController.RequestSelectorPrompt(GlobalStrings.QUEST_SELECTOR_PROMPT, quests, afterSelect); } public void AddFriendClicked() { UnityAction<int> afterSelect = (int response) => { Action<string> afterInput = (string input) => { PF_PlayerData.AddFriend(input, (PF_PlayerData.AddFriendMethod) response, (bool result) => { if(result) { Dictionary<string, object> eventData = new Dictionary<string, object>(); // no real data to be sent with this event, just sending an empty dict for now... PF_Bridge.LogCustomEvent(PF_Bridge.CustomEventTypes.Client_FriendAdded, eventData); PF_PlayerData.GetFriendsList(() => { UpdateFriendList(); }); } }); }; DialogCanvasController.RequestTextInputPrompt(GlobalStrings.ADD_FRIEND_PROMPT, string.Format(GlobalStrings.ADD_FRIEND_MSG, (PF_PlayerData.AddFriendMethod)response), afterInput); }; DialogCanvasController.RequestSelectorPrompt(GlobalStrings.FRIEND_SELECTOR_PROMPT, Enum.GetNames(typeof(PF_PlayerData.AddFriendMethod)).ToList(), afterSelect); } public void UpdateMyRank(string stat) { UnityAction<int> afterRank = (int rank) => { this.myPosition.text = rank > 0 ? "" + rank : "--"; }; //PF_GameData.GetMyCharacterLeaderboardRank(stat, afterRank); PF_GameData.GetMyPlayerLeaderboardRank(stat, afterRank); } public void UpdateTop10LB(string stat) { UnityAction afterGetLB= () => { Debug.Log ("Update Top10 LB UI"); if(PF_GameData.currentTop10LB.Count > 0) { int count = 0; foreach(var rank in PF_GameData.currentTop10LB) { this.Top10LB.items[count].Rank.text = "" + (rank.Position +1); this.Top10LB.items[count].Name.text = string.IsNullOrEmpty(rank.DisplayName) ? rank.PlayFabId : rank.DisplayName; this.Top10LB.items[count].Value.text = "" + rank.StatValue; count++; } if(count < 10) { for(int z = count; z < 10; z++) { this.Top10LB.items[z].Rank.text = "" + (z+1); this.Top10LB.items[z].Name.text = string.Empty; this.Top10LB.items[z].Value.text = string.Empty; } } } }; PF_GameData.GetPlayerLeaderboard(stat, afterGetLB); } public void UpdateFriendsLB(string stat) { Debug.Log ("Update Friend LB UI"); UnityAction afterGetLB= () => { if(PF_GameData.friendsLB.Count > 0) { int count = 0; foreach(var rank in PF_GameData.friendsLB) { this.FriendsLB.items[count].Rank.text = "" + (rank.Position +1); this.FriendsLB.items[count].Name.text = string.IsNullOrEmpty(rank.DisplayName) ? rank.PlayFabId : rank.DisplayName; this.FriendsLB.items[count].Value.text = "" + rank.StatValue; count++; } if(count < 10) { for(int z = count; z < 10; z++) { this.FriendsLB.items[z].Rank.text = "" + (z+1); this.FriendsLB.items[z].Name.text = string.Empty; this.FriendsLB.items[z].Value.text = string.Empty; } } } }; //PF_GameData.GetCharacterLeaderboard(stat, afterGetLB); // not using this based on the character LB issues. PF_GameData.GetFriendsLeaderboard(stat, afterGetLB); } public void UpdateFriendList() { UnityAction afterGetFriends = () => { Debug.Log ("Update Friend List UI"); LayoutElement[] children = this.friendListView.GetComponentsInChildren<LayoutElement> (); for (int z = 0; z < children.Length; z++) { if (children [z].gameObject != this.friendListView.gameObject) { DestroyImmediate(children [z].gameObject); } } foreach(var friend in PF_PlayerData.playerFriends) { Transform item = Instantiate(this.friendItemPrefab); Text txt = item.GetComponentInChildren<Text>(); txt.text = friend.TitleDisplayName; //string id = friend.FriendPlayFabId; Button btn = item.GetComponent<Button>(); FriendInfo friendCaptured = friend; btn.onClick.RemoveAllListeners(); btn.onClick.AddListener(() => { FriendClicked(friendCaptured); }); item.SetParent(this.friendListView, false); } }; PF_PlayerData.GetFriendsList(afterGetFriends); } public void FriendClicked(FriendInfo friend) { Debug.Log(friend.FriendPlayFabId); this.detailsController.gameObject.SetActive(true); this.detailsController.Init(friend); } public void CloseSocialPrompt() { this.gameObject.SetActive(false); } }
/* * File.cs - Implementation of the "System.IO.File" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.IO { using System; using Platform; public sealed class File { // Cannot instantiate this class. private File() {} // Open a file for text appending. public static StreamWriter AppendText(String path) { return new StreamWriter(path, true); } // Make a copy of a file. public static void Copy(String sourceFileName, String destFileName) { Copy(sourceFileName, destFileName, false); } public static void Copy(String sourceFileName, String destFileName, bool overwrite) { // Open the source to be copied. FileStream src = new FileStream (sourceFileName, FileMode.Open, FileAccess.Read); // Open the destination to be copied to. FileStream dest; try { if(overwrite) { dest = new FileStream (destFileName, FileMode.Create, FileAccess.Write); } else { dest = new FileStream (destFileName, FileMode.CreateNew, FileAccess.Write); } } catch { // Could not open the destination, so close the source. src.Close(); throw; } // Copy the contents of the file. try { byte[] buffer = new byte [FileStream.BUFSIZ]; int len; while((len = src.Read(buffer, 0, FileStream.BUFSIZ)) > 0) { dest.Write(buffer, 0, len); } } finally { src.Close(); dest.Close(); } } // Create a stream for a file. public static FileStream Create(String path) { return Create(path, FileStream.BUFSIZ); } public static FileStream Create(String path, int bufferSize) { return new FileStream (path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize); } // Create a file for text writing. public static StreamWriter CreateText(String path) { return new StreamWriter(path, false); } // Delete a file. public static void Delete(String path) { Directory.ValidatePath(path); Errno errno = DirMethods.Delete(path); if (errno != Errno.ENOENT) Directory.HandleErrorsFile(errno); } // Determine whether a file exists. public static bool Exists(String path) { try { Directory.ValidatePath(path); } catch(Exception) { return false; } FileType type = FileMethods.GetFileType(path); return (type != FileType.directory && type != FileType.unknown); } // Get a file's creation time. public static DateTime GetCreationTime(String path) { long ticks; Directory.ValidatePath(path); Directory.HandleErrorsFile (DirMethods.GetCreationTime(path, out ticks)); return (new DateTime(ticks)).ToLocalTime(); } // Get a file's last access time. public static DateTime GetLastAccessTime(String path) { long ticks; Directory.ValidatePath(path); Directory.HandleErrorsFile (DirMethods.GetLastAccess(path, out ticks)); return (new DateTime(ticks)).ToLocalTime(); } // Get a file's last modification time. public static DateTime GetLastWriteTime(String path) { long ticks; Directory.ValidatePath(path); Directory.HandleErrorsFile (DirMethods.GetLastModification(path, out ticks)); return (new DateTime(ticks)).ToLocalTime(); } // Move a file to a new location. public static void Move(String sourceFileName, String destFileName) { Directory.Move(sourceFileName, destFileName); } // Open a file stream. public static FileStream Open(String path, FileMode mode) { return new FileStream (path, mode, FileAccess.ReadWrite, FileShare.None); } public static FileStream Open (String path, FileMode mode, FileAccess access) { return new FileStream(path, mode, access, FileShare.None); } public static FileStream Open (String path, FileMode mode, FileAccess access, FileShare share) { return new FileStream(path, mode, access, share); } // Open a file for reading. public static FileStream OpenRead(String path) { return new FileStream (path, FileMode.Open, FileAccess.Read, FileShare.None); } // Open a text file for reading. public static StreamReader OpenText(String path) { return new StreamReader(path); } // Open a file for writing. public static FileStream OpenWrite(String path) { return new FileStream (path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); } // Set the creation time on a file. public static void SetCreationTime(String path, DateTime creationTime) { Directory.ValidatePath(path); Directory.HandleErrorsFile (FileMethods.SetCreationTime (path, creationTime.ToUniversalTime().Ticks)); } // Set the last access time on a file. public static void SetLastAccessTime(String path, DateTime lastAccessTime) { Directory.ValidatePath(path); Directory.HandleErrorsFile (FileMethods.SetLastAccessTime (path, lastAccessTime.ToUniversalTime().Ticks)); } // Set the last modification time on a file. public static void SetLastWriteTime(String path, DateTime lastWriteTime) { Directory.ValidatePath(path); Directory.HandleErrorsFile (FileMethods.SetLastWriteTime (path, lastWriteTime.ToUniversalTime().Ticks)); } #if !ECMA_COMPAT // Get the attributes for a file. public static FileAttributes GetAttributes(String path) { int attrs; Directory.ValidatePath(path); Directory.HandleErrorsFile (FileMethods.GetAttributes(path, out attrs)); return (FileAttributes)attrs; } // Get a file's UTC creation time. public static DateTime GetCreationTimeUtc(String path) { long ticks; Directory.ValidatePath(path); Directory.HandleErrorsFile (DirMethods.GetCreationTime(path, out ticks)); return new DateTime(ticks); } // Get a file's UTC last access time. public static DateTime GetLastAccessTimeUtc(String path) { long ticks; Directory.ValidatePath(path); Directory.HandleErrorsFile (DirMethods.GetLastAccess(path, out ticks)); return new DateTime(ticks); } // Get a file's UTC last modification time. public static DateTime GetLastWriteTimeUtc(String path) { long ticks; Directory.ValidatePath(path); Directory.HandleErrorsFile (DirMethods.GetLastModification(path, out ticks)); return new DateTime(ticks); } // Set the attributes on a file. public static void SetAttributes (String path, FileAttributes fileAttributes) { Directory.ValidatePath(path); Directory.HandleErrorsFile (FileMethods.SetAttributes(path, (int)fileAttributes)); } // Set the UTC creation time on a file. public static void SetCreationTimeUtc(String path, DateTime creationTime) { Directory.ValidatePath(path); Directory.HandleErrorsFile (FileMethods.SetCreationTime(path, creationTime.Ticks)); } // Set the UTC last access time on a file. public static void SetLastAccessTimeUtc (String path, DateTime lastAccessTime) { Directory.ValidatePath(path); Directory.HandleErrorsFile (FileMethods.SetLastAccessTime (path, lastAccessTime.Ticks)); } // Set the UTC last modification time on a file. public static void SetLastWriteTimeUtc(String path, DateTime lastWriteTime) { Directory.ValidatePath(path); Directory.HandleErrorsFile (FileMethods.SetLastWriteTime (path, lastWriteTime.Ticks)); } // Get the length of a file. internal static long GetLength(String path) { long length; Directory.ValidatePath(path); Directory.HandleErrorsFile (FileMethods.GetLength(path, out length)); return length; } #endif // !ECMA_COMPAT }; // class File }; // namespace System.IO
using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Baseline; using Marten.Exceptions; using Marten.Linq.Filters; using Marten.Linq.Parsing; using Marten.Linq.SqlGeneration; using Weasel.Postgresql; using Marten.Schema; using Marten.Schema.Arguments; using Marten.Storage; using Marten.Util; using NpgsqlTypes; using Weasel.Core; using Weasel.Postgresql.SqlGeneration; using Weasel.Postgresql.Tables; namespace Marten.Linq.Fields { public class DuplicatedField: IField { private readonly Func<Expression, object> _parseObject = expression => expression.Value(); private readonly bool useTimestampWithoutTimeZoneForDateTime; private string _columnName; public DuplicatedField(EnumStorage enumStorage, IField innerField, bool useTimestampWithoutTimeZoneForDateTime = true, bool notNull = false) { InnerField = innerField; MemberName = InnerField.Members.Select(x => x.Name).Join(""); NotNull = notNull; ColumnName = MemberName.ToTableAlias(); this.useTimestampWithoutTimeZoneForDateTime = useTimestampWithoutTimeZoneForDateTime; PgType = PostgresqlProvider.Instance.GetDatabaseType(FieldType, enumStorage); if (FieldType.IsEnum) { if (enumStorage == EnumStorage.AsString) { DbType = NpgsqlDbType.Varchar; PgType = "varchar"; _parseObject = expression => { var raw = expression.Value(); if (raw == null) { return null; } return Enum.GetName(FieldType, raw); }; } else { DbType = NpgsqlDbType.Integer; PgType = "integer"; } } else if (FieldType.IsDateTime()) { PgType = this.useTimestampWithoutTimeZoneForDateTime ? "timestamp without time zone" : "timestamp with time zone"; DbType = this.useTimestampWithoutTimeZoneForDateTime ? NpgsqlDbType.Timestamp : NpgsqlDbType.TimestampTz; } else if (FieldType == typeof(DateTimeOffset) || FieldType == typeof(DateTimeOffset?)) { PgType = "timestamp with time zone"; DbType = NpgsqlDbType.TimestampTz; } else { DbType = PostgresqlProvider.Instance.ToParameterType(FieldType); } } public bool NotNull { get; } public bool OnlyForSearching { get; set; } = false; /// <summary> /// Used to override the assigned DbType used by Npgsql when a parameter /// is used in a query against this column /// </summary> public NpgsqlDbType DbType { get; set; } internal UpsertArgument UpsertArgument => new UpsertArgument { Arg = "arg_" + ColumnName.ToLower(), Column = ColumnName.ToLower(), PostgresType = PgType, Members = Members, DbType = DbType }; public string ColumnName { get => _columnName; set { _columnName = value; TypedLocator = "d." + _columnName; } } internal IField InnerField { get; } public string RawLocator => TypedLocator; public object GetValueForCompiledQueryParameter(Expression valueExpression) { return _parseObject(valueExpression); } public bool ShouldUseContainmentOperator() { return false; } string IField.SelectorForDuplication(string pgType) { throw new NotSupportedException(); } public ISqlFragment CreateComparison(string op, ConstantExpression value, Expression memberExpression) { if (value.Value == null) { return op switch { "=" => new IsNullFilter(this), "!=" => new IsNotNullFilter(this), _ => throw new BadLinqExpressionException($"Can only compare property {MemberName} by '=' or '!=' with null value") }; } return new ComparisonFilter(this, new CommandParameter(_parseObject(value), DbType), op); } public string JSONBLocator { get; set; } public string LocatorForIncludedDocumentId => TypedLocator; public string LocatorFor(string rootTableAlias) { return $"{rootTableAlias}.{_columnName}"; } public string TypedLocator { get; set; } public string UpdateSqlFragment() { return $"{ColumnName} = {InnerField.SelectorForDuplication(PgType)}"; } public static DuplicatedField For<T>(StoreOptions options, Expression<Func<T, object>> expression, bool useTimestampWithoutTimeZoneForDateTime = true) { var inner = new DocumentMapping<T>(options).FieldFor(expression); // Hokey, but it's just for testing for now. if (inner.Members.Length > 1) throw new NotSupportedException("Not yet supporting deep properties yet. Soon."); return new DuplicatedField(options.EnumStorage, inner, useTimestampWithoutTimeZoneForDateTime); } // I say you don't need a ForeignKey public virtual TableColumn ToColumn() { return new TableColumn(ColumnName, PgType); } void ISqlFragment.Apply(CommandBuilder builder) { builder.Append(TypedLocator); } bool ISqlFragment.Contains(string sqlText) { return TypedLocator.Contains(sqlText); } public Type FieldType => InnerField.FieldType; public MemberInfo[] Members => InnerField.Members; public string MemberName { get; } public string PgType { get; set; } // settable so it can be overidden by users public string ToOrderExpression(Expression expression) { return TypedLocator; } } }
/* * Deed API * * Land Registry Deed API * * OpenAPI spec version: 1.3.8 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Reflection; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace IO.Swagger.Client { /// <summary> /// Represents a set of configuration settings /// </summary> public class Configuration { /// <summary> /// Initializes a new instance of the Configuration class with different settings /// </summary> /// <param name="apiClient">Api client</param> /// <param name="defaultHeader">Dictionary of default HTTP header</param> /// <param name="username">Username</param> /// <param name="password">Password</param> /// <param name="accessToken">accessToken</param> /// <param name="apiKey">Dictionary of API key</param> /// <param name="apiKeyPrefix">Dictionary of API key prefix</param> /// <param name="tempFolderPath">Temp folder path</param> /// <param name="dateTimeFormat">DateTime format string</param> /// <param name="timeout">HTTP connection timeout (in milliseconds)</param> /// <param name="userAgent">HTTP user agent</param> public Configuration(ApiClient apiClient = null, Dictionary<String, String> defaultHeader = null, string username = null, string password = null, string accessToken = null, Dictionary<String, String> apiKey = null, Dictionary<String, String> apiKeyPrefix = null, string tempFolderPath = null, string dateTimeFormat = null, int timeout = 100000, string userAgent = "Swagger-Codegen/1.0.0/csharp" ) { setApiClientUsingDefault(apiClient); Username = username; Password = password; AccessToken = accessToken; UserAgent = userAgent; if (defaultHeader != null) DefaultHeader = defaultHeader; if (apiKey != null) ApiKey = apiKey; if (apiKeyPrefix != null) ApiKeyPrefix = apiKeyPrefix; TempFolderPath = tempFolderPath; DateTimeFormat = dateTimeFormat; Timeout = timeout; } /// <summary> /// Initializes a new instance of the Configuration class. /// </summary> /// <param name="apiClient">Api client.</param> public Configuration(ApiClient apiClient) { setApiClientUsingDefault(apiClient); } /// <summary> /// Version of the package. /// </summary> /// <value>Version of the package.</value> public const string Version = "1.0.0"; /// <summary> /// Gets or sets the default Configuration. /// </summary> /// <value>Configuration.</value> public static Configuration Default = new Configuration(); /// <summary> /// Default creation of exceptions for a given method name and response object /// </summary> public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) => { int status = (int) response.StatusCode; if (status >= 400) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.Content), response.Content); if (status == 0) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.ErrorMessage), response.ErrorMessage); return null; }; /// <summary> /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. /// </summary> /// <value>Timeout.</value> public int Timeout { get { return ApiClient.RestClient.Timeout; } set { if (ApiClient != null) ApiClient.RestClient.Timeout = value; } } /// <summary> /// Gets or sets the default API client for making HTTP calls. /// </summary> /// <value>The API client.</value> public ApiClient ApiClient; /// <summary> /// Set the ApiClient using Default or ApiClient instance. /// </summary> /// <param name="apiClient">An instance of ApiClient.</param> /// <returns></returns> public void setApiClientUsingDefault (ApiClient apiClient = null) { if (apiClient == null) { if (Default != null && Default.ApiClient == null) Default.ApiClient = new ApiClient(); ApiClient = Default != null ? Default.ApiClient : new ApiClient(); } else { if (Default != null && Default.ApiClient == null) Default.ApiClient = apiClient; ApiClient = apiClient; } } private Dictionary<String, String> _defaultHeaderMap = new Dictionary<String, String>(); /// <summary> /// Gets or sets the default header. /// </summary> public Dictionary<String, String> DefaultHeader { get { return _defaultHeaderMap; } set { _defaultHeaderMap = value; } } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> public void AddDefaultHeader(string key, string value) { _defaultHeaderMap[key] = value; } /// <summary> /// Add Api Key Header. /// </summary> /// <param name="key">Api Key name.</param> /// <param name="value">Api Key value.</param> /// <returns></returns> public void AddApiKey(string key, string value) { ApiKey[key] = value; } /// <summary> /// Sets the API key prefix. /// </summary> /// <param name="key">Api Key name.</param> /// <param name="value">Api Key value.</param> public void AddApiKeyPrefix(string key, string value) { ApiKeyPrefix[key] = value; } /// <summary> /// Gets or sets the HTTP user agent. /// </summary> /// <value>Http user agent.</value> public String UserAgent { get; set; } /// <summary> /// Gets or sets the username (HTTP basic authentication). /// </summary> /// <value>The username.</value> public String Username { get; set; } /// <summary> /// Gets or sets the password (HTTP basic authentication). /// </summary> /// <value>The password.</value> public String Password { get; set; } /// <summary> /// Gets or sets the access token for OAuth2 authentication. /// </summary> /// <value>The access token.</value> public String AccessToken { get; set; } /// <summary> /// Gets or sets the API key based on the authentication name. /// </summary> /// <value>The API key.</value> public Dictionary<String, String> ApiKey = new Dictionary<String, String>(); /// <summary> /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. /// </summary> /// <value>The prefix of the API key.</value> public Dictionary<String, String> ApiKeyPrefix = new Dictionary<String, String>(); /// <summary> /// Get the API key with prefix. /// </summary> /// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param> /// <returns>API key with prefix.</returns> public string GetApiKeyWithPrefix (string apiKeyIdentifier) { var apiKeyValue = ""; ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue); var apiKeyPrefix = ""; if (ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) return apiKeyPrefix + " " + apiKeyValue; else return apiKeyValue; } private string _tempFolderPath = Path.GetTempPath(); /// <summary> /// Gets or sets the temporary folder path to store the files downloaded from the server. /// </summary> /// <value>Folder path.</value> public String TempFolderPath { get { return _tempFolderPath; } set { if (String.IsNullOrEmpty(value)) { _tempFolderPath = value; return; } // create the directory if it does not exist if (!Directory.Exists(value)) Directory.CreateDirectory(value); // check if the path contains directory separator at the end if (value[value.Length - 1] == Path.DirectorySeparatorChar) _tempFolderPath = value; else _tempFolderPath = value + Path.DirectorySeparatorChar; } } private const string ISO8601_DATETIME_FORMAT = "o"; private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; /// <summary> /// Gets or sets the the date time format used when serializing in the ApiClient /// By default, it's set to ISO 8601 - "o", for others see: /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx /// No validation is done to ensure that the string you're providing is valid /// </summary> /// <value>The DateTimeFormat string</value> public String DateTimeFormat { get { return _dateTimeFormat; } set { if (string.IsNullOrEmpty(value)) { // Never allow a blank or null string, go back to the default _dateTimeFormat = ISO8601_DATETIME_FORMAT; return; } // Caution, no validation when you choose date time format other than ISO 8601 // Take a look at the above links _dateTimeFormat = value; } } /// <summary> /// Returns a string with essential information for debugging. /// </summary> public static String ToDebugReport() { String report = "C# SDK (IO.Swagger) Debug Report:\n"; report += " OS: " + Environment.OSVersion + "\n"; report += " .NET Framework Version: " + Assembly .GetExecutingAssembly() .GetReferencedAssemblies() .Where(x => x.Name == "System.Core").First().Version.ToString() + "\n"; report += " Version of the API: 1.3.8\n"; report += " SDK Package Version: 1.0.0\n"; return report; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Runtime.CompilerServices; using System.Threading.Tasks; using BTCPayServer.Lightning; using BTCPayServer.Lightning.CLightning; using BTCPayServer.Payments.Lightning; using BTCPayServer.Tests.Lnd; using BTCPayServer.Tests.Logging; using Microsoft.Extensions.Logging; using NBitcoin; using NBitcoin.RPC; using NBitpayClient; using NBXplorer; namespace BTCPayServer.Tests { public class ServerTester : IDisposable { public List<IDisposable> Resources = new List<IDisposable>(); readonly string _Directory; public ILoggerProvider LoggerProvider { get; } internal ILog TestLogs; public ServerTester(string scope, bool newDb, ILog testLogs, ILoggerProvider loggerProvider) { LoggerProvider = loggerProvider; this.TestLogs = testLogs; _Directory = scope; if (Directory.Exists(_Directory)) Utils.DeleteDirectory(_Directory); if (!Directory.Exists(_Directory)) Directory.CreateDirectory(_Directory); NetworkProvider = new BTCPayNetworkProvider(ChainName.Regtest); ExplorerNode = new RPCClient(RPCCredentialString.Parse(GetEnvironment("TESTS_BTCRPCCONNECTION", "server=http://127.0.0.1:43782;ceiwHEbqWI83:DwubwWsoo3")), NetworkProvider.GetNetwork<BTCPayNetwork>("BTC").NBitcoinNetwork); ExplorerNode.ScanRPCCapabilities(); ExplorerClient = new ExplorerClient(NetworkProvider.GetNetwork<BTCPayNetwork>("BTC").NBXplorerNetwork, new Uri(GetEnvironment("TESTS_BTCNBXPLORERURL", "http://127.0.0.1:32838/"))); PayTester = new BTCPayServerTester(TestLogs, LoggerProvider, Path.Combine(_Directory, "pay")) { NBXplorerUri = ExplorerClient.Address, TestDatabase = Enum.Parse<TestDatabases>(GetEnvironment("TESTS_DB", TestDatabases.Postgres.ToString()), true), // TODO: The fact that we use same conn string as development database can cause huge problems with tests // since in dev we already can have some users / stores registered, while on CI database is being initalized // for the first time and first registered user gets admin status by default Postgres = GetEnvironment("TESTS_POSTGRES", "User ID=postgres;Include Error Detail=true;Host=127.0.0.1;Port=39372;Database=btcpayserver"), MySQL = GetEnvironment("TESTS_MYSQL", "User ID=root;Host=127.0.0.1;Port=33036;Database=btcpayserver") }; if (newDb) { var r = RandomUtils.GetUInt32(); PayTester.Postgres = PayTester.Postgres.Replace("btcpayserver", $"btcpayserver{r}"); PayTester.MySQL = PayTester.MySQL.Replace("btcpayserver", $"btcpayserver{r}"); } PayTester.Port = int.Parse(GetEnvironment("TESTS_PORT", Utils.FreeTcpPort().ToString(CultureInfo.InvariantCulture)), CultureInfo.InvariantCulture); PayTester.HostName = GetEnvironment("TESTS_HOSTNAME", "127.0.0.1"); PayTester.InContainer = bool.Parse(GetEnvironment("TESTS_INCONTAINER", "false")); PayTester.SSHPassword = GetEnvironment("TESTS_SSHPASSWORD", "opD3i2282D"); PayTester.SSHKeyFile = GetEnvironment("TESTS_SSHKEYFILE", ""); PayTester.SSHConnection = GetEnvironment("TESTS_SSHCONNECTION", "root@127.0.0.1:21622"); PayTester.SocksEndpoint = GetEnvironment("TESTS_SOCKSENDPOINT", "localhost:9050"); } #if ALTCOINS public void ActivateLTC() { LTCExplorerNode = new RPCClient(RPCCredentialString.Parse(GetEnvironment("TESTS_LTCRPCCONNECTION", "server=http://127.0.0.1:43783;ceiwHEbqWI83:DwubwWsoo3")), NetworkProvider.GetNetwork<BTCPayNetwork>("LTC").NBitcoinNetwork); LTCExplorerClient = new ExplorerClient(NetworkProvider.GetNetwork<BTCPayNetwork>("LTC").NBXplorerNetwork, new Uri(GetEnvironment("TESTS_LTCNBXPLORERURL", "http://127.0.0.1:32838/"))); PayTester.Chains.Add("LTC"); PayTester.LTCNBXplorerUri = LTCExplorerClient.Address; } public void ActivateLBTC() { LBTCExplorerNode = new RPCClient(RPCCredentialString.Parse(GetEnvironment("TESTS_LBTCRPCCONNECTION", "server=http://127.0.0.1:19332;liquid:liquid")), NetworkProvider.GetNetwork<BTCPayNetwork>("LBTC").NBitcoinNetwork); LBTCExplorerClient = new ExplorerClient(NetworkProvider.GetNetwork<BTCPayNetwork>("LBTC").NBXplorerNetwork, new Uri(GetEnvironment("TESTS_LBTCNBXPLORERURL", "http://127.0.0.1:32838/"))); PayTester.Chains.Add("LBTC"); PayTester.LBTCNBXplorerUri = LBTCExplorerClient.Address; } public void ActivateETH() { PayTester.Chains.Add("ETH"); } #endif public void ActivateLightning() { ActivateLightning(LightningConnectionType.Charge); } public void ActivateLightning(LightningConnectionType internalNode) { var btc = NetworkProvider.GetNetwork<BTCPayNetwork>("BTC").NBitcoinNetwork; CustomerLightningD = LightningClientFactory.CreateClient(GetEnvironment("TEST_CUSTOMERLIGHTNINGD", "type=clightning;server=tcp://127.0.0.1:30992/"), btc); MerchantLightningD = LightningClientFactory.CreateClient(GetEnvironment("TEST_MERCHANTLIGHTNINGD", "type=clightning;server=tcp://127.0.0.1:30993/"), btc); MerchantCharge = new ChargeTester(this, "TEST_MERCHANTCHARGE", "type=charge;server=http://127.0.0.1:54938/;api-token=foiewnccewuify;allowinsecure=true", "merchant_lightningd", btc); MerchantLnd = new LndMockTester(this, "TEST_MERCHANTLND", "http://lnd:lnd@127.0.0.1:35531/", "merchant_lnd", btc); PayTester.UseLightning = true; PayTester.IntegratedLightning = GetLightningConnectionString(internalNode, true); } public string GetLightningConnectionString(LightningConnectionType? connectionType, bool isMerchant) { string connectionString = null; if (connectionType is null) return LightningSupportedPaymentMethod.InternalNode; if (connectionType == LightningConnectionType.Charge) { if (isMerchant) connectionString = $"type=charge;server={MerchantCharge.Client.Uri.AbsoluteUri};allowinsecure=true"; else throw new NotSupportedException(); } else if (connectionType == LightningConnectionType.CLightning) { if (isMerchant) connectionString = "type=clightning;server=" + ((CLightningClient)MerchantLightningD).Address.AbsoluteUri; else connectionString = "type=clightning;server=" + ((CLightningClient)CustomerLightningD).Address.AbsoluteUri; } else if (connectionType == LightningConnectionType.LndREST) { if (isMerchant) connectionString = $"type=lnd-rest;server={MerchantLnd.Swagger.BaseUrl};allowinsecure=true"; else throw new NotSupportedException(); } else throw new NotSupportedException(connectionType.ToString()); return connectionString; } public bool Dockerized { get; set; } public Task StartAsync() { return PayTester.StartAsync(); } /// <summary> /// Connect a customer LN node to the merchant LN node /// </summary> /// <returns></returns> public async Task EnsureChannelsSetup() { TestLogs.LogInformation("Connecting channels"); BTCPayServer.Lightning.Tests.ConnectChannels.Logs = LoggerProvider.CreateLogger("Connect channels"); await BTCPayServer.Lightning.Tests.ConnectChannels.ConnectAll(ExplorerNode, GetLightningSenderClients(), GetLightningDestClients()).ConfigureAwait(false); TestLogs.LogInformation("Channels connected"); } private IEnumerable<ILightningClient> GetLightningSenderClients() { yield return CustomerLightningD; } private IEnumerable<ILightningClient> GetLightningDestClients() { yield return MerchantLightningD; yield return MerchantLnd.Client; } public void SendLightningPayment(Invoice invoice) { SendLightningPaymentAsync(invoice).GetAwaiter().GetResult(); } public async Task SendLightningPaymentAsync(Invoice invoice) { var bolt11 = invoice.CryptoInfo.Where(o => o.PaymentUrls.BOLT11 != null).First().PaymentUrls.BOLT11; bolt11 = bolt11.Replace("lightning:", "", StringComparison.OrdinalIgnoreCase); await CustomerLightningD.Pay(bolt11); } public async Task<T> WaitForEvent<T>(Func<Task> action, Func<T, bool> correctEvent = null) { var tcs = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously); var sub = PayTester.GetService<EventAggregator>().Subscribe<T>(evt => { if (correctEvent is null) tcs.TrySetResult(evt); else if (correctEvent(evt)) { tcs.TrySetResult(evt); } }); await action.Invoke(); var result = await tcs.Task; sub.Dispose(); return result; } public ILightningClient CustomerLightningD { get; set; } public ILightningClient MerchantLightningD { get; private set; } public ChargeTester MerchantCharge { get; private set; } public LndMockTester MerchantLnd { get; set; } internal string GetEnvironment(string variable, string defaultValue) { var var = Environment.GetEnvironmentVariable(variable); return String.IsNullOrEmpty(var) ? defaultValue : var; } public TestAccount NewAccount() { return new TestAccount(this); } public BTCPayNetworkProvider NetworkProvider { get; private set; } public RPCClient ExplorerNode { get; set; } #if ALTCOINS public RPCClient LTCExplorerNode { get; set; } public RPCClient LBTCExplorerNode { get; set; } public ExplorerClient LTCExplorerClient { get; set; } public ExplorerClient LBTCExplorerClient { get; set; } #endif public ExplorerClient ExplorerClient { get; set; } readonly HttpClient _Http = new HttpClient(); public BTCPayServerTester PayTester { get; set; } public List<string> Stores { get; internal set; } = new List<string>(); public void Dispose() { foreach (var r in this.Resources) r.Dispose(); TestLogs.LogInformation("Disposing the BTCPayTester..."); foreach (var store in Stores) { Xunit.Assert.True(PayTester.StoreRepository.DeleteStore(store).GetAwaiter().GetResult()); } if (PayTester != null) PayTester.Dispose(); TestLogs.LogInformation("BTCPayTester disposed"); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Reflection; using log4net; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Grid.Framework; namespace OpenSim.Grid.UserServer.Modules { public delegate void logOffUser(UUID AgentID); public class UserManager { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public event logOffUser OnLogOffUser; private logOffUser handlerLogOffUser; private UserDataBaseService m_userDataBaseService; private BaseHttpServer m_httpServer; /// <summary> /// /// </summary> /// <param name="userDataBaseService"></param> public UserManager(UserDataBaseService userDataBaseService) { m_userDataBaseService = userDataBaseService; } public void Initialise(IGridServiceCore core) { } public void PostInitialise() { } private string RESTGetUserProfile(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { UUID id; UserProfileData userProfile; try { id = new UUID(param); } catch (Exception) { httpResponse.StatusCode = 500; return "Malformed Param [" + param + "]"; } userProfile = m_userDataBaseService.GetUserProfile(id); if (userProfile == null) { httpResponse.StatusCode = 404; return "Not Found."; } return ProfileToXmlRPCResponse(userProfile).ToString(); } public void RegisterHandlers(BaseHttpServer httpServer) { m_httpServer = httpServer; m_httpServer.AddStreamHandler(new RestStreamHandler("GET", "/users/", RESTGetUserProfile)); m_httpServer.AddXmlRPCHandler("get_user_by_name", XmlRPCGetUserMethodName); m_httpServer.AddXmlRPCHandler("get_user_by_uuid", XmlRPCGetUserMethodUUID); m_httpServer.AddXmlRPCHandler("get_avatar_picker_avatar", XmlRPCGetAvatarPickerAvatar); // Used by IAR module to do password checks m_httpServer.AddXmlRPCHandler("authenticate_user_by_password", XmlRPCAuthenticateUserMethodPassword); m_httpServer.AddXmlRPCHandler("update_user_current_region", XmlRPCAtRegion); m_httpServer.AddXmlRPCHandler("logout_of_simulator", XmlRPCLogOffUserMethodUUID); m_httpServer.AddXmlRPCHandler("get_agent_by_uuid", XmlRPCGetAgentMethodUUID); m_httpServer.AddXmlRPCHandler("update_user_profile", XmlRpcResponseXmlRPCUpdateUserProfile); m_httpServer.AddStreamHandler(new RestStreamHandler("DELETE", "/usersessions/", RestDeleteUserSessionMethod)); } /// <summary> /// Deletes an active agent session /// </summary> /// <param name="request">The request</param> /// <param name="path">The path (eg /bork/narf/test)</param> /// <param name="param">Parameters sent</param> /// <param name="httpRequest">HTTP request header object</param> /// <param name="httpResponse">HTTP response header object</param> /// <returns>Success "OK" else error</returns> public string RestDeleteUserSessionMethod(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { // TODO! Important! return "OK"; } public XmlRpcResponse AvatarPickerListtoXmlRPCResponse(UUID queryID, List<AvatarPickerAvatar> returnUsers) { XmlRpcResponse response = new XmlRpcResponse(); Hashtable responseData = new Hashtable(); // Query Result Information responseData["queryid"] = queryID.ToString(); responseData["avcount"] = returnUsers.Count.ToString(); for (int i = 0; i < returnUsers.Count; i++) { responseData["avatarid" + i] = returnUsers[i].AvatarID.ToString(); responseData["firstname" + i] = returnUsers[i].firstName; responseData["lastname" + i] = returnUsers[i].lastName; } response.Value = responseData; return response; } /// <summary> /// Converts a user profile to an XML element which can be returned /// </summary> /// <param name="profile">The user profile</param> /// <returns>A string containing an XML Document of the user profile</returns> public XmlRpcResponse ProfileToXmlRPCResponse(UserProfileData profile) { XmlRpcResponse response = new XmlRpcResponse(); Hashtable responseData = new Hashtable(); // Account information responseData["firstname"] = profile.FirstName; responseData["lastname"] = profile.SurName; responseData["email"] = profile.Email; responseData["uuid"] = profile.ID.ToString(); // Server Information responseData["server_inventory"] = profile.UserInventoryURI; responseData["server_asset"] = profile.UserAssetURI; // Profile Information responseData["profile_about"] = profile.AboutText; responseData["profile_firstlife_about"] = profile.FirstLifeAboutText; responseData["profile_firstlife_image"] = profile.FirstLifeImage.ToString(); responseData["profile_can_do"] = profile.CanDoMask.ToString(); responseData["profile_want_do"] = profile.WantDoMask.ToString(); responseData["profile_image"] = profile.Image.ToString(); responseData["profile_created"] = profile.Created.ToString(); responseData["profile_lastlogin"] = profile.LastLogin.ToString(); // Home region information responseData["home_coordinates_x"] = profile.HomeLocation.X.ToString(); responseData["home_coordinates_y"] = profile.HomeLocation.Y.ToString(); responseData["home_coordinates_z"] = profile.HomeLocation.Z.ToString(); responseData["home_region"] = profile.HomeRegion.ToString(); responseData["home_region_id"] = profile.HomeRegionID.ToString(); responseData["home_look_x"] = profile.HomeLookAt.X.ToString(); responseData["home_look_y"] = profile.HomeLookAt.Y.ToString(); responseData["home_look_z"] = profile.HomeLookAt.Z.ToString(); responseData["user_flags"] = profile.UserFlags.ToString(); responseData["god_level"] = profile.GodLevel.ToString(); responseData["custom_type"] = profile.CustomType; responseData["partner"] = profile.Partner.ToString(); response.Value = responseData; return response; } #region XMLRPC User Methods /// <summary> /// Authenticate a user using their password /// </summary> /// <param name="request">Must contain values for "user_uuid" and "password" keys</param> /// <param name="remoteClient"></param> /// <returns></returns> public XmlRpcResponse XmlRPCAuthenticateUserMethodPassword(XmlRpcRequest request, IPEndPoint remoteClient) { // m_log.DebugFormat("[USER MANAGER]: Received authenticated user by password request from {0}", remoteClient); Hashtable requestData = (Hashtable)request.Params[0]; string userUuidRaw = (string)requestData["user_uuid"]; string password = (string)requestData["password"]; if (null == userUuidRaw) return Util.CreateUnknownUserErrorResponse(); UUID userUuid; if (!UUID.TryParse(userUuidRaw, out userUuid)) return Util.CreateUnknownUserErrorResponse(); UserProfileData userProfile = m_userDataBaseService.GetUserProfile(userUuid); if (null == userProfile) return Util.CreateUnknownUserErrorResponse(); string authed; if (null == password) { authed = "FALSE"; } else { if (m_userDataBaseService.AuthenticateUserByPassword(userUuid, password)) authed = "TRUE"; else authed = "FALSE"; } // m_log.DebugFormat( // "[USER MANAGER]: Authentication by password result from {0} for {1} is {2}", // remoteClient, userUuid, authed); XmlRpcResponse response = new XmlRpcResponse(); Hashtable responseData = new Hashtable(); responseData["auth_user"] = authed; response.Value = responseData; return response; } public XmlRpcResponse XmlRPCGetAvatarPickerAvatar(XmlRpcRequest request, IPEndPoint remoteClient) { // XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable)request.Params[0]; List<AvatarPickerAvatar> returnAvatar = new List<AvatarPickerAvatar>(); UUID queryID = new UUID(UUID.Zero.ToString()); if (requestData.Contains("avquery") && requestData.Contains("queryid")) { queryID = new UUID((string)requestData["queryid"]); returnAvatar = m_userDataBaseService.GenerateAgentPickerRequestResponse(queryID, (string)requestData["avquery"]); } m_log.InfoFormat("[AVATARINFO]: Servicing Avatar Query: " + (string)requestData["avquery"]); return AvatarPickerListtoXmlRPCResponse(queryID, returnAvatar); } public XmlRpcResponse XmlRPCAtRegion(XmlRpcRequest request, IPEndPoint remoteClient) { XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable)request.Params[0]; Hashtable responseData = new Hashtable(); string returnstring = "FALSE"; if (requestData.Contains("avatar_id") && requestData.Contains("region_handle") && requestData.Contains("region_uuid")) { // ulong cregionhandle = 0; UUID regionUUID; UUID avatarUUID; UUID.TryParse((string)requestData["avatar_id"], out avatarUUID); UUID.TryParse((string)requestData["region_uuid"], out regionUUID); if (avatarUUID != UUID.Zero) { UserProfileData userProfile = m_userDataBaseService.GetUserProfile(avatarUUID); userProfile.CurrentAgent.Region = regionUUID; userProfile.CurrentAgent.Handle = (ulong)Convert.ToInt64((string)requestData["region_handle"]); //userProfile.CurrentAgent. m_userDataBaseService.CommitAgent(ref userProfile); //setUserProfile(userProfile); returnstring = "TRUE"; } } responseData.Add("returnString", returnstring); response.Value = responseData; return response; } public XmlRpcResponse XmlRPCGetUserMethodName(XmlRpcRequest request, IPEndPoint remoteClient) { // XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable)request.Params[0]; UserProfileData userProfile; if (requestData.Contains("avatar_name")) { string query = (string)requestData["avatar_name"]; if (null == query) return Util.CreateUnknownUserErrorResponse(); // Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]"); string[] querysplit = query.Split(' '); if (querysplit.Length == 2) { userProfile = m_userDataBaseService.GetUserProfile(querysplit[0], querysplit[1]); if (userProfile == null) { return Util.CreateUnknownUserErrorResponse(); } } else { return Util.CreateUnknownUserErrorResponse(); } } else { return Util.CreateUnknownUserErrorResponse(); } return ProfileToXmlRPCResponse(userProfile); } public XmlRpcResponse XmlRPCGetUserMethodUUID(XmlRpcRequest request, IPEndPoint remoteClient) { // XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable)request.Params[0]; UserProfileData userProfile; //CFK: this clogs the UserServer log and is not necessary at this time. //CFK: m_log.Debug("METHOD BY UUID CALLED"); if (requestData.Contains("avatar_uuid")) { try { UUID guess = new UUID((string)requestData["avatar_uuid"]); userProfile = m_userDataBaseService.GetUserProfile(guess); } catch (FormatException) { return Util.CreateUnknownUserErrorResponse(); } if (userProfile == null) { return Util.CreateUnknownUserErrorResponse(); } } else { return Util.CreateUnknownUserErrorResponse(); } return ProfileToXmlRPCResponse(userProfile); } public XmlRpcResponse XmlRPCGetAgentMethodUUID(XmlRpcRequest request, IPEndPoint remoteClient) { XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable)request.Params[0]; UserProfileData userProfile; //CFK: this clogs the UserServer log and is not necessary at this time. //CFK: m_log.Debug("METHOD BY UUID CALLED"); if (requestData.Contains("avatar_uuid")) { UUID guess; UUID.TryParse((string)requestData["avatar_uuid"], out guess); if (guess == UUID.Zero) { return Util.CreateUnknownUserErrorResponse(); } userProfile = m_userDataBaseService.GetUserProfile(guess); if (userProfile == null) { return Util.CreateUnknownUserErrorResponse(); } // no agent??? if (userProfile.CurrentAgent == null) { return Util.CreateUnknownUserErrorResponse(); } Hashtable responseData = new Hashtable(); responseData["handle"] = userProfile.CurrentAgent.Handle.ToString(); responseData["session"] = userProfile.CurrentAgent.SessionID.ToString(); if (userProfile.CurrentAgent.AgentOnline) responseData["agent_online"] = "TRUE"; else responseData["agent_online"] = "FALSE"; response.Value = responseData; } else { return Util.CreateUnknownUserErrorResponse(); } return response; } public XmlRpcResponse XmlRpcResponseXmlRPCUpdateUserProfile(XmlRpcRequest request, IPEndPoint remoteClient) { m_log.Debug("[UserManager]: Got request to update user profile"); XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable)request.Params[0]; Hashtable responseData = new Hashtable(); if (!requestData.Contains("avatar_uuid")) { return Util.CreateUnknownUserErrorResponse(); } UUID UserUUID = new UUID((string)requestData["avatar_uuid"]); UserProfileData userProfile = m_userDataBaseService.GetUserProfile(UserUUID); if (null == userProfile) { return Util.CreateUnknownUserErrorResponse(); } // don't know how yet. if (requestData.Contains("AllowPublish")) { } if (requestData.Contains("FLImageID")) { userProfile.FirstLifeImage = new UUID((string)requestData["FLImageID"]); } if (requestData.Contains("ImageID")) { userProfile.Image = new UUID((string)requestData["ImageID"]); } // dont' know how yet if (requestData.Contains("MaturePublish")) { } if (requestData.Contains("AboutText")) { userProfile.AboutText = (string)requestData["AboutText"]; } if (requestData.Contains("FLAboutText")) { userProfile.FirstLifeAboutText = (string)requestData["FLAboutText"]; } // not in DB yet. if (requestData.Contains("ProfileURL")) { } if (requestData.Contains("home_region")) { try { userProfile.HomeRegion = Convert.ToUInt64((string)requestData["home_region"]); } catch (ArgumentException) { m_log.Error("[PROFILE]:Failed to set home region, Invalid Argument"); } catch (FormatException) { m_log.Error("[PROFILE]:Failed to set home region, Invalid Format"); } catch (OverflowException) { m_log.Error("[PROFILE]:Failed to set home region, Value was too large"); } } if (requestData.Contains("home_region_id")) { UUID regionID; UUID.TryParse((string)requestData["home_region_id"], out regionID); userProfile.HomeRegionID = regionID; } if (requestData.Contains("home_pos_x")) { try { userProfile.HomeLocationX = (float)Convert.ToDecimal((string)requestData["home_pos_x"], Culture.NumberFormatInfo); } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set home postion x"); } } if (requestData.Contains("home_pos_y")) { try { userProfile.HomeLocationY = (float)Convert.ToDecimal((string)requestData["home_pos_y"], Culture.NumberFormatInfo); } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set home postion y"); } } if (requestData.Contains("home_pos_z")) { try { userProfile.HomeLocationZ = (float)Convert.ToDecimal((string)requestData["home_pos_z"], Culture.NumberFormatInfo); } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set home postion z"); } } if (requestData.Contains("home_look_x")) { try { userProfile.HomeLookAtX = (float)Convert.ToDecimal((string)requestData["home_look_x"], Culture.NumberFormatInfo); } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set home lookat x"); } } if (requestData.Contains("home_look_y")) { try { userProfile.HomeLookAtY = (float)Convert.ToDecimal((string)requestData["home_look_y"], Culture.NumberFormatInfo); } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set home lookat y"); } } if (requestData.Contains("home_look_z")) { try { userProfile.HomeLookAtZ = (float)Convert.ToDecimal((string)requestData["home_look_z"], Culture.NumberFormatInfo); } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set home lookat z"); } } if (requestData.Contains("user_flags")) { try { userProfile.UserFlags = Convert.ToInt32((string)requestData["user_flags"]); } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set user flags"); } } if (requestData.Contains("god_level")) { try { userProfile.GodLevel = Convert.ToInt32((string)requestData["god_level"]); } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set god level"); } } if (requestData.Contains("custom_type")) { try { userProfile.CustomType = (string)requestData["custom_type"]; } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set custom type"); } } if (requestData.Contains("partner")) { try { userProfile.Partner = new UUID((string)requestData["partner"]); } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set partner"); } } else { userProfile.Partner = UUID.Zero; } // call plugin! bool ret = m_userDataBaseService.UpdateUserProfile(userProfile); responseData["returnString"] = ret.ToString(); response.Value = responseData; return response; } public XmlRpcResponse XmlRPCLogOffUserMethodUUID(XmlRpcRequest request, IPEndPoint remoteClient) { XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable)request.Params[0]; if (requestData.Contains("avatar_uuid")) { try { UUID userUUID = new UUID((string)requestData["avatar_uuid"]); UUID RegionID = new UUID((string)requestData["region_uuid"]); ulong regionhandle = (ulong)Convert.ToInt64((string)requestData["region_handle"]); Vector3 position = new Vector3( (float)Convert.ToDecimal((string)requestData["region_pos_x"], Culture.NumberFormatInfo), (float)Convert.ToDecimal((string)requestData["region_pos_y"], Culture.NumberFormatInfo), (float)Convert.ToDecimal((string)requestData["region_pos_z"], Culture.NumberFormatInfo)); Vector3 lookat = new Vector3( (float)Convert.ToDecimal((string)requestData["lookat_x"], Culture.NumberFormatInfo), (float)Convert.ToDecimal((string)requestData["lookat_y"], Culture.NumberFormatInfo), (float)Convert.ToDecimal((string)requestData["lookat_z"], Culture.NumberFormatInfo)); handlerLogOffUser = OnLogOffUser; if (handlerLogOffUser != null) handlerLogOffUser(userUUID); m_userDataBaseService.LogOffUser(userUUID, RegionID, regionhandle, position, lookat); } catch (FormatException) { m_log.Warn("[LOGOUT]: Error in Logout XMLRPC Params"); return response; } } else { return Util.CreateUnknownUserErrorResponse(); } return response; } #endregion public void HandleAgentLocation(UUID agentID, UUID regionID, ulong regionHandle) { UserProfileData userProfile = m_userDataBaseService.GetUserProfile(agentID); if (userProfile != null) { userProfile.CurrentAgent.Region = regionID; userProfile.CurrentAgent.Handle = regionHandle; m_userDataBaseService.CommitAgent(ref userProfile); } } public void HandleAgentLeaving(UUID agentID, UUID regionID, ulong regionHandle) { UserProfileData userProfile = m_userDataBaseService.GetUserProfile(agentID); if (userProfile != null) { if (userProfile.CurrentAgent.Region == regionID) { UserAgentData userAgent = userProfile.CurrentAgent; if (userAgent != null && userAgent.AgentOnline) { userAgent.AgentOnline = false; userAgent.LogoutTime = Util.UnixTimeSinceEpoch(); if (regionID != UUID.Zero) { userAgent.Region = regionID; } userAgent.Handle = regionHandle; userProfile.LastLogin = userAgent.LogoutTime; m_userDataBaseService.CommitAgent(ref userProfile); handlerLogOffUser = OnLogOffUser; if (handlerLogOffUser != null) handlerLogOffUser(agentID); } } } } public void HandleRegionStartup(UUID regionID) { m_userDataBaseService.LogoutUsers(regionID); } public void HandleRegionShutdown(UUID regionID) { m_userDataBaseService.LogoutUsers(regionID); } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Nick Berard, http://www.coderjournal.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // All code in this file requires .NET Framework 2.0 or later. #if !NET_1_1 && !NET_1_0 [assembly: Elmah.Scc("$Id: MySqlErrorLog.cs addb64b2f0fa 2012-03-07 18:50:16Z azizatif $")] namespace Elmah { #region Imports using System; using System.Collections; using System.Data; using MySql.Data.MySqlClient; #endregion /// <summary> /// An <see cref="ErrorLog"/> implementation that uses /// <a href="http://www.mysql.com/">MySQL</a> as its backing store. /// </summary> public class MySqlErrorLog : ErrorLog { private readonly string _connectionString; private const int _maxAppNameLength = 60; /// <summary> /// Initializes a new instance of the <see cref="SqlErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public MySqlErrorLog(IDictionary config) { if (config == null) throw new ArgumentNullException("config"); string connectionString = ConnectionStringHelper.GetConnectionString(config); // // If there is no connection string to use then throw an // exception to abort construction. // if (connectionString.Length == 0) throw new ApplicationException("Connection string is missing for the SQL error log."); _connectionString = connectionString; // // Set the application name as this implementation provides // per-application isolation over a single store. // string appName = Mask.NullString((string)config["applicationName"]); if (appName.Length > _maxAppNameLength) { throw new ApplicationException(string.Format( "Application name is too long. Maximum length allowed is {0} characters.", _maxAppNameLength.ToString("N0"))); } ApplicationName = appName; } /// <summary> /// Initializes a new instance of the <see cref="SqlErrorLog"/> class /// to use a specific connection string for connecting to the database. /// </summary> public MySqlErrorLog(string connectionString) { if (connectionString == null) throw new ArgumentNullException("connectionString"); if (connectionString.Length == 0) throw new ArgumentException(null, "connectionString"); _connectionString = connectionString; } /// <summary> /// Gets the name of this error log implementation. /// </summary> public override string Name { get { return "MySQL Server Error Log"; } } /// <summary> /// Gets the connection string used by the log to connect to the database. /// </summary> public virtual string ConnectionString { get { return _connectionString; } } /// <summary> /// Logs an error to the database. /// </summary> /// <remarks> /// Use the stored procedure called by this implementation to set a /// policy on how long errors are kept in the log. The default /// implementation stores all errors for an indefinite time. /// </remarks> public override string Log(Error error) { if (error == null) throw new ArgumentNullException("error"); string errorXml = ErrorXml.EncodeString(error); Guid id = Guid.NewGuid(); using (MySqlConnection connection = new MySqlConnection(ConnectionString)) using (MySqlCommand command = Commands.LogError( id, ApplicationName, error.HostName, error.Type, error.Source, error.Message, error.User, error.StatusCode, error.Time.ToUniversalTime(), errorXml)) { command.Connection = connection; connection.Open(); command.ExecuteNonQuery(); return id.ToString(); } } /// <summary> /// Returns a page of errors from the databse in descending order /// of logged time. /// </summary> public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList) { if (pageIndex < 0) throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null); if (pageSize < 0) throw new ArgumentOutOfRangeException("pageSize", pageSize, null); using (MySqlConnection connection = new MySqlConnection(ConnectionString)) using (MySqlCommand command = Commands.GetErrorsXml(ApplicationName, pageIndex, pageSize)) { command.Connection = connection; connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { Debug.Assert(reader != null); if (errorEntryList != null) { while (reader.Read()) { Error error = new Error(); error.ApplicationName = reader["Application"].ToString(); error.HostName = reader["Host"].ToString(); error.Type = reader["Type"].ToString(); error.Source = reader["Source"].ToString(); error.Message = reader["Message"].ToString(); error.User = reader["User"].ToString(); error.StatusCode = Convert.ToInt32(reader["StatusCode"]); error.Time = Convert.ToDateTime(reader.GetString("TimeUtc")).ToLocalTime(); errorEntryList.Add(new ErrorLogEntry(this, reader["ErrorId"].ToString(), error)); } } reader.Close(); } return (int)command.Parameters["TotalCount"].Value; } } /// <summary> /// Returns the specified error from the database, or null /// if it does not exist. /// </summary> public override ErrorLogEntry GetError(string id) { if (id == null) throw new ArgumentNullException("id"); if (id.Length == 0) throw new ArgumentException(null, "id"); Guid errorGuid; try { errorGuid = new Guid(id); } catch (FormatException e) { throw new ArgumentException(e.Message, "id", e); } string errorXml = null; using (MySqlConnection connection = new MySqlConnection(ConnectionString)) using (MySqlCommand command = Commands.GetErrorXml(ApplicationName, errorGuid)) { command.Connection = connection; connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { Debug.Assert(reader != null); while (reader.Read()) { errorXml = reader.GetString("AllXml"); } reader.Close(); } } if (errorXml == null) return null; Error error = ErrorXml.DecodeString(errorXml); return new ErrorLogEntry(this, id, error); } private static class Commands { public static MySqlCommand LogError( Guid id, string appName, string hostName, string typeName, string source, string message, string user, int statusCode, DateTime time, string xml) { MySqlCommand command = new MySqlCommand("elmah_LogError"); command.CommandType = CommandType.StoredProcedure; MySqlParameterCollection parameters = command.Parameters; parameters.Add("ErrorId", MySqlDbType.String, 36).Value = id.ToString(); parameters.Add("Application", MySqlDbType.VarChar, _maxAppNameLength).Value = appName.Substring(0, Math.Min(_maxAppNameLength, appName.Length)); parameters.Add("Host", MySqlDbType.VarChar, 30).Value = hostName.Substring(0, Math.Min(30, hostName.Length)); parameters.Add("Type", MySqlDbType.VarChar, 100).Value = typeName.Substring(0, Math.Min(100, typeName.Length)); parameters.Add("Source", MySqlDbType.VarChar, 60).Value = source.Substring(0, Math.Min(60, source.Length)); parameters.Add("Message", MySqlDbType.VarChar, 500).Value = message.Substring(0, Math.Min(500, message.Length)); parameters.Add("User", MySqlDbType.VarChar, 50).Value = user.Substring(0, Math.Min(50, user.Length)); parameters.Add("AllXml", MySqlDbType.Text).Value = xml; parameters.Add("StatusCode", MySqlDbType.Int32).Value = statusCode; parameters.Add("TimeUtc", MySqlDbType.Datetime).Value = time; return command; } public static MySqlCommand GetErrorXml(string appName, Guid id) { MySqlCommand command = new MySqlCommand("elmah_GetErrorXml"); command.CommandType = CommandType.StoredProcedure; MySqlParameterCollection parameters = command.Parameters; parameters.Add("Id", MySqlDbType.String, 36).Value = id.ToString(); parameters.Add("App", MySqlDbType.VarChar, _maxAppNameLength).Value = appName.Substring(0, Math.Min(_maxAppNameLength, appName.Length)); return command; } public static MySqlCommand GetErrorsXml(string appName, int pageIndex, int pageSize) { MySqlCommand command = new MySqlCommand("elmah_GetErrorsXml"); command.CommandType = CommandType.StoredProcedure; MySqlParameterCollection parameters = command.Parameters; parameters.Add("App", MySqlDbType.VarChar, _maxAppNameLength).Value = appName.Substring(0, Math.Min(_maxAppNameLength, appName.Length)); parameters.Add("PageIndex", MySqlDbType.Int32).Value = pageIndex; parameters.Add("PageSize", MySqlDbType.Int32).Value = pageSize; parameters.Add("TotalCount", MySqlDbType.Int32).Direction = ParameterDirection.Output; return command; } public static void GetErrorsXmlOutputs(MySqlCommand command, out int totalCount) { Debug.Assert(command != null); totalCount = (int)command.Parameters["TotalCount"].Value; } } } } #endif //!NET_1_1 && !NET_1_0
// // Copyright 2012, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Threading.Tasks; using System.Linq; using System.Collections.Generic; using Xamarin.Utilities; using System.Net; using System.Text; namespace Xamarin.Auth { /// <summary> /// Implements OAuth 2.0 implicit granting. http://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-4.2 /// </summary> #if XAMARIN_AUTH_INTERNAL internal class OAuth2Authenticator : WebRedirectAuthenticator #else public class OAuth2Authenticator : WebRedirectAuthenticator #endif { string clientId; string clientSecret; string scope; Uri authorizeUrl; Uri redirectUrl; Uri accessTokenUrl; GetUsernameAsyncFunc getUsernameAsync; string requestState; bool reportedForgery = false; /// <summary> /// Initializes a new <see cref="Xamarin.Auth.OAuth2Authenticator"/> /// that authenticates using implicit granting (token). /// </summary> /// <param name='clientId'> /// Client identifier. /// </param> /// <param name='scope'> /// Authorization scope. /// </param> /// <param name='authorizeUrl'> /// Authorize URL. /// </param> /// <param name='redirectUrl'> /// Redirect URL. /// </param> /// <param name='getUsernameAsync'> /// Method used to fetch the username of an account /// after it has been successfully authenticated. /// </param> public OAuth2Authenticator (string clientId, string scope, Uri authorizeUrl, Uri redirectUrl, GetUsernameAsyncFunc getUsernameAsync = null) : this (redirectUrl) { if (string.IsNullOrEmpty (clientId)) { throw new ArgumentException ("clientId must be provided", "clientId"); } this.clientId = clientId; this.scope = scope ?? ""; if (authorizeUrl == null) { throw new ArgumentNullException ("authorizeUrl"); } this.authorizeUrl = authorizeUrl; if (redirectUrl == null) { throw new ArgumentNullException ("redirectUrl"); } this.redirectUrl = redirectUrl; this.getUsernameAsync = getUsernameAsync; this.accessTokenUrl = null; } /// <summary> /// Initializes a new instance <see cref="Xamarin.Auth.OAuth2Authenticator"/> /// that authenticates using authorization codes (code). /// </summary> /// <param name='clientId'> /// Client identifier. /// </param> /// <param name='clientSecret'> /// Client secret. /// </param> /// <param name='scope'> /// Authorization scope. /// </param> /// <param name='authorizeUrl'> /// Authorize URL. /// </param> /// <param name='redirectUrl'> /// Redirect URL. /// </param> /// <param name='accessTokenUrl'> /// URL used to request access tokens after an authorization code was received. /// </param> /// <param name='getUsernameAsync'> /// Method used to fetch the username of an account /// after it has been successfully authenticated. /// </param> public OAuth2Authenticator (string clientId, string clientSecret, string scope, Uri authorizeUrl, Uri redirectUrl, Uri accessTokenUrl, GetUsernameAsyncFunc getUsernameAsync = null) : this (redirectUrl, clientSecret, accessTokenUrl) { if (string.IsNullOrEmpty (clientId)) { throw new ArgumentException ("clientId must be provided", "clientId"); } this.clientId = clientId; if (string.IsNullOrEmpty (clientSecret)) { throw new ArgumentException ("clientSecret must be provided", "clientSecret"); } this.clientSecret = clientSecret; this.scope = scope ?? ""; if (authorizeUrl == null) { throw new ArgumentNullException ("authorizeUrl"); } this.authorizeUrl = authorizeUrl; if (redirectUrl == null) { throw new ArgumentNullException ("redirectUrl"); } this.redirectUrl = redirectUrl; if (accessTokenUrl == null) { throw new ArgumentNullException ("accessTokenUrl"); } this.accessTokenUrl = accessTokenUrl; this.getUsernameAsync = getUsernameAsync; } OAuth2Authenticator (Uri redirectUrl, string clientSecret = null, Uri accessTokenUrl = null) : base (redirectUrl, redirectUrl) { if (redirectUrl == null) { throw new ArgumentNullException ("redirectUrl"); } this.redirectUrl = redirectUrl; this.clientSecret = clientSecret; this.accessTokenUrl = accessTokenUrl; // // Generate a unique state string to check for forgeries // var chars = new char[16]; var rand = new Random (); for (var i = 0; i < chars.Length; i++) { chars [i] = (char)rand.Next ((int)'a', (int)'z' + 1); } this.requestState = new string (chars); } public Uri AccessTokenUrl { get { return accessTokenUrl; } set { accessTokenUrl = value; }} bool IsImplicit { get { return accessTokenUrl == null; } } /// <summary> /// Method that returns the initial URL to be displayed in the web browser. /// </summary> /// <returns> /// A task that will return the initial URL. /// </returns> public override Task<Uri> GetInitialUrlAsync () { RedirectCalled = false; var url = new Uri (string.Format ( "{0}?client_id={1}&redirect_uri={2}&response_type={3}&scope={4}&state={5}", authorizeUrl.AbsoluteUri, Uri.EscapeDataString (clientId), Uri.EscapeDataString (redirectUrl.AbsoluteUri), IsImplicit ? "token" : "code", Uri.EscapeDataString (scope), Uri.EscapeDataString (requestState))); var tcs = new TaskCompletionSource<Uri> (); tcs.SetResult (url); return tcs.Task; } /// <summary> /// Raised when a new page has been loaded. /// </summary> /// <param name='url'> /// URL of the page. /// </param> /// <param name='query'> /// The parsed query of the URL. /// </param> /// <param name='fragment'> /// The parsed fragment of the URL. /// </param> protected override void OnPageEncountered (Uri url, IDictionary<string, string> query, IDictionary<string, string> fragment) { var all = new Dictionary<string, string> (query); foreach (var kv in fragment) all [kv.Key] = kv.Value; // // Check for forgeries // if (all.ContainsKey ("state")) { if (all ["state"] != requestState && !reportedForgery) { reportedForgery = true; OnError ("Invalid state from server. Possible forgery!"); return; } } // // Continue processing // base.OnPageEncountered (url, query, fragment); } /// <summary> /// Raised when a new page has been loaded. /// </summary> /// <param name='url'> /// URL of the page. /// </param> /// <param name='query'> /// The parsed query string of the URL. /// </param> /// <param name='fragment'> /// The parsed fragment of the URL. /// </param> protected override void OnRedirectPageLoaded (Uri url, IDictionary<string, string> query, IDictionary<string, string> fragment) { // // Look for the access_token // if (fragment.ContainsKey ("access_token")) { // // We found an access_token // OnRetrievedAccountProperties (fragment); } else if (!IsImplicit) { // // Look for the code // if (query.ContainsKey ("code")) { var code = query ["code"]; RequestAccessTokenAsync (code).ContinueWith (task => { if (task.IsFaulted) { OnError (task.Exception); } else { OnRetrievedAccountProperties (task.Result); } }, TaskScheduler.FromCurrentSynchronizationContext ()); } else { OnError ("Expected code in response, but did not receive one."); return; } } else { OnError ("Expected access_token in response, but did not receive one."); return; } } /// <summary> /// Implements: http://tools.ietf.org/html/rfc6749#section-4.1 /// </summary> /// <returns> /// The access token async. /// </returns> /// <param name='code'> /// Code. /// </param> Task<IDictionary<string,string>> RequestAccessTokenAsync (string code) { var queryValues = new Dictionary<string, string> { { "grant_type", "authorization_code" }, { "code", code }, { "redirect_uri", redirectUrl.AbsoluteUri }, { "client_id", clientId }, }; if (!string.IsNullOrEmpty (clientSecret)) { queryValues ["client_secret"] = clientSecret; } return RequestAccessTokenAsync (queryValues); } internal Task<IDictionary<string,string>> RequestAccessTokenAsync (IDictionary<string, string> queryValues) { var query = queryValues.FormEncode (); var req = WebRequest.Create (accessTokenUrl); req.Method = "POST"; var body = Encoding.UTF8.GetBytes (query); req.ContentLength = body.Length; req.ContentType = "application/x-www-form-urlencoded"; using (var s = req.GetRequestStream ()) { s.Write (body, 0, body.Length); } return req.GetResponseAsync ().ContinueWith (task => { var res = task.Result; var text = res.GetResponseText (); // Parse the response var data = text.Contains ("{") ? WebEx.JsonDecode (text) : WebEx.FormDecode (text); if (data.ContainsKey ("error")) { throw new AuthException ("Error authenticating: " + data ["error"]); } else if (data.ContainsKey ("access_token")) { return data; } else { throw new AuthException ("Expected access_token in access token response, but did not receive one."); } }, TaskScheduler.Default); } /// <summary> /// Event handler that is fired when an access token has been retreived. /// </summary> /// <param name='accountProperties'> /// The retrieved account properties /// </param> protected virtual void OnRetrievedAccountProperties (IDictionary<string, string> accountProperties) { // // Now we just need a username for the account // if (getUsernameAsync != null) { getUsernameAsync (accountProperties).ContinueWith (task => { if (task.IsFaulted) { OnError (task.Exception); } else { OnSucceeded (task.Result, accountProperties); } }, TaskScheduler.FromCurrentSynchronizationContext ()); } else { OnSucceeded ("", accountProperties); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using glassfactory.Areas.HelpPage.ModelDescriptions; using glassfactory.Areas.HelpPage.Models; namespace glassfactory.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; internal class test { public static int Main() { int x; int y; bool pass = true; x = -10; y = 4; x = x + y; if (x != -6) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x + y failed. x: {0}, \texpected: -6\n", x); pass = false; } x = -10; y = 4; x = x - y; if (x != -14) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x - y failed. x: {0}, \texpected: -14\n", x); pass = false; } x = -10; y = 4; x = x * y; if (x != -40) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x * y failed. x: {0}, \texpected: -40\n", x); pass = false; } x = -10; y = 4; x = x / y; if (x != -2) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x / y failed. x: {0}, \texpected: -2\n", x); pass = false; } x = -10; y = 4; x = x % y; if (x != -2) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x % y failed. x: {0}, \texpected: -2\n", x); pass = false; } x = -10; y = 4; x = x << y; if (x != -160) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x << y failed. x: {0}, \texpected: -160\n", x); pass = false; } x = -10; y = 4; x = x >> y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x >> y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x = x & y; if (x != 4) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x & y failed. x: {0}, \texpected: 4\n", x); pass = false; } x = -10; y = 4; x = x ^ y; if (x != -14) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x ^ y failed. x: {0}, \texpected: -14\n", x); pass = false; } x = -10; y = 4; x = x | y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x | y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x += x + y; if (x != -16) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x + y failed. x: {0}, \texpected: -16\n", x); pass = false; } x = -10; y = 4; x += x - y; if (x != -24) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x - y failed. x: {0}, \texpected: -24\n", x); pass = false; } x = -10; y = 4; x += x * y; if (x != -50) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x * y failed. x: {0}, \texpected: -50\n", x); pass = false; } x = -10; y = 4; x += x / y; if (x != -12) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x / y failed. x: {0}, \texpected: -12\n", x); pass = false; } x = -10; y = 4; x += x % y; if (x != -12) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x % y failed. x: {0}, \texpected: -12\n", x); pass = false; } x = -10; y = 4; x += x << y; if (x != -170) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x << y failed. x: {0}, \texpected: -170\n", x); pass = false; } x = -10; y = 4; x += x >> y; if (x != -11) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x >> y failed. x: {0}, \texpected: -11\n", x); pass = false; } x = -10; y = 4; x += x & y; if (x != -6) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x & y failed. x: {0}, \texpected: -6\n", x); pass = false; } x = -10; y = 4; x += x ^ y; if (x != -24) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x ^ y failed. x: {0}, \texpected: -24\n", x); pass = false; } x = -10; y = 4; x += x | y; if (x != -20) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x | y failed. x: {0}, \texpected: -20\n", x); pass = false; } x = -10; y = 4; x -= x + y; if (x != -4) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x + y failed. x: {0}, \texpected: -4\n", x); pass = false; } x = -10; y = 4; x -= x - y; if (x != 4) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x - y failed. x: {0}, \texpected: 4\n", x); pass = false; } x = -10; y = 4; x -= x * y; if (x != 30) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x * y failed. x: {0}, \texpected: 30\n", x); pass = false; } x = -10; y = 4; x -= x / y; if (x != -8) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x / y failed. x: {0}, \texpected: -8\n", x); pass = false; } x = -10; y = 4; x -= x % y; if (x != -8) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x % y failed. x: {0}, \texpected: -8\n", x); pass = false; } x = -10; y = 4; x -= x << y; if (x != 150) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x << y failed. x: {0}, \texpected: 150\n", x); pass = false; } x = -10; y = 4; x -= x >> y; if (x != -9) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x >> y failed. x: {0}, \texpected: -9\n", x); pass = false; } x = -10; y = 4; x -= x & y; if (x != -14) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x & y failed. x: {0}, \texpected: -14\n", x); pass = false; } x = -10; y = 4; x -= x ^ y; if (x != 4) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x ^ y failed. x: {0}, \texpected: 4\n", x); pass = false; } x = -10; y = 4; x -= x | y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x | y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x *= x + y; if (x != 60) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x + y failed. x: {0}, \texpected: 60\n", x); pass = false; } x = -10; y = 4; x *= x - y; if (x != 140) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x - y failed. x: {0}, \texpected: 140\n", x); pass = false; } x = -10; y = 4; x *= x * y; if (x != 400) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x * y failed. x: {0}, \texpected: 400\n", x); pass = false; } x = -10; y = 4; x *= x / y; if (x != 20) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x / y failed. x: {0}, \texpected: 20\n", x); pass = false; } x = -10; y = 4; x *= x % y; if (x != 20) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x % y failed. x: {0}, \texpected: 20\n", x); pass = false; } x = -10; y = 4; x *= x << y; if (x != 1600) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x << y failed. x: {0}, \texpected: 1600\n", x); pass = false; } x = -10; y = 4; x *= x >> y; if (x != 10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x >> y failed. x: {0}, \texpected: 10\n", x); pass = false; } x = -10; y = 4; x *= x & y; if (x != -40) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x & y failed. x: {0}, \texpected: -40\n", x); pass = false; } x = -10; y = 4; x *= x ^ y; if (x != 140) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x ^ y failed. x: {0}, \texpected: 140\n", x); pass = false; } x = -10; y = 4; x *= x | y; if (x != 100) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x | y failed. x: {0}, \texpected: 100\n", x); pass = false; } x = -10; y = 4; x /= x + y; if (x != 1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x + y failed. x: {0}, \texpected: 1\n", x); pass = false; } x = -10; y = 4; x /= x - y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x - y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x /= x * y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x * y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x /= x / y; if (x != 5) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x / y failed. x: {0}, \texpected: 5\n", x); pass = false; } x = -10; y = 4; x /= x % y; if (x != 5) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x % y failed. x: {0}, \texpected: 5\n", x); pass = false; } x = -10; y = 4; x /= x << y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x << y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x /= x >> y; if (x != 10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x >> y failed. x: {0}, \texpected: 10\n", x); pass = false; } x = -10; y = 4; x /= x & y; if (x != -2) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x & y failed. x: {0}, \texpected: -2\n", x); pass = false; } x = -10; y = 4; x /= x ^ y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x ^ y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x /= x | y; if (x != 1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x | y failed. x: {0}, \texpected: 1\n", x); pass = false; } x = -10; y = 4; x %= x + y; if (x != -4) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x + y failed. x: {0}, \texpected: -4\n", x); pass = false; } x = -10; y = 4; x %= x - y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x - y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x %= x * y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x * y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x %= x / y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x / y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x %= x % y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x % y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x %= x << y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x << y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x %= x >> y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x >> y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x %= x & y; if (x != -2) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x & y failed. x: {0}, \texpected: -2\n", x); pass = false; } x = -10; y = 4; x %= x ^ y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x ^ y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x %= x | y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x | y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x <<= x + y; if (x != -671088640) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x + y failed. x: {0}, \texpected: -671088640\n", x); pass = false; } x = -10; y = 4; x <<= x - y; if (x != -2621440) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x - y failed. x: {0}, \texpected: -2621440\n", x); pass = false; } x = -10; y = 4; x <<= x * y; if (x != -167772160) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x * y failed. x: {0}, \texpected: -167772160\n", x); pass = false; } x = -10; y = 4; x <<= x / y; if (x != -2147483648) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x / y failed. x: {0}, \texpected: -2147483648\n", x); pass = false; } x = -10; y = 4; x <<= x % y; if (x != -2147483648) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x % y failed. x: {0}, \texpected: -2147483648\n", x); pass = false; } x = -10; y = 4; x <<= x << y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x << y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x <<= x >> y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x >> y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x <<= x & y; if (x != -160) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x & y failed. x: {0}, \texpected: -160\n", x); pass = false; } x = -10; y = 4; x <<= x ^ y; if (x != -2621440) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x ^ y failed. x: {0}, \texpected: -2621440\n", x); pass = false; } x = -10; y = 4; x <<= x | y; if (x != -41943040) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x | y failed. x: {0}, \texpected: -41943040\n", x); pass = false; } x = -10; y = 4; x >>= x + y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x + y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x >>= x - y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x - y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x >>= x * y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x * y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x >>= x / y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x / y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x >>= x % y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x % y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x >>= x << y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x << y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x >>= x >> y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x >> y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x >>= x & y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x & y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x >>= x ^ y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x ^ y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x >>= x | y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x | y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x &= x + y; if (x != -14) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x + y failed. x: {0}, \texpected: -14\n", x); pass = false; } x = -10; y = 4; x &= x - y; if (x != -14) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x - y failed. x: {0}, \texpected: -14\n", x); pass = false; } x = -10; y = 4; x &= x * y; if (x != -48) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x * y failed. x: {0}, \texpected: -48\n", x); pass = false; } x = -10; y = 4; x &= x / y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x / y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x &= x % y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x % y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x &= x << y; if (x != -160) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x << y failed. x: {0}, \texpected: -160\n", x); pass = false; } x = -10; y = 4; x &= x >> y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x >> y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x &= x & y; if (x != 4) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x & y failed. x: {0}, \texpected: 4\n", x); pass = false; } x = -10; y = 4; x &= x ^ y; if (x != -14) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x ^ y failed. x: {0}, \texpected: -14\n", x); pass = false; } x = -10; y = 4; x &= x | y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x | y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x ^= x + y; if (x != 12) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x + y failed. x: {0}, \texpected: 12\n", x); pass = false; } x = -10; y = 4; x ^= x - y; if (x != 4) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x - y failed. x: {0}, \texpected: 4\n", x); pass = false; } x = -10; y = 4; x ^= x * y; if (x != 46) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x * y failed. x: {0}, \texpected: 46\n", x); pass = false; } x = -10; y = 4; x ^= x / y; if (x != 8) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x / y failed. x: {0}, \texpected: 8\n", x); pass = false; } x = -10; y = 4; x ^= x % y; if (x != 8) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x % y failed. x: {0}, \texpected: 8\n", x); pass = false; } x = -10; y = 4; x ^= x << y; if (x != 150) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x << y failed. x: {0}, \texpected: 150\n", x); pass = false; } x = -10; y = 4; x ^= x >> y; if (x != 9) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x >> y failed. x: {0}, \texpected: 9\n", x); pass = false; } x = -10; y = 4; x ^= x & y; if (x != -14) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x & y failed. x: {0}, \texpected: -14\n", x); pass = false; } x = -10; y = 4; x ^= x ^ y; if (x != 4) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x ^ y failed. x: {0}, \texpected: 4\n", x); pass = false; } x = -10; y = 4; x ^= x | y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x | y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x |= x + y; if (x != -2) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x + y failed. x: {0}, \texpected: -2\n", x); pass = false; } x = -10; y = 4; x |= x - y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x - y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x |= x * y; if (x != -2) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x * y failed. x: {0}, \texpected: -2\n", x); pass = false; } x = -10; y = 4; x |= x / y; if (x != -2) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x / y failed. x: {0}, \texpected: -2\n", x); pass = false; } x = -10; y = 4; x |= x % y; if (x != -2) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x % y failed. x: {0}, \texpected: -2\n", x); pass = false; } x = -10; y = 4; x |= x << y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x << y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x |= x >> y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x >> y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x |= x & y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x & y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x |= x ^ y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x ^ y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x |= x | y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x | y failed. x: {0}, \texpected: -10\n", x); pass = false; } if (pass) { Console.WriteLine("PASSED."); return 100; } else return 1; } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // James Driscoll, mailto:jamesdriscoll@btinternet.com // with contributions from Hath1 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // All code in this file requires .NET Framework 1.1 or later. #if !NET_1_0 [assembly: Elmah.Scc("$Id: OracleErrorLog.cs addb64b2f0fa 2012-03-07 18:50:16Z azizatif $")] namespace Elmah { #region Imports using System; using System.Data; using System.Data.OracleClient; using System.IO; using System.Text; using IDictionary = System.Collections.IDictionary; using IList = System.Collections.IList; #endregion /// <summary> /// An <see cref="ErrorLog"/> implementation that uses Oracle as its backing store. /// </summary> public class OracleErrorLog : ErrorLog { private readonly string _connectionString; private string _schemaOwner; private bool _schemaOwnerInitialized; private const int _maxAppNameLength = 60; private const int _maxSchemaNameLength = 30; /// <summary> /// Initializes a new instance of the <see cref="OracleErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public OracleErrorLog(IDictionary config) { if (config == null) throw new ArgumentNullException("config"); string connectionString = ConnectionStringHelper.GetConnectionString(config); // // If there is no connection string to use then throw an // exception to abort construction. // if (connectionString.Length == 0) throw new ApplicationException("Connection string is missing for the Oracle error log."); _connectionString = connectionString; // // Set the application name as this implementation provides // per-application isolation over a single store. // string appName = Mask.NullString((string)config["applicationName"]); if (appName.Length > _maxAppNameLength) { throw new ApplicationException(string.Format( "Application name is too long. Maximum length allowed is {0} characters.", _maxAppNameLength.ToString("N0"))); } ApplicationName = appName; SchemaOwner = (string)config["schemaOwner"]; } /// <summary> /// Initializes a new instance of the <see cref="OracleErrorLog"/> class /// to use a specific connection string for connecting to the database. /// </summary> public OracleErrorLog(string connectionString) { if (connectionString == null) throw new ArgumentNullException("connectionString"); if (connectionString.Length == 0) throw new ArgumentException(null, "connectionString"); _connectionString = connectionString; } /// <summary> /// Initializes a new instance of the <see cref="OracleErrorLog"/> class /// to use a specific connection string for connecting to the database and /// a specific schema owner. /// </summary> public OracleErrorLog(string connectionString, string schemaOwner) : this(connectionString) { SchemaOwner = schemaOwner; } /// <summary> /// Gets the name of the schema owner where the errors are being stored. /// </summary> public string SchemaOwner { get { return Mask.NullString(_schemaOwner); } set { if (_schemaOwnerInitialized) throw new InvalidOperationException("The schema owner cannot be reset once initialized."); _schemaOwner = Mask.NullString(value); if (_schemaOwner.Length == 0) return; if (_schemaOwner.Length > _maxSchemaNameLength) throw new ApplicationException(string.Format( "Oracle schema owner is too long. Maximum length allowed is {0} characters.", _maxSchemaNameLength.ToString("N0"))); _schemaOwner = _schemaOwner + "."; _schemaOwnerInitialized = true; } } /// <summary> /// Gets the name of this error log implementation. /// </summary> public override string Name { get { return "Oracle Error Log"; } } /// <summary> /// Gets the connection string used by the log to connect to the database. /// </summary> public virtual string ConnectionString { get { return _connectionString; } } /// <summary> /// Logs an error to the database. /// </summary> /// <remarks> /// Use the stored procedure called by this implementation to set a /// policy on how long errors are kept in the log. The default /// implementation stores all errors for an indefinite time. /// </remarks> public override string Log(Error error) { if (error == null) throw new ArgumentNullException("error"); string errorXml = ErrorXml.EncodeString(error); Guid id = Guid.NewGuid(); using (OracleConnection connection = new OracleConnection(this.ConnectionString)) using (OracleCommand command = connection.CreateCommand()) { connection.Open(); using (OracleTransaction transaction = connection.BeginTransaction()) { // because we are storing the XML data in a NClob, we need to jump through a few hoops!! // so first we've got to operate within a transaction command.Transaction = transaction; // then we need to create a temporary lob on the database server command.CommandText = "declare xx nclob; begin dbms_lob.createtemporary(xx, false, 0); :tempblob := xx; end;"; command.CommandType = CommandType.Text; OracleParameterCollection parameters = command.Parameters; parameters.Add("tempblob", OracleType.NClob).Direction = ParameterDirection.Output; command.ExecuteNonQuery(); // now we can get a handle to the NClob OracleLob xmlLob = (OracleLob)parameters[0].Value; // create a temporary buffer in which to store the XML byte[] tempbuff = Encoding.Unicode.GetBytes(errorXml); // and finally we can write to it! xmlLob.BeginBatch(OracleLobOpenMode.ReadWrite); xmlLob.Write(tempbuff,0,tempbuff.Length); xmlLob.EndBatch(); command.CommandText = SchemaOwner + "pkg_elmah$log_error.LogError"; command.CommandType = CommandType.StoredProcedure; parameters.Clear(); parameters.Add("v_ErrorId", OracleType.NVarChar, 32).Value = id.ToString("N"); parameters.Add("v_Application", OracleType.NVarChar, _maxAppNameLength).Value = string.IsNullOrEmpty(error.ApplicationName) ? this.ApplicationName : error.ApplicationName;; parameters.Add("v_Host", OracleType.NVarChar, 30).Value = error.HostName; parameters.Add("v_Type", OracleType.NVarChar, 100).Value = error.Type; parameters.Add("v_Source", OracleType.NVarChar, 60).Value = error.Source; parameters.Add("v_Message", OracleType.NVarChar, 500).Value = error.Message; parameters.Add("v_User", OracleType.NVarChar, 50).Value = error.User; parameters.Add("v_AllXml", OracleType.NClob).Value = xmlLob; parameters.Add("v_StatusCode", OracleType.Int32).Value = error.StatusCode; parameters.Add("v_TimeUtc", OracleType.DateTime).Value = error.Time.ToUniversalTime(); command.ExecuteNonQuery(); transaction.Commit(); } return id.ToString(); } } /// <summary> /// Returns a page of errors from the databse in descending order /// of logged time. /// </summary> public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList) { if (pageIndex < 0) throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null); if (pageSize < 0) throw new ArgumentOutOfRangeException("pageSize", pageSize, null); using (OracleConnection connection = new OracleConnection(this.ConnectionString)) using (OracleCommand command = connection.CreateCommand()) { command.CommandText = SchemaOwner + "pkg_elmah$get_error.GetErrorsXml"; command.CommandType = CommandType.StoredProcedure; OracleParameterCollection parameters = command.Parameters; parameters.Add("v_Application", OracleType.NVarChar, _maxAppNameLength).Value = ApplicationName; parameters.Add("v_PageIndex", OracleType.Int32).Value = pageIndex; parameters.Add("v_PageSize", OracleType.Int32).Value = pageSize; parameters.Add("v_TotalCount", OracleType.Int32).Direction = ParameterDirection.Output; parameters.Add("v_Results", OracleType.Cursor).Direction = ParameterDirection.Output; connection.Open(); using (OracleDataReader reader = command.ExecuteReader()) { Debug.Assert(reader != null); if (errorEntryList != null) { while (reader.Read()) { string id = reader["ErrorId"].ToString(); Guid guid = new Guid(id); Error error = new Error(); error.ApplicationName = reader["Application"].ToString(); error.HostName = reader["Host"].ToString(); error.Type = reader["Type"].ToString(); error.Source = reader["Source"].ToString(); error.Message = reader["Message"].ToString(); error.User = reader["UserName"].ToString(); error.StatusCode = Convert.ToInt32(reader["StatusCode"]); error.Time = Convert.ToDateTime(reader["TimeUtc"]).ToLocalTime(); errorEntryList.Add(new ErrorLogEntry(this, guid.ToString(), error)); } } reader.Close(); } return (int)command.Parameters["v_TotalCount"].Value; } } /// <summary> /// Returns the specified error from the database, or null /// if it does not exist. /// </summary> public override ErrorLogEntry GetError(string id) { if (id == null) throw new ArgumentNullException("id"); if (id.Length == 0) throw new ArgumentException(null, "id"); Guid errorGuid; try { errorGuid = new Guid(id); } catch (FormatException e) { throw new ArgumentException(e.Message, "id", e); } string errorXml; using (OracleConnection connection = new OracleConnection(this.ConnectionString)) using (OracleCommand command = connection.CreateCommand()) { command.CommandText = SchemaOwner + "pkg_elmah$get_error.GetErrorXml"; command.CommandType = CommandType.StoredProcedure; OracleParameterCollection parameters = command.Parameters; parameters.Add("v_Application", OracleType.NVarChar, _maxAppNameLength).Value = ApplicationName; parameters.Add("v_ErrorId", OracleType.NVarChar, 32).Value = errorGuid.ToString("N"); parameters.Add("v_AllXml", OracleType.NClob).Direction = ParameterDirection.Output; connection.Open(); command.ExecuteNonQuery(); OracleLob xmlLob = (OracleLob)command.Parameters["v_AllXml"].Value; StreamReader streamreader = new StreamReader(xmlLob, Encoding.Unicode); char[] cbuffer = new char[1000]; int actual; StringBuilder sb = new StringBuilder(); while((actual = streamreader.Read(cbuffer, 0, cbuffer.Length)) >0) sb.Append(cbuffer, 0, actual); errorXml = sb.ToString(); } if (errorXml == null) return null; Error error = ErrorXml.DecodeString(errorXml); return new ErrorLogEntry(this, id, error); } } } #endif //!NET_1_0
using System; using System.Collections; using System.IO; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities.Collections; namespace Org.BouncyCastle.Bcpg.OpenPgp { /// <remarks> /// Class to hold a single master secret key and its subkeys. /// <p> /// Often PGP keyring files consist of multiple master keys, if you are trying to process /// or construct one of these you should use the <c>PgpSecretKeyRingBundle</c> class. /// </p> /// </remarks> public class PgpSecretKeyRing : PgpKeyRing { private readonly IList keys; private readonly IList extraPubKeys; internal PgpSecretKeyRing( IList keys) : this(keys, new ArrayList()) { } private PgpSecretKeyRing( IList keys, IList extraPubKeys) { this.keys = keys; this.extraPubKeys = extraPubKeys; } public PgpSecretKeyRing( byte[] encoding) : this(new MemoryStream(encoding)) { } public PgpSecretKeyRing( Stream inputStream) { this.keys = new ArrayList(); this.extraPubKeys = new ArrayList(); BcpgInputStream bcpgInput = BcpgInputStream.Wrap(inputStream); PacketTag initialTag = bcpgInput.NextPacketTag(); if (initialTag != PacketTag.SecretKey && initialTag != PacketTag.SecretSubkey) { throw new IOException("secret key ring doesn't start with secret key tag: " + "tag 0x" + ((int)initialTag).ToString("X")); } SecretKeyPacket secret = (SecretKeyPacket) bcpgInput.ReadPacket(); // // ignore GPG comment packets if found. // while (bcpgInput.NextPacketTag() == PacketTag.Experimental2) { bcpgInput.ReadPacket(); } TrustPacket trust = ReadOptionalTrustPacket(bcpgInput); // revocation and direct signatures ArrayList keySigs = ReadSignaturesAndTrust(bcpgInput); ArrayList ids, idTrusts, idSigs; ReadUserIDs(bcpgInput, out ids, out idTrusts, out idSigs); keys.Add(new PgpSecretKey(secret, new PgpPublicKey(secret.PublicKeyPacket, trust, keySigs, ids, idTrusts, idSigs))); // Read subkeys while (bcpgInput.NextPacketTag() == PacketTag.SecretSubkey || bcpgInput.NextPacketTag() == PacketTag.PublicSubkey) { if (bcpgInput.NextPacketTag() == PacketTag.SecretSubkey) { SecretSubkeyPacket sub = (SecretSubkeyPacket) bcpgInput.ReadPacket(); // // ignore GPG comment packets if found. // while (bcpgInput.NextPacketTag() == PacketTag.Experimental2) { bcpgInput.ReadPacket(); } TrustPacket subTrust = ReadOptionalTrustPacket(bcpgInput); ArrayList sigList = ReadSignaturesAndTrust(bcpgInput); keys.Add(new PgpSecretKey(sub, new PgpPublicKey(sub.PublicKeyPacket, subTrust, sigList))); } else { PublicSubkeyPacket sub = (PublicSubkeyPacket) bcpgInput.ReadPacket(); TrustPacket subTrust = ReadOptionalTrustPacket(bcpgInput); ArrayList sigList = ReadSignaturesAndTrust(bcpgInput); extraPubKeys.Add(new PgpPublicKey(sub, subTrust, sigList)); } } } /// <summary>Return the public key for the master key.</summary> public PgpPublicKey GetPublicKey() { return ((PgpSecretKey) keys[0]).PublicKey; } /// <summary>Return the master private key.</summary> public PgpSecretKey GetSecretKey() { return (PgpSecretKey) keys[0]; } /// <summary>Allows enumeration of the secret keys.</summary> /// <returns>An <c>IEnumerable</c> of <c>PgpSecretKey</c> objects.</returns> public IEnumerable GetSecretKeys() { return new EnumerableProxy(keys); } public PgpSecretKey GetSecretKey( long keyId) { foreach (PgpSecretKey k in keys) { if (keyId == k.KeyId) { return k; } } return null; } /// <summary> /// Return an iterator of the public keys in the secret key ring that /// have no matching private key. At the moment only personal certificate data /// appears in this fashion. /// </summary> /// <returns>An <c>IEnumerable</c> of unattached, or extra, public keys.</returns> public IEnumerable GetExtraPublicKeys() { return new EnumerableProxy(extraPubKeys); } public byte[] GetEncoded() { MemoryStream bOut = new MemoryStream(); Encode(bOut); return bOut.ToArray(); } public void Encode( Stream outStr) { if (outStr == null) throw new ArgumentNullException("outStr"); foreach (PgpSecretKey key in keys) { key.Encode(outStr); } foreach (PgpPublicKey extraPubKey in extraPubKeys) { extraPubKey.Encode(outStr); } } /// <summary> /// Replace the public key set on the secret ring with the corresponding key off the public ring. /// </summary> /// <param name="secretRing">Secret ring to be changed.</param> /// <param name="publicRing">Public ring containing the new public key set.</param> public static PgpSecretKeyRing ReplacePublicKeys( PgpSecretKeyRing secretRing, PgpPublicKeyRing publicRing) { IList newList = new ArrayList(secretRing.keys.Count); foreach (PgpSecretKey sk in secretRing.keys) { PgpPublicKey pk = null; try { pk = publicRing.GetPublicKey(sk.KeyId); } catch (PgpException e) { throw new InvalidOperationException(e.Message, e); } newList.Add(PgpSecretKey.ReplacePublicKey(sk, pk)); } return new PgpSecretKeyRing(newList); } /// <summary> /// Return a copy of the passed in secret key ring, with the master key and sub keys encrypted /// using a new password and the passed in algorithm. /// </summary> /// <param name="ring">The <c>PgpSecretKeyRing</c> to be copied.</param> /// <param name="oldPassPhrase">The current password for key.</param> /// <param name="newPassPhrase">The new password for the key.</param> /// <param name="newEncAlgorithm">The algorithm to be used for the encryption.</param> /// <param name="rand">Source of randomness.</param> public static PgpSecretKeyRing CopyWithNewPassword( PgpSecretKeyRing ring, char[] oldPassPhrase, char[] newPassPhrase, SymmetricKeyAlgorithmTag newEncAlgorithm, SecureRandom rand) { IList newKeys = new ArrayList(ring.keys.Count); foreach (PgpSecretKey secretKey in ring.GetSecretKeys()) { newKeys.Add(PgpSecretKey.CopyWithNewPassword(secretKey, oldPassPhrase, newPassPhrase, newEncAlgorithm, rand)); } return new PgpSecretKeyRing(newKeys, ring.extraPubKeys); } /// <summary> /// Returns a new key ring with the secret key passed in either added or /// replacing an existing one with the same key ID. /// </summary> /// <param name="secRing">The secret key ring to be modified.</param> /// <param name="secKey">The secret key to be inserted.</param> /// <returns>A new <c>PgpSecretKeyRing</c></returns> public static PgpSecretKeyRing InsertSecretKey( PgpSecretKeyRing secRing, PgpSecretKey secKey) { ArrayList keys = new ArrayList(secRing.keys); bool found = false; bool masterFound = false; for (int i = 0; i != keys.Count; i++) { PgpSecretKey key = (PgpSecretKey) keys[i]; if (key.KeyId == secKey.KeyId) { found = true; keys[i] = secKey; } if (key.IsMasterKey) { masterFound = true; } } if (!found) { if (secKey.IsMasterKey) { if (masterFound) throw new ArgumentException("cannot add a master key to a ring that already has one"); keys.Insert(0, secKey); } else { keys.Add(secKey); } } return new PgpSecretKeyRing(keys, secRing.extraPubKeys); } /// <summary>Returns a new key ring with the secret key passed in removed from the key ring.</summary> /// <param name="secRing">The secret key ring to be modified.</param> /// <param name="secKey">The secret key to be removed.</param> /// <returns>A new <c>PgpSecretKeyRing</c>, or null if secKey is not found.</returns> public static PgpSecretKeyRing RemoveSecretKey( PgpSecretKeyRing secRing, PgpSecretKey secKey) { ArrayList keys = new ArrayList(secRing.keys); bool found = false; for (int i = 0; i < keys.Count; i++) { PgpSecretKey key = (PgpSecretKey)keys[i]; if (key.KeyId == secKey.KeyId) { found = true; keys.RemoveAt(i); } } return found ? new PgpSecretKeyRing(keys, secRing.extraPubKeys) : null; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: BitConverter ** ** ** Purpose: Allows developers to view the base data types as ** an arbitrary array of bits. ** ** ===========================================================*/ namespace System { using System; using System.Runtime.CompilerServices; // The BitConverter class contains methods for // converting an array of bytes to one of the base data // types, as well as for converting a base data type to an // array of bytes. // // Only statics, does not need to be marked with the serializable attribute public static class BitConverter { // This field indicates the "endianess" of the architecture. // The value is set to true if the architecture is // little endian; false if it is big endian. #if BIGENDIAN public static readonly bool IsLittleEndian /* = false */; #else public static readonly bool IsLittleEndian = true; #endif // Converts a byte into an array of bytes with length one. public static byte[] GetBytes( bool value ) { byte[] r = new byte[1]; r[0] = (value ? (byte)Boolean.True : (byte)Boolean.False); return r; } // Converts a char into an array of bytes with length two. public static byte[] GetBytes( char value ) { return GetBytes( (short)value ); } // Converts a short into an array of bytes with length // two. public unsafe static byte[] GetBytes( short value ) { byte[] bytes = new byte[2]; fixed(byte* b = bytes) { *((short*)b) = value; } return bytes; } // Converts an int into an array of bytes with length // four. public unsafe static byte[] GetBytes( int value ) { byte[] bytes = new byte[4]; fixed(byte* b = bytes) { *((int*)b) = value; } return bytes; } // Converts a long into an array of bytes with length // eight. public unsafe static byte[] GetBytes( long value ) { byte[] bytes = new byte[8]; fixed(byte* b = bytes) { *((long*)b) = value; } return bytes; } // Converts an ushort into an array of bytes with // length two. [CLSCompliant( false )] public static byte[] GetBytes( ushort value ) { return GetBytes( (short)value ); } // Converts an uint into an array of bytes with // length four. [CLSCompliant( false )] public static byte[] GetBytes( uint value ) { return GetBytes( (int)value ); } // Converts an unsigned long into an array of bytes with // length eight. [CLSCompliant( false )] public static byte[] GetBytes( ulong value ) { return GetBytes( (long)value ); } // Converts a float into an array of bytes with length // four. public unsafe static byte[] GetBytes( float value ) { return GetBytes( *(int*)&value ); } // Converts a double into an array of bytes with length // eight. public unsafe static byte[] GetBytes( double value ) { return GetBytes( *(long*)&value ); } // Converts an array of bytes into a char. public static char ToChar( byte[] value, int startIndex ) { return (char)ToInt16( value, startIndex ); } // Converts an array of bytes into a short. public static unsafe short ToInt16( byte[] value, int startIndex ) { if(value == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.value ); } if((uint)startIndex >= value.Length) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index ); } if(startIndex > value.Length - 2) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_ArrayPlusOffTooSmall ); } fixed(byte* pbyte = &value[startIndex]) { if(startIndex % 2 == 0) { // data is aligned return *((short*)pbyte); } else { if(IsLittleEndian) { return (short)((*pbyte) | (*(pbyte + 1) << 8)); } else { return (short)((*pbyte << 8) | (*(pbyte + 1))); } } } } // Converts an array of bytes into an int. public static unsafe int ToInt32( byte[] value, int startIndex ) { if(value == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.value ); } if((uint)startIndex >= value.Length) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index ); } if(startIndex > value.Length - 4) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_ArrayPlusOffTooSmall ); } fixed(byte* pbyte = &value[startIndex]) { if(startIndex % 4 == 0) { // data is aligned return *((int*)pbyte); } else { if(IsLittleEndian) { return (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); } else { return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); } } } } // Converts an array of bytes into a long. public static unsafe long ToInt64( byte[] value, int startIndex ) { if(value == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.value ); } if((uint)startIndex >= value.Length) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index ); } if(startIndex > value.Length - 8) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_ArrayPlusOffTooSmall ); } fixed(byte* pbyte = &value[startIndex]) { if(startIndex % 8 == 0) { // data is aligned return *((long*)pbyte); } else { if(IsLittleEndian) { int i1 = (*(pbyte )) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); int i2 = (*(pbyte + 4)) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24); return (uint)i1 | ((long)i2 << 32); } else { int i1 = (*(pbyte ) << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); int i2 = (*(pbyte + 4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7)); return (uint)i2 | ((long)i1 << 32); } } } } // Converts an array of bytes into an ushort. // [CLSCompliant( false )] public static ushort ToUInt16( byte[] value, int startIndex ) { return (ushort)ToInt16( value, startIndex ); } // Converts an array of bytes into an uint. // [CLSCompliant( false )] public static uint ToUInt32( byte[] value, int startIndex ) { return (uint)ToInt32( value, startIndex ); } // Converts an array of bytes into an unsigned long. // [CLSCompliant( false )] public static ulong ToUInt64( byte[] value, int startIndex ) { return (ulong)ToInt64( value, startIndex ); } // Converts an array of bytes into a float. unsafe public static float ToSingle( byte[] value, int startIndex ) { int val = ToInt32( value, startIndex ); return *(float*)&val; } // Converts an array of bytes into a double. unsafe public static double ToDouble( byte[] value, int startIndex ) { long val = ToInt64( value, startIndex ); return *(double*)&val; } private static char GetHexValue( int i ) { BCLDebug.Assert( i >= 0 && i < 16, "i is out of range." ); if(i < 10) { return (char)(i + '0'); } return (char)(i - 10 + 'A'); } // Converts an array of bytes into a String. public static String ToString( byte[] value, int startIndex, int length ) { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "byteArray" ); #else throw new ArgumentNullException(); #endif } int arrayLen = value.Length; if(startIndex < 0 || (startIndex >= arrayLen && startIndex > 0)) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_StartIndex" ) ); #else throw new ArgumentOutOfRangeException(); #endif } int realLength = length; if(realLength < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "length", Environment.GetResourceString( "ArgumentOutOfRange_GenericPositive" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(startIndex > arrayLen - realLength) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_ArrayPlusOffTooSmall" ) ); #else throw new ArgumentException(); #endif } if(realLength == 0) { return string.Empty; } char[] chArray = new char[realLength * 3]; int i = 0; int index = startIndex; for(i = 0; i < realLength * 3; i += 3) { byte b = value[index++]; chArray[i] = GetHexValue( b / 16 ); chArray[i + 1] = GetHexValue( b % 16 ); chArray[i + 2] = '-'; } // We don't need the last '-' character return new String( chArray, 0, chArray.Length - 1 ); } // Converts an array of bytes into a String. public static String ToString( byte[] value ) { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } return ToString( value, 0, value.Length ); } // Converts an array of bytes into a String. public static String ToString( byte[] value, int startIndex ) { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } return ToString( value, startIndex, value.Length - startIndex ); } /*==================================ToBoolean=================================== **Action: Convert an array of bytes to a boolean value. We treat this array ** as if the first 4 bytes were an Int4 an operate on this value. **Returns: True if the Int4 value of the first 4 bytes is non-zero. **Arguments: value -- The byte array ** startIndex -- The position within the array. **Exceptions: See ToInt4. ==============================================================================*/ // Converts an array of bytes into a boolean. public static bool ToBoolean( byte[] value, int startIndex ) { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } if(startIndex < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(startIndex > value.Length - 1) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return (value[startIndex] == 0) ? false : true; } public static unsafe long DoubleToInt64Bits( double value ) { return *((long*)&value); } public static unsafe double Int64BitsToDouble( long value ) { return *((double*)&value); } } }
// TarOutputStream.cs // // Copyright (C) 2001 Mike Krueger // Copyright 2005 John Reilly // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; using System.IO; namespace ICSharpCode.SharpZipLib.Tar { /// <summary> /// The TarOutputStream writes a UNIX tar archive as an OutputStream. /// Methods are provided to put entries, and then write their contents /// by writing to this stream using write(). /// </summary> /// public public class TarOutputStream : Stream { #region Constructors /// <summary> /// Construct TarOutputStream using default block factor /// </summary> /// <param name="outputStream">stream to write to</param> public TarOutputStream(Stream outputStream) : this(outputStream, TarBuffer.DefaultBlockFactor) { } /// <summary> /// Construct TarOutputStream with user specified block factor /// </summary> /// <param name="outputStream">stream to write to</param> /// <param name="blockFactor">blocking factor</param> public TarOutputStream(Stream outputStream, int blockFactor) { if ( outputStream == null ) { throw new ArgumentNullException("outputStream"); } this.outputStream = outputStream; buffer = TarBuffer.CreateOutputTarBuffer(outputStream, blockFactor); assemblyBuffer = new byte[TarBuffer.BlockSize]; blockBuffer = new byte[TarBuffer.BlockSize]; } #endregion /// <summary> /// Get/set flag indicating ownership of the underlying stream. /// When the flag is true <see cref="Close"></see> will close the underlying stream also. /// </summary> public bool IsStreamOwner { get { return buffer.IsStreamOwner; } set { buffer.IsStreamOwner = value; } } /// <summary> /// true if the stream supports reading; otherwise, false. /// </summary> public override bool CanRead { get { return outputStream.CanRead; } } /// <summary> /// true if the stream supports seeking; otherwise, false. /// </summary> public override bool CanSeek { get { return outputStream.CanSeek; } } /// <summary> /// true if stream supports writing; otherwise, false. /// </summary> public override bool CanWrite { get { return outputStream.CanWrite; } } /// <summary> /// length of stream in bytes /// </summary> public override long Length { get { return outputStream.Length; } } /// <summary> /// gets or sets the position within the current stream. /// </summary> public override long Position { get { return outputStream.Position; } set { outputStream.Position = value; } } /// <summary> /// set the position within the current stream /// </summary> /// <param name="offset">The offset relative to the <paramref name="origin"/> to seek to</param> /// <param name="origin">The <see cref="SeekOrigin"/> to seek from.</param> /// <returns>The new position in the stream.</returns> public override long Seek(long offset, SeekOrigin origin) { return outputStream.Seek(offset, origin); } /// <summary> /// Set the length of the current stream /// </summary> /// <param name="value">The new stream length.</param> public override void SetLength(long value) { outputStream.SetLength(value); } /// <summary> /// Read a byte from the stream and advance the position within the stream /// by one byte or returns -1 if at the end of the stream. /// </summary> /// <returns>The byte value or -1 if at end of stream</returns> public override int ReadByte() { return outputStream.ReadByte(); } /// <summary> /// read bytes from the current stream and advance the position within the /// stream by the number of bytes read. /// </summary> /// <param name="buffer">The buffer to store read bytes in.</param> /// <param name="offset">The index into the buffer to being storing bytes at.</param> /// <param name="count">The desired number of bytes to read.</param> /// <returns>The total number of bytes read, or zero if at the end of the stream. /// The number of bytes may be less than the <paramref name="count">count</paramref> /// requested if data is not avialable.</returns> public override int Read(byte[] buffer, int offset, int count) { return outputStream.Read(buffer, offset, count); } /// <summary> /// All buffered data is written to destination /// </summary> public override void Flush() { outputStream.Flush(); } /// <summary> /// Ends the TAR archive without closing the underlying OutputStream. /// The result is that the EOF block of nulls is written. /// </summary> public void Finish() { if ( IsEntryOpen ) { CloseEntry(); } WriteEofBlock(); } /// <summary> /// Ends the TAR archive and closes the underlying OutputStream. /// </summary> /// <remarks>This means that Finish() is called followed by calling the /// TarBuffer's Close().</remarks> public override void Close() { if ( !isClosed ) { isClosed = true; Finish(); buffer.Close(); } } /// <summary> /// Get the record size being used by this stream's TarBuffer. /// </summary> public int RecordSize { get { return buffer.RecordSize; } } /// <summary> /// Get the record size being used by this stream's TarBuffer. /// </summary> /// <returns> /// The TarBuffer record size. /// </returns> [Obsolete("Use RecordSize property instead")] public int GetRecordSize() { return buffer.RecordSize; } /// <summary> /// Get a value indicating wether an entry is open, requiring more data to be written. /// </summary> bool IsEntryOpen { get { return (currBytes < currSize); } } /// <summary> /// Put an entry on the output stream. This writes the entry's /// header and positions the output stream for writing /// the contents of the entry. Once this method is called, the /// stream is ready for calls to write() to write the entry's /// contents. Once the contents are written, closeEntry() /// <B>MUST</B> be called to ensure that all buffered data /// is completely written to the output stream. /// </summary> /// <param name="entry"> /// The TarEntry to be written to the archive. /// </param> public void PutNextEntry(TarEntry entry) { if ( entry == null ) { throw new ArgumentNullException("entry"); } if (entry.TarHeader.Name.Length >= TarHeader.NAMELEN) { TarHeader longHeader = new TarHeader(); longHeader.TypeFlag = TarHeader.LF_GNU_LONGNAME; longHeader.Name = longHeader.Name + "././@LongLink"; longHeader.UserId = 0; longHeader.GroupId = 0; longHeader.GroupName = ""; longHeader.UserName = ""; longHeader.LinkName = ""; longHeader.Size = entry.TarHeader.Name.Length; longHeader.WriteHeader(blockBuffer); buffer.WriteBlock(blockBuffer); // Add special long filename header block int nameCharIndex = 0; while (nameCharIndex < entry.TarHeader.Name.Length) { Array.Clear(blockBuffer, 0, blockBuffer.Length); TarHeader.GetAsciiBytes(entry.TarHeader.Name, nameCharIndex, this.blockBuffer, 0, TarBuffer.BlockSize); nameCharIndex += TarBuffer.BlockSize; buffer.WriteBlock(blockBuffer); } } entry.WriteEntryHeader(blockBuffer); buffer.WriteBlock(blockBuffer); currBytes = 0; currSize = entry.IsDirectory ? 0 : entry.Size; } /// <summary> /// Close an entry. This method MUST be called for all file /// entries that contain data. The reason is that we must /// buffer data written to the stream in order to satisfy /// the buffer's block based writes. Thus, there may be /// data fragments still being assembled that must be written /// to the output stream before this entry is closed and the /// next entry written. /// </summary> public void CloseEntry() { if (assemblyBufferLength > 0) { Array.Clear(assemblyBuffer, assemblyBufferLength, assemblyBuffer.Length - assemblyBufferLength); buffer.WriteBlock(assemblyBuffer); currBytes += assemblyBufferLength; assemblyBufferLength = 0; } if (currBytes < currSize) { string errorText = string.Format( "Entry closed at '{0}' before the '{1}' bytes specified in the header were written", currBytes, currSize); throw new TarException(errorText); } } /// <summary> /// Writes a byte to the current tar archive entry. /// This method simply calls Write(byte[], int, int). /// </summary> /// <param name="value"> /// The byte to be written. /// </param> public override void WriteByte(byte value) { Write(new byte[] { value }, 0, 1); } /// <summary> /// Writes bytes to the current tar archive entry. This method /// is aware of the current entry and will throw an exception if /// you attempt to write bytes past the length specified for the /// current entry. The method is also (painfully) aware of the /// record buffering required by TarBuffer, and manages buffers /// that are not a multiple of recordsize in length, including /// assembling records from small buffers. /// </summary> /// <param name = "buffer"> /// The buffer to write to the archive. /// </param> /// <param name = "offset"> /// The offset in the buffer from which to get bytes. /// </param> /// <param name = "count"> /// The number of bytes to write. /// </param> public override void Write(byte[] buffer, int offset, int count) { if ( buffer == null ) { throw new ArgumentNullException("buffer"); } if ( offset < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("offset"); #else throw new ArgumentOutOfRangeException("offset", "Cannot be negative"); #endif } if ( buffer.Length - offset < count ) { throw new ArgumentException("offset and count combination is invalid"); } if ( count < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", "Cannot be negative"); #endif } if ( (currBytes + count) > currSize ) { string errorText = string.Format("request to write '{0}' bytes exceeds size in header of '{1}' bytes", count, this.currSize); #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", errorText); #endif } // // We have to deal with assembly!!! // The programmer can be writing little 32 byte chunks for all // we know, and we must assemble complete blocks for writing. // TODO REVIEW Maybe this should be in TarBuffer? Could that help to // eliminate some of the buffer copying. // if (assemblyBufferLength > 0) { if ((assemblyBufferLength + count ) >= blockBuffer.Length) { int aLen = blockBuffer.Length - assemblyBufferLength; Array.Copy(assemblyBuffer, 0, blockBuffer, 0, assemblyBufferLength); Array.Copy(buffer, offset, blockBuffer, assemblyBufferLength, aLen); this.buffer.WriteBlock(blockBuffer); currBytes += blockBuffer.Length; offset += aLen; count -= aLen; assemblyBufferLength = 0; } else { Array.Copy(buffer, offset, assemblyBuffer, assemblyBufferLength, count); offset += count; assemblyBufferLength += count; count -= count; } } // // When we get here we have EITHER: // o An empty "assembly" buffer. // o No bytes to write (count == 0) // while (count > 0) { if (count < blockBuffer.Length) { Array.Copy(buffer, offset, assemblyBuffer, assemblyBufferLength, count); assemblyBufferLength += count; break; } this.buffer.WriteBlock(buffer, offset); int bufferLength = blockBuffer.Length; currBytes += bufferLength; count -= bufferLength; offset += bufferLength; } } /// <summary> /// Write an EOF (end of archive) block to the tar archive. /// An EOF block consists of all zeros. /// </summary> void WriteEofBlock() { Array.Clear(blockBuffer, 0, blockBuffer.Length); buffer.WriteBlock(blockBuffer); } #region Instance Fields /// <summary> /// bytes written for this entry so far /// </summary> long currBytes; /// <summary> /// current 'Assembly' buffer length /// </summary> int assemblyBufferLength; /// <summary> /// Flag indicating wether this instance has been closed or not. /// </summary> bool isClosed; /// <summary> /// Size for the current entry /// </summary> protected long currSize; /// <summary> /// single block working buffer /// </summary> protected byte[] blockBuffer; /// <summary> /// 'Assembly' buffer used to assemble data before writing /// </summary> protected byte[] assemblyBuffer; /// <summary> /// TarBuffer used to provide correct blocking factor /// </summary> protected TarBuffer buffer; /// <summary> /// the destination stream for the archive contents /// </summary> protected Stream outputStream; #endregion } } /* The original Java file had this header: ** Authored by Timothy Gerard Endres ** <mailto:time@gjt.org> <http://www.trustice.com> ** ** This work has been placed into the public domain. ** You may use this work in any way and for any purpose you wish. ** ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR ** REDISTRIBUTION OF THIS SOFTWARE. ** */
using System; namespace ICSharpCode.SharpZipLib.Core { #region EventArgs /// <summary> /// Event arguments for scanning. /// </summary> public class ScanEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanEventArgs"/> /// </summary> /// <param name="name">The file or directory name.</param> public ScanEventArgs(string name) { name_ = name; } #endregion Constructors /// <summary> /// The file or directory name for this event. /// </summary> public string Name { get { return name_; } } /// <summary> /// Get set a value indicating if scanning should continue or not. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } #region Instance Fields private string name_; private bool continueRunning_ = true; #endregion Instance Fields } /// <summary> /// Event arguments during processing of a single file or directory. /// </summary> public class ProgressEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanEventArgs"/> /// </summary> /// <param name="name">The file or directory name if known.</param> /// <param name="processed">The number of bytes processed so far</param> /// <param name="target">The total number of bytes to process, 0 if not known</param> public ProgressEventArgs(string name, long processed, long target) { name_ = name; processed_ = processed; target_ = target; } #endregion Constructors /// <summary> /// The name for this event if known. /// </summary> public string Name { get { return name_; } } /// <summary> /// Get set a value indicating wether scanning should continue or not. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } /// <summary> /// Get a percentage representing how much of the <see cref="Target"></see> has been processed /// </summary> /// <value>0.0 to 100.0 percent; 0 if target is not known.</value> public float PercentComplete { get { float result; if (target_ <= 0) { result = 0; } else { result = ((float)processed_ / (float)target_) * 100.0f; } return result; } } /// <summary> /// The number of bytes processed so far /// </summary> public long Processed { get { return processed_; } } /// <summary> /// The number of bytes to process. /// </summary> /// <remarks>Target may be 0 or negative if the value isnt known.</remarks> public long Target { get { return target_; } } #region Instance Fields private string name_; private long processed_; private long target_; private bool continueRunning_ = true; #endregion Instance Fields } /// <summary> /// Event arguments for directories. /// </summary> public class DirectoryEventArgs : ScanEventArgs { #region Constructors /// <summary> /// Initialize an instance of <see cref="DirectoryEventArgs"></see>. /// </summary> /// <param name="name">The name for this directory.</param> /// <param name="hasMatchingFiles">Flag value indicating if any matching files are contained in this directory.</param> public DirectoryEventArgs(string name, bool hasMatchingFiles) : base(name) { hasMatchingFiles_ = hasMatchingFiles; } #endregion Constructors /// <summary> /// Get a value indicating if the directory contains any matching files or not. /// </summary> public bool HasMatchingFiles { get { return hasMatchingFiles_; } } private readonly #region Instance Fields bool hasMatchingFiles_; #endregion Instance Fields } /// <summary> /// Arguments passed when scan failures are detected. /// </summary> public class ScanFailureEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanFailureEventArgs"></see> /// </summary> /// <param name="name">The name to apply.</param> /// <param name="e">The exception to use.</param> public ScanFailureEventArgs(string name, Exception e) { name_ = name; exception_ = e; continueRunning_ = true; } #endregion Constructors /// <summary> /// The applicable name. /// </summary> public string Name { get { return name_; } } /// <summary> /// The applicable exception. /// </summary> public Exception Exception { get { return exception_; } } /// <summary> /// Get / set a value indicating wether scanning should continue. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } #region Instance Fields private string name_; private Exception exception_; private bool continueRunning_; #endregion Instance Fields } #endregion EventArgs #region Delegates /// <summary> /// Delegate invoked before starting to process a file. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void ProcessFileHandler(object sender, ScanEventArgs e); /// <summary> /// Delegate invoked during processing of a file or directory /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void ProgressHandler(object sender, ProgressEventArgs e); /// <summary> /// Delegate invoked when a file has been completely processed. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void CompletedFileHandler(object sender, ScanEventArgs e); /// <summary> /// Delegate invoked when a directory failure is detected. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void DirectoryFailureHandler(object sender, ScanFailureEventArgs e); /// <summary> /// Delegate invoked when a file failure is detected. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void FileFailureHandler(object sender, ScanFailureEventArgs e); #endregion Delegates /// <summary> /// FileSystemScanner provides facilities scanning of files and directories. /// </summary> public class FileSystemScanner { #region Constructors /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="filter">The <see cref="PathFilter">file filter</see> to apply when scanning.</param> public FileSystemScanner(string filter) { fileFilter_ = new PathFilter(filter); } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param> /// <param name="directoryFilter">The <see cref="PathFilter"> directory filter</see> to apply.</param> public FileSystemScanner(string fileFilter, string directoryFilter) { fileFilter_ = new PathFilter(fileFilter); directoryFilter_ = new PathFilter(directoryFilter); } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The file <see cref="IScanFilter">filter</see> to apply.</param> public FileSystemScanner(IScanFilter fileFilter) { fileFilter_ = fileFilter; } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The file <see cref="IScanFilter">filter</see> to apply.</param> /// <param name="directoryFilter">The directory <see cref="IScanFilter">filter</see> to apply.</param> public FileSystemScanner(IScanFilter fileFilter, IScanFilter directoryFilter) { fileFilter_ = fileFilter; directoryFilter_ = directoryFilter; } #endregion Constructors #region Delegates /// <summary> /// Delegate to invoke when a directory is processed. /// </summary> public event EventHandler<DirectoryEventArgs> ProcessDirectory; /// <summary> /// Delegate to invoke when a file is processed. /// </summary> public ProcessFileHandler ProcessFile; /// <summary> /// Delegate to invoke when processing for a file has finished. /// </summary> public CompletedFileHandler CompletedFile; /// <summary> /// Delegate to invoke when a directory failure is detected. /// </summary> public DirectoryFailureHandler DirectoryFailure; /// <summary> /// Delegate to invoke when a file failure is detected. /// </summary> public FileFailureHandler FileFailure; #endregion Delegates /// <summary> /// Raise the DirectoryFailure event. /// </summary> /// <param name="directory">The directory name.</param> /// <param name="e">The exception detected.</param> private bool OnDirectoryFailure(string directory, Exception e) { DirectoryFailureHandler handler = DirectoryFailure; bool result = (handler != null); if (result) { var args = new ScanFailureEventArgs(directory, e); handler(this, args); alive_ = args.ContinueRunning; } return result; } /// <summary> /// Raise the FileFailure event. /// </summary> /// <param name="file">The file name.</param> /// <param name="e">The exception detected.</param> private bool OnFileFailure(string file, Exception e) { FileFailureHandler handler = FileFailure; bool result = (handler != null); if (result) { var args = new ScanFailureEventArgs(file, e); FileFailure(this, args); alive_ = args.ContinueRunning; } return result; } /// <summary> /// Raise the ProcessFile event. /// </summary> /// <param name="file">The file name.</param> private void OnProcessFile(string file) { ProcessFileHandler handler = ProcessFile; if (handler != null) { var args = new ScanEventArgs(file); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Raise the complete file event /// </summary> /// <param name="file">The file name</param> private void OnCompleteFile(string file) { CompletedFileHandler handler = CompletedFile; if (handler != null) { var args = new ScanEventArgs(file); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Raise the ProcessDirectory event. /// </summary> /// <param name="directory">The directory name.</param> /// <param name="hasMatchingFiles">Flag indicating if the directory has matching files.</param> private void OnProcessDirectory(string directory, bool hasMatchingFiles) { EventHandler<DirectoryEventArgs> handler = ProcessDirectory; if (handler != null) { var args = new DirectoryEventArgs(directory, hasMatchingFiles); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Scan a directory. /// </summary> /// <param name="directory">The base directory to scan.</param> /// <param name="recurse">True to recurse subdirectories, false to scan a single directory.</param> public void Scan(string directory, bool recurse) { alive_ = true; ScanDir(directory, recurse); } private void ScanDir(string directory, bool recurse) { try { string[] names = System.IO.Directory.GetFiles(directory); bool hasMatch = false; for (int fileIndex = 0; fileIndex < names.Length; ++fileIndex) { if (!fileFilter_.IsMatch(names[fileIndex])) { names[fileIndex] = null; } else { hasMatch = true; } } OnProcessDirectory(directory, hasMatch); if (alive_ && hasMatch) { foreach (string fileName in names) { try { if (fileName != null) { OnProcessFile(fileName); if (!alive_) { break; } } } catch (Exception e) { if (!OnFileFailure(fileName, e)) { throw; } } } } } catch (Exception e) { if (!OnDirectoryFailure(directory, e)) { throw; } } if (alive_ && recurse) { try { string[] names = System.IO.Directory.GetDirectories(directory); foreach (string fulldir in names) { if ((directoryFilter_ == null) || (directoryFilter_.IsMatch(fulldir))) { ScanDir(fulldir, true); if (!alive_) { break; } } } } catch (Exception e) { if (!OnDirectoryFailure(directory, e)) { throw; } } } } #region Instance Fields /// <summary> /// The file filter currently in use. /// </summary> private IScanFilter fileFilter_; /// <summary> /// The directory filter currently in use. /// </summary> private IScanFilter directoryFilter_; /// <summary> /// Flag indicating if scanning should continue running. /// </summary> private bool alive_; #endregion Instance Fields } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Collections.Generic { // The SortedDictionary class implements a generic sorted list of keys // and values. Entries in a sorted list are sorted by their keys and // are accessible both by key and by index. The keys of a sorted dictionary // can be ordered either according to a specific IComparer // implementation given when the sorted dictionary is instantiated, or // according to the IComparable implementation provided by the keys // themselves. In either case, a sorted dictionary does not allow entries // with duplicate or null keys. // // A sorted list internally maintains two arrays that store the keys and // values of the entries. The capacity of a sorted list is the allocated // length of these internal arrays. As elements are added to a sorted list, the // capacity of the sorted list is automatically increased as required by // reallocating the internal arrays. The capacity is never automatically // decreased, but users can call either TrimExcess or // Capacity explicitly. // // The GetKeyList and GetValueList methods of a sorted list // provides access to the keys and values of the sorted list in the form of // List implementations. The List objects returned by these // methods are aliases for the underlying sorted list, so modifications // made to those lists are directly reflected in the sorted list, and vice // versa. // // The SortedList class provides a convenient way to create a sorted // copy of another dictionary, such as a Hashtable. For example: // // Hashtable h = new Hashtable(); // h.Add(...); // h.Add(...); // ... // SortedList s = new SortedList(h); // // The last line above creates a sorted list that contains a copy of the keys // and values stored in the hashtable. In this particular example, the keys // will be ordered according to the IComparable interface, which they // all must implement. To impose a different ordering, SortedList also // has a constructor that allows a specific IComparer implementation to // be specified. // [DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))] [DebuggerDisplay("Count = {Count}")] [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class SortedList<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue> { private TKey[] keys; // Do not rename (binary serialization) private TValue[] values; // Do not rename (binary serialization) private int _size; // Do not rename (binary serialization) private int version; // Do not rename (binary serialization) private IComparer<TKey> comparer; // Do not rename (binary serialization) private KeyList keyList; // Do not rename (binary serialization) private ValueList valueList; // Do not rename (binary serialization) [NonSerialized] private object _syncRoot; private const int DefaultCapacity = 4; // Constructs a new sorted list. The sorted list is initially empty and has // a capacity of zero. Upon adding the first element to the sorted list the // capacity is increased to DefaultCapacity, and then increased in multiples of two as // required. The elements of the sorted list are ordered according to the // IComparable interface, which must be implemented by the keys of // all entries added to the sorted list. public SortedList() { keys = Array.Empty<TKey>(); values = Array.Empty<TValue>(); _size = 0; comparer = Comparer<TKey>.Default; } // Constructs a new sorted list. The sorted list is initially empty and has // a capacity of zero. Upon adding the first element to the sorted list the // capacity is increased to 16, and then increased in multiples of two as // required. The elements of the sorted list are ordered according to the // IComparable interface, which must be implemented by the keys of // all entries added to the sorted list. // public SortedList(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum); keys = new TKey[capacity]; values = new TValue[capacity]; comparer = Comparer<TKey>.Default; } // Constructs a new sorted list with a given IComparer // implementation. The sorted list is initially empty and has a capacity of // zero. Upon adding the first element to the sorted list the capacity is // increased to 16, and then increased in multiples of two as required. The // elements of the sorted list are ordered according to the given // IComparer implementation. If comparer is null, the // elements are compared to each other using the IComparable // interface, which in that case must be implemented by the keys of all // entries added to the sorted list. // public SortedList(IComparer<TKey> comparer) : this() { if (comparer != null) { this.comparer = comparer; } } // Constructs a new sorted dictionary with a given IComparer // implementation and a given initial capacity. The sorted list is // initially empty, but will have room for the given number of elements // before any reallocations are required. The elements of the sorted list // are ordered according to the given IComparer implementation. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented // by the keys of all entries added to the sorted list. // public SortedList(int capacity, IComparer<TKey> comparer) : this(comparer) { Capacity = capacity; } // Constructs a new sorted list containing a copy of the entries in the // given dictionary. The elements of the sorted list are ordered according // to the IComparable interface, which must be implemented by the // keys of all entries in the given dictionary as well as keys // subsequently added to the sorted list. // public SortedList(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { } // Constructs a new sorted list containing a copy of the entries in the // given dictionary. The elements of the sorted list are ordered according // to the given IComparer implementation. If comparer is // null, the elements are compared to each other using the // IComparable interface, which in that case must be implemented // by the keys of all entries in the given dictionary as well as keys // subsequently added to the sorted list. // public SortedList(IDictionary<TKey, TValue> dictionary, IComparer<TKey> comparer) : this((dictionary != null ? dictionary.Count : 0), comparer) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); int count = dictionary.Count; if (count != 0) { TKey[] keys = this.keys; dictionary.Keys.CopyTo(keys, 0); dictionary.Values.CopyTo(values, 0); Debug.Assert(count == this.keys.Length); if (count > 1) { comparer = Comparer; // obtain default if this is null. Array.Sort<TKey, TValue>(keys, values, comparer); for (int i = 1; i != keys.Length; ++i) { if (comparer.Compare(keys[i - 1], keys[i]) == 0) { throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, keys[i])); } } } } _size = count; } // Adds an entry with the given key and value to this sorted list. An // ArgumentException is thrown if the key is already present in the sorted list. // public void Add(TKey key, TValue value) { if (key == null) throw new ArgumentNullException(nameof(key)); int i = Array.BinarySearch<TKey>(keys, 0, _size, key, comparer); if (i >= 0) throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key), nameof(key)); Insert(~i, key, value); } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) { Add(keyValuePair.Key, keyValuePair.Value); } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair) { int index = IndexOfKey(keyValuePair.Key); if (index >= 0 && EqualityComparer<TValue>.Default.Equals(values[index], keyValuePair.Value)) { return true; } return false; } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair) { int index = IndexOfKey(keyValuePair.Key); if (index >= 0 && EqualityComparer<TValue>.Default.Equals(values[index], keyValuePair.Value)) { RemoveAt(index); return true; } return false; } // Returns the capacity of this sorted list. The capacity of a sorted list // represents the allocated length of the internal arrays used to store the // keys and values of the list, and thus also indicates the maximum number // of entries the list can contain before a reallocation of the internal // arrays is required. // public int Capacity { get { return keys.Length; } set { if (value != keys.Length) { if (value < _size) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_SmallCapacity); } if (value > 0) { TKey[] newKeys = new TKey[value]; TValue[] newValues = new TValue[value]; if (_size > 0) { Array.Copy(keys, 0, newKeys, 0, _size); Array.Copy(values, 0, newValues, 0, _size); } keys = newKeys; values = newValues; } else { keys = Array.Empty<TKey>(); values = Array.Empty<TValue>(); } } } } public IComparer<TKey> Comparer { get { return comparer; } } void IDictionary.Add(object key, object value) { if (key == null) throw new ArgumentNullException(nameof(key)); if (value == null && !(default(TValue) == null)) // null is an invalid value for Value types throw new ArgumentNullException(nameof(value)); if (!(key is TKey)) throw new ArgumentException(SR.Format(SR.Arg_WrongType, key, typeof(TKey)), nameof(key)); if (!(value is TValue) && value != null) // null is a valid value for Reference Types throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value)); Add((TKey)key, (TValue)value); } // Returns the number of entries in this sorted list. public int Count { get { return _size; } } // Returns a collection representing the keys of this sorted list. This // method returns the same object as GetKeyList, but typed as an // ICollection instead of an IList. public IList<TKey> Keys { get { return GetKeyListHelper(); } } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return GetKeyListHelper(); } } ICollection IDictionary.Keys { get { return GetKeyListHelper(); } } IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys { get { return GetKeyListHelper(); } } // Returns a collection representing the values of this sorted list. This // method returns the same object as GetValueList, but typed as an // ICollection instead of an IList. // public IList<TValue> Values { get { return GetValueListHelper(); } } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return GetValueListHelper(); } } ICollection IDictionary.Values { get { return GetValueListHelper(); } } IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values { get { return GetValueListHelper(); } } private KeyList GetKeyListHelper() { if (keyList == null) keyList = new KeyList(this); return keyList; } private ValueList GetValueListHelper() { if (valueList == null) valueList = new ValueList(this); return valueList; } bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } } bool IDictionary.IsReadOnly { get { return false; } } bool IDictionary.IsFixedSize { get { return false; } } bool ICollection.IsSynchronized { get { return false; } } // Synchronization root for this object. object ICollection.SyncRoot { get { if (_syncRoot == null) { Threading.Interlocked.CompareExchange(ref _syncRoot, new object(), null); } return _syncRoot; } } // Removes all entries from this sorted list. public void Clear() { // clear does not change the capacity version++; // Don't need to doc this but we clear the elements so that the gc can reclaim the references. if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>()) { Array.Clear(keys, 0, _size); } if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>()) { Array.Clear(values, 0, _size); } _size = 0; } bool IDictionary.Contains(object key) { if (IsCompatibleKey(key)) { return ContainsKey((TKey)key); } return false; } // Checks if this sorted list contains an entry with the given key. public bool ContainsKey(TKey key) { return IndexOfKey(key) >= 0; } // Checks if this sorted list contains an entry with the given value. The // values of the entries of the sorted list are compared to the given value // using the Object.Equals method. This method performs a linear // search and is substantially slower than the Contains // method. public bool ContainsValue(TValue value) { return IndexOfValue(value) >= 0; } // Copies the values in this SortedList to an array. void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index); } if (array.Length - arrayIndex < Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } for (int i = 0; i < Count; i++) { KeyValuePair<TKey, TValue> entry = new KeyValuePair<TKey, TValue>(keys[i], values[i]); array[arrayIndex + i] = entry; } } void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array)); } if (index < 0 || index > array.Length) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); } if (array.Length - index < Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } KeyValuePair<TKey, TValue>[] keyValuePairArray = array as KeyValuePair<TKey, TValue>[]; if (keyValuePairArray != null) { for (int i = 0; i < Count; i++) { keyValuePairArray[i + index] = new KeyValuePair<TKey, TValue>(keys[i], values[i]); } } else { object[] objects = array as object[]; if (objects == null) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } try { for (int i = 0; i < Count; i++) { objects[i + index] = new KeyValuePair<TKey, TValue>(keys[i], values[i]); } } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } } private const int MaxArrayLength = 0X7FEFFFFF; // Ensures that the capacity of this sorted list is at least the given // minimum value. If the current capacity of the list is less than // min, the capacity is increased to twice the current capacity or // to min, whichever is larger. private void EnsureCapacity(int min) { int newCapacity = keys.Length == 0 ? DefaultCapacity : keys.Length * 2; // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow. // Note that this check works even when _items.Length overflowed thanks to the (uint) cast if ((uint)newCapacity > MaxArrayLength) newCapacity = MaxArrayLength; if (newCapacity < min) newCapacity = min; Capacity = newCapacity; } // Returns the value of the entry at the given index. private TValue GetByIndex(int index) { if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); return values[index]; } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } IDictionaryEnumerator IDictionary.GetEnumerator() { return new Enumerator(this, Enumerator.DictEntry); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } // Returns the key of the entry at the given index. private TKey GetKey(int index) { if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); return keys[index]; } // Returns the value associated with the given key. If an entry with the // given key is not found, the returned value is null. public TValue this[TKey key] { get { int i = IndexOfKey(key); if (i >= 0) return values[i]; throw new KeyNotFoundException(); } set { if (((object)key) == null) throw new ArgumentNullException(nameof(key)); int i = Array.BinarySearch<TKey>(keys, 0, _size, key, comparer); if (i >= 0) { values[i] = value; version++; return; } Insert(~i, key, value); } } object IDictionary.this[object key] { get { if (IsCompatibleKey(key)) { int i = IndexOfKey((TKey)key); if (i >= 0) { return values[i]; } } return null; } set { if (!IsCompatibleKey(key)) { throw new ArgumentNullException(nameof(key)); } if (value == null && !(default(TValue) == null)) throw new ArgumentNullException(nameof(value)); TKey tempKey = (TKey)key; try { this[tempKey] = (TValue)value; } catch (InvalidCastException) { throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value)); } } } // Returns the index of the entry with a given key in this sorted list. The // key is located through a binary search, and thus the average execution // time of this method is proportional to Log2(size), where // size is the size of this sorted list. The returned value is -1 if // the given key does not occur in this sorted list. Null is an invalid // key value. public int IndexOfKey(TKey key) { if (key == null) throw new ArgumentNullException(nameof(key)); int ret = Array.BinarySearch<TKey>(keys, 0, _size, key, comparer); return ret >= 0 ? ret : -1; } // Returns the index of the first occurrence of an entry with a given value // in this sorted list. The entry is located through a linear search, and // thus the average execution time of this method is proportional to the // size of this sorted list. The elements of the list are compared to the // given value using the Object.Equals method. public int IndexOfValue(TValue value) { return Array.IndexOf(values, value, 0, _size); } // Inserts an entry with a given key and value at a given index. private void Insert(int index, TKey key, TValue value) { if (_size == keys.Length) EnsureCapacity(_size + 1); if (index < _size) { Array.Copy(keys, index, keys, index + 1, _size - index); Array.Copy(values, index, values, index + 1, _size - index); } keys[index] = key; values[index] = value; _size++; version++; } public bool TryGetValue(TKey key, out TValue value) { int i = IndexOfKey(key); if (i >= 0) { value = values[i]; return true; } value = default(TValue); return false; } // Removes the entry at the given index. The size of the sorted list is // decreased by one. public void RemoveAt(int index) { if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); _size--; if (index < _size) { Array.Copy(keys, index + 1, keys, index, _size - index); Array.Copy(values, index + 1, values, index, _size - index); } if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>()) { keys[_size] = default(TKey); } if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>()) { values[_size] = default(TValue); } version++; } // Removes an entry from this sorted list. If an entry with the specified // key exists in the sorted list, it is removed. An ArgumentException is // thrown if the key is null. public bool Remove(TKey key) { int i = IndexOfKey(key); if (i >= 0) RemoveAt(i); return i >= 0; } void IDictionary.Remove(object key) { if (IsCompatibleKey(key)) { Remove((TKey)key); } } // Sets the capacity of this sorted list to the size of the sorted list. // This method can be used to minimize a sorted list's memory overhead once // it is known that no new elements will be added to the sorted list. To // completely clear a sorted list and release all memory referenced by the // sorted list, execute the following statements: // // SortedList.Clear(); // SortedList.TrimExcess(); public void TrimExcess() { int threshold = (int)(((double)keys.Length) * 0.9); if (_size < threshold) { Capacity = _size; } } private static bool IsCompatibleKey(object key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } return (key is TKey); } private struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator { private SortedList<TKey, TValue> _sortedList; private TKey _key; private TValue _value; private int _index; private int _version; private int _getEnumeratorRetType; // What should Enumerator.Current return? internal const int KeyValuePair = 1; internal const int DictEntry = 2; internal Enumerator(SortedList<TKey, TValue> sortedList, int getEnumeratorRetType) { _sortedList = sortedList; _index = 0; _version = _sortedList.version; _getEnumeratorRetType = getEnumeratorRetType; _key = default(TKey); _value = default(TValue); } public void Dispose() { _index = 0; _key = default(TKey); _value = default(TValue); } object IDictionaryEnumerator.Key { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _key; } } public bool MoveNext() { if (_version != _sortedList.version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if ((uint)_index < (uint)_sortedList.Count) { _key = _sortedList.keys[_index]; _value = _sortedList.values[_index]; _index++; return true; } _index = _sortedList.Count + 1; _key = default(TKey); _value = default(TValue); return false; } DictionaryEntry IDictionaryEnumerator.Entry { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return new DictionaryEntry(_key, _value); } } public KeyValuePair<TKey, TValue> Current { get { return new KeyValuePair<TKey, TValue>(_key, _value); } } object IEnumerator.Current { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } if (_getEnumeratorRetType == DictEntry) { return new DictionaryEntry(_key, _value); } else { return new KeyValuePair<TKey, TValue>(_key, _value); } } } object IDictionaryEnumerator.Value { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _value; } } void IEnumerator.Reset() { if (_version != _sortedList.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _index = 0; _key = default(TKey); _value = default(TValue); } } private sealed class SortedListKeyEnumerator : IEnumerator<TKey>, IEnumerator { private SortedList<TKey, TValue> _sortedList; private int _index; private int _version; private TKey _currentKey; internal SortedListKeyEnumerator(SortedList<TKey, TValue> sortedList) { _sortedList = sortedList; _version = sortedList.version; } public void Dispose() { _index = 0; _currentKey = default(TKey); } public bool MoveNext() { if (_version != _sortedList.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if ((uint)_index < (uint)_sortedList.Count) { _currentKey = _sortedList.keys[_index]; _index++; return true; } _index = _sortedList.Count + 1; _currentKey = default(TKey); return false; } public TKey Current { get { return _currentKey; } } object IEnumerator.Current { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _currentKey; } } void IEnumerator.Reset() { if (_version != _sortedList.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _index = 0; _currentKey = default(TKey); } } private sealed class SortedListValueEnumerator : IEnumerator<TValue>, IEnumerator { private SortedList<TKey, TValue> _sortedList; private int _index; private int _version; private TValue _currentValue; internal SortedListValueEnumerator(SortedList<TKey, TValue> sortedList) { _sortedList = sortedList; _version = sortedList.version; } public void Dispose() { _index = 0; _currentValue = default(TValue); } public bool MoveNext() { if (_version != _sortedList.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if ((uint)_index < (uint)_sortedList.Count) { _currentValue = _sortedList.values[_index]; _index++; return true; } _index = _sortedList.Count + 1; _currentValue = default(TValue); return false; } public TValue Current { get { return _currentValue; } } object IEnumerator.Current { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _currentValue; } } void IEnumerator.Reset() { if (_version != _sortedList.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _index = 0; _currentValue = default(TValue); } } [DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] [Serializable] public sealed class KeyList : IList<TKey>, ICollection { private SortedList<TKey, TValue> _dict; // Do not rename (binary serialization) internal KeyList(SortedList<TKey, TValue> dictionary) { _dict = dictionary; } public int Count { get { return _dict._size; } } public bool IsReadOnly { get { return true; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return ((ICollection)_dict).SyncRoot; } } public void Add(TKey key) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public void Clear() { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public bool Contains(TKey key) { return _dict.ContainsKey(key); } public void CopyTo(TKey[] array, int arrayIndex) { // defer error checking to Array.Copy Array.Copy(_dict.keys, 0, array, arrayIndex, _dict.Count); } void ICollection.CopyTo(Array array, int arrayIndex) { if (array != null && array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); try { // defer error checking to Array.Copy Array.Copy(_dict.keys, 0, array, arrayIndex, _dict.Count); } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } public void Insert(int index, TKey value) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public TKey this[int index] { get { return _dict.GetKey(index); } set { throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); } } public IEnumerator<TKey> GetEnumerator() { return new SortedListKeyEnumerator(_dict); } IEnumerator IEnumerable.GetEnumerator() { return new SortedListKeyEnumerator(_dict); } public int IndexOf(TKey key) { if (((object)key) == null) throw new ArgumentNullException(nameof(key)); int i = Array.BinarySearch<TKey>(_dict.keys, 0, _dict.Count, key, _dict.comparer); if (i >= 0) return i; return -1; } public bool Remove(TKey key) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); // return false; } public void RemoveAt(int index) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } } [DebuggerTypeProxy(typeof(DictionaryValueCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] [Serializable] public sealed class ValueList : IList<TValue>, ICollection { private SortedList<TKey, TValue> _dict; // Do not rename (binary serialization) internal ValueList(SortedList<TKey, TValue> dictionary) { _dict = dictionary; } public int Count { get { return _dict._size; } } public bool IsReadOnly { get { return true; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return ((ICollection)_dict).SyncRoot; } } public void Add(TValue key) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public void Clear() { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public bool Contains(TValue value) { return _dict.ContainsValue(value); } public void CopyTo(TValue[] array, int arrayIndex) { // defer error checking to Array.Copy Array.Copy(_dict.values, 0, array, arrayIndex, _dict.Count); } void ICollection.CopyTo(Array array, int index) { if (array != null && array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); try { // defer error checking to Array.Copy Array.Copy(_dict.values, 0, array, index, _dict.Count); } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } public void Insert(int index, TValue value) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public TValue this[int index] { get { return _dict.GetByIndex(index); } set { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } } public IEnumerator<TValue> GetEnumerator() { return new SortedListValueEnumerator(_dict); } IEnumerator IEnumerable.GetEnumerator() { return new SortedListValueEnumerator(_dict); } public int IndexOf(TValue value) { return Array.IndexOf(_dict.values, value, 0, _dict.Count); } public bool Remove(TValue value) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); // return false; } public void RemoveAt(int index) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } } } }
#region File Header and License // /* // DistributedLockProxy.cs // Copyright 2008-2017 Gibraltar Software, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // */ #endregion using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; namespace Gibraltar.DistributedLocking.Internal { /// <summary> /// A class to hold a lock for this process (app domain) and pass it fairly to other waiting threads before release. /// </summary> internal class DistributedLockProxy { private const int LockPollingDelay = 16; // 16 ms wait between attempts to open a lock file. private const int BackOffDelay = LockPollingDelay * 3; // 48 ms wait when another process requests a turn. private readonly ConcurrentQueue<DistributedLock> _waitQueue = new ConcurrentQueue<DistributedLock>(); private readonly object _currentLockLock = new object(); private readonly IDistributedLockProvider _provider; private readonly string _name; private DistributedLock _currentLockTurn; //protected by currentLockLock private IDisposable _lock;//protected by currentLockLock private IDisposable _lockRequest;//protected by currentLockLock private DateTimeOffset _minTimeNextTurn = DateTimeOffset.MinValue; private bool _disposed; /// <summary> /// Raised when the lock is disposed. /// </summary> internal event EventHandler Disposed; internal DistributedLockProxy(IDistributedLockProvider provider, string name) { _provider = provider; _name = name; } #region Public Properties and Methods ///<summary> ///Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. ///</summary> ///<filterpriority>2</filterpriority> public void Dispose() { // Call the underlying implementation Dispose(true); // SuppressFinalize because there won't be anything left to finalize GC.SuppressFinalize(this); } /// <summary> /// The name of the lock within the scope. /// </summary> public string Name => _name; /// <summary> /// Whether this lock instance has been disposed (and thus does not hold any locks). /// </summary> public bool IsDisposed => _disposed; /// <summary> /// Reports how many threads are in the queue waiting on the lock (some may have timed out and given up already). /// (Reports -1 if the proxy is idle (no current turn).) /// </summary> public int WaitingCount => (_currentLockTurn == null) ? -1 : _waitQueue.Count; #endregion #region Internal Properties and Methods /// <summary> /// Object persistence policy for this instance: Whether to dispose this instance when file lock is released. /// </summary> internal bool DisposeOnClose { get; set; } /// <summary> /// Check the thread with the current turn for the lock and grant a secondary lock if applicable. /// </summary> /// <param name="candidateLock">An unexpired lock request on the current thread, or null to just check the turn thread.</param> /// <returns>The activity Id with the current turn for the lock, or null if there are none holding or waiting.</returns> internal Guid? CheckCurrentTurnThread(DistributedLock candidateLock) { var currentLockId = DistributedLockManager.CurrentLockId; if (candidateLock != null && candidateLock.OwningLockId != currentLockId) throw new InvalidOperationException("A lock request may only be waited on by the thread which created it."); lock (_currentLockLock) { if (_currentLockTurn != null) { var currentOwningLockId = _currentLockTurn.OwningLockId; if (candidateLock != null && currentLockId == currentOwningLockId) { candidateLock.GrantTheLock(_currentLockTurn); // Set it as a secondary lock on that holder (same thread). if (candidateLock.ActualLock == _currentLockTurn) // Sanity-check that it was successful. candidateLock.OurLockProxy = this; // So its dispose-on-close setting pass-through can function. } return currentOwningLockId; // Whether it's a match or some other thread. } return null; // No thread owns the lock. } } /// <summary> /// Queue a lock request (RepositoryLock instance). Must be followed by a call to AwaitOurTurnOrTimeout (which can block). /// </summary> /// <param name="lockRequest"></param> internal void QueueRequest(DistributedLock lockRequest) { if (string.Equals(lockRequest.Name, _name, StringComparison.OrdinalIgnoreCase) == false) throw new InvalidOperationException("A lock request may not be queued to a proxy for a different full name."); if (lockRequest.OwningLockId != DistributedLockManager.CurrentLockId) throw new InvalidOperationException("A lock request may only be queued by the thread which created it."); _waitQueue.Enqueue(lockRequest); } /// <summary> /// Wait for our turn to have the lock (and wait for the lock) up to our time limit /// </summary> /// <param name="lockRequest"></param> /// <returns></returns> internal bool AwaitOurTurnOrTimeout(DistributedLock lockRequest) { if (lockRequest.IsExpired) throw new InvalidOperationException("Can't wait on an expired lock request."); if (string.Equals(lockRequest.Name, _name, StringComparison.OrdinalIgnoreCase) == false) throw new InvalidOperationException("A lock request may not be queued to a proxy for a different full name."); if (lockRequest.OwningLockId != DistributedLockManager.CurrentLockId) throw new InvalidOperationException("A lock request may only be waited on by the thread which created it."); lockRequest.OurLockProxy = this; // Mark the request as pending with us. // Do NOT clear out current lock owner, this will allow DequeueNextRequest to find one already there, if any. bool ourTurn = StartNextTurn(lockRequest); // Gets its own queue lock. if (ourTurn == false) { // It's not our turn yet, we need to wait our turn. Are we willing to wait? if (lockRequest.WaitForLock && lockRequest.WaitTimeout > DateTimeOffset.Now) ourTurn = lockRequest.AwaitTurnOrTimeout(); // Still not our turn? if (ourTurn == false) { if (!CommonCentralLogic.SilentMode) { // Who actually has the lock right now? lock(_currentLockLock) { if (_currentLockTurn != null) { var currentOwningActivityId = _currentLockTurn.OwningLockId; Trace.WriteLine(string.Format("{0}\r\nA lock request gave up because it is still being held by another thread.\r\n" + "Lock file: {1}\r\nCurrent holding Activity: {2}", lockRequest.WaitForLock ? "Lock request timed out" : "Lock request couldn't wait", _name, currentOwningActivityId)); } else { Trace.TraceError("Lock request turn error\r\nA lock request failed to get its turn but the current lock turn is null. " + "This probably should not happen.\r\nLock file: {0}\r\n", _name); } } } lockRequest.Dispose(); // Expire the request. return false; // Failed to get the lock. Time to give up. } } // Yay, now it's our turn! Do we already hold the lock? bool validLock; IDisposable curLock; lock(_currentLockLock) { curLock = _lock; } if (curLock != null) validLock = true; // It's our request's turn and this proxy already holds the lock! else validLock = TryGetLock(lockRequest); // Can we get the lock? // Do we actually have the lock now? if (validLock) { lockRequest.GrantTheLock(lockRequest); // It owns the actual lock itself now. } else { if (!CommonCentralLogic.SilentMode) { Trace.WriteLine(string.Format("{0}\r\nA lock request gave up because it could not obtain the file lock. " + "It is most likely still held by another process.\r\nLock file: {1}", lockRequest.WaitForLock ? "Lock request timed out" : "Lock request couldn't wait", _name)); } lockRequest.Dispose(); // Failed to get the lock. Expire the request and give up. } return validLock; } #endregion #region Private Properties and Methods /// <summary> /// Try to get the actual file lock on behalf of the current request. /// </summary> /// <param name="currentRequest"></param> /// <returns></returns> private bool TryGetLock(DistributedLock currentRequest) { var waitForLock = currentRequest.WaitForLock; var lockTimeout = currentRequest.WaitTimeout; var validLock = false; while (waitForLock == false || DateTimeOffset.Now < lockTimeout) { if (DateTimeOffset.Now >= _minTimeNextTurn) // Make sure we aren't in a back-off delay. { var newLock = _provider.GetLock(_name); if (newLock != null) { lock(_currentLockLock) { _lock = newLock; // We have the lock! Close our lock request if we have one so later we can detect if anyone else does. if (_lockRequest != null) { _lockRequest.Dispose(); _lockRequest = null; } } validLock = true; // Report that we have the lock now. } } // Otherwise, just pretend we couldn't get the lock in this attempt. if (validLock == false && waitForLock) { // We didn't get the lock and we want to wait for it, so try to open a lock request. lock(_currentLockLock) { if (_lockRequest == null) _lockRequest = _provider.GetLockRequest(_name); // Tell the other process we'd like a turn. } // Then we should allow some real time to pass before trying again because external locks aren't very fast. Thread.Sleep(LockPollingDelay); } else { // We either got the lock or the user doesn't want to keep retrying, so exit the loop. break; } } return validLock; } /// <summary> /// Find the next request still waiting and signal it to go. Or return true if the current caller may proceed. /// </summary> /// <param name="currentRequest">The request the caller is waiting on, or null for none.</param> /// <returns>True if the caller's supplied request is the next turn, false otherwise.</returns> private bool StartNextTurn(DistributedLock currentRequest) { lock (_currentLockLock) { int dequeueCount = DequeueNextRequest(); // Find the next turn if there isn't one already underway. if (_currentLockTurn != null) { // If we popped a new turn off the queue make sure it gets started. if (dequeueCount > 0) _currentLockTurn.SignalMyTurn(); // Signal the thread waiting on that request to proceed. if (ReferenceEquals(_currentLockTurn, currentRequest)) // Is the current request the next turn? { return true; // Yes, so skip waiting and just tell our caller they can go ahead (and wait for the lock). } } else { // Otherwise, nothing else is waiting on the lock! Time to shut it down. if (_lockRequest != null) { _lockRequest.Dispose(); // Release the lock request (an open read) since we're no longer waiting on it. _lockRequest = null; } if (_lock != null) { _lock.Dispose(); // Release the external lock. _lock = null; } if (DisposeOnClose) Dispose(); } return false; } } private int DequeueNextRequest() { lock (_currentLockLock) { var dequeueCount = 0; RuntimeHelpers.PrepareConstrainedRegions(); // Make sure we don't thread-abort in the middle of this logic. try { } finally { while (_currentLockTurn == null && _waitQueue.TryDequeue(out _currentLockTurn) == true) { dequeueCount++; if (_currentLockTurn.IsExpired) { _currentLockTurn.Dispose(); // There's no one waiting on that request, so just discard it. _currentLockTurn = null; // Get the next one (if any) on next loop. } else { _currentLockTurn.Disposed += Lock_Disposed; // Subscribe to their Disposed event. Now we care. } } } return dequeueCount; } } /// <summary> /// Performs the actual releasing of managed and unmanaged resources. /// Most usage should instead call Dispose(), which will call Dispose(true) for you /// and will suppress redundant finalization. /// </summary> /// <param name="releaseManaged">Indicates whether to release managed resources. /// This should only be called with true, except from the finalizer which should call Dispose(false).</param> private void Dispose(bool releaseManaged) { if (releaseManaged) { // Free managed resources here (normal Dispose() stuff, which should itself call Dispose(true)) // Other objects may be referenced in this case if (!_disposed) { _disposed = true; // Make sure we don't do it more than once. // Empty our queue (although it should already be empty!). while (_waitQueue.IsEmpty == false) { if (_waitQueue.TryDequeue(out var lockInstance)) { lockInstance.SafeDispose();// Tell any threads still waiting that their request has expired. } } lock(_currentLockLock) { if (_currentLockTurn == null) { // No thread is currently prepared to do this, so clear them here. if (_lockRequest != null) { _lockRequest.Dispose(); _lockRequest = null; } if (_lock != null) { _lock.Dispose(); _lock = null; } } } // We're not fully disposed until the current lock owner gets disposed so we can release the lock. // But fire the event to tell the RepositoryLockManager that we are no longer a valid proxy. OnDispose(); } } else { // Even in this case when we are in the finalizer We need to be sure we release any object handles we may still have. _lockRequest = null; _lock = null; } } private void OnDispose() { EventHandler tempEvent = Disposed; if (tempEvent != null) { tempEvent.Invoke(this, new EventArgs()); } } private void Lock_Disposed(object sender, EventArgs e) { DistributedLock disposingLock = (DistributedLock)sender; disposingLock.Disposed -= Lock_Disposed; // Unsubscribe. //we need to remove this object from the lock collection lock (_currentLockLock) { // Only remove the lock if the one we're disposing is the original top-level lock for that key. if (_currentLockTurn == null || ReferenceEquals(_currentLockTurn, disposingLock) == false) return; // Wasn't our current holder, so we don't care about it. _currentLockTurn = null; // It's disposed, no longer current owner. if (_disposed == false) { // We're releasing the lock for this thread. We need to check if any other process has a request pending. // And if so, we need to force this process to wait a minimum delay, even if we don't have one waiting now. if (_lock != null && _provider.CheckLockRequest(_name)) { _minTimeNextTurn = DateTimeOffset.Now.AddMilliseconds(BackOffDelay); // Back off for a bit. _lock.Dispose(); // We have to give up the OS lock because other processes need a chance. _lock = null; } StartNextTurn(null); // Find and signal the next turn to go ahead (also handles all-done). } else { // We're already disposed, so we'd better release the lock and request now if we still have them! if (_lockRequest != null) { _lockRequest.Dispose(); _lockRequest = null; } if (_lock != null) { _lock.Dispose(); _lock = null; } } } } #endregion } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MediaElementRenderer.cs" company="In The Hand Ltd"> // Copyright (c) 2017-19 In The Hand Ltd, All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using AVFoundation; using AVKit; using CoreMedia; using Foundation; using InTheHand.Forms; using System; using System.Collections.Generic; using System.IO; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof(InTheHand.Forms.MediaElement), typeof(InTheHand.Forms.Platform.iOS.MediaElementRenderer))] namespace InTheHand.Forms.Platform.iOS { public sealed class MediaElementRenderer : ViewRenderer<InTheHand.Forms.MediaElement, UIView> { IMediaElementController Controller => Element as IMediaElementController; private AVPlayerViewController _avPlayerViewController = new AVPlayerViewController(); private NSObject _playedToEndObserver; private NSObject _rateObserver; private NSObject _statusObserver; TimeSpan Position { get { if (_avPlayerViewController.Player.CurrentTime.IsInvalid) return TimeSpan.Zero; return TimeSpan.FromSeconds(_avPlayerViewController.Player.CurrentTime.Seconds); } } protected override void OnElementChanged(Xamarin.Forms.Platform.iOS.ElementChangedEventArgs<MediaElement> e) { base.OnElementChanged(e); if (e.OldElement != null) { e.OldElement.PropertyChanged -= OnElementPropertyChanged; e.OldElement.SeekRequested -= MediaElementSeekRequested; e.OldElement.StateRequested -= MediaElementStateRequested; e.OldElement.PositionRequested -= MediaElementPositionRequested; e.OldElement.VolumeRequested -= MediaElementVolumeRequested; if (_playedToEndObserver != null) { NSNotificationCenter.DefaultCenter.RemoveObserver(_playedToEndObserver); _playedToEndObserver = null; } // stop video if playing if (_avPlayerViewController?.Player?.CurrentItem != null) { RemoveStatusObserver(); _avPlayerViewController.Player.Pause(); _avPlayerViewController.Player.Seek(CMTime.Zero); _avPlayerViewController.Player.ReplaceCurrentItemWithPlayerItem(null); AVAudioSession.SharedInstance().SetActive(false); } } if (e.NewElement != null) { SetNativeControl(_avPlayerViewController.View); Element.PropertyChanged += OnElementPropertyChanged; Element.SeekRequested += MediaElementSeekRequested; Element.StateRequested += MediaElementStateRequested; Element.PositionRequested += MediaElementPositionRequested; Element.VolumeRequested += MediaElementVolumeRequested; _avPlayerViewController.ShowsPlaybackControls = Element.ShowsPlaybackControls; _avPlayerViewController.VideoGravity = AspectToGravity(Element.Aspect); if (Element.KeepScreenOn) { SetKeepScreenOn(true); } _playedToEndObserver = NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, PlayedToEnd); UpdateBackgroundColor(); UpdateSource(); } } void UpdateBackgroundColor() { Control.BackgroundColor = Element.BackgroundColor.ToUIColor(); } private bool _idleTimerDisabled = false; private void SetKeepScreenOn(bool value) { if (value) { if (!UIApplication.SharedApplication.IdleTimerDisabled) { _idleTimerDisabled = true; UIApplication.SharedApplication.IdleTimerDisabled = true; } } else { if (_idleTimerDisabled) { _idleTimerDisabled = false; UIApplication.SharedApplication.IdleTimerDisabled = false; } } } private AVUrlAssetOptions GetOptionsWithHeaders(IDictionary<string, string> headers) { var nativeHeaders = new NSMutableDictionary(); foreach (var header in headers) { nativeHeaders.Add((NSString)header.Key, (NSString)header.Value); } var nativeHeadersKey = (NSString)"AVURLAssetHTTPHeaderFieldsKey"; var options = new AVUrlAssetOptions(NSDictionary.FromObjectAndKey( nativeHeaders, nativeHeadersKey )); return options; } private void UpdateSource() { if (Element.Source != null) { AVAsset asset = null; if (Element.Source.Scheme == null) { // file path asset = AVAsset.FromUrl(NSUrl.FromFilename(Element.Source.OriginalString)); } else if (Element.Source.Scheme == "ms-appx") { // used for a file embedded in the application package asset = AVAsset.FromUrl(NSUrl.FromFilename(Element.Source.LocalPath.Substring(1))); } else if (Element.Source.Scheme == "ms-appdata") { string filePath = ResolveMsAppDataUri(Element.Source); if (string.IsNullOrEmpty(filePath)) throw new ArgumentException("Invalid Uri", "Source"); asset = AVAsset.FromUrl(NSUrl.FromFilename(filePath)); } else if (Element.Source.IsFile) { asset = AVAsset.FromUrl(NSUrl.FromFilename(Element.Source.LocalPath)); } else { asset = AVUrlAsset.Create(NSUrl.FromString(Element.Source.AbsoluteUri), GetOptionsWithHeaders(Element.HttpHeaders)); } var item = new AVPlayerItem(asset); RemoveStatusObserver(); _statusObserver = (NSObject)item.AddObserver("status", NSKeyValueObservingOptions.New, ObserveStatus); if (_avPlayerViewController.Player != null) { _avPlayerViewController.Player.ReplaceCurrentItemWithPlayerItem(item); } else { _avPlayerViewController.Player = new AVPlayer(item); _rateObserver = (NSObject)_avPlayerViewController.Player.AddObserver("rate", NSKeyValueObservingOptions.New, ObserveRate); } if (Element.AutoPlay) { Play(); } } else { if (Element.CurrentState == MediaElementState.Playing || Element.CurrentState == MediaElementState.Buffering) { _avPlayerViewController.Player.ReplaceCurrentItemWithPlayerItem(null); Controller.CurrentState = MediaElementState.Stopped; } } } internal static string ResolveMsAppDataUri(Uri uri) { if (uri.Scheme == "ms-appdata") { string filePath; if (uri.LocalPath.StartsWith("/local")) { var libraryPath = NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User)[0].Path; filePath = Path.Combine(libraryPath, uri.LocalPath.Substring(7)); } else if (uri.LocalPath.StartsWith("/temp")) { filePath = Path.Combine(Path.GetTempPath(), uri.LocalPath.Substring(6)); } else { throw new ArgumentException("Invalid Uri", "Source"); } return filePath; } else { throw new ArgumentException("uri"); } } protected override void Dispose(bool disposing) { if (_playedToEndObserver != null) { NSNotificationCenter.DefaultCenter.RemoveObserver(_playedToEndObserver); _playedToEndObserver = null; } if (_rateObserver != null) { _avPlayerViewController?.Player?.RemoveObserver(_rateObserver, "rate"); _rateObserver = null; } RemoveStatusObserver(); _avPlayerViewController?.Player?.ReplaceCurrentItemWithPlayerItem(null); base.Dispose(disposing); } private void RemoveStatusObserver() { if (_statusObserver != null) { try { _avPlayerViewController?.Player?.CurrentItem?.RemoveObserver(_statusObserver, "status"); } catch { } finally { _statusObserver = null; } } } private void MediaElementVolumeRequested(object sender, EventArgs e) { Controller.Volume = _avPlayerViewController.Player.Volume; } void MediaElementPositionRequested(object sender, EventArgs e) { Controller.Position = Position; } void MediaElementSeekRequested(object sender, SeekRequested e) { if (_avPlayerViewController.Player.Status != AVPlayerStatus.ReadyToPlay || _avPlayerViewController.Player.CurrentItem == null) return; NSValue[] ranges = _avPlayerViewController.Player.CurrentItem.SeekableTimeRanges; CMTime seekTo = new CMTime(Convert.ToInt64(e.Position.TotalMilliseconds), 1000); foreach (NSValue v in ranges) { if (seekTo >= v.CMTimeRangeValue.Start && seekTo < (v.CMTimeRangeValue.Start + v.CMTimeRangeValue.Duration)) { _avPlayerViewController.Player.Seek(seekTo, SeekComplete); break; } } } void MediaElementStateRequested(object sender, StateRequested e) { if (_avPlayerViewController.Player.CurrentItem == null) return; MediaElementVolumeRequested(this, EventArgs.Empty); switch (e.State) { case MediaElementState.Playing: Play(); break; case MediaElementState.Paused: if (Element.KeepScreenOn) { SetKeepScreenOn(false); } if (_avPlayerViewController.Player != null) { _avPlayerViewController.Player.Pause(); Controller.CurrentState = MediaElementState.Paused; } break; case MediaElementState.Stopped: if (Element.KeepScreenOn) { SetKeepScreenOn(false); } // ios has no stop... _avPlayerViewController?.Player.Pause(); _avPlayerViewController?.Player.Seek(CMTime.Zero); Controller.CurrentState = MediaElementState.Stopped; NSError err = AVAudioSession.SharedInstance().SetActive(false); break; } Controller.Position = Position; } void ObserveRate(NSObservedChange e) { if (Controller is object) { switch (_avPlayerViewController.Player.Rate) { case 0.0f: Controller.CurrentState = MediaElementState.Paused; break; case 1.0f: Controller.CurrentState = MediaElementState.Playing; break; } Controller.Position = Position; } } private void ObserveStatus(NSObservedChange e) { Controller.Volume = _avPlayerViewController.Player.Volume; switch (_avPlayerViewController.Player.Status) { case AVPlayerStatus.Failed: Controller.OnMediaFailed(); break; case AVPlayerStatus.ReadyToPlay: if (double.IsNaN(_avPlayerViewController.Player.CurrentItem.Duration.Seconds)) { Controller.OnMediaFailed(); } else { Controller.CurrentState = _avPlayerViewController.Player.Rate == 0.0f ? MediaElementState.Stopped : MediaElementState.Playing; Controller.Duration = TimeSpan.FromSeconds(_avPlayerViewController.Player.CurrentItem.Duration.Seconds); Controller.VideoHeight = (int)_avPlayerViewController.Player.CurrentItem.Asset.NaturalSize.Height; Controller.VideoWidth = (int)_avPlayerViewController.Player.CurrentItem.Asset.NaturalSize.Width; Controller.OnMediaOpened(); Controller.Position = Position; } break; } } void Play() { var audioSession = AVAudioSession.SharedInstance(); NSError err = audioSession.SetCategory(AVAudioSession.CategoryPlayback); audioSession.SetMode(AVAudioSession.ModeMoviePlayback, out err); err = audioSession.SetActive(true); if (_avPlayerViewController.Player != null) { _avPlayerViewController.Player.Play(); Controller.CurrentState = MediaElementState.Playing; } if (Element.KeepScreenOn) { SetKeepScreenOn(true); } } private void PlayedToEnd(NSNotification notification) { if (Element.IsLooping) { _avPlayerViewController.Player.Seek(CMTime.Zero); _avPlayerViewController.Player.Play(); } else { SetKeepScreenOn(false); Controller.Position = Position; try { Device.BeginInvokeOnMainThread(Controller.OnMediaEnded); } catch { } } } /*private void Touched() { if (_avPlayerViewController.Player.Rate == 1.0) { Element.Pause(); //player.Pause(); } else { if(_avPlayerViewController.Player.CurrentTime == _avPlayerViewController.Player.CurrentItem.Duration) { _avPlayerViewController.Player.Seek(CMTime.FromSeconds(0,1)); } Element.Play(); //player.Play(); } }*/ protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { switch (e.PropertyName) { case nameof(Aspect): _avPlayerViewController.VideoGravity = AspectToGravity(Element.Aspect); break; case nameof(MediaElement.BackgroundColor): UpdateBackgroundColor(); break; case nameof(MediaElement.CurrentState): switch (Element.CurrentState) { case MediaElementState.Playing: Play(); break; case MediaElementState.Paused: if (Element.KeepScreenOn) { SetKeepScreenOn(false); } _avPlayerViewController.Player.Pause(); break; case MediaElementState.Stopped: if (Element.KeepScreenOn) { SetKeepScreenOn(false); } // ios has no stop... _avPlayerViewController.Player.Pause(); _avPlayerViewController.Player.Seek(CMTime.Zero); var err = AVAudioSession.SharedInstance().SetActive(false); break; } break; case nameof(MediaElement.KeepScreenOn): if (!Element.KeepScreenOn) { SetKeepScreenOn(false); } else if (Element.CurrentState == MediaElementState.Playing) { // only toggle this on if property is set while video is already running SetKeepScreenOn(true); } break; case nameof(MediaElement.ShowsPlaybackControls): _avPlayerViewController.ShowsPlaybackControls = Element.ShowsPlaybackControls; break; case nameof(MediaElement.Source): UpdateSource(); break; case nameof(MediaElement.Volume): _avPlayerViewController.Player.Volume = (float)Element.Volume; break; } base.OnElementPropertyChanged(sender, e); } static AVLayerVideoGravity AspectToGravity(Aspect aspect) { switch (aspect) { case Aspect.Fill: return AVLayerVideoGravity.Resize; case Aspect.AspectFill: return AVLayerVideoGravity.ResizeAspectFill; default: return AVLayerVideoGravity.ResizeAspect; } } private void SeekComplete(bool finished) { if (finished) { Controller?.OnSeekCompleted(); } } } } /*using AVFoundation; using AVKit; using CoreMedia; using Foundation; using InTheHand.Forms; using System; using System.Collections.Generic; using System.IO; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof(MediaElement), typeof(InTheHand.Forms.Platform.iOS.MediaElementRenderer))] namespace InTheHand.Forms.Platform.iOS { public sealed class MediaElementRenderer : AVPlayerViewController, IVisualElementRenderer { MediaElement MediaElement { get; set; } IMediaElementController Controller => MediaElement as IMediaElementController; #pragma warning disable 0414 VisualElementPackager _packager; EventTracker _events; VisualElementTracker _tracker; #pragma warning restore 0414 NSObject _playToEndObserver; NSObject _statusObserver; NSObject _rateObserver; VisualElement IVisualElementRenderer.Element => MediaElement; UIView IVisualElementRenderer.NativeView { get { if (_isDisposed) return new UIView(); return View; } } UIViewController IVisualElementRenderer.ViewController => this; bool _idleTimerDisabled = false; public MediaElementRenderer() { _playToEndObserver = NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, PlayedToEnd); View.AutoresizingMask = UIViewAutoresizing.FlexibleDimensions; View.ContentMode = UIViewContentMode.ScaleToFill; } public override bool ShouldAutorotate() { return true; } void SetKeepScreenOn(bool value) { if (value) { if (!UIApplication.SharedApplication.IdleTimerDisabled) { _idleTimerDisabled = true; UIApplication.SharedApplication.IdleTimerDisabled = true; } } else if (_idleTimerDisabled) { _idleTimerDisabled = false; UIApplication.SharedApplication.IdleTimerDisabled = false; } } private AVUrlAssetOptions GetOptionsWithHeaders(IDictionary<string, string> headers) { var nativeHeaders = new NSMutableDictionary(); foreach (var header in headers) { nativeHeaders.Add((NSString)header.Key, (NSString)header.Value); } var nativeHeadersKey = (NSString)"AVURLAssetHTTPHeaderFieldsKey"; var options = new AVUrlAssetOptions(NSDictionary.FromObjectAndKey( nativeHeaders, nativeHeadersKey )); return options; } private bool _isDisposed = false; protected override void Dispose(bool disposing) { if (!_isDisposed) { _isDisposed = true; Player?.Pause(); if (_playToEndObserver != null) { NSNotificationCenter.DefaultCenter.RemoveObserver(_playToEndObserver); _playToEndObserver.Dispose(); _playToEndObserver = null; } if (_rateObserver != null) { _rateObserver.Dispose(); _rateObserver = null; } RemoveStatusObserver(); Player?.Dispose(); Player = null; View.RemoveFromSuperview(); View.Dispose(); if (disposing) { _events?.Dispose(); _tracker?.Dispose(); _packager?.Dispose(); } System.Diagnostics.Debug.WriteLine("BeforeDispose"); base.Dispose(disposing); System.Diagnostics.Debug.WriteLine("AfterDispose"); } } void RemoveStatusObserver() { if (_statusObserver != null) { _statusObserver.Dispose(); _statusObserver = null; } } void ObserveRate(NSObservedChange e) { if (!_isDisposed && Controller is object) { switch (Player.Rate) { case 0.0f: Controller.CurrentState = MediaElementState.Paused; break; case 1.0f: Controller.CurrentState = MediaElementState.Playing; break; } Controller.Position = Position; } } void ObserveStatus(NSObservedChange e) { if (!_isDisposed && Controller is object) { Controller.Volume = Player.Volume; switch (Player.Status) { case AVPlayerStatus.Failed: Controller.OnMediaFailed(); break; case AVPlayerStatus.ReadyToPlay: if (!Player.CurrentItem.Duration.IsInvalid && !Player.CurrentItem.Duration.IsIndefinite) { Controller.Duration = TimeSpan.FromSeconds(Player.CurrentItem.Duration.Seconds); } Controller.VideoHeight = (int)Player.CurrentItem.Asset.NaturalSize.Height; Controller.VideoWidth = (int)Player.CurrentItem.Asset.NaturalSize.Width; Controller.OnMediaOpened(); Controller.Position = Position; break; } } } TimeSpan Position { get { if (Player.CurrentTime.IsInvalid) return TimeSpan.Zero; return TimeSpan.FromSeconds(Player.CurrentTime.Seconds); } } void PlayedToEnd(NSNotification notification) { if (MediaElement.IsLooping) { Player.Seek(CMTime.Zero); Controller.Position = Position; Player.Play(); } else { SetKeepScreenOn(false); Controller.Position = Position; try { Device.BeginInvokeOnMainThread(Controller.OnMediaEnded); } catch { } } } void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (_isDisposed) return; switch (e.PropertyName) { case nameof(MediaElement.Aspect): VideoGravity = AspectToGravity(MediaElement.Aspect); break; case nameof(MediaElement.KeepScreenOn): if (!MediaElement.KeepScreenOn) { SetKeepScreenOn(false); } else if (MediaElement.CurrentState == MediaElementState.Playing) { // only toggle this on if property is set while video is already running SetKeepScreenOn(true); } break; case nameof(MediaElement.ShowsPlaybackControls): ShowsPlaybackControls = MediaElement.ShowsPlaybackControls; break; case nameof(MediaElement.Source): UpdateSource(); break; case nameof(MediaElement.Volume): Player.Volume = (float)MediaElement.Volume; break; } } void MediaElementSeekRequested(object sender, SeekRequested e) { if (Player.Status != AVPlayerStatus.ReadyToPlay || Player.CurrentItem == null) return; NSValue[] ranges = Player.CurrentItem.SeekableTimeRanges; CMTime seekTo = new CMTime(Convert.ToInt64(e.Position.TotalMilliseconds), 1000); foreach (NSValue v in ranges) { if (seekTo >= v.CMTimeRangeValue.Start && seekTo < (v.CMTimeRangeValue.Start + v.CMTimeRangeValue.Duration)) { Player.Seek(seekTo, SeekComplete); break; } } } void Play() { var audioSession = AVAudioSession.SharedInstance(); NSError err = audioSession.SetCategory(AVAudioSession.CategoryPlayback); audioSession.SetMode(AVAudioSession.ModeMoviePlayback, out err); err = audioSession.SetActive(true); if (Player != null) { Player.Play(); Controller.CurrentState = MediaElementState.Playing; } if (MediaElement.KeepScreenOn) { SetKeepScreenOn(true); } } void MediaElementStateRequested(object sender, StateRequested e) { MediaElementVolumeRequested(this, EventArgs.Empty); switch (e.State) { case MediaElementState.Playing: Play(); break; case MediaElementState.Paused: if (MediaElement.KeepScreenOn) { SetKeepScreenOn(false); } if (Player != null) { Player.Pause(); Controller.CurrentState = MediaElementState.Paused; } break; case MediaElementState.Stopped: if (MediaElement.KeepScreenOn) { SetKeepScreenOn(false); } // ios has no stop... Player.Pause(); Player.Seek(CMTime.Zero); Controller.CurrentState = MediaElementState.Stopped; NSError err = AVAudioSession.SharedInstance().SetActive(false); break; } Controller.Position = Position; } static AVLayerVideoGravity AspectToGravity(Aspect aspect) { switch (aspect) { case Aspect.Fill: return AVLayerVideoGravity.Resize; case Aspect.AspectFill: return AVLayerVideoGravity.ResizeAspectFill; default: return AVLayerVideoGravity.ResizeAspect; } } void SeekComplete(bool finished) { if (finished) { Controller.OnSeekCompleted(); } } SizeRequest IVisualElementRenderer.GetDesiredSize(double widthConstraint, double heightConstraint) { if (_isDisposed) return new SizeRequest(new Size(widthConstraint, heightConstraint)); return View.GetSizeRequest(widthConstraint, heightConstraint, 240, 180); } void IVisualElementRenderer.SetElement(VisualElement element) { MediaElement oldElement = MediaElement; if (oldElement != null) { oldElement.PropertyChanged -= OnElementPropertyChanged; oldElement.SeekRequested -= MediaElementSeekRequested; oldElement.StateRequested -= MediaElementStateRequested; oldElement.PositionRequested -= MediaElementPositionRequested; oldElement.VolumeRequested -= MediaElementVolumeRequested; } MediaElement = (MediaElement)element; if (element != null) { Color currentColor = oldElement?.BackgroundColor ?? Color.Default; if (element.BackgroundColor != currentColor) { UpdateBackgroundColor(); } MediaElement.PropertyChanged += OnElementPropertyChanged; MediaElement.SeekRequested += MediaElementSeekRequested; MediaElement.StateRequested += MediaElementStateRequested; MediaElement.PositionRequested += MediaElementPositionRequested; MediaElement.VolumeRequested += MediaElementVolumeRequested; UpdateSource(); VideoGravity = AspectToGravity(MediaElement.Aspect); _tracker = new VisualElementTracker(this); _packager = new VisualElementPackager(this); _packager.Load(); _events = new EventTracker(this); _events.LoadEvents(View); } OnElementChanged(new VisualElementChangedEventArgs(oldElement, element)); } private void MediaElementVolumeRequested(object sender, EventArgs e) { Controller.Volume = Player.Volume; } void MediaElementPositionRequested(object sender, EventArgs e) { Controller.Position = Position; } public event EventHandler<VisualElementChangedEventArgs> ElementChanged; void OnElementChanged(VisualElementChangedEventArgs e) { ElementChanged?.Invoke(this, e); } void IVisualElementRenderer.SetElementSize(Size size) { Layout.LayoutChildIntoBoundingRegion(MediaElement, new Rectangle(MediaElement.X, MediaElement.Y, size.Width, size.Height)); } public override void ViewDidLayoutSubviews() { base.ViewDidLayoutSubviews(); if (!_isDisposed) { // This is a temporary fix to stop zero width/height on resize or control expanding beyond page dimensions View.Frame = new CoreGraphics.CGRect(View.Frame.Left, View.Frame.Top, Math.Min(Math.Max(View.Frame.Width, View.Superview.Bounds.Width - View.Frame.X), View.Superview.Bounds.Width), Math.Min(Math.Max(View.Frame.Height, View.Superview.Bounds.Height - View.Frame.Y), View.Superview.Bounds.Height)); } } void UpdateBackgroundColor() { View.BackgroundColor = MediaElement.BackgroundColor.ToUIColor(); } } }*/
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Threading.Tasks; using FluentAssertions; using IdentityModel; using IdentityServer4.Configuration; using IdentityServer4.Models; using IdentityServer4.Stores; using IdentityServer4.UnitTests.Common; using IdentityServer4.UnitTests.Validation; using IdentityServer4.Validation; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using Xunit; namespace IdentityServer4.Tests.Validation.Secrets { public class PrivateKeyJwtSecretValidation { private readonly ISecretValidator _validator; private readonly IClientStore _clients; public PrivateKeyJwtSecretValidation() { _validator = new PrivateKeyJwtSecretValidator( new MockHttpContextAccessor( new IdentityServerOptions() { IssuerUri = "https://idsrv3.com" } ), new LoggerFactory().CreateLogger<PrivateKeyJwtSecretValidator>() ); _clients = new InMemoryClientStore(ClientValidationTestClients.Get()); } private JwtSecurityToken CreateToken(string clientId, DateTime? nowOverride = null) { var certificate = TestCert.Load(); var now = nowOverride ?? DateTime.UtcNow; var token = new JwtSecurityToken( clientId, "https://idsrv3.com/connect/token", new List<Claim>() { new Claim("jti", Guid.NewGuid().ToString()), new Claim(JwtClaimTypes.Subject, clientId), new Claim(JwtClaimTypes.IssuedAt, now.ToEpochTime().ToString(), ClaimValueTypes.Integer64) }, now, now.AddMinutes(1), new SigningCredentials( new X509SecurityKey(certificate), SecurityAlgorithms.RsaSha256 ) ); return token; } [Fact] public async Task Invalid_Certificate_X5t_Only_Requires_Full_Certificate() { var clientId = "certificate_valid"; var client = await _clients.FindEnabledClientByIdAsync(clientId); var token = CreateToken(clientId); var secret = new ParsedSecret { Id = clientId, Credential = new JwtSecurityTokenHandler().WriteToken(token), Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); result.Success.Should().BeFalse(); } [Fact] public async Task Invalid_Certificate_Thumbprint() { var clientId = "certificate_invalid"; var client = await _clients.FindEnabledClientByIdAsync(clientId); var secret = new ParsedSecret { Id = clientId, Credential = new JwtSecurityTokenHandler().WriteToken(CreateToken(clientId)), Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); result.Success.Should().BeFalse(); } [Fact] public async Task Valid_Certificate_Base64() { var clientId = "certificate_base64_valid"; var client = await _clients.FindEnabledClientByIdAsync(clientId); var secret = new ParsedSecret { Id = clientId, Credential = new JwtSecurityTokenHandler().WriteToken(CreateToken(clientId)), Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); result.Success.Should().BeTrue(); } [Fact] public async Task Invalid_Certificate_Base64() { var clientId = "certificate_base64_invalid"; var client = await _clients.FindEnabledClientByIdAsync(clientId); var secret = new ParsedSecret { Id = clientId, Credential = new JwtSecurityTokenHandler().WriteToken(CreateToken(clientId)), Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); result.Success.Should().BeFalse(); } [Fact] public async Task Invalid_Issuer() { var clientId = "certificate_valid"; var client = await _clients.FindEnabledClientByIdAsync(clientId); var token = CreateToken(clientId); token.Payload.Remove(JwtClaimTypes.Issuer); token.Payload.Add(JwtClaimTypes.Issuer, "invalid"); var secret = new ParsedSecret { Id = clientId, Credential = new JwtSecurityTokenHandler().WriteToken(token), Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); result.Success.Should().BeFalse(); } [Fact] public async Task Invalid_Subject() { var clientId = "certificate_valid"; var client = await _clients.FindEnabledClientByIdAsync(clientId); var token = CreateToken(clientId); token.Payload.Remove(JwtClaimTypes.Subject); token.Payload.Add(JwtClaimTypes.Subject, "invalid"); var secret = new ParsedSecret { Id = clientId, Credential = new JwtSecurityTokenHandler().WriteToken(token), Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); result.Success.Should().BeFalse(); } [Fact] public async Task Invalid_Expired_Token() { var clientId = "certificate_valid"; var client = await _clients.FindEnabledClientByIdAsync(clientId); var token = CreateToken(clientId, DateTime.UtcNow.AddHours(-1)); var secret = new ParsedSecret { Id = clientId, Credential = new JwtSecurityTokenHandler().WriteToken(token), Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); result.Success.Should().BeFalse(); } [Fact] public async Task Invalid_Unsigned_Token() { var clientId = "certificate_valid"; var client = await _clients.FindEnabledClientByIdAsync(clientId); var token = CreateToken(clientId); token.Header.Remove("alg"); token.Header.Add("alg", "none"); var secret = new ParsedSecret { Id = clientId, Credential = new JwtSecurityTokenHandler().WriteToken(token), Type = IdentityServerConstants.ParsedSecretTypes.JwtBearer }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); result.Success.Should().BeFalse(); } } }
/* * Created by Alessandro Binhara * User: Administrator * Date: 29/4/2005 * Time: 18:13 * * Description: An SQL Builder, Object Interface to Database Tables * Its based on DataObjects from php PEAR * 1. Builds SQL statements based on the objects vars and the builder methods. * 2. acts as a datastore for a table row. * The core class is designed to be extended for each of your tables so that you put the * data logic inside the data classes. * included is a Generator to make your configuration files and your base classes. * * CSharp DataObject * Copyright (c) 2005, Alessandro de Oliveira Binhara * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * - Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &AS IS& AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Data; using System.Collections; using System.Data.Common; namespace CsDO.Lib { #region Conf public class Conf { static IDataBase _driver; static DataPool _dataPool; static bool _dataPooling; static Conf() { _driver = new CsDO.Drivers.Generic(); _dataPool = DataPool.New(); _dataPooling = false; } public static IDataBase Driver { get { return _driver; } set { _driver = value; } } public static DataPool DataPool { get { return _dataPool; } } public static bool DataPooling { get { return _dataPooling; } set { _dataPooling = value; } } } #endregion #region IDatabase public interface IDataBase { DbCommand getCommand(String sql); DbCommand getSystemCommand(String sql); DbDataAdapter getDataAdapter(DbCommand command); DbConnection getConnection(); void open(string URL); void close(); DbConnection Connection { get; } DataTable getSchema(); DataTable getSchema(string collectionName); DataTable getSchema(string collectionName, string[] restrictions); DbParameter getParameter(); DbParameter getParameter(string name, DbType type, int size); } #endregion public class DataBase : Singleton, IDisposable { protected IList dataReaders = new ArrayList(); new public static DataBase New() { return (DataBase) Instance(typeof(DataBase)); } #region IDisposable Members public void Dispose() { DisposeDataReaders(); } private void DisposeDataReaders() { if (dataReaders.Count > 0) { foreach (IDataReader dataReader in dataReaders) { dataReader.Dispose(); } } dataReaders.Clear(); } #endregion public int Exec(String query) { if (query.ToLower().Contains("update")) Conf.DataPool.Clear(); DisposeDataReaders(); IDbCommand command = Conf.Driver.getCommand(query); Int32 rowsaffected; rowsaffected = command.ExecuteNonQuery(); return rowsaffected; } public int Exec(DbTransaction trans, String query) { if (query.ToLower().Contains("update")) Conf.DataPool.Clear(); DisposeDataReaders(); DbCommand command = Conf.Driver.getCommand(query); Int32 rowsaffected; command.Transaction = trans; rowsaffected = command.ExecuteNonQuery(); return rowsaffected; } public int Exec(string query, DbParameter[] Params) { if (query.ToLower().Contains("update")) Conf.DataPool.Clear(); DisposeDataReaders(); DbCommand command = Conf.Driver.getCommand(query); if (Params != null) { foreach (DbParameter param in Params) { if (param.Value == null) param.Value = DBNull.Value; if (command.Parameters.Contains(param)) command.Parameters[param.ParameterName] = param; else command.Parameters.Add(param); } } int result = command.ExecuteNonQuery(); return result; } public int Exec(DbTransaction trans, string query, DbParameter[] Params) { if (query.ToLower().Contains("update")) Conf.DataPool.Clear(); DisposeDataReaders(); DbCommand command = Conf.Driver.getCommand(query); if (Params != null) { foreach (DbParameter param in Params) { if (param.Value == null) param.Value = DBNull.Value; if (command.Parameters.Contains(param)) command.Parameters[param.ParameterName] = param; else command.Parameters.Add(param); } } command.Transaction = trans; int result = command.ExecuteNonQuery(); return result; } public int ExecSys(String query) { IDbCommand command = Conf.Driver.getSystemCommand(query); Int32 rowsaffected; rowsaffected = command.ExecuteNonQuery(); return rowsaffected; } public IDataReader Query(String query) { DisposeDataReaders(); IDbCommand command = Conf.Driver.getCommand(query); IDataReader dr = command.ExecuteReader(CommandBehavior.CloseConnection); dataReaders.Add(dr); return dr; } public IDataReader Query(CommandType cmdType, string query, IDataParameter[] Params) { DisposeDataReaders(); IDbCommand command = Conf.Driver.getCommand(query); if (cmdType == CommandType.StoredProcedure) command.CommandText = query; command.CommandType = cmdType; if (Params != null) { foreach (IDataParameter param in Params) { if (param.Value == null) param.Value = DBNull.Value; if (command.Parameters.Contains(param)) command.Parameters[param.ParameterName] = param; else command.Parameters.Add(param); } } IDataReader dr = command.ExecuteReader(CommandBehavior.CloseConnection); dataReaders.Add(dr); return dr; } public DataSet QueryDS(CommandType cmdType, string query, DbParameter[] Params) { DbCommand command = Conf.Driver.getCommand(query); DbDataAdapter da = Conf.Driver.getDataAdapter(command); DataSet ds = new DataSet(); command.CommandTimeout = 90; command.CommandType = cmdType; try { if (Params != null) { foreach (DbParameter param in Params) { if (command.Parameters.Contains(param)) command.Parameters[param.ParameterName] = param; else command.Parameters.Add(param); } } da.Fill(ds); command.Parameters.Clear(); } catch (Exception ex) { da = null; ds.Clear(); ds = null; throw (ex); } return ds; } public DataTable QueryDT(string query) { return QueryDT(CommandType.Text, query, null); } public DataTable QueryDT(CommandType cmdType, string query, DbParameter[] Params) { DataSet ds = QueryDS(cmdType, query, Params); if (ds.Tables.Count > 0) return ds.Tables[0]; else return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute; using EditorBrowsableState = System.ComponentModel.EditorBrowsableState; using Internal.Runtime.CompilerServices; #pragma warning disable SA1121 // explicitly using type aliases instead of built-in types #if BIT64 using nuint = System.UInt64; #else // BIT64 using nuint = System.UInt32; #endif // BIT64 namespace System { /// <summary> /// Memory represents a contiguous region of arbitrary memory similar to <see cref="Span{T}"/>. /// Unlike <see cref="Span{T}"/>, it is not a byref-like type. /// </summary> [DebuggerTypeProxy(typeof(MemoryDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly struct Memory<T> : IEquatable<Memory<T>> { // NOTE: With the current implementation, Memory<T> and ReadOnlyMemory<T> must have the same layout, // as code uses Unsafe.As to cast between them. // The highest order bit of _index is used to discern whether _object is a pre-pinned array. // (_index < 0) => _object is a pre-pinned array, so Pin() will not allocate a new GCHandle // (else) => Pin() needs to allocate a new GCHandle to pin the object. private readonly object? _object; private readonly int _index; private readonly int _length; /// <summary> /// Creates a new memory over the entirety of the target array. /// </summary> /// <param name="array">The target array.</param> /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[]? array) { if (array == null) { this = default; return; // returns default } if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) ThrowHelper.ThrowArrayTypeMismatchException(); _object = array; _index = 0; _length = array.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(T[]? array, int start) { if (array == null) { if (start != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); this = default; return; // returns default } if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length) ThrowHelper.ThrowArgumentOutOfRangeException(); _object = array; _index = start; _length = array.Length - start; } /// <summary> /// Creates a new memory over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the memory.</param> /// <param name="length">The number of items in the memory.</param> /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[]? array, int start, int length) { if (array == null) { if (start != 0 || length != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); this = default; return; // returns default } if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) ThrowHelper.ThrowArrayTypeMismatchException(); #if BIT64 // See comment in Span<T>.Slice for how this works. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)array.Length) ThrowHelper.ThrowArgumentOutOfRangeException(); #else if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); #endif _object = array; _index = start; _length = length; } /// <summary> /// Creates a new memory from a memory manager that provides specific method implementations beginning /// at 0 index and ending at 'end' index (exclusive). /// </summary> /// <param name="manager">The memory manager.</param> /// <param name="length">The number of items in the memory.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="length"/> is negative. /// </exception> /// <remarks>For internal infrastructure only</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager<T> manager, int length) { Debug.Assert(manager != null); if (length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(); _object = manager; _index = 0; _length = length; } /// <summary> /// Creates a new memory from a memory manager that provides specific method implementations beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="manager">The memory manager.</param> /// <param name="start">The index at which to begin the memory.</param> /// <param name="length">The number of items in the memory.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or <paramref name="length"/> is negative. /// </exception> /// <remarks>For internal infrastructure only</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager<T> manager, int start, int length) { Debug.Assert(manager != null); if (length < 0 || start < 0) ThrowHelper.ThrowArgumentOutOfRangeException(); _object = manager; _index = start; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(object? obj, int start, int length) { // No validation performed in release builds; caller must provide any necessary validation. // 'obj is T[]' below also handles things like int[] <-> uint[] being convertible Debug.Assert((obj == null) || (typeof(T) == typeof(char) && obj is string) #if FEATURE_UTF8STRING || ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && obj is Utf8String) #endif // FEATURE_UTF8STRING || (obj is T[]) || (obj is MemoryManager<T>)); _object = obj; _index = start; _length = length; } /// <summary> /// Defines an implicit conversion of an array to a <see cref="Memory{T}"/> /// </summary> public static implicit operator Memory<T>(T[]? array) => new Memory<T>(array); /// <summary> /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/> /// </summary> public static implicit operator Memory<T>(ArraySegment<T> segment) => new Memory<T>(segment.Array, segment.Offset, segment.Count); /// <summary> /// Defines an implicit conversion of a <see cref="Memory{T}"/> to a <see cref="ReadOnlyMemory{T}"/> /// </summary> public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) => Unsafe.As<Memory<T>, ReadOnlyMemory<T>>(ref memory); /// <summary> /// Returns an empty <see cref="Memory{T}"/> /// </summary> public static Memory<T> Empty => default; /// <summary> /// The number of items in the memory. /// </summary> public int Length => _length; /// <summary> /// Returns true if Length is 0. /// </summary> public bool IsEmpty => _length == 0; /// <summary> /// For <see cref="Memory{Char}"/>, returns a new instance of string that represents the characters pointed to by the memory. /// Otherwise, returns a <see cref="string"/> with the name of the type and the number of elements. /// </summary> public override string ToString() { if (typeof(T) == typeof(char)) { return (_object is string str) ? str.Substring(_index, _length) : Span.ToString(); } #if FEATURE_UTF8STRING else if (typeof(T) == typeof(Char8)) { // TODO_UTF8STRING: Call into optimized transcoding routine when it's available. Span<T> span = Span; return Encoding.UTF8.GetString(new ReadOnlySpan<byte>(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length)); } #endif // FEATURE_UTF8STRING return string.Format("System.Memory<{0}>[{1}]", typeof(T).Name, _length); } /// <summary> /// Forms a slice out of the given memory, beginning at 'start'. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start) { if ((uint)start > (uint)_length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } // It is expected for _index + start to be negative if the memory is already pre-pinned. return new Memory<T>(_object, _index + start, _length - start); } /// <summary> /// Forms a slice out of the given memory, beginning at 'start', of given length /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start, int length) { #if BIT64 // See comment in Span<T>.Slice for how this works. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)_length) ThrowHelper.ThrowArgumentOutOfRangeException(); #else if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); #endif // It is expected for _index + start to be negative if the memory is already pre-pinned. return new Memory<T>(_object, _index + start, length); } /// <summary> /// Returns a span from the memory. /// </summary> public unsafe Span<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { // This property getter has special support for returning a mutable Span<char> that wraps // an immutable String instance. This is obviously a dangerous feature and breaks type safety. // However, we need to handle the case where a ReadOnlyMemory<char> was created from a string // and then cast to a Memory<T>. Such a cast can only be done with unsafe or marshaling code, // in which case that's the dangerous operation performed by the dev, and we're just following // suit here to make it work as best as possible. ref T refToReturn = ref Unsafe.AsRef<T>(null); int lengthOfUnderlyingSpan = 0; // Copy this field into a local so that it can't change out from under us mid-operation. object? tmpObject = _object; if (tmpObject != null) { if (typeof(T) == typeof(char) && tmpObject.GetType() == typeof(string)) { // Special-case string since it's the most common for ROM<char>. refToReturn = ref Unsafe.As<char, T>(ref Unsafe.As<string>(tmpObject).GetRawStringData()); lengthOfUnderlyingSpan = Unsafe.As<string>(tmpObject).Length; } #if FEATURE_UTF8STRING else if ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && tmpObject.GetType() == typeof(Utf8String)) { refToReturn = ref Unsafe.As<byte, T>(ref Unsafe.As<Utf8String>(tmpObject).DangerousGetMutableReference()); lengthOfUnderlyingSpan = Unsafe.As<Utf8String>(tmpObject).Length; } #endif // FEATURE_UTF8STRING else if (RuntimeHelpers.ObjectHasComponentSize(tmpObject)) { // We know the object is not null, it's not a string, and it is variable-length. The only // remaining option is for it to be a T[] (or a U[] which is blittable to T[], like int[] // and uint[]). Otherwise somebody used private reflection to set this field, and we're not // too worried about type safety violations at this point. // 'tmpObject is T[]' below also handles things like int[] <-> uint[] being convertible Debug.Assert(tmpObject is T[]); refToReturn = ref Unsafe.As<byte, T>(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData()); lengthOfUnderlyingSpan = Unsafe.As<T[]>(tmpObject).Length; } else { // We know the object is not null, and it's not variable-length, so it must be a MemoryManager<T>. // Otherwise somebody used private reflection to set this field, and we're not too worried about // type safety violations at that point. Note that it can't be a MemoryManager<U>, even if U and // T are blittable (e.g., MemoryManager<int> to MemoryManager<uint>), since there exists no // constructor or other public API which would allow such a conversion. Debug.Assert(tmpObject is MemoryManager<T>); Span<T> memoryManagerSpan = Unsafe.As<MemoryManager<T>>(tmpObject).GetSpan(); refToReturn = ref MemoryMarshal.GetReference(memoryManagerSpan); lengthOfUnderlyingSpan = memoryManagerSpan.Length; } // If the Memory<T> or ReadOnlyMemory<T> instance is torn, this property getter has undefined behavior. // We try to detect this condition and throw an exception, but it's possible that a torn struct might // appear to us to be valid, and we'll return an undesired span. Such a span is always guaranteed at // least to be in-bounds when compared with the original Memory<T> instance, so using the span won't // AV the process. nuint desiredStartIndex = (uint)_index & (uint)ReadOnlyMemory<T>.RemoveFlagsBitMask; int desiredLength = _length; #if BIT64 // See comment in Span<T>.Slice for how this works. if ((ulong)desiredStartIndex + (ulong)(uint)desiredLength > (ulong)(uint)lengthOfUnderlyingSpan) { ThrowHelper.ThrowArgumentOutOfRangeException(); } #else if ((uint)desiredStartIndex > (uint)lengthOfUnderlyingSpan || (uint)desiredLength > (uint)(lengthOfUnderlyingSpan - desiredStartIndex)) { ThrowHelper.ThrowArgumentOutOfRangeException(); } #endif refToReturn = ref Unsafe.Add(ref refToReturn, (IntPtr)(void*)desiredStartIndex); lengthOfUnderlyingSpan = desiredLength; } return new Span<T>(ref refToReturn, lengthOfUnderlyingSpan); } } /// <summary> /// Copies the contents of the memory into the destination. If the source /// and destination overlap, this method behaves as if the original values are in /// a temporary location before the destination is overwritten. /// /// <param name="destination">The Memory to copy items into.</param> /// <exception cref="System.ArgumentException"> /// Thrown when the destination is shorter than the source. /// </exception> /// </summary> public void CopyTo(Memory<T> destination) => Span.CopyTo(destination.Span); /// <summary> /// Copies the contents of the memory into the destination. If the source /// and destination overlap, this method behaves as if the original values are in /// a temporary location before the destination is overwritten. /// /// <returns>If the destination is shorter than the source, this method /// return false and no data is written to the destination.</returns> /// </summary> /// <param name="destination">The span to copy items into.</param> public bool TryCopyTo(Memory<T> destination) => Span.TryCopyTo(destination.Span); /// <summary> /// Creates a handle for the memory. /// The GC will not move the memory until the returned <see cref="MemoryHandle"/> /// is disposed, enabling taking and using the memory's address. /// <exception cref="System.ArgumentException"> /// An instance with nonprimitive (non-blittable) members cannot be pinned. /// </exception> /// </summary> public unsafe MemoryHandle Pin() { // Just like the Span property getter, we have special support for a mutable Memory<char> // that wraps an immutable String instance. This might happen if a caller creates an // immutable ROM<char> wrapping a String, then uses Unsafe.As to create a mutable M<char>. // This needs to work, however, so that code that uses a single Memory<char> field to store either // a readable ReadOnlyMemory<char> or a writable Memory<char> can still be pinned and // used for interop purposes. // It's possible that the below logic could result in an AV if the struct // is torn. This is ok since the caller is expecting to use raw pointers, // and we're not required to keep this as safe as the other Span-based APIs. object? tmpObject = _object; if (tmpObject != null) { if (typeof(T) == typeof(char) && tmpObject is string s) { GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned); ref char stringData = ref Unsafe.Add(ref s.GetRawStringData(), _index); return new MemoryHandle(Unsafe.AsPointer(ref stringData), handle); } #if FEATURE_UTF8STRING else if ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && tmpObject is Utf8String utf8String) { GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned); ref byte stringData = ref utf8String.DangerousGetMutableReference(_index); return new MemoryHandle(Unsafe.AsPointer(ref stringData), handle); } #endif // FEATURE_UTF8STRING else if (RuntimeHelpers.ObjectHasComponentSize(tmpObject)) { // 'tmpObject is T[]' below also handles things like int[] <-> uint[] being convertible Debug.Assert(tmpObject is T[]); // Array is already pre-pinned if (_index < 0) { void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData()), _index & ReadOnlyMemory<T>.RemoveFlagsBitMask); return new MemoryHandle(pointer); } else { GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned); void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData()), _index); return new MemoryHandle(pointer, handle); } } else { Debug.Assert(tmpObject is MemoryManager<T>); return Unsafe.As<MemoryManager<T>>(tmpObject).Pin(_index); } } return default; } /// <summary> /// Copies the contents from the memory into a new array. This heap /// allocates, so should generally be avoided, however it is sometimes /// necessary to bridge the gap with APIs written in terms of arrays. /// </summary> public T[] ToArray() => Span.ToArray(); /// <summary> /// Determines whether the specified object is equal to the current object. /// Returns true if the object is Memory or ReadOnlyMemory and if both objects point to the same array and have the same length. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) { if (obj is ReadOnlyMemory<T>) { return ((ReadOnlyMemory<T>)obj).Equals(this); } else if (obj is Memory<T> memory) { return Equals(memory); } else { return false; } } /// <summary> /// Returns true if the memory points to the same array and has the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public bool Equals(Memory<T> other) { return _object == other._object && _index == other._index && _length == other._length; } /// <summary> /// Serves as the default hash function. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { // We use RuntimeHelpers.GetHashCode instead of Object.GetHashCode because the hash // code is based on object identity and referential equality, not deep equality (as common with string). return (_object != null) ? HashCode.Combine(RuntimeHelpers.GetHashCode(_object), _index, _length) : 0; } } }
using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Linq; using System.Threading.Tasks; using System.Threading; using Outlander.Core.Client; using Outlander.Core; namespace Outlander.Core.Client.Scripting { public interface IScript { string Id { get; } string Name { get; } DateTime StartTime { get; } IDictionary<string, string> ScriptVars { get; } void Stop(); Task Run(string id, string name, string script, params string[] args); } public class Script : IScript { private readonly IServiceLocator _serviceLocator; private readonly Tokenizer _tokenizer; private readonly IScriptLog _log; private readonly IIfBlocksParser _ifBlocksParser; private TaskCompletionSource<object> _taskCompletionSource; private CancellationTokenSource _taskCancelationSource; private ScriptContext _scriptContext; private string[] _scriptLines; private IDictionary<int, IfBlocks> _ifBlocks = new Dictionary<int, IfBlocks>(); private IDictionary<string, int> _gotos = new Dictionary<string, int>(); private ISimpleDictionary<string, string> _localVars = new SimpleDictionary<string, string>(); private IDictionary<string, ITokenHandler> _tokenHandlers = new Dictionary<string, ITokenHandler>(); private ActionTracker _actionTracker = new ActionTracker(); private ActionReporter _actionReporter; public Script(IServiceLocator serviceLocator, Tokenizer tokenizer) { _serviceLocator = serviceLocator; _tokenizer = tokenizer; _taskCompletionSource = new TaskCompletionSource<object>(); _taskCancelationSource = new CancellationTokenSource(); _actionReporter = new ActionReporter("id", _serviceLocator.Get<IScriptLog>(), _serviceLocator.Get<IIfBlockExecuter>()); _actionReporter.Subscribe(_actionTracker); _ifBlocksParser = _serviceLocator.Get<IIfBlocksParser>(); _log = _serviceLocator.Get<IScriptLog>(); _tokenHandlers["exit"] = new ExitTokenHandler(); _tokenHandlers["comment"] = new ContinueTokenHandler(); _tokenHandlers["debuglevel"] = new DebugLevelTokenHandler(); _tokenHandlers["var"] = new VarTokenHandler(); _tokenHandlers["globalvar"] = new GlobalVarTokenHandler(); _tokenHandlers["unvar"] = new UnVarTokenHandler(); _tokenHandlers["hasvar"] = new HasVarTokenHandler(); _tokenHandlers["goto"] = new GotoTokenHandler(); _tokenHandlers["waitfor"] = serviceLocator.Get<WaitForTokenHandler>(); _tokenHandlers["waitforre"] = serviceLocator.Get<WaitForReTokenHandler>(); _tokenHandlers["pause"] = new PauseTokenHandler(); _tokenHandlers["put"] = new SendCommandTokenHandler(); _tokenHandlers["echo"] = new EchoTokenHandler(); _tokenHandlers["match"] = new MatchTokenHandler(); _tokenHandlers["matchre"] = new MatchTokenHandler(); _tokenHandlers["matchwait"] = serviceLocator.Get<MatchWaitTokenHandler>(); _tokenHandlers["if"] = new IfTokenHandler(); _tokenHandlers["if_"] = new IfArgTokenHandler(); _tokenHandlers["save"] = new SaveTokenHandler(); _tokenHandlers["move"] = new MoveTokenHandler(); _tokenHandlers["nextroom"] = new NextroomTokenHandler(); _tokenHandlers["send"] = new SendTokenHandler(); _tokenHandlers["parse"] = new ParseTokenHandler(); _tokenHandlers["containsre"] = new ContainsReTokenHandler(); _tokenHandlers["gosub"] = new GoSubTokenHandler(); _tokenHandlers["return"] = new ReturnTokenHandler(); _tokenHandlers["label"] = new ContinueTokenHandler((context, token) => { if(context.DebugLevel > 0) { _log.Log(Name, "passing label: {0}".ToFormat(token.Value), context.LineNumber); } }); } public string Id { get; private set; } public string Name { get; private set; } public DateTime StartTime { get; private set; } public IDictionary<string, string> ScriptVars { get { return _localVars.Values(); } } public void Stop() { _taskCancelationSource.Cancel(); } public Task Run(string id, string name, string script, params string[] args) { StartTime = DateTime.Now; Id = id; Name = name; _log.Started(name, StartTime); _ifBlocksParser.For(script).Apply(x => { _ifBlocks[x.IfEvalLineNumber] = x; }); //var start = DateTime.Now; //_log.Log(name, "after if: {0}".ToFormat(start), 0); _localVars["0"] = string.Join(" ", args); args.Apply((x, idx) => _localVars["{0}".ToFormat(idx + 1)] = x); _scriptContext = new ScriptContext(Id, Name, _taskCancelationSource.Token, _serviceLocator, _localVars); _scriptLines = script.Split(new string[]{ "\n" }, StringSplitOptions.None); //_log.Log(name, "after split: {0}".ToFormat(DateTime.Now - start), 0); _scriptLines.Apply((line, num) => { if(string.IsNullOrWhiteSpace(line)) return; var match = Regex.Match(line.TrimStart(), RegexPatterns.Label, RegexOptions.Multiline); if(match.Success) { _gotos[match.Groups[1].Value] = num; } }); //_log.Log(name, "after gotos: {0}".ToFormat(DateTime.Now), 0); try { Execute(_taskCancelationSource.Token); } catch(OperationCanceledException) { _taskCompletionSource.TrySetCanceled(); _actionTracker.EndTransmission(); } catch(Exception exc) { _taskCompletionSource.TrySetException(exc); _log.Log(_scriptContext.Name, "Error: " + exc.Message, _scriptContext.LineNumber); _actionTracker.EndTransmission(); } return _taskCompletionSource.Task; } private void Execute(CancellationToken cancelToken) { bool canceled = false; for(int i = 0; i < _scriptLines.Length; i++) { _scriptContext.LineNumber = i; cancelToken.ThrowIfCancellationRequested(); var line = _scriptLines[i]; var token = _tokenizer.Tokenize(line.TrimStart()).FirstOrDefault(); if(token != null && !token.Ignore) { var actionToken = token as ActionToken; if(actionToken != null) { var actionContext = new ActionContext(); actionContext.ScriptName = _scriptContext.Name; actionContext.LineNumber = i; actionContext.Token = actionToken; RunAction(actionContext, _actionTracker, _scriptContext.LocalVars); continue; } var ifToken = token as IfToken; if(ifToken != null && ifToken.ReplaceBlocks) { ifToken.Blocks = _ifBlocks[i]; } var task = _tokenHandlers[token.Type].Execute(_scriptContext, token); try { task.Wait(cancelToken); } catch(AggregateException) { canceled = true; _taskCompletionSource.TrySetCanceled(); _actionTracker.EndTransmission(); break; } if(!string.IsNullOrWhiteSpace(task.Result.Goto)) { if(!_gotos.ContainsKey(task.Result.Goto)) { _log.Log(_scriptContext.Name, "cannot find label '{0}'".ToFormat(task.Result.Goto), i); canceled = true; _taskCompletionSource.TrySetCanceled(); _actionTracker.EndTransmission(); break; } i = _gotos[task.Result.Goto] - 1; _scriptContext.CurrentArgs = task.Result.Args; } else { i = _scriptContext.LineNumber; } } } if(!canceled) _taskCompletionSource.TrySetResult(null); } private CancellationToken RunAction(ActionContext actionContext, IDataTracker<ActionContext> tracker, ISimpleDictionary<string, string> localVars) { var cancelSource = new CancellationTokenSource(); var context = new ScriptContext( _scriptContext.Id, _scriptContext.Name, cancelSource.Token, _serviceLocator, localVars); actionContext.ScriptContext = context; _scriptContext.CancelToken.Register(() => { cancelSource.Cancel(); }); Task.Factory.StartNew(() => { var handler = new ActionTokenHandler(actionContext, tracker); handler.Execute(context, actionContext.Token); }, cancelSource.Token); return cancelSource.Token; } } public class ActionTracker : DataTracker<ActionContext> { } public class ActionReporter : DataReporter<ActionContext> { private readonly IScriptLog _scriptLog; private readonly IIfBlockExecuter _executer; public ActionReporter(string id, IScriptLog scriptLog, IIfBlockExecuter executer) : base(id) { _scriptLog = scriptLog; _executer = executer; } public override void OnNext(ActionContext value) { if(value.ScriptContext.DebugLevel > 0) { _scriptLog.Log(value.ScriptName, "action triggered: {0}".ToFormat(value.Token.When), value.LineNumber); } var result = Regex.Replace(value.Match, value.Token.When, value.Token.Action, RegexOptions.Multiline); _executer.ExecuteBlocks(result, value.ScriptContext); } } }
using Support; using Mp3Sharp; /* * 12/12/99 Based on Ibitstream. Exceptions thrown on errors, * Tempoarily removed seek functionality. mdm@techie.com * * 02/12/99 : Java Conversion by E.B , ebsp@iname.com , JavaLayer * *---------------------------------------------------------------------- * @(#) ibitstream.h 1.5, last edit: 6/15/94 16:55:34 * @(#) Copyright (C) 1993, 1994 Tobias Bading (bading@cs.tu-berlin.de) * @(#) Berlin University of Technology * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * Changes made by Jeff Tsay : * 04/14/97 : Added function prototypes for new syncing and seeking * mechanisms. Also made this file portable. *----------------------------------------------------------------------- */ namespace javazoom.jl.decoder { using System; using System.Diagnostics; /// <summary> The <code>Bistream</code> class is responsible for parsing /// an MPEG audio bitstream. /// * /// <b>REVIEW:</b> much of the parsing currently occurs in the /// various decoders. This should be moved into this class and associated /// inner classes. /// </summary> internal sealed class Bitstream : BitstreamErrors { private void InitBlock() { crc = new Crc16[1]; syncbuf = new sbyte[4]; frame_bytes = new sbyte[BUFFER_INT_SIZE * 4]; framebuffer = new int[BUFFER_INT_SIZE]; header = new Header(); } /// <summary> Syncrhronization control constant for the initial /// synchronization to the start of a frame. /// </summary> internal static sbyte INITIAL_SYNC = 0; /// <summary> Syncrhronization control constant for non-iniital frame /// synchronizations. /// </summary> internal static sbyte STRICT_SYNC = 1; // max. 1730 bytes per frame: 144 * 384kbit/s / 32000 Hz + 2 Bytes CRC /// <summary> Maximum size of the frame buffer. /// </summary> private const int BUFFER_INT_SIZE = 433; /// <summary> The frame buffer that holds the data for the current frame. /// </summary> //UPGRADE_NOTE: Final was removed from the declaration of 'framebuffer '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' //UPGRADE_NOTE: The initialization of 'framebuffer' was moved to method 'InitBlock'. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1005"' private int[] framebuffer; /// <summary> Number of valid bytes in the frame buffer. /// </summary> private int framesize; /// <summary> The bytes read from the stream. /// </summary> //UPGRADE_NOTE: The initialization of 'frame_bytes' was moved to method 'InitBlock'. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1005"' private sbyte[] frame_bytes; /// <summary> Index into <code>framebuffer</code> where the next bits are /// retrieved. /// </summary> private int wordpointer; /// <summary> Number (0-31, from MSB to LSB) of next bit for get_bits() /// </summary> private int bitindex; /// <summary> The current specified syncword /// </summary> private int syncword; /// <summary>* /// </summary> private bool single_ch_mode; //private int current_frame_number; //private int last_frame_number; //UPGRADE_NOTE: Final was removed from the declaration of 'bitmask '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' private int[] bitmask = new int[]{0, 0x00000001, 0x00000003, 0x00000007, 0x0000000F, 0x0000001F, 0x0000003F, 0x0000007F, 0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF, 0x00000FFF, 0x00001FFF, 0x00003FFF, 0x00007FFF, 0x0000FFFF, 0x0001FFFF}; //UPGRADE_NOTE: Final was removed from the declaration of 'source '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' private BackStream source; //UPGRADE_NOTE: Final was removed from the declaration of 'header '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' //UPGRADE_NOTE: The initialization of 'header' was moved to method 'InitBlock'. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1005"' private Header header; //UPGRADE_NOTE: Final was removed from the declaration of 'syncbuf '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' //UPGRADE_NOTE: The initialization of 'syncbuf' was moved to method 'InitBlock'. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1005"' private sbyte[] syncbuf; //UPGRADE_NOTE: The initialization of 'crc' was moved to method 'InitBlock'. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1005"' private Crc16[] crc; //private ByteArrayOutputStream _baos = null; // E.B /// <summary> Construct a IBitstream that reads data from a /// given InputStream. /// * /// </summary> /// <param name="in The">InputStream to read from. /// /// </param> internal Bitstream(BackStream in_Renamed) { InitBlock(); if (in_Renamed == null) throw new System.NullReferenceException("in"); source = in_Renamed; // ROB - fuck the SupportClass, let's roll our own. new SupportClass.BackInputStream(in_Renamed, 1024); //_baos = new ByteArrayOutputStream(); // E.B closeFrame(); //current_frame_number = -1; //last_frame_number = -1; } public void close() { try { //UPGRADE_TODO: Method 'java.io.FilterInputStream.close' was converted to 'System.IO.BinaryReader.Close' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_javaioFilterInputStreamclose"' source.Close(); //_baos = null; } catch (System.IO.IOException ex) { throw newBitstreamException(javazoom.jl.decoder.BitstreamErrors_Fields.STREAM_ERROR, ex); } } /// <summary> Reads and parses the next frame from the input source. /// </summary> /// <returns> the Header describing details of the frame read, /// or null if the end of the stream has been reached. /// /// </returns> internal Header readFrame() { Header result = null; try { result = readNextFrame(); } catch (BitstreamException ex) { if (ex.ErrorCode != javazoom.jl.decoder.BitstreamErrors_Fields.STREAM_EOF) { // wrap original exception so stack trace is maintained. throw newBitstreamException(ex.ErrorCode, ex); } } return result; } private Header readNextFrame() { if (framesize == - 1) { nextFrame(); } return header; } /// <summary>* /// </summary> private void nextFrame() { // entire frame is read by the header class. header.read_header(this, crc); } /// <summary> Unreads the bytes read from the frame. /// @throws BitstreamException /// </summary> // REVIEW: add new error codes for this. public void unreadFrame() { if (wordpointer == - 1 && bitindex == - 1 && (framesize > 0)) { try { //source.UnRead(SupportClass.ToByteArray(frame_bytes), 0, framesize); source.UnRead(framesize); } catch (System.IO.IOException ex) { throw newBitstreamException(javazoom.jl.decoder.BitstreamErrors_Fields.STREAM_ERROR); } } } public void closeFrame() { framesize = - 1; wordpointer = - 1; bitindex = - 1; } /// <summary> Determines if the next 4 bytes of the stream represent a /// frame header. /// </summary> public bool isSyncCurrentPosition(int syncmode) { int read = readBytes(syncbuf, 0, 4); int headerstring = ((syncbuf[0] << 24) & (int) SupportClass.Identity(0xFF000000)) | ((syncbuf[1] << 16) & 0x00FF0000) | ((syncbuf[2] << 8) & 0x0000FF00) | ((syncbuf[3] << 0) & 0x000000FF); try { //source.UnRead(SupportClass.ToByteArray(syncbuf), 0, read); source.UnRead(read); } catch (System.IO.IOException ex) { } bool sync = false; switch (read) { case 0: Trace.WriteLine( "0 bytes read == sync?", "Bitstream" ); sync = true; break; case 4: sync = isSyncMark(headerstring, syncmode, syncword); break; } return sync; } // REVIEW: this class should provide inner classes to // parse the frame contents. Eventually, readBits will // be removed. public int readBits(int n) { return get_bits(n); } public int readCheckedBits(int n) { // REVIEW: implement CRC check. return get_bits(n); } protected internal BitstreamException newBitstreamException(int errorcode) { return new BitstreamException(errorcode, null); } //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to 'System.Exception' which has different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1100"' protected internal BitstreamException newBitstreamException(int errorcode, System.Exception throwable) { return new BitstreamException(errorcode, throwable); } /// <summary> Get next 32 bits from bitstream. /// They are stored in the headerstring. /// syncmod allows Synchro flag ID /// The returned value is False at the end of stream. /// </summary> internal int syncHeader(sbyte syncmode) { bool sync; int headerstring; // read additinal 2 bytes int bytesRead = readBytes(syncbuf, 0, 3); if (bytesRead != 3) throw newBitstreamException(javazoom.jl.decoder.BitstreamErrors_Fields.STREAM_EOF, null); //_baos.write(syncbuf, 0, 3); // E.B headerstring = ((syncbuf[0] << 16) & 0x00FF0000) | ((syncbuf[1] << 8) & 0x0000FF00) | ((syncbuf[2] << 0) & 0x000000FF); #if THROW_ON_SYNC_LOSS // t/DD: If we don't resync in a reasonable amount of time, // throw an exception int bytesSkipped = 0; bool lostSyncYet = false; #endif do { headerstring <<= 8; if (readBytes(syncbuf, 3, 1) != 1) throw newBitstreamException(javazoom.jl.decoder.BitstreamErrors_Fields.STREAM_EOF, null); //_baos.write(syncbuf, 3, 1); // E.B headerstring |= (syncbuf[3] & 0x000000FF); sync = isSyncMark(headerstring, syncmode, syncword); #if THROW_ON_SYNC_LOSS // Just for debugging -- if we lost sync, bitch if (!sync && !lostSyncYet) { lostSyncYet = true; Trace.WriteLine( "Lost Sync :(", "Bitstream" ); } if (lostSyncYet && sync) { Trace.WriteLine( "Found Sync", "Bitstream" ); } // If we haven't resynced within a frame (or so) give up and // throw an exception. (Could try harder?) ++ bytesSkipped; if ((bytesSkipped % 2048) == 0) // A paranoia check -- is the code hanging in a loop here? { Trace.WriteLine( "Sync still not found", "Bitstream" ); // throw newBitstreamException(javazoom.jl.decoder.BitstreamErrors_Fields.STREAM_ERROR, // null); } #endif } while (!sync); //current_frame_number++; //if (last_frame_number < current_frame_number) last_frame_number = current_frame_number; return headerstring; } public bool isSyncMark(int headerstring, int syncmode, int word) { bool sync = false; if (syncmode == INITIAL_SYNC) { //sync = ((headerstring & 0xFFF00000) == 0xFFF00000); sync = ((headerstring & 0xFFE00000) == 0xFFE00000); // SZD: MPEG 2.5 } else { //sync = ((headerstring & 0xFFF80C00) == word) sync = ((headerstring & 0xFFE00000) == 0xFFE00000) // ROB -- THIS IS PROBABLY WRONG. A WEAKER CHECK. && (((headerstring & 0x000000C0) == 0x000000C0) == single_ch_mode); } // filter out invalid sample rate if (sync) { sync = (((SupportClass.URShift(headerstring, 10)) & 3) != 3); if (!sync) Trace.WriteLine("INVALID SAMPLE RATE DETECTED", "Bitstream"); } // filter out invalid layer if (sync) { sync = (((SupportClass.URShift(headerstring, 17)) & 3) != 0); if (!sync) Trace.WriteLine("INVALID LAYER DETECTED", "Bitstream"); } // filter out invalid version if (sync) { sync = (((SupportClass.URShift(headerstring, 19)) & 3) != 1); if (!sync) Console.WriteLine("INVALID VERSION DETECTED"); } return sync; } /// <summary> Reads the data for the next frame. The frame is not parsed /// until parse frame is called. /// </summary> internal void read_frame_data(int bytesize) { int numread = 0; readFully(frame_bytes, 0, bytesize); framesize = bytesize; wordpointer = - 1; bitindex = - 1; } /// <summary> Parses the data previously read with read_frame_data(). /// </summary> internal void parse_frame() { // Convert Bytes read to int int b = 0; sbyte[] byteread = frame_bytes; int bytesize = framesize; for (int k = 0; k < bytesize; k = k + 4) { int convert = 0; sbyte b0 = 0; sbyte b1 = 0; sbyte b2 = 0; sbyte b3 = 0; b0 = byteread[k]; if (k + 1 < bytesize) b1 = byteread[k + 1]; if (k + 2 < bytesize) b2 = byteread[k + 2]; if (k + 3 < bytesize) b3 = byteread[k + 3]; framebuffer[b++] = ((b0 << 24) & (int) SupportClass.Identity(0xFF000000)) | ((b1 << 16) & 0x00FF0000) | ((b2 << 8) & 0x0000FF00) | (b3 & 0x000000FF); } wordpointer = 0; bitindex = 0; } /// <summary> Read bits from buffer into the lower bits of an unsigned int. /// The LSB contains the latest read bit of the stream. /// (1 <= number_of_bits <= 16) /// </summary> public int get_bits(int number_of_bits) { int returnvalue = 0; int sum = bitindex + number_of_bits; // E.B // There is a problem here, wordpointer could be -1 ?! if (wordpointer < 0) wordpointer = 0; // E.B : End. if (sum <= 32) { // all bits contained in *wordpointer returnvalue = (SupportClass.URShift(framebuffer[wordpointer], (32 - sum))) & bitmask[number_of_bits]; // returnvalue = (wordpointer[0] >> (32 - sum)) & bitmask[number_of_bits]; if ((bitindex += number_of_bits) == 32) { bitindex = 0; wordpointer++; // added by me! } return returnvalue; } // Magouille a Voir //((short[])&returnvalue)[0] = ((short[])wordpointer + 1)[0]; //wordpointer++; // Added by me! //((short[])&returnvalue + 1)[0] = ((short[])wordpointer)[0]; int Right = (framebuffer[wordpointer] & 0x0000FFFF); wordpointer++; int Left = (framebuffer[wordpointer] & (int) SupportClass.Identity(0xFFFF0000)); returnvalue = ((Right << 16) & (int) SupportClass.Identity(0xFFFF0000)) | ((SupportClass.URShift(Left, 16)) & 0x0000FFFF); returnvalue = SupportClass.URShift(returnvalue, 48 - sum); // returnvalue >>= 16 - (number_of_bits - (32 - bitindex)) returnvalue &= bitmask[number_of_bits]; bitindex = sum - 32; return returnvalue; } /// <summary> Set the word we want to sync the header to. /// In Big-Endian byte order /// </summary> internal void set_syncword(int syncword0) { syncword = syncword0 & unchecked((int)0xFFFFFF3F); single_ch_mode = ((syncword0 & 0x000000C0) == 0x000000C0); } /// <summary> Reads the exact number of bytes from the source /// input stream into a byte array. /// * /// </summary> /// <param name="b The">byte array to read the specified number /// of bytes into. /// </param> /// <param name="offs The">index in the array where the first byte /// read should be stored. /// </param> /// <param name="len the">number of bytes to read. /// * /// </param> /// <exception cref=""> BitstreamException is thrown if the specified /// number of bytes could not be read from the stream. /// /// </exception> private void readFully(sbyte[] b, int offs, int len) { try { while (len > 0) { int bytesread = source.Read(b, offs, len); if (bytesread == - 1 || bytesread == 0) // t/DD -- .NET returns 0 at end-of-stream! { // t/DD: this really SHOULD throw an exception here... Trace.WriteLine( "readFully -- returning success at EOF? (" + bytesread + ")", "Bitstream" ); while (len-- > 0) { b[offs++] = 0; } break; //throw newBitstreamException(UNEXPECTED_EOF, new EOFException()); } offs += bytesread; len -= bytesread; } } catch (System.IO.IOException ex) { throw newBitstreamException(javazoom.jl.decoder.BitstreamErrors_Fields.STREAM_ERROR, ex); } } /// <summary> Simlar to readFully, but doesn't throw exception when /// EOF is reached. /// </summary> private int readBytes(sbyte[] b, int offs, int len) { int totalBytesRead = 0; try { while (len > 0) { int bytesread = source.Read(b, offs, len); // for (int i = 0; i < len; i++) b[i] = (sbyte)Temp[i]; if (bytesread == - 1 || bytesread == 0) { break; } totalBytesRead += bytesread; offs += bytesread; len -= bytesread; } } catch (System.IO.IOException ex) { throw newBitstreamException(javazoom.jl.decoder.BitstreamErrors_Fields.STREAM_ERROR, ex); } return totalBytesRead; } /// <summary> Returns ID3v2 tags. /// </summary> /*public ByteArrayOutputStream getID3v2() { return _baos; }*/ } }
// Copyright (c) 2017-2019 Jae-jun Kang // See the file LICENSE for details. using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Threading; namespace x2net { /// <summary> /// Abstract base class for TCP/IP client links. /// </summary> public abstract class AbstractTcpClient : ClientLink { private int retryCount; private DateTime startTime; private EndPoint remoteEndPoint; private volatile bool connecting; // Connection properties /// <summary> /// Gets whether this client link is currently connected or not. /// </summary> public bool Connected { get { try { using (new ReadLock(rwlock)) { return (session != null && ((AbstractTcpSession)session).SocketConnected); } } catch { return false; } } } /// <summary> /// Gets or sets the remote host address string to connect to. /// </summary> public string RemoteHost { get; set; } /// <summary> /// Gets or sets the remote port number to connect to. /// </summary> public int RemotePort { get; set; } // Socket option properties /// <summary> /// Gets or sets a boolean value indicating whether the client sockets /// are not to use the Nagle algorithm. /// </summary> public bool NoDelay { get; set; } // Connect properties /// <summary> /// Gets or sets the maximum number of connection retries before this /// link declares a connection failure. /// </summary> /// <remarks> /// Default value is 0 (no retry). A negative integer such as -1 means /// that the link should retry for unlimited times. /// </remarks> public int MaxRetryCount { get; set; } /// <summary> /// Gets or sets the initial connection retry interval time in milliseconds. /// </summary> public double RetryInterval { get; set; } // Reconnect properties /// <summary> /// Gets or sets a boolean value indicating whether this link should /// start a new connection attempt automatically on disconnect, toward /// the previous remote endpoint. /// </summary> public bool AutoReconnect { get; set; } /// <summary> /// Gets or sets the average delay before automatic reconnect, /// in milliseconds, around which an actual delay is picked randomly. /// </summary> public int ReconnectDelay { get; set; } /// <summary> /// Initializes a new instance of the AbstractTcpClient class. /// </summary> protected AbstractTcpClient(string name) : base(name) { // Default socket options NoDelay = true; RetryInterval = 1000; // 1 sec by default ReconnectDelay = 1000; // 1 sec by default } /// <summary> /// Connects to the endpoint RemoteHost:RemotePort. /// </summary> public void Connect() { Connect(RemoteHost, RemotePort); } /// <summary> /// Connects to the specified remote address (host:port). /// </summary> public void Connect(string address) { Connect(address, 0); } /// <summary> /// Connects to the specified remote address. The port parameter is used /// when the given address does not contain a remote port number, /// </summary> public void Connect(string address, int port) { int index = address.LastIndexOf(':'); if (index >= 0 && address.Length > 15) { // Might be an IPv6 strig without a port specification. if (address.Split(':').Length > 6 && address.LastIndexOf("]:") < 0) { index = -1; } } if (0 < index && index < (address.Length - 1)) { string portString = address.Substring(index + 1).Trim(); if (Int32.TryParse(portString, out port)) { address = address.Substring(0, index).Trim(); } } RemoteHost = address; RemotePort = port; IPAddress ip; try { ip = Dns.GetHostAddresses(address)[0]; } catch (Exception e) { Trace.Error("{0} error resolving target host {1} : {2}", Name, address, e.Message); throw; } Connect(ip, RemotePort); } /// <summary> /// Connects to the specified IP address and port. /// </summary> public void Connect(IPAddress ip, int port) { connecting = true; LinkSession session = Session; if (session != null && ((AbstractTcpSession)session).SocketConnected) { Disconnect(); Trace.Info("{0} disconnected to initiate a new connection", Name); } Connect(null, new IPEndPoint(ip, port)); } public void Disconnect() { LinkSession session; using (new WriteLock(rwlock)) { if (ReferenceEquals(this.session, null)) { return; } session = this.session; this.session = null; } session.Close(); } private void Connect(Socket socket, EndPoint endpoint) { Trace.Info("{0} connecting to {1}", Name, endpoint); startTime = DateTime.UtcNow; ConnectInternal(socket, endpoint); } /// <summary> /// <see cref="ClientLink.Reconnect"/> /// </summary> public override void Reconnect() { if (remoteEndPoint == null) { Trace.Error("{0} no reconnect target", Name); return; } if (connecting) { return; } Connect(null, remoteEndPoint); } protected override void OnSessionConnectedInternal(bool result, object context) { base.OnSessionConnectedInternal(result, context); connecting = false; } protected override void OnSessionDisconnectedInternal(int handle, object context) { base.OnSessionDisconnectedInternal(handle, context); if (!closing) { if (AutoReconnect) { if (ReconnectDelay > 0) { int max = (ReconnectDelay << 1) + 1; int delay = new Random().Next(max); Thread.Sleep(delay); } Reconnect(); } } } /// <summary> /// Provides an actual implementation of asynchronous Connect. /// </summary> protected abstract void ConnectInternal(Socket socket, EndPoint endpoint); /// <summary> /// <see cref="ClientLink.OnConnectInternal"/> /// </summary> protected override void OnConnectInternal(LinkSession session) { base.OnConnectInternal(session); // Reset the retry counter. retryCount = 0; var tcpSession = (AbstractTcpSession)session; Socket socket = tcpSession.Socket; // Adjust socket options. socket.NoDelay = NoDelay; // Save the remote endpoint to reconnect. remoteEndPoint = socket.RemoteEndPoint; tcpSession.BeginReceive(true); Trace.Info("{0} {1} connected to {2}", Name, tcpSession.InternalHandle, socket.RemoteEndPoint); } /// <summary> /// Called by a derived link class when a connection attempt fails. /// </summary> protected virtual void OnConnectError(Socket socket, EndPoint endpoint) { if (MaxRetryCount < 0 || (MaxRetryCount > 0 && retryCount < MaxRetryCount)) { // Exponential backoff applied (up to x8) int count = Math.Min(retryCount, 3); double interval = RetryInterval * (1 << count); ++retryCount; double elapsedMillisecs = (DateTime.UtcNow - startTime).TotalMilliseconds; if (elapsedMillisecs < interval) { Thread.Sleep((int)(interval - elapsedMillisecs)); } Connect(socket, endpoint); } else { socket.Close(); connecting = false; OnLinkSessionConnectedInternal(false, endpoint); } } protected override void SetupInternal() { base.SetupInternal(); var holdingFlow = Flow; if (!ReferenceEquals(holdingFlow, null)) { holdingFlow.SubscribeTo(Name); } } protected override void TeardownInternal() { var holdingFlow = Flow; if (!ReferenceEquals(holdingFlow, null)) { holdingFlow.UnsubscribeFrom(Name); } base.TeardownInternal(); } } }
using XPT.Games.Generic.Constants; using XPT.Games.Generic.Maps; using XPT.Games.Twinion.Entities; namespace XPT.Games.Twinion.Maps { /// <summary> /// L1: Gauntlet Droit /// </summary> class TwMap02 : TwMap { public override int MapIndex => 2; public override int MapID => 0x0103; protected override int RandomEncounterChance => 15; protected override int RandomEncounterExtraCount => 0; private const int BEENHERE = 1; private const int GOTFLAG = 1; protected override void FnEvent01(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Through here is the Main Entrance."); TeleportParty(player, type, doMsgs, 1, 1, 140, Direction.West); } protected override void FnEvent02(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 1, 3, 159, Direction.South); } protected override void FnEvent03(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Now, enter the Coil Maze, and retrieve the Gauntlet."); TeleportParty(player, type, doMsgs, 1, 3, 247, Direction.West); } protected override void FnEvent04(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "To the North side...."); TeleportParty(player, type, doMsgs, 1, 3, 155, Direction.North); } protected override void FnEvent05(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "The sign here reads: The gauntlet has been thrown down in the Coil Maze."); ShowText(player, type, doMsgs, "Now you must return it to its birth place, to solve this quest and complete this most simple phase."); } protected override void FnEvent06(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Depart not from the path which Fate has assigned you! You shall come full circle in time. And begin here what ends asunder."); } protected override void FnEvent07(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "This way to the Great Egress."); } protected override void FnEvent08(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "The Great Egress..."); } protected override void FnEvent09(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "As you see, not all teleports lead to a different dungeon."); } protected override void FnEvent0B(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetPartyCount(player, type, doMsgs) == 1) { if (HasItem(player, type, doMsgs, LAVAGLOVE) || GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LAVAQUEST) == 2) { int teleportroom = 0; RemoveItem(player, type, doMsgs, LAVAGLOVE); ShowText(player, type, doMsgs, "You've won the challenge of the Gauntlet. I shall send you to its end."); switch (GetGuild(player, type, doMsgs)) { case BARBARIAN: teleportroom = 31; break; case KNIGHT: teleportroom = 47; break; case RANGER: teleportroom = 63; break; case THIEF: teleportroom = 79; break; case WIZARD: teleportroom = 95; break; case CLERIC: teleportroom = 111; break; } TeleportParty(player, type, doMsgs, 1, 3, teleportroom, Direction.East); } else { ShowText(player, type, doMsgs, "A wind whistles, 'Bring me the gauntlet from the maze south of here....'"); TeleportParty(player, type, doMsgs, 1, 3, 120, Direction.East); } } else { ShowText(player, type, doMsgs, "A forceful wind pushes your party back from the ancient forge. It howls, 'You must each step forth alone!'"); TeleportParty(player, type, doMsgs, 1, 3, 120, Direction.East); } } protected override void FnEvent0C(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Here you enter the Coils of the Maze..."); } protected override void FnEvent0D(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowPortrait(player, type, doMsgs, FOUNTAIN); if (GetPartyLevel(player, type, doMsgs, 10)) { Nothing(player, type, doMsgs); } else if (GetHealthCurrent(player, type, doMsgs) < GetHealthMax(player, type, doMsgs)) { ShowText(player, type, doMsgs, "The refreshing waters heal your wounds."); ModifyHealth(player, type, doMsgs, GetHealthMax(player, type, doMsgs)); } else { Nothing(player, type, doMsgs); } } private void Nothing(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "The fountain does nothing for you."); } protected override void FnEvent0F(TwPlayerServer player, MapEventType type, bool doMsgs) { if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.FIRSTQUEST) == 0)) { int skill = 0; int spell = 0; int itemA = 0; switch (GetTile(player, type, doMsgs)) { case 31: ShowText(player, type, doMsgs, "Well done, great Barbarian!"); skill = ARCHERY_SKILL; spell = STORM_WIND_SPELL; itemA = GREENLOCKPICK; break; case 47: ShowText(player, type, doMsgs, "Well done, noble Knight!"); skill = CHANNEL_SKILL; spell = CURSE_SPELL; itemA = CRYSTALBALL; break; case 63: ShowText(player, type, doMsgs, "Well done, loyal Ranger!"); skill = INTIMIDATE_SKILL; spell = PETRIFY_SPELL; itemA = CROSSBOW; break; case 79: ShowText(player, type, doMsgs, "Well done, master Thief!"); skill = ARCHERY_SKILL; spell = BACKFIRE_SPELL; itemA = LEATHERJACKET; break; case 95: ShowText(player, type, doMsgs, "Well done, master Wizard!"); skill = DEFLECT_MAGIC_SKILL; spell = HEAL_SPELL; itemA = QUARTERSTAFF; break; case 111: ShowText(player, type, doMsgs, "Well done, devout Cleric!"); skill = RUNE_READING_SKILL; spell = LIGHTNING_SPELL; itemA = QUARTERSTAFF; break; } SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.FIRSTQUEST, 1); SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LAVAQUEST, 2); ShowText(player, type, doMsgs, "Take this spell and this skill as rewards for your questing; and gain experience from your actions."); ModifyExperience(player, type, doMsgs, 1000); SetSkill(player, type, doMsgs, skill, 1); GiveSpell(player, type, doMsgs, spell, 1); GiveItem(player, type, doMsgs, itemA); } else { ShowText(player, type, doMsgs, "You've already received your rewards."); } } protected override void FnEvent14(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; if (HasItem(player, type, doMsgs, READTRACKSTALISMAN)) { ShowText(player, type, doMsgs, "Mages hurl magic at you!"); } else { SetTreasure(player, type, doMsgs, READTRACKSTALISMAN, 0, 0, 0, 0, 35); ShowText(player, type, doMsgs, "You come across some ancient Wizards!"); } switch (GetPartyCount(player, type, doMsgs)) { case 1: AddEncounter(player, type, doMsgs, 01, 27); break; case 2: for (i = 1; i <= 3; i++) { AddEncounter(player, type, doMsgs, i, 27); } break; default: ShowText(player, type, doMsgs, "And their familiars!"); for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 34); } for (i = 3; i <= 4; i++) { AddEncounter(player, type, doMsgs, i, 27); } break; } } protected override void FnEvent15(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; if (HasItem(player, type, doMsgs, CRYSTALBALL)) { ShowText(player, type, doMsgs, "Some Berserkers turn to attack!"); } else { SetTreasure(player, type, doMsgs, CRYSTALBALL, 0, 0, 0, 0, 100); ShowText(player, type, doMsgs, "Berserkers fighting over a spherical crystal draw you into the fray!"); } switch (GetPartyCount(player, type, doMsgs)) { case 1: AddEncounter(player, type, doMsgs, 01, 31); break; case 2: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 32); } break; default: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 32); } for (i = 3; i <= 4; i++) { AddEncounter(player, type, doMsgs, i, 33); } break; } } protected override void FnEvent16(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; if (HasItem(player, type, doMsgs, HEALPOTION)) { ShowText(player, type, doMsgs, "You encounter some novice adventurers."); } else { ShowText(player, type, doMsgs, "Wizards and Brigands traveling together challenge you to combat! The wager is your life for their potion!"); SetTreasure(player, type, doMsgs, HEALPOTION, 0, 0, 0, 0, 100); } switch (GetPartyCount(player, type, doMsgs)) { case 1: AddEncounter(player, type, doMsgs, 01, 25); break; case 2: AddEncounter(player, type, doMsgs, 1, 25); AddEncounter(player, type, doMsgs, 2, 26); break; default: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 26); } for (i = 5; i <= 6; i++) { AddEncounter(player, type, doMsgs, i, 25); } break; } } protected override void FnEvent17(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; switch (GetPartyCount(player, type, doMsgs)) { case 1: AddEncounter(player, type, doMsgs, 01, 35); break; case 2: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 35); } break; default: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 25); } for (i = 3; i <= 5; i++) { AddEncounter(player, type, doMsgs, i, 35); } break; } } protected override void FnEvent18(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasItem(player, type, doMsgs, TELEPORTPASS)) { ShowText(player, type, doMsgs, "Young thieves jump you!"); } else { SetTreasure(player, type, doMsgs, TELEPORTPASS, 0, 0, 0, 0, 100); ShowText(player, type, doMsgs, "A thief tucks a sheet of paper under his jacket as he and his colleagues hear you approach."); } if (GetPartyCount(player, type, doMsgs) == 1 || GetPartyCount(player, type, doMsgs) == 2) { AddEncounter(player, type, doMsgs, 01, 35); AddEncounter(player, type, doMsgs, 02, 34); } else { AddEncounter(player, type, doMsgs, 01, 34); AddEncounter(player, type, doMsgs, 02, 35); AddEncounter(player, type, doMsgs, 03, 36); AddEncounter(player, type, doMsgs, 04, 37); } } protected override void FnEvent19(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Small pinholes of light seep through the cracks in the wall here."); if ((HasUsedSkill(player, type, ref doMsgs, DETECT_SKILL) >= 3) || (HasUsedSpell(player, type, ref doMsgs, TRUE_SEEING_SPELL) >= 1) || UsedItem(player, type, ref doMsgs, CRYSTALBALL, CRYSTALBALL) || UsedItem(player, type, ref doMsgs, VALKYRIESHELM, VALKYRIESHELM) || UsedItem(player, type, ref doMsgs, RINGOFTHIEVES, RINGOFTHIEVES) || UsedItem(player, type, ref doMsgs, HELMOFWISDOM, HELMOFWISDOM)) { SetWallItem(player, type, doMsgs, DOOR, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); ShowText(player, type, doMsgs, "You've uncovered a hidden door!"); ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } else { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); ClearWallItem(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } } protected override void FnEvent1A(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; if (HasItem(player, type, doMsgs, LAVAGLOVE)) { ShowText(player, type, doMsgs, "Rogues rush out at you from the shadows."); SetTreasure(player, type, doMsgs, LONGSWORD, HEALPOTION, 0, 0, 0, 250); } else if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LAVAQUEST) == 2 || (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LAVAQUEST) == 0)) { ShowText(player, type, doMsgs, "You spot the Lava Glove on the rogue leader's hand, as he signals his henchmen to attack!"); SetTreasure(player, type, doMsgs, LAVAGLOVE, MANAELIXIR, ELIXIROFHEALTH, 0, 0, 1000); } else if (!HasItem(player, type, doMsgs, LAVAGLOVE)) { ShowText(player, type, doMsgs, "You spot the Lava Glove on the rogue leader's hand, as he signals his henchmen to attack!"); SetTreasure(player, type, doMsgs, LAVAGLOVE, HEALPOTION, 0, 0, 0, 250); } switch (GetPartyCount(player, type, doMsgs)) { case 1: AddEncounter(player, type, doMsgs, 01, 26); AddEncounter(player, type, doMsgs, 05, 37); break; case 2: AddEncounter(player, type, doMsgs, 01, 26); AddEncounter(player, type, doMsgs, 02, 28); AddEncounter(player, type, doMsgs, 06, 37); break; default: for (i = 1; i <= 4; i++) { AddEncounter(player, type, doMsgs, i, 26); } AddEncounter(player, type, doMsgs, 5, 29); AddEncounter(player, type, doMsgs, 6, 37); break; } } protected override void FnEvent1B(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ENDGAMETELE) == 1) { ShowText(player, type, doMsgs, "This is the nexus point from where you start your final journey..."); TeleportParty(player, type, doMsgs, 2, 3, 255, Direction.North); } else { ShowText(player, type, doMsgs, "What a magnificent carving, you must come back and examine it more closely when you have time."); ShowText(player, type, doMsgs, "But right now there's too much to do."); } } protected override void FnEvent1C(TwPlayerServer player, MapEventType type, bool doMsgs) { ClearWallItem(player, type, doMsgs, 157, Direction.West); ClearWallItem(player, type, doMsgs, 124, Direction.West); } protected override void FnEvent1D(TwPlayerServer player, MapEventType type, bool doMsgs) { if ((GetFlag(player, type, doMsgs, FlagTypeParty, BEENHERE) == 0)) { ShowText(player, type, doMsgs, "Swords and sorcery come rushing at you!"); } else if (GetFlag(player, type, doMsgs, FlagTypeParty, BEENHERE) == 1) { ShowText(player, type, doMsgs, "Duelists and Wizards attack as you approach."); SetTreasure(player, type, doMsgs, BROADSWORD, QUARTERSTAFF, 0, 0, 0, 200); } if (GetPartyCount(player, type, doMsgs) == 1 || GetPartyCount(player, type, doMsgs) == 2) { AddEncounter(player, type, doMsgs, 01, 38); AddEncounter(player, type, doMsgs, 05, 39); } else { AddEncounter(player, type, doMsgs, 01, 39); AddEncounter(player, type, doMsgs, 02, 40); AddEncounter(player, type, doMsgs, 03, 38); AddEncounter(player, type, doMsgs, 04, 39); } } protected override void FnEvent1E(TwPlayerServer player, MapEventType type, bool doMsgs) { if ((GetFlag(player, type, doMsgs, FlagTypeTile, GOTFLAG) == 0)) { int i = 0; i = GetFlag(player, type, doMsgs, FlagTypeParty, BEENHERE); if (i <= 1) { i++; SetFlag(player, type, doMsgs, FlagTypeParty, BEENHERE, i); } SetFlag(player, type, doMsgs, FlagTypeTile, GOTFLAG, 1); } } protected override void FnEvent1F(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "This seems an odd place for a teleport."); TeleportParty(player, type, doMsgs, 1, 3, 123, Direction.South); } protected override void FnEvent20(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 1, 3, 152, Direction.West); } protected override void FnEvent21(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Into the corner with you."); TeleportParty(player, type, doMsgs, 1, 3, 240, Direction.East); } protected override void FnEvent22(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 1, 3, 250, Direction.North); } protected override void FnEvent23(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowRunes(player, type, ref doMsgs, "The Gauntlet is a useful item. But first you must enter the coils to retrieve it."); } protected override void FnEvent24(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "The rewards are worthwhile, if you are careful and search all the corners."); } protected override void FnEvent25(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Welcome to the southern half of The Gauntlet."); ShowText(player, type, doMsgs, "Feel free to explore the coils while you are here."); } protected override void FnEvent26(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowRunes(player, type, ref doMsgs, "They can be found to the north by going east and south of where you are."); } protected override void FnEvent27(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "There must be a portal tucked away in some distant corner."); } protected override void FnEvent28(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowRunes(player, type, ref doMsgs, "To the northeast, there lies such a portal."); } protected override void FnEvent29(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Westward, an ancient foundry, now extinct, lies at the bottom of a shaft. It was here that the Lava Glove was born...and here it must return once you've retrieved it."); } protected override void FnEvent2A(TwPlayerServer player, MapEventType type, bool doMsgs) { if (UsedItem(player, type, ref doMsgs, GREENLOCKPICK, BLUELOCKPICK) || HasUsedSkill(player, type, ref doMsgs, LOCKPICK_SKILL) > 1) { ShowText(player, type, doMsgs, "You've picked the lock. Proceed."); ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } else { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); ShowText(player, type, doMsgs, "A locked door impedes your progress here."); } } protected override void FnEvent2B(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasItem(player, type, doMsgs, LAVAGLOVE) && (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LAVAQUEST) == 0)) { SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LAVAQUEST, 1); ShowText(player, type, doMsgs, "Well done! Now, to the ancient foundry near the heart of this level. You must step onto the foundry in the center to return the Gauntlet!"); ShowText(player, type, doMsgs, "Hurry, your rewards await!"); } } protected override void FnEvent2C(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Magical waters spill out of the southern portal here; culminating in a small puddle on the floor."); } protected override void FnEvent2D(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetPartyCount(player, type, doMsgs) == 1) { ShowText(player, type, doMsgs, "To the Snake River."); TeleportParty(player, type, doMsgs, 1, 2, 223, Direction.West); } else { TeleportParty(player, type, doMsgs, 1, 3, GetTile(player, type, doMsgs), Direction.North); ShowText(player, type, doMsgs, "Your party must split and enter this narrow portal one by one to proceed."); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.StreamAnalytics; using Microsoft.Azure.Management.StreamAnalytics.Models; namespace Microsoft.Azure.Management.StreamAnalytics { public static partial class TransformationOperationsExtensions { /// <summary> /// Create or update a transformation for a stream analytics job. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.StreamAnalytics.ITransformationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the stream analytics job. /// </param> /// <param name='jobName'> /// Required. The name of the stream analytics job. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a /// transformation for the stream analytics job. /// </param> /// <returns> /// The response of the transformation create operation. /// </returns> public static TransformationCreateOrUpdateResponse CreateOrUpdate(this ITransformationOperations operations, string resourceGroupName, string jobName, TransformationCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((ITransformationOperations)s).CreateOrUpdateAsync(resourceGroupName, jobName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create or update a transformation for a stream analytics job. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.StreamAnalytics.ITransformationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the stream analytics job. /// </param> /// <param name='jobName'> /// Required. The name of the stream analytics job. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a /// transformation for the stream analytics job. /// </param> /// <returns> /// The response of the transformation create operation. /// </returns> public static Task<TransformationCreateOrUpdateResponse> CreateOrUpdateAsync(this ITransformationOperations operations, string resourceGroupName, string jobName, TransformationCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, jobName, parameters, CancellationToken.None); } /// <summary> /// Create or update a transformation for a stream analytics job. The /// raw json content will be used. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.StreamAnalytics.ITransformationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the stream analytics job. /// </param> /// <param name='jobName'> /// Required. The name of the stream analytics job. /// </param> /// <param name='transformationName'> /// Required. The name of the transformation for the stream analytics /// job. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a /// transformation for the stream analytics job. It is in json format. /// </param> /// <returns> /// The response of the transformation create operation. /// </returns> public static TransformationCreateOrUpdateResponse CreateOrUpdateWithRawJsonContent(this ITransformationOperations operations, string resourceGroupName, string jobName, string transformationName, TransformationCreateOrUpdateWithRawJsonContentParameters parameters) { return Task.Factory.StartNew((object s) => { return ((ITransformationOperations)s).CreateOrUpdateWithRawJsonContentAsync(resourceGroupName, jobName, transformationName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create or update a transformation for a stream analytics job. The /// raw json content will be used. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.StreamAnalytics.ITransformationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the stream analytics job. /// </param> /// <param name='jobName'> /// Required. The name of the stream analytics job. /// </param> /// <param name='transformationName'> /// Required. The name of the transformation for the stream analytics /// job. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a /// transformation for the stream analytics job. It is in json format. /// </param> /// <returns> /// The response of the transformation create operation. /// </returns> public static Task<TransformationCreateOrUpdateResponse> CreateOrUpdateWithRawJsonContentAsync(this ITransformationOperations operations, string resourceGroupName, string jobName, string transformationName, TransformationCreateOrUpdateWithRawJsonContentParameters parameters) { return operations.CreateOrUpdateWithRawJsonContentAsync(resourceGroupName, jobName, transformationName, parameters, CancellationToken.None); } /// <summary> /// Get the transformation for a stream analytics job. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.StreamAnalytics.ITransformationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the stream analytics job. /// </param> /// <param name='jobName'> /// Required. The name of the stream analytics job. /// </param> /// <param name='transformationName'> /// Required. The name of the transformation for the stream analytics /// job. /// </param> /// <returns> /// The response of the transformation get operation. /// </returns> public static TransformationsGetResponse Get(this ITransformationOperations operations, string resourceGroupName, string jobName, string transformationName) { return Task.Factory.StartNew((object s) => { return ((ITransformationOperations)s).GetAsync(resourceGroupName, jobName, transformationName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the transformation for a stream analytics job. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.StreamAnalytics.ITransformationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the stream analytics job. /// </param> /// <param name='jobName'> /// Required. The name of the stream analytics job. /// </param> /// <param name='transformationName'> /// Required. The name of the transformation for the stream analytics /// job. /// </param> /// <returns> /// The response of the transformation get operation. /// </returns> public static Task<TransformationsGetResponse> GetAsync(this ITransformationOperations operations, string resourceGroupName, string jobName, string transformationName) { return operations.GetAsync(resourceGroupName, jobName, transformationName, CancellationToken.None); } /// <summary> /// Update an transformation for a stream analytics job. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.StreamAnalytics.ITransformationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the stream analytics job. /// </param> /// <param name='jobName'> /// Required. The name of the stream analytics job. /// </param> /// <param name='transformationName'> /// Required. The name of the transformation for the stream analytics /// job. /// </param> /// <param name='parameters'> /// Required. The parameters required to update an transformation for /// the stream analytics job. /// </param> /// <returns> /// The response of the transformation patch operation. /// </returns> public static TransformationPatchResponse Update(this ITransformationOperations operations, string resourceGroupName, string jobName, string transformationName, TransformationPatchParameters parameters) { return Task.Factory.StartNew((object s) => { return ((ITransformationOperations)s).UpdateAsync(resourceGroupName, jobName, transformationName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update an transformation for a stream analytics job. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.StreamAnalytics.ITransformationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the stream analytics job. /// </param> /// <param name='jobName'> /// Required. The name of the stream analytics job. /// </param> /// <param name='transformationName'> /// Required. The name of the transformation for the stream analytics /// job. /// </param> /// <param name='parameters'> /// Required. The parameters required to update an transformation for /// the stream analytics job. /// </param> /// <returns> /// The response of the transformation patch operation. /// </returns> public static Task<TransformationPatchResponse> UpdateAsync(this ITransformationOperations operations, string resourceGroupName, string jobName, string transformationName, TransformationPatchParameters parameters) { return operations.UpdateAsync(resourceGroupName, jobName, transformationName, parameters, CancellationToken.None); } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Messages.Messages File: ExecutionMessage.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Messages { using System; using System.ComponentModel; using System.Runtime.Serialization; using System.Xml.Serialization; using Ecng.Common; using StockSharp.Localization; /// <summary> /// The types of data that contain information in <see cref="ExecutionMessage"/>. /// </summary> [DataContract] [Serializable] public enum ExecutionTypes { /// <summary> /// Tick trade. /// </summary> [EnumMember] Tick, /// <summary> /// Transaction. /// </summary> [EnumMember] Transaction, /// <summary> /// Obsolete. /// </summary> [EnumMember] [Obsolete] Obsolete, /// <summary> /// Order log. /// </summary> [EnumMember] OrderLog, } /// <summary> /// The message contains information about the execution. /// </summary> [Serializable] [DataContract] public class ExecutionMessage : BaseSubscriptionIdMessage<ExecutionMessage>, ITransactionIdMessage, IServerTimeMessage, ISecurityIdMessage, ISeqNumMessage, IPortfolioNameMessage, IErrorMessage, IStrategyIdMessage, IGeneratedMessage { /// <inheritdoc /> [DataMember] [DisplayNameLoc(LocalizedStrings.SecurityIdKey)] [DescriptionLoc(LocalizedStrings.SecurityIdKey, true)] [MainCategory] public SecurityId SecurityId { get; set; } /// <inheritdoc /> [DataMember] [DisplayNameLoc(LocalizedStrings.PortfolioKey)] [DescriptionLoc(LocalizedStrings.PortfolioNameKey)] [MainCategory] public string PortfolioName { get; set; } /// <summary> /// Client code assigned by the broker. /// </summary> [DataMember] [MainCategory] [DisplayNameLoc(LocalizedStrings.ClientCodeKey)] [DescriptionLoc(LocalizedStrings.ClientCodeDescKey)] public string ClientCode { get; set; } /// <summary> /// Broker firm code. /// </summary> [DataMember] [MainCategory] [CategoryLoc(LocalizedStrings.Str2593Key)] [DisplayNameLoc(LocalizedStrings.BrokerKey)] [DescriptionLoc(LocalizedStrings.Str2619Key)] public string BrokerCode { get; set; } /// <summary> /// The depositary where the physical security. /// </summary> [DisplayNameLoc(LocalizedStrings.DepoKey)] [DescriptionLoc(LocalizedStrings.DepoNameKey)] [MainCategory] public string DepoName { get; set; } /// <inheritdoc /> [DataMember] [DisplayNameLoc(LocalizedStrings.ServerTimeKey)] [DescriptionLoc(LocalizedStrings.ServerTimeKey, true)] [MainCategory] public DateTimeOffset ServerTime { get; set; } /// <inheritdoc /> [DataMember] [DisplayNameLoc(LocalizedStrings.TransactionKey)] [DescriptionLoc(LocalizedStrings.TransactionIdKey, true)] [MainCategory] public long TransactionId { get; set; } /// <summary> /// Data type, information about which is contained in the <see cref="ExecutionMessage"/>. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.DataTypeKey)] [DescriptionLoc(LocalizedStrings.Str110Key)] [MainCategory] //[Nullable] public ExecutionTypes? ExecutionType { get; set; } /// <summary> /// Is the action an order cancellation. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.CancelKey)] [DescriptionLoc(LocalizedStrings.IsActionOrderCancellationKey)] [MainCategory] public bool IsCancellation { get; set; } /// <summary> /// Order ID. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.OrderIdKey)] [DescriptionLoc(LocalizedStrings.OrderIdKey, true)] [MainCategory] //[Nullable] public long? OrderId { get; set; } /// <summary> /// Order ID (as string, if electronic board does not use numeric order ID representation). /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.OrderIdStringKey)] [DescriptionLoc(LocalizedStrings.OrderIdStringDescKey)] [MainCategory] public string OrderStringId { get; set; } /// <summary> /// Board order id. Uses in case of <see cref="ExecutionMessage.OrderId"/> and <see cref="ExecutionMessage.OrderStringId"/> is a brokerage system ids. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.Str117Key)] [DescriptionLoc(LocalizedStrings.Str118Key)] [MainCategory] public string OrderBoardId { get; set; } ///// <summary> ///// Derived order ID (e.g., conditional order generated a real exchange order). ///// </summary> //[DataMember] //[DisplayNameLoc(LocalizedStrings.DerivedKey)] //[DescriptionLoc(LocalizedStrings.DerivedOrderIdKey)] //[MainCategory] //[Nullable] //public long? DerivedOrderId { get; set; } ///// <summary> ///// Derived order ID (e.g., conditional order generated a real exchange order). ///// </summary> //[DataMember] //[DisplayNameLoc(LocalizedStrings.DerivedStringKey)] //[DescriptionLoc(LocalizedStrings.DerivedStringDescKey)] //[MainCategory] //public string DerivedOrderStringId { get; set; } /// <summary> /// Is the message contains order info. /// </summary> public bool HasOrderInfo { get; set; } /// <summary> /// Is the message contains trade info. /// </summary> public bool HasTradeInfo { get; set; } /// <summary> /// Order price. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.PriceKey)] [DescriptionLoc(LocalizedStrings.OrderPriceKey)] [MainCategory] public decimal OrderPrice { get; set; } /// <summary> /// Number of contracts in the order. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.VolumeOrderKey)] [DescriptionLoc(LocalizedStrings.OrderVolumeKey)] [MainCategory] //[Nullable] public decimal? OrderVolume { get; set; } /// <summary> /// Number of contracts in the trade. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.VolumeTradeKey)] [DescriptionLoc(LocalizedStrings.TradeVolumeKey)] [MainCategory] //[Nullable] public decimal? TradeVolume { get; set; } /// <summary> /// Visible quantity of contracts in order. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.VisibleVolumeKey)] [DescriptionLoc(LocalizedStrings.Str127Key)] [MainCategory] //[Nullable] public decimal? VisibleVolume { get; set; } /// <summary> /// Order side (buy or sell). /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.Str128Key)] [DescriptionLoc(LocalizedStrings.Str129Key)] [MainCategory] public Sides Side { get; set; } /// <summary> /// Order contracts balance. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.Str130Key)] [DescriptionLoc(LocalizedStrings.Str131Key)] [MainCategory] //[Nullable] public decimal? Balance { get; set; } /// <summary> /// Order type. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.Str132Key)] [DescriptionLoc(LocalizedStrings.Str133Key)] [MainCategory] public OrderTypes? OrderType { get; set; } /// <summary> /// System order status. /// </summary> [DataMember] [Browsable(false)] //[Nullable] public long? OrderStatus { get; set; } /// <summary> /// Order state. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.StateKey)] [DescriptionLoc(LocalizedStrings.Str134Key)] [MainCategory] //[Nullable] public OrderStates? OrderState { get; set; } /// <summary> /// Placed order comment. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.Str135Key)] [DescriptionLoc(LocalizedStrings.Str136Key)] [MainCategory] public string Comment { get; set; } /// <summary> /// Message for order (created by the trading system when registered, changed or cancelled). /// </summary> [DisplayNameLoc(LocalizedStrings.Str137Key)] [DescriptionLoc(LocalizedStrings.Str138Key)] [MainCategory] public string SystemComment { get; set; } /// <summary> /// Is a system trade. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.Str139Key)] [DescriptionLoc(LocalizedStrings.Str140Key)] [MainCategory] //[Nullable] public bool? IsSystem { get; set; } /// <summary> /// Order expiry time. The default is <see langword="null" />, which mean (GTC). /// </summary> /// <remarks> /// If the value is equal <see langword="null" />, order will be GTC (good til cancel). Or uses exact date. /// </remarks> [DataMember] [DisplayNameLoc(LocalizedStrings.Str141Key)] [DescriptionLoc(LocalizedStrings.Str142Key)] [MainCategory] public DateTimeOffset? ExpiryDate { get; set; } /// <summary> /// Limit order execution condition. /// </summary> [DisplayNameLoc(LocalizedStrings.Str143Key)] [DescriptionLoc(LocalizedStrings.Str144Key)] [MainCategory] //[Nullable] public TimeInForce? TimeInForce { get; set; } /// <summary> /// Trade ID. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.OrderIdKey)] [DescriptionLoc(LocalizedStrings.Str145Key)] [MainCategory] //[Nullable] public long? TradeId { get; set; } /// <summary> /// Trade ID (as string, if electronic board does not use numeric order ID representation). /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.OrderIdStringKey)] [DescriptionLoc(LocalizedStrings.Str146Key)] [MainCategory] public string TradeStringId { get; set; } /// <summary> /// Trade price. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.PriceKey)] [DescriptionLoc(LocalizedStrings.Str147Key)] [MainCategory] //[Nullable] public decimal? TradePrice { get; set; } /// <summary> /// System trade status. /// </summary> [DataMember] [Browsable(false)] //[Nullable] public int? TradeStatus { get; set; } /// <summary> /// Deal initiator (seller or buyer). /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.InitiatorKey)] [DescriptionLoc(LocalizedStrings.Str149Key)] [MainCategory] //[Nullable] public Sides? OriginSide { get; set; } /// <summary> /// Number of open positions (open interest). /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.Str150Key)] [DescriptionLoc(LocalizedStrings.Str151Key)] [MainCategory] //[Nullable] public decimal? OpenInterest { get; set; } /// <inheritdoc /> [DisplayNameLoc(LocalizedStrings.Str152Key)] [DescriptionLoc(LocalizedStrings.Str153Key, true)] [MainCategory] [XmlIgnore] public Exception Error { get; set; } /// <summary> /// Order condition (e.g., stop- and algo- orders parameters). /// </summary> [DisplayNameLoc(LocalizedStrings.Str154Key)] [DescriptionLoc(LocalizedStrings.Str155Key)] [CategoryLoc(LocalizedStrings.Str156Key)] [XmlIgnore] public OrderCondition Condition { get; set; } /// <summary> /// Is tick uptrend or downtrend in price. Uses only <see cref="ExecutionType"/> for <see cref="ExecutionTypes.Tick"/>. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.Str157Key)] [DescriptionLoc(LocalizedStrings.Str158Key)] [MainCategory] //[Nullable] public bool? IsUpTick { get; set; } /// <summary> /// Commission (broker, exchange etc.). Uses when <see cref="ExecutionType"/> set to <see cref="ExecutionTypes.Transaction"/>. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.Str159Key)] [DescriptionLoc(LocalizedStrings.Str160Key)] [MainCategory] //[Nullable] public decimal? Commission { get; set; } /// <summary> /// Commission currency. Can be <see lnagword="null"/>. /// </summary> public string CommissionCurrency { get; set; } /// <summary> /// Network latency. Uses when <see cref="ExecutionType"/> set to <see cref="ExecutionTypes.Transaction"/>. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.Str161Key)] [DescriptionLoc(LocalizedStrings.Str162Key)] [MainCategory] //[Nullable] public TimeSpan? Latency { get; set; } /// <summary> /// Slippage in trade price. Uses when <see cref="ExecutionType"/> set to <see cref="ExecutionTypes.Transaction"/>. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.Str163Key)] [DescriptionLoc(LocalizedStrings.Str164Key)] [MainCategory] //[Nullable] public decimal? Slippage { get; set; } /// <summary> /// User order id. Uses when <see cref="ExecutionType"/> set to <see cref="ExecutionTypes.Transaction"/>. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.Str165Key)] [DescriptionLoc(LocalizedStrings.Str166Key)] [MainCategory] public string UserOrderId { get; set; } /// <inheritdoc /> [DataMember] public string StrategyId { get; set; } /// <summary> /// Trading security currency. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.CurrencyKey)] [DescriptionLoc(LocalizedStrings.Str382Key)] [MainCategory] //[Nullable] public CurrencyTypes? Currency { get; set; } /// <summary> /// The profit, realized by trade. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.PnLKey)] [DescriptionLoc(LocalizedStrings.PnLKey, true)] [MainCategory] //[Nullable] public decimal? PnL { get; set; } /// <summary> /// The position, generated by order or trade. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.Str862Key)] [DescriptionLoc(LocalizedStrings.Str862Key, true)] [MainCategory] //[Nullable] public decimal? Position { get; set; } /// <summary> /// Is the order of market-maker. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.MarketMakerKey)] [DescriptionLoc(LocalizedStrings.MarketMakerOrderKey, true)] public bool? IsMarketMaker { get; set; } /// <summary> /// Is margin enabled. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.MarginKey)] [DescriptionLoc(LocalizedStrings.IsMarginKey)] public bool? IsMargin { get; set; } /// <summary> /// Is order manual. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.ManualKey)] [DescriptionLoc(LocalizedStrings.IsOrderManualKey)] public bool? IsManual { get; set; } /// <summary> /// Average execution price. /// </summary> [DataMember] public decimal? AveragePrice { get; set; } /// <summary> /// Yield. /// </summary> [DataMember] public decimal? Yield { get; set; } /// <summary> /// Minimum quantity of an order to be executed. /// </summary> [DataMember] public decimal? MinVolume { get; set; } /// <summary> /// Position effect. /// </summary> [DataMember] public OrderPositionEffects? PositionEffect { get; set; } /// <summary> /// Post-only order. /// </summary> [DataMember] public bool? PostOnly { get; set; } /// <summary> /// Used to identify whether the order initiator is an aggressor or not in the trade. /// </summary> [DataMember] public bool? Initiator { get; set; } /// <inheritdoc /> [DataMember] public long SeqNum { get; set; } /// <inheritdoc /> [DataMember] public DataType BuildFrom { get; set; } /// <summary> /// Margin leverage. /// </summary> [DataMember] public int? Leverage { get; set; } /// <summary> /// Order id (buy). /// </summary> [DataMember] public long? OrderBuyId { get; set; } /// <summary> /// Order id (sell). /// </summary> [DataMember] public long? OrderSellId { get; set; } /// <summary> /// Initializes a new instance of the <see cref="ExecutionMessage"/>. /// </summary> public ExecutionMessage() : base(MessageTypes.Execution) { } /// <inheritdoc /> public override DataType DataType => ExecutionType.Value.ToDataType(); /// <inheritdoc /> public override string ToString() { var str = base.ToString() + $",T(S)={ServerTime:yyyy/MM/dd HH:mm:ss.fff},({ExecutionType}),Sec={SecurityId},O/T={HasOrderInfo}/{HasTradeInfo},Ord={OrderId}/{TransactionId}/{OriginalTransactionId},Fail={Error},Price={OrderPrice},OrdVol={OrderVolume},TrVol={TradeVolume},Bal={Balance},TId={TradeId},Pf={PortfolioName},TPrice={TradePrice},UId={UserOrderId},Type={OrderType},State={OrderState},Cond={Condition}"; if (!StrategyId.IsEmpty()) str += $",Strategy={StrategyId}"; if (PositionEffect != null) str += $",PosEffect={PositionEffect.Value}"; if (PostOnly != null) str += $",PostOnly={PostOnly.Value}"; if (Initiator != null) str += $",Initiator={Initiator.Value}"; if (SeqNum != default) str += $",SeqNum={SeqNum}"; if (Leverage != null) str += $",Leverage={Leverage.Value}"; if (OrderBuyId != null) str += $",buy (id)={OrderBuyId.Value}"; if (OrderSellId != null) str += $",sell (id)={OrderSellId.Value}"; return str; } /// <inheritdoc /> public override void CopyTo(ExecutionMessage destination) { base.CopyTo(destination); destination.Balance = Balance; destination.Comment = Comment; destination.Condition = Condition?.Clone(); destination.ClientCode = ClientCode; destination.BrokerCode = BrokerCode; destination.Currency = Currency; destination.ServerTime = ServerTime; destination.DepoName = DepoName; destination.Error = Error; destination.ExpiryDate = ExpiryDate; destination.IsSystem = IsSystem; destination.OpenInterest = OpenInterest; destination.OrderId = OrderId; destination.OrderStringId = OrderStringId; destination.OrderBoardId = OrderBoardId; destination.ExecutionType = ExecutionType; destination.IsCancellation = IsCancellation; //destination.Action = Action; destination.OrderState = OrderState; destination.OrderStatus = OrderStatus; destination.OrderType = OrderType; destination.OriginSide = OriginSide; destination.PortfolioName = PortfolioName; destination.OrderPrice = OrderPrice; destination.SecurityId = SecurityId; destination.Side = Side; destination.SystemComment = SystemComment; destination.TimeInForce = TimeInForce; destination.TradeId = TradeId; destination.TradeStringId = TradeStringId; destination.TradePrice = TradePrice; destination.TradeStatus = TradeStatus; destination.TransactionId = TransactionId; destination.OrderVolume = OrderVolume; destination.TradeVolume = TradeVolume; //destination.IsFinished = IsFinished; destination.VisibleVolume = VisibleVolume; destination.IsUpTick = IsUpTick; destination.Commission = Commission; destination.Latency = Latency; destination.Slippage = Slippage; destination.UserOrderId = UserOrderId; destination.StrategyId = StrategyId; //destination.DerivedOrderId = DerivedOrderId; //destination.DerivedOrderStringId = DerivedOrderStringId; destination.PnL = PnL; destination.Position = Position; destination.HasTradeInfo = HasTradeInfo; destination.HasOrderInfo = HasOrderInfo; destination.IsMarketMaker = IsMarketMaker; destination.IsMargin = IsMargin; destination.IsManual = IsManual; destination.CommissionCurrency = CommissionCurrency; destination.AveragePrice = AveragePrice; destination.Yield = Yield; destination.MinVolume = MinVolume; destination.PositionEffect = PositionEffect; destination.PostOnly = PostOnly; destination.Initiator = Initiator; destination.SeqNum = SeqNum; destination.BuildFrom = BuildFrom; destination.Leverage = Leverage; destination.OrderBuyId = OrderBuyId; destination.OrderSellId = OrderSellId; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { #region Methods [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeBeforeMethodName() { var markup = @" using System; class MyClass { public void $$Foo(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeInParameterList() { var markup = @" using System; class MyClass { public void Foo(int x, $$string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeAfterParameterList() { var markup = @" using System; class MyClass { public void Foo(int x, string y)$$ { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeBeforeMethodDeclaration() { var markup = @" using System; class MyClass { $$public void Foo(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnMetadataReference_InIdentifier_ShouldFail() { var markup = @" class C { static void Main(string[] args) { ((System.IFormattable)null).ToSt$$ring(""test"", null); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedErrorText: FeaturesResources.The_member_is_defined_in_metadata); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnMetadataReference_AtBeginningOfInvocation_ShouldFail() { var markup = @" class C { static void Main(string[] args) { $$((System.IFormattable)null).ToString(""test"", null); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedErrorText: FeaturesResources.The_member_is_defined_in_metadata); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnMetadataReference_InArgumentsOfInvocation_ShouldFail() { var markup = @" class C { static void Main(string[] args) { ((System.IFormattable)null).ToString(""test"",$$ null); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedErrorText: FeaturesResources.The_member_is_defined_in_metadata); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnMetadataReference_AfterInvocation_ShouldFail() { var markup = @" class C { string s = ((System.IFormattable)null).ToString(""test"", null)$$; }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedErrorText: FeaturesResources.You_can_only_change_the_signature_of_a_constructor_indexer_method_or_delegate); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeInMethodBody_ViaCommand() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { $$ } }"; await TestChangeSignatureViaCommandAsync( LanguageNames.CSharp, markup, expectedSuccess: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeInMethodBody_ViaSmartTag() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { [||] } }"; await TestMissingAsync(markup); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_BeginningOfIdentifier() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { $$Bar(x, y); } public void Bar(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(int x, string y) { Bar(y, x); } public void Bar(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_ArgumentList() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { $$Bar(x, y); } public void Bar(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(int x, string y) { Bar(y, x); } public void Bar(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_NestedCalls1() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { Bar($$Baz(x, y), y); } public void Bar(int x, string y) { } public int Baz(int x, string y) { return 1; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(int x, string y) { Bar(Baz(y, x), y); } public void Bar(int x, string y) { } public int Baz(string y, int x) { return 1; } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_NestedCalls2() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { Bar$$(Baz(x, y), y); } public void Bar(int x, string y) { } public int Baz(int x, string y) { return 1; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(int x, string y) { Bar(y, Baz(x, y)); } public void Bar(string y, int x) { } public int Baz(int x, string y) { return 1; } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_NestedCalls3() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { Bar(Baz(x, y), $$y); } public void Bar(int x, string y) { } public int Baz(int x, string y) { return 1; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(int x, string y) { Bar(y, Baz(x, y)); } public void Bar(string y, int x) { } public int Baz(int x, string y) { return 1; } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_Attribute() { var markup = @" using System; [$$My(1, 2)] class MyAttribute : Attribute { public MyAttribute(int x, int y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; [My(2, 1)] class MyAttribute : Attribute { public MyAttribute(int y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_OnlyHasCandidateSymbols() { var markup = @" class Test { void M(int x, string y) { } void M(int x, double y) { } void M2() { $$M(""s"", 1); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Test { void M(string y, int x) { } void M(int x, double y) { } void M2() { M(1, ""s""); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_CallToOtherConstructor() { var markup = @" class Program { public Program(int x, int y) : this(1, 2, 3)$$ { } public Program(int x, int y, int z) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" class Program { public Program(int x, int y) : this(3, 2, 1) { } public Program(int z, int y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_CallToBaseConstructor() { var markup = @" class B { public B(int a, int b) { } } class D : B { public D(int x, int y) : base(1, 2)$$ { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class B { public B(int b, int a) { } } class D : B { public D(int x, int y) : base(2, 1) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } #endregion #region Indexers [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeAtBeginningOfDeclaration() { var markup = @" class Program { $$int this[int x, string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InParameters() { var markup = @" class Program { int this[int x, $$string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeAtEndOfDeclaration() { var markup = @" class Program { int this[int x, string y]$$ { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeInAccessor() { var markup = @" class Program { int this[int x, string y] { get { return $$5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeOnReference_BeforeTarget() { var markup = @" class Program { void M(Program p) { var t = $$p[5, ""test""]; } int this[int x, string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M(Program p) { var t = p[""test"", 5]; } int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeOnReference_InArgumentList() { var markup = @" class Program { void M(Program p) { var t = p[5, ""test""$$]; } int this[int x, string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M(Program p) { var t = p[""test"", 5]; } int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } #endregion #region Delegates [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderDelegateParameters_ObjectCreation1() { var markup = @" public class C { void T() { var d = new $$D((x, y) => { }); } public delegate void D(int x, int y); }"; var permutation = new[] { 1, 0 }; var updatedCode = @" public class C { void T() { var d = new D((y, x) => { }); } public delegate void D(int y, int x); }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderDelegateParameters_ObjectCreation2() { var markup = @" public class CD<T> { public delegate void D(T t, T u); } class Test { public void M() { var dele = new CD<int>.$$D((int x, int y) => { }); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" public class CD<T> { public delegate void D(T u, T t); } class Test { public void M() { var dele = new CD<int>.D((int y, int x) => { }); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } #endregion #region CodeRefactoring [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_InvokeBeforeMethodName() { var markup = @" using System; class MyClass { public void [||]Foo(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(string y, int x) { } }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: true, updatedSignature: permutation, expectedCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_NotInMethodBody() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { [||] } }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_InLambda() { var markup = @" class Program { void M(int x) { System.Func<int, int, int> f = (a, b)[||] => { return a; }; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M(int x) { System.Func<int, int, int> f = (b, a) => { return a; }; } }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: true, updatedSignature: permutation, expectedCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_NotInLambdaBody() { var markup = @" class Program { void M(int x) { System.Func<int, int, int> f = (a, b) => { [||]return a; }; } }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_AtCallSite_ViaCommand() { var markup = @" class Program { void M(int x, int y) { M($$5, 6); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M(int y, int x) { M(6, 5); } }"; await TestChangeSignatureViaCommandAsync( LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_AtCallSite_ViaCodeAction() { var markup = @" class Program { void M(int x, int y) { M([||]5, 6); } }"; await TestMissingAsync(markup); } #endregion } }
namespace Tests.NHibernateTests { using System; using System.Collections.Generic; using log4net; using Microsoft.Practices.ServiceLocation; using NHibernate.Exceptions; using NUnit.Framework; using global::SharpArchContrib.Data.NHibernate; [TestFixture] [Category(TestCategories.FileDbTests)] public class TransactionTests : TransactionTestsBase { private const string TestEntityName = "TransactionTest"; private List<ITransactionTestProvider> transactionTestProviders = new List<ITransactionTestProvider>(); public TransactionTests() { ServiceLocatorInitializer.Init(typeof(SystemTransactionManager)); //transactionTestProviders.Add(new SharpArchContrib.PostSharp.NHibernate.SystemTransactionTestProvider()); //transactionTestProviders.Add(new SharpArchContrib.PostSharp.NHibernate.SystemUnitOfWorkTestProvider()); this.transactionTestProviders.Add( ServiceLocator.Current.GetInstance<ITransactionTestProvider>("SystemTransactionTestProvider")); this.transactionTestProviders.Add( ServiceLocator.Current.GetInstance<ITransactionTestProvider>("SystemUnitOfWorkTestProvider")); ServiceLocatorInitializer.Init(typeof(NHibernateTransactionManager)); //transactionTestProviders.Add(new SharpArchContrib.PostSharp.NHibernate.NHibernateTransactionTestProvider()); //transactionTestProviders.Add(new SharpArchContrib.PostSharp.NHibernate.NHibernateUnitOfWorkTestProvider()); this.transactionTestProviders.Add( ServiceLocator.Current.GetInstance<ITransactionTestProvider>("NHibernateTransactionTestProvider")); this.transactionTestProviders.Add( ServiceLocator.Current.GetInstance<ITransactionTestProvider>("NHibernateUnitOfWorkTestProvider")); } [Test] public void MultipleOperations() { this.PerformTest("MultipleOperations", testProvider => this.PerformMultipleOperations(testProvider)); } [Test] public void MultipleOperationsRollbackFirst() { this.PerformTest( "MultipleOperationsRollbackFirst", testProvider => this.PerformMultipleOperationsRollbackFirst(testProvider)); } [Test] public void MultipleOperationsRollbackLast() { this.PerformTest( "MultipleOperationsRollbackLast", testProvider => this.PerformMultipleOperationsRollbackLast(testProvider)); } [Test] public void NestedCommit() { this.PerformTest("NestedCommit", testProvider => this.PerformNestedCommit(testProvider)); } [Test] public void NestedForceRollback() { this.PerformTest("NestedForceRollback", testProvider => this.PerformNestedForceRollback(testProvider)); } [Test] public void NestedInnerForceRollback() { this.PerformTest( "NestedInnerForceRollback", testProvider => this.PerformNestedInnerForceRollback(testProvider)); } public void PerformTest(string testName, Func<ITransactionTestProvider, bool> function) { var logger = LogManager.GetLogger(this.GetType()); logger.Debug(string.Format("Starting test {0}", testName)); try { foreach (var transactionTestProvider in this.transactionTestProviders) { this.SetUp(); try { logger.Debug(string.Format("Transaction Provider: {0}", transactionTestProvider.Name)); try { function(transactionTestProvider); } catch (Exception err) { logger.Debug(err); throw; } finally { logger.Debug( string.Format( "*** Completed Work With Transaction Provider: {0}", transactionTestProvider.Name)); } } finally { this.TearDown(); } } } finally { logger.Debug(string.Format("*** Completed test {0}", testName)); } } [Test] public void Rollback() { this.PerformTest("Rollback", testProvider => this.PerformRollback(testProvider)); } [Test] public void RollsbackOnException() { this.PerformTest("RollsbackOnException", testProvider => this.PerformRollsbackOnException(testProvider)); } [Test] public void RollsbackOnExceptionWithSilentException() { this.PerformTest( "RollsbackOnExceptionWithSilentException", testProvider => this.PerformRollsbackOnExceptionWithSilentException(testProvider)); } [Test] public void SingleOperation() { this.PerformTest("SingleOperation", testProvider => this.PerformSingleOperation(testProvider)); } protected override void InitializeData() { base.InitializeData(); this.transactionTestProviders = this.GenerateTransactionManagers(); } private List<ITransactionTestProvider> GenerateTransactionManagers() { foreach (var transactionTestProvider in this.transactionTestProviders) { transactionTestProvider.TestEntityRepository = this.testEntityRepository; } return this.transactionTestProviders; } // Tests call Setup and TearDown manually for each iteration of the loop since // we want a clean database for each iteration. We could use the parameterized // test feature of Nunit 2.5 but, unfortunately that doesn't work with all test runners (e.g. Resharper) private bool PerformMultipleOperations(ITransactionTestProvider transactionTestProvider) { transactionTestProvider.InitTransactionManager(); transactionTestProvider.DoCommit(TestEntityName); transactionTestProvider.CheckNumberOfEntities(1); transactionTestProvider.DoCommit(TestEntityName + "1"); transactionTestProvider.CheckNumberOfEntities(2); return true; } private bool PerformMultipleOperationsRollbackFirst(ITransactionTestProvider transactionTestProvider) { transactionTestProvider.InitTransactionManager(); transactionTestProvider.DoRollback(); transactionTestProvider.CheckNumberOfEntities(0); transactionTestProvider.DoCommit(TestEntityName); transactionTestProvider.CheckNumberOfEntities(1); return true; } private bool PerformMultipleOperationsRollbackLast(ITransactionTestProvider transactionTestProvider) { transactionTestProvider.InitTransactionManager(); transactionTestProvider.DoCommit(TestEntityName + "1"); transactionTestProvider.CheckNumberOfEntities(1); transactionTestProvider.DoRollback(); transactionTestProvider.CheckNumberOfEntities(1); return true; } private bool PerformNestedCommit(ITransactionTestProvider transactionTestProvider) { transactionTestProvider.InitTransactionManager(); transactionTestProvider.DoNestedCommit(); transactionTestProvider.CheckNumberOfEntities(2); return true; } private bool PerformNestedForceRollback(ITransactionTestProvider transactionTestProvider) { transactionTestProvider.InitTransactionManager(); transactionTestProvider.DoNestedForceRollback(); transactionTestProvider.CheckNumberOfEntities(0); return true; } private bool PerformNestedInnerForceRollback(ITransactionTestProvider transactionTestProvider) { transactionTestProvider.InitTransactionManager(); transactionTestProvider.DoNestedInnerForceRollback(); transactionTestProvider.CheckNumberOfEntities(0); return true; } private bool PerformRollback(ITransactionTestProvider transactionTestProvider) { transactionTestProvider.InitTransactionManager(); transactionTestProvider.DoRollback(); transactionTestProvider.CheckNumberOfEntities(0); return true; } private bool PerformRollsbackOnException(ITransactionTestProvider transactionTestProvider) { transactionTestProvider.InitTransactionManager(); transactionTestProvider.DoCommit(TestEntityName); transactionTestProvider.CheckNumberOfEntities(1); Assert.Throws<GenericADOException>(() => transactionTestProvider.DoCommit(TestEntityName)); transactionTestProvider.CheckNumberOfEntities(1); return true; } private bool PerformRollsbackOnExceptionWithSilentException(ITransactionTestProvider transactionTestProvider) { transactionTestProvider.InitTransactionManager(); transactionTestProvider.DoCommit(TestEntityName); transactionTestProvider.CheckNumberOfEntities(1); transactionTestProvider.DoCommitSilenceException(TestEntityName); transactionTestProvider.CheckNumberOfEntities(1); return true; } private bool PerformSingleOperation(ITransactionTestProvider transactionTestProvider) { transactionTestProvider.InitTransactionManager(); transactionTestProvider.DoCommit(TestEntityName); transactionTestProvider.CheckNumberOfEntities(1); return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Microsoft.Security", "CA2112:SecuredTypesShouldNotExposeFields", Scope = "type", Target = "System.ComponentModel.EventDescriptorCollection")] namespace System.ComponentModel { /// <summary> /// Represents a collection of events. /// </summary> public class EventDescriptorCollection : ICollection, IList { private EventDescriptor[] _events; private readonly string[] _namedSort; private readonly IComparer _comparer; private bool _eventsOwned; private bool _needSort; private readonly bool _readOnly; /// <summary> /// An empty AttributeCollection that can used instead of creating a new one with no items. /// </summary> public static readonly EventDescriptorCollection Empty = new EventDescriptorCollection(null, true); /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.EventDescriptorCollection'/> class. /// </summary> public EventDescriptorCollection(EventDescriptor[] events) { if (events == null) { _events = Array.Empty<EventDescriptor>(); } else { _events = events; Count = events.Length; } _eventsOwned = true; } /// <summary> /// Initializes a new instance of an event descriptor collection, and allows you to mark the /// collection as read-only so it cannot be modified. /// </summary> public EventDescriptorCollection(EventDescriptor[] events, bool readOnly) : this(events) { _readOnly = readOnly; } private EventDescriptorCollection(EventDescriptor[] events, int eventCount, string[] namedSort, IComparer comparer) { _eventsOwned = false; if (namedSort != null) { _namedSort = (string[])namedSort.Clone(); } _comparer = comparer; _events = events; Count = eventCount; _needSort = true; } /// <summary> /// Gets the number of event descriptors in the collection. /// </summary> public int Count { get; private set; } /// <summary> /// Gets the event with the specified index number. /// </summary> public virtual EventDescriptor this[int index] { get { if (index >= Count) { throw new IndexOutOfRangeException(); } EnsureEventsOwned(); return _events[index]; } } /// <summary> /// Gets the event with the specified name. /// </summary> public virtual EventDescriptor this[string name] => Find(name, false); public int Add(EventDescriptor value) { if (_readOnly) { throw new NotSupportedException(); } EnsureSize(Count + 1); _events[Count++] = value; return Count - 1; } public void Clear() { if (_readOnly) { throw new NotSupportedException(); } Count = 0; } public bool Contains(EventDescriptor value) => IndexOf(value) >= 0; void ICollection.CopyTo(Array array, int index) { EnsureEventsOwned(); Array.Copy(_events, 0, array, index, Count); } private void EnsureEventsOwned() { if (!_eventsOwned) { _eventsOwned = true; if (_events != null) { EventDescriptor[] newEvents = new EventDescriptor[Count]; Array.Copy(_events, 0, newEvents, 0, Count); _events = newEvents; } } if (_needSort) { _needSort = false; InternalSort(_namedSort); } } private void EnsureSize(int sizeNeeded) { if (sizeNeeded <= _events.Length) { return; } if (_events.Length == 0) { Count = 0; _events = new EventDescriptor[sizeNeeded]; return; } EnsureEventsOwned(); int newSize = Math.Max(sizeNeeded, _events.Length * 2); EventDescriptor[] newEvents = new EventDescriptor[newSize]; Array.Copy(_events, 0, newEvents, 0, Count); _events = newEvents; } /// <summary> /// Gets the description of the event with the specified /// name in the collection. /// </summary> public virtual EventDescriptor Find(string name, bool ignoreCase) { EventDescriptor p = null; if (ignoreCase) { for (int i = 0; i < Count; i++) { if (string.Equals(_events[i].Name, name, StringComparison.OrdinalIgnoreCase)) { p = _events[i]; break; } } } else { for (int i = 0; i < Count; i++) { if (string.Equals(_events[i].Name, name, StringComparison.Ordinal)) { p = _events[i]; break; } } } return p; } public int IndexOf(EventDescriptor value) => Array.IndexOf(_events, value, 0, Count); public void Insert(int index, EventDescriptor value) { if (_readOnly) { throw new NotSupportedException(); } EnsureSize(Count + 1); if (index < Count) { Array.Copy(_events, index, _events, index + 1, Count - index); } _events[index] = value; Count++; } public void Remove(EventDescriptor value) { if (_readOnly) { throw new NotSupportedException(); } int index = IndexOf(value); if (index != -1) { RemoveAt(index); } } public void RemoveAt(int index) { if (_readOnly) { throw new NotSupportedException(); } if (index < Count - 1) { Array.Copy(_events, index + 1, _events, index, Count - index - 1); } _events[Count - 1] = null; Count--; } /// <summary> /// Gets an enumerator for this <see cref='System.ComponentModel.EventDescriptorCollection'/>. /// </summary> public IEnumerator GetEnumerator() { // We can only return an enumerator on the events we actually have. if (_events.Length == Count) { return _events.GetEnumerator(); } else { return new ArraySubsetEnumerator(_events, Count); } } /// <summary> /// Sorts the members of this EventDescriptorCollection, using the default sort for this collection, /// which is usually alphabetical. /// </summary> public virtual EventDescriptorCollection Sort() { return new EventDescriptorCollection(_events, Count, _namedSort, _comparer); } /// <summary> /// Sorts the members of this EventDescriptorCollection. Any specified NamedSort arguments will /// be applied first, followed by sort using the specified IComparer. /// </summary> public virtual EventDescriptorCollection Sort(string[] names) { return new EventDescriptorCollection(_events, Count, names, _comparer); } /// <summary> /// Sorts the members of this EventDescriptorCollection. Any specified NamedSort arguments will /// be applied first, followed by sort using the specified IComparer. /// </summary> public virtual EventDescriptorCollection Sort(string[] names, IComparer comparer) { return new EventDescriptorCollection(_events, Count, names, comparer); } /// <summary> /// Sorts the members of this EventDescriptorCollection, using the specified IComparer to compare, /// the EventDescriptors contained in the collection. /// </summary> public virtual EventDescriptorCollection Sort(IComparer comparer) { return new EventDescriptorCollection(_events, Count, _namedSort, comparer); } /// <summary> /// Sorts the members of this EventDescriptorCollection. Any specified NamedSort arguments will /// be applied first, followed by sort using the specified IComparer. /// </summary> protected void InternalSort(string[] names) { if (_events.Length == 0) { return; } InternalSort(_comparer); if (names != null && names.Length > 0) { List<EventDescriptor> eventList = new List<EventDescriptor>(_events); int foundCount = 0; int eventCount = _events.Length; for (int i = 0; i < names.Length; i++) { for (int j = 0; j < eventCount; j++) { EventDescriptor currentEvent = eventList[j]; // Found a matching event. Here, we add it to our array. We also // mark it as null in our array list so we don't add it twice later. // if (currentEvent != null && currentEvent.Name.Equals(names[i])) { _events[foundCount++] = currentEvent; eventList[j] = null; break; } } } // At this point we have filled in the first "foundCount" number of propeties, one for each // name in our name array. If a name didn't match, then it is ignored. Next, we must fill // in the rest of the properties. We now have a sparse array containing the remainder, so // it's easy. // for (int i = 0; i < eventCount; i++) { if (eventList[i] != null) { _events[foundCount++] = eventList[i]; } } Debug.Assert(foundCount == eventCount, "We did not completely fill our event array"); } } /// <summary> /// Sorts the members of this EventDescriptorCollection using the specified IComparer. /// </summary> protected void InternalSort(IComparer sorter) { if (sorter == null) { TypeDescriptor.SortDescriptorArray(this); } else { Array.Sort(_events, sorter); } } bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => null; int ICollection.Count => Count; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); object IList.this[int index] { get => this[index]; set { if (_readOnly) { throw new NotSupportedException(); } if (index >= Count) { throw new IndexOutOfRangeException(); } EnsureEventsOwned(); _events[index] = (EventDescriptor)value; } } int IList.Add(object value) => Add((EventDescriptor)value); bool IList.Contains(object value) => Contains((EventDescriptor)value); void IList.Clear() => Clear(); int IList.IndexOf(object value) => IndexOf((EventDescriptor)value); void IList.Insert(int index, object value) => Insert(index, (EventDescriptor)value); void IList.Remove(object value) => Remove((EventDescriptor)value); void IList.RemoveAt(int index) => RemoveAt(index); bool IList.IsReadOnly => _readOnly; bool IList.IsFixedSize => _readOnly; private class ArraySubsetEnumerator : IEnumerator { private readonly Array _array; private readonly int _total; private int _current; public ArraySubsetEnumerator(Array array, int count) { Debug.Assert(count == 0 || array != null, "if array is null, count should be 0"); Debug.Assert(array == null || count <= array.Length, "Trying to enumerate more than the array contains"); _array = array; _total = count; _current = -1; } public bool MoveNext() { if (_current < _total - 1) { _current++; return true; } else { return false; } } public void Reset() => _current = -1; public object Current { get { if (_current == -1) { throw new InvalidOperationException(); } else { return _array.GetValue(_current); } } } } } }
// Copyright (c) 1995-2009 held by the author(s). All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1998 { /// <summary> /// Section 5.2.5.5. Repair is complete. COMPLETE /// </summary> [Serializable] [XmlRoot] [XmlInclude(typeof(EntityID))] public partial class RepairCompletePdu : LogisticsFamilyPdu, IEquatable<RepairCompletePdu> { /// <summary> /// Entity that is receiving service /// </summary> private EntityID _receivingEntityID = new EntityID(); /// <summary> /// Entity that is supplying /// </summary> private EntityID _repairingEntityID = new EntityID(); /// <summary> /// Enumeration for type of repair /// </summary> private ushort _repair; /// <summary> /// padding, number prevents conflict with superclass ivar name /// </summary> private short _padding2; /// <summary> /// Initializes a new instance of the <see cref="RepairCompletePdu"/> class. /// </summary> public RepairCompletePdu() { PduType = (byte)9; } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(RepairCompletePdu left, RepairCompletePdu right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(RepairCompletePdu left, RepairCompletePdu right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public override int GetMarshalledSize() { int marshalSize = 0; marshalSize = base.GetMarshalledSize(); marshalSize += this._receivingEntityID.GetMarshalledSize(); // this._receivingEntityID marshalSize += this._repairingEntityID.GetMarshalledSize(); // this._repairingEntityID marshalSize += 2; // this._repair marshalSize += 2; // this._padding2 return marshalSize; } /// <summary> /// Gets or sets the Entity that is receiving service /// </summary> [XmlElement(Type = typeof(EntityID), ElementName = "receivingEntityID")] public EntityID ReceivingEntityID { get { return this._receivingEntityID; } set { this._receivingEntityID = value; } } /// <summary> /// Gets or sets the Entity that is supplying /// </summary> [XmlElement(Type = typeof(EntityID), ElementName = "repairingEntityID")] public EntityID RepairingEntityID { get { return this._repairingEntityID; } set { this._repairingEntityID = value; } } /// <summary> /// Gets or sets the Enumeration for type of repair /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "repair")] public ushort Repair { get { return this._repair; } set { this._repair = value; } } /// <summary> /// Gets or sets the padding, number prevents conflict with superclass ivar name /// </summary> [XmlElement(Type = typeof(short), ElementName = "padding2")] public short Padding2 { get { return this._padding2; } set { this._padding2 = value; } } /// <summary> /// Automatically sets the length of the marshalled data, then calls the marshal method. /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> public override void MarshalAutoLengthSet(DataOutputStream dos) { // Set the length prior to marshalling data this.Length = (ushort)this.GetMarshalledSize(); this.Marshal(dos); } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Marshal(DataOutputStream dos) { base.Marshal(dos); if (dos != null) { try { this._receivingEntityID.Marshal(dos); this._repairingEntityID.Marshal(dos); dos.WriteUnsignedShort((ushort)this._repair); dos.WriteShort((short)this._padding2); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Unmarshal(DataInputStream dis) { base.Unmarshal(dis); if (dis != null) { try { this._receivingEntityID.Unmarshal(dis); this._repairingEntityID.Unmarshal(dis); this._repair = dis.ReadUnsignedShort(); this._padding2 = dis.ReadShort(); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Reflection(StringBuilder sb) { sb.AppendLine("<RepairCompletePdu>"); base.Reflection(sb); try { sb.AppendLine("<receivingEntityID>"); this._receivingEntityID.Reflection(sb); sb.AppendLine("</receivingEntityID>"); sb.AppendLine("<repairingEntityID>"); this._repairingEntityID.Reflection(sb); sb.AppendLine("</repairingEntityID>"); sb.AppendLine("<repair type=\"ushort\">" + this._repair.ToString(CultureInfo.InvariantCulture) + "</repair>"); sb.AppendLine("<padding2 type=\"short\">" + this._padding2.ToString(CultureInfo.InvariantCulture) + "</padding2>"); sb.AppendLine("</RepairCompletePdu>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as RepairCompletePdu; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(RepairCompletePdu obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } ivarsEqual = base.Equals(obj); if (!this._receivingEntityID.Equals(obj._receivingEntityID)) { ivarsEqual = false; } if (!this._repairingEntityID.Equals(obj._repairingEntityID)) { ivarsEqual = false; } if (this._repair != obj._repair) { ivarsEqual = false; } if (this._padding2 != obj._padding2) { ivarsEqual = false; } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ base.GetHashCode(); result = GenerateHash(result) ^ this._receivingEntityID.GetHashCode(); result = GenerateHash(result) ^ this._repairingEntityID.GetHashCode(); result = GenerateHash(result) ^ this._repair.GetHashCode(); result = GenerateHash(result) ^ this._padding2.GetHashCode(); return result; } } }
// This file is part of the OWASP O2 Platform (http://www.owasp.org/index.php/OWASP_O2_Platform) and is released under the Apache 2.0 License (http://www.apache.org/licenses/LICENSE-2.0) using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Xml.Serialization; namespace FluentSharp.CoreLib.API { public class KO2Config // : IO2Config { public static string defaultLocalScriptFolder = ""; public int MAX_LOCALSCRIPTFOLDER_PARENTPATHSIZE = 120; public string defaultO2LocalTempFolder = @""; public string hardCodedO2LocalTempFolder { get; set; } public string AutoSavedScripts { get; set; } public string LocalScriptsFolder { get; set; } public string LocallyDevelopedScriptsFolder { get; set; } public string ScriptsTemplatesFolder { get; set; } public string O2GitHub_ExternalDlls { get; set; } public string O2GitHub_Binaries { get; set; } public string O2GitHub_FilesWithNoCode { get; set; } public string O2DownloadLocation { get; set; } public string UserData { get; set; } public string ReferencesDownloadLocation { get; set; } public string EmbeddedAssemblies { get; set; } public string O2FindingsFileExtension { get; set; } //public static string dependencyInjectionTest { get; set; } public KO2Config() { Calculate_O2TempDir(); MapFolders_And_Set_DefaultValues(); } public KO2Config MapFolders_And_Set_DefaultValues(string newRootFolderForAllO2Temp) { defaultO2LocalTempFolder = newRootFolderForAllO2Temp; defaultLocalScriptFolder = defaultO2LocalTempFolder.pathCombine(O2ConfigSettings.defaultLocalScriptName); return MapFolders_And_Set_DefaultValues(); } public KO2Config MapFolders_And_Set_DefaultValues() { try { hardCodedO2LocalTempFolder = defaultO2LocalTempFolder.pathCombine(DateTime.Now.ToShortDateString().Replace("/", "_")); var o2TempDir = hardCodedO2LocalTempFolder; // so that we don't trigger the auto creation of the tempDir ReferencesDownloadLocation = o2TempDir.pathCombine(@"../_ReferencesDownloaded"); EmbeddedAssemblies = o2TempDir.pathCombine(@"../_EmbeddedAssemblies"); LocallyDevelopedScriptsFolder = o2TempDir.pathCombine(@"../_Scripts_Local"); UserData = o2TempDir.pathCombine(@"../_USERDATA"); O2FindingsFileExtension = ".O2Findings"; setLocalScriptsFolder(defaultLocalScriptFolder); ScriptsTemplatesFolder = defaultLocalScriptFolder + @"\_Templates"; O2GitHub_ExternalDlls = O2ConfigSettings.defaultO2GitHub_ExternalDlls; O2GitHub_Binaries = O2ConfigSettings.defaultO2GitHub_Binaries; O2GitHub_FilesWithNoCode = O2ConfigSettings.defaultO2GitHub_FilesWithNoCode; AutoSavedScripts = o2TempDir.pathCombine(@"../_AutoSavedScripts") .pathCombine(DateTime.Now.ToShortDateString().Replace("/", "_")); // can't used safeFileName() here because the DI object is not created AssemblyResolver.Init(); } catch (Exception ex) { ex.logWithStackTrace("[KO2Config][MapFolders_And_Set_DefaultValues] usually from KO2Config.ctor"); ex.logWithStackTrace("[KO2Config][Calculate_O2TempDir]"); } return this; } public KO2Config Calculate_O2TempDir() { try { defaultO2LocalTempFolder = O2ConfigSettings.defaultO2LocalTempName; defaultLocalScriptFolder = O2ConfigSettings.defaultLocalScriptName; //if we are running from an installed version if (CurrentExecutableDirectory.contains(new string[] { "Program Files (x86)", "Program Files" })) // need a better way to identify an install scenario if (CurrentExecutableDirectory.contains(@"OWASP\OWASP O2 Platform")) { defaultO2LocalTempFolder = getValidLocalSystemTempFolder().path_Combine(defaultO2LocalTempFolder); defaultLocalScriptFolder = getValidLocalSystemTempFolder().path_Combine(defaultLocalScriptFolder); return this; } // Use locally folder (happens when the main zip is downloaded directly defaultO2LocalTempFolder = CurrentExecutableDirectory.pathCombine(defaultO2LocalTempFolder); defaultLocalScriptFolder = CurrentExecutableDirectory.pathCombine(defaultLocalScriptFolder); if (O2ConfigSettings.CheckForTempDirMaxSizeCheck) if (defaultLocalScriptFolder.size() > MAX_LOCALSCRIPTFOLDER_PARENTPATHSIZE) { "[o2setup] defaultLocalScriptFolder path was more than 120 chars: {0}".debug(defaultLocalScriptFolder); var applicationData = getValidLocalSystemTempFolder(); var baseTempFolder = applicationData.pathCombine("O2_" + O2ConfigSettings.O2Version); "[o2setup] using as baseTempFolder: {0}".debug(baseTempFolder); defaultLocalScriptFolder = baseTempFolder.pathCombine(O2ConfigSettings.defaultLocalScriptName); defaultO2LocalTempFolder = baseTempFolder.pathCombine(O2ConfigSettings.defaultO2LocalTempName); //"[o2setup] set LocalScriptsFolder to: {0}".debug(defaultLocalScriptFolder); } } catch(Exception ex) { ex.logWithStackTrace("[KO2Config][Calculate_O2TempDir]"); } return this; } public string getValidLocalSystemTempFolder() { var folder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); if (folder.dirExists()) return folder; folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); if (folder.dirExists()) return folder; folder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); if (folder.dirExists()) return folder; "in getValidLocalSystemTempFolder could not find a valid folder".error(); return null; } public string O2TempDir { get { if (hardCodedO2LocalTempFolder == null) return null; O2Kernel_Files.checkIfDirectoryExistsAndCreateIfNot(hardCodedO2LocalTempFolder); return hardCodedO2LocalTempFolder; } set { hardCodedO2LocalTempFolder = value; } } public string ToolsOrApis { get { return O2TempDir.pathCombine("..//_ToolsOrApis"); } } public string EmbededLibrariesFolder { get { return defaultO2LocalTempFolder.pathCombine(@"_EmbeddedAssemblies"); } } public string Version { get { return Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } public void setLocalScriptsFolder(string newLocalScriptsFolder) { LocalScriptsFolder = newLocalScriptsFolder; } public string CurrentExecutableDirectory { get { try { var entryAssembly = Assembly.GetEntryAssembly(); if (entryAssembly.isNull() || entryAssembly.GetName().Name.contains("FluentSharp").isFalse()) // if the main Assembly is not called O2 (for example under VisualStudio), then use the location of this assembly (FluentSharp.WinForms) entryAssembly = Assembly.GetExecutingAssembly(); return Path.GetDirectoryName(entryAssembly.Location); } catch (Exception ex) { ex.log(); } return AppDomain.CurrentDomain.BaseDirectory; } } public String CurrentExecutableFileName { get { return Path.GetFileName(Process.GetCurrentProcess().ProcessName); } } public string ExecutingAssembly { get { return Assembly.GetExecutingAssembly().Location; } } public string TempFileNameInTempDirectory { get { return O2TempDir.pathCombine(O2Kernel_Files.getTempFileName()); } } public string TempFolderInTempDirectory { get { string tempFolder = O2TempDir.pathCombine(O2Kernel_Files.getTempFolderName()); Directory.CreateDirectory(tempFolder); return tempFolder; } } public string getTempFileInTempDirectory(string extension) { return TempFileNameInTempDirectory + (extension.StartsWith(".") ? extension : ("." + extension)); } public string getTempFolderInTempDirectory(string stringToAddToTempDirectoryName) { var tempFolder = TempFolderInTempDirectory; var tempFolderWithExtraString = Path.GetDirectoryName(tempFolder).pathCombine(stringToAddToTempDirectoryName + "_" + Path.GetFileName(tempFolder)); Directory.CreateDirectory(tempFolderWithExtraString); Directory.Delete(tempFolder); return tempFolderWithExtraString; } public void addPathToCurrentExecutableEnvironmentPathVariable(String sPathToAdd) { string sCurrentEnvironmentPath = Environment.GetEnvironmentVariable("Path"); if (sCurrentEnvironmentPath != null && sCurrentEnvironmentPath.index(sPathToAdd) == -1) { String sUpdatedPathValue = String.Format("{0};{1}", sCurrentEnvironmentPath, sPathToAdd); Environment.SetEnvironmentVariable("Path", sUpdatedPathValue); } } public void closeO2Process() { PublicDI.log.info("Received request to close down current O2 Process"); O2Kernel_Processes.KillCurrentO2Process(2000); // wait 2 seconds before killing the process //System.Windows.Forms.Application.Exit(); } } [Serializable] public class Setting { public string Name { get; set; } public string Value { get; set; } } [Serializable] public class DependencyInjection { [XmlAttribute] public string Type { get; set; } [XmlAttribute] public string Parameter { get; set; } [XmlAttribute] public string Value { get; set; } } }
// // Copyright (C) Microsoft. All rights reserved. // using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; using System.Collections.Generic; using System.ComponentModel; namespace Microsoft.PowerShell.Management.Activities { /// <summary> /// Activity to invoke the Microsoft.PowerShell.Management\Test-Connection command in a Workflow. /// </summary> [System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")] public sealed class TestConnection : PSRemotingActivity { /// <summary> /// Gets the display name of the command invoked by this activity. /// </summary> public TestConnection() { this.DisplayName = "Test-Connection"; } /// <summary> /// Gets the fully qualified name of the command invoked by this activity. /// </summary> public override string PSCommandName { get { return "Microsoft.PowerShell.Management\\Test-Connection"; } } // Arguments /// <summary> /// Provides access to the AsJob parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> AsJob { get; set; } /// <summary> /// Provides access to the DcomAuthentication parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.AuthenticationLevel> DcomAuthentication { get; set; } /// <summary> /// Provides access to the WsmanAuthentication parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> WsmanAuthentication { get; set; } /// <summary> /// Provides access to the Protocol parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> Protocol { get; set; } /// <summary> /// Provides access to the BufferSize parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Int32> BufferSize { get; set; } /// <summary> /// Provides access to the ComputerName parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> ComputerName { get; set; } /// <summary> /// Provides access to the Count parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Int32> Count { get; set; } /// <summary> /// Provides access to the Credential parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.PSCredential> Credential { get; set; } /// <summary> /// Provides access to the Source parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> Source { get; set; } /// <summary> /// Provides access to the Impersonation parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.ImpersonationLevel> Impersonation { get; set; } /// <summary> /// Provides access to the ThrottleLimit parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Int32> ThrottleLimit { get; set; } /// <summary> /// Provides access to the TimeToLive parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Int32> TimeToLive { get; set; } /// <summary> /// Provides access to the Delay parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Int32> Delay { get; set; } /// <summary> /// Provides access to the Quiet parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> Quiet { get; set; } // Module defining this command // Optional custom code for this activity /// <summary> /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. /// </summary> /// <param name="context">The NativeActivityContext for the currently running activity.</param> /// <returns>A populated instance of System.Management.Automation.PowerShell</returns> /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks> protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context) { System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create(); System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments if(AsJob.Expression != null) { targetCommand.AddParameter("AsJob", AsJob.Get(context)); } if(DcomAuthentication.Expression != null) { targetCommand.AddParameter("DcomAuthentication", DcomAuthentication.Get(context)); } if(WsmanAuthentication.Expression != null) { targetCommand.AddParameter("WsmanAuthentication", WsmanAuthentication.Get(context)); } if(Protocol.Expression != null) { targetCommand.AddParameter("Protocol", Protocol.Get(context)); } if(BufferSize.Expression != null) { targetCommand.AddParameter("BufferSize", BufferSize.Get(context)); } if(ComputerName.Expression != null) { targetCommand.AddParameter("ComputerName", ComputerName.Get(context)); } if(Count.Expression != null) { targetCommand.AddParameter("Count", Count.Get(context)); } if(Credential.Expression != null) { targetCommand.AddParameter("Credential", Credential.Get(context)); } if(Source.Expression != null) { targetCommand.AddParameter("Source", Source.Get(context)); } if(Impersonation.Expression != null) { targetCommand.AddParameter("Impersonation", Impersonation.Get(context)); } if(ThrottleLimit.Expression != null) { targetCommand.AddParameter("ThrottleLimit", ThrottleLimit.Get(context)); } if(TimeToLive.Expression != null) { targetCommand.AddParameter("TimeToLive", TimeToLive.Get(context)); } if(Delay.Expression != null) { targetCommand.AddParameter("Delay", Delay.Get(context)); } if(Quiet.Expression != null) { targetCommand.AddParameter("Quiet", Quiet.Get(context)); } return new ActivityImplementationContext() { PowerShellInstance = invoker }; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Sql { /// <summary> /// Represents all the operations to manage Azure SQL Database and Database /// Server Audit policy. Contains operations to: Create, Retrieve and /// Update audit policy. /// </summary> internal partial class AuditingPolicyOperations : IServiceOperations<SqlManagementClient>, IAuditingPolicyOperations { /// <summary> /// Initializes a new instance of the AuditingPolicyOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal AuditingPolicyOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Sql.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Creates or updates an Azure SQL Database auditing policy. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the auditing /// policy applies. /// </param> /// <param name='parameters'> /// Required. The required parameters for createing or updating a Azure /// SQL Database auditing policy. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> CreateOrUpdateDatebasePolicyAsync(string resourceGroupName, string serverName, string databaseName, DatabaseAuditingPolicyCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateDatebasePolicyAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/databases/"; url = url + Uri.EscapeDataString(databaseName); url = url + "/auditingPolicies/Default"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject databaseAuditingPolicyCreateOrUpdateParametersValue = new JObject(); requestDoc = databaseAuditingPolicyCreateOrUpdateParametersValue; JObject propertiesValue = new JObject(); databaseAuditingPolicyCreateOrUpdateParametersValue["properties"] = propertiesValue; if (parameters.Properties.AuditingState != null) { propertiesValue["auditingState"] = parameters.Properties.AuditingState; } if (parameters.Properties.EventTypesToAudit != null) { propertiesValue["eventTypesToAudit"] = parameters.Properties.EventTypesToAudit; } if (parameters.Properties.StorageAccountName != null) { propertiesValue["storageAccountName"] = parameters.Properties.StorageAccountName; } if (parameters.Properties.StorageAccountKey != null) { propertiesValue["storageAccountKey"] = parameters.Properties.StorageAccountKey; } if (parameters.Properties.StorageAccountSecondaryKey != null) { propertiesValue["storageAccountSecondaryKey"] = parameters.Properties.StorageAccountSecondaryKey; } if (parameters.Properties.StorageTableEndpoint != null) { propertiesValue["storageTableEndpoint"] = parameters.Properties.StorageTableEndpoint; } if (parameters.Properties.StorageAccountResourceGroupName != null) { propertiesValue["storageAccountResourceGroupName"] = parameters.Properties.StorageAccountResourceGroupName; } if (parameters.Properties.StorageAccountSubscriptionId != null) { propertiesValue["storageAccountSubscriptionId"] = parameters.Properties.StorageAccountSubscriptionId; } if (parameters.Properties.RetentionDays != null) { propertiesValue["retentionDays"] = parameters.Properties.RetentionDays; } if (parameters.Properties.UseServerDefault != null) { propertiesValue["useServerDefault"] = parameters.Properties.UseServerDefault; } if (parameters.Properties.AuditLogsTableName != null) { propertiesValue["auditLogsTableName"] = parameters.Properties.AuditLogsTableName; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Creates or updates an Azure SQL Database Server auditing policy. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='parameters'> /// Required. The required parameters for createing or updating a Azure /// SQL Database Server auditing policy. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> CreateOrUpdateServerPolicyAsync(string resourceGroupName, string serverName, ServerAuditingPolicyCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateServerPolicyAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/auditingPolicies/Default"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject serverAuditingPolicyCreateOrUpdateParametersValue = new JObject(); requestDoc = serverAuditingPolicyCreateOrUpdateParametersValue; JObject propertiesValue = new JObject(); serverAuditingPolicyCreateOrUpdateParametersValue["properties"] = propertiesValue; if (parameters.Properties.AuditingState != null) { propertiesValue["auditingState"] = parameters.Properties.AuditingState; } if (parameters.Properties.EventTypesToAudit != null) { propertiesValue["eventTypesToAudit"] = parameters.Properties.EventTypesToAudit; } if (parameters.Properties.StorageAccountName != null) { propertiesValue["storageAccountName"] = parameters.Properties.StorageAccountName; } if (parameters.Properties.StorageAccountKey != null) { propertiesValue["storageAccountKey"] = parameters.Properties.StorageAccountKey; } if (parameters.Properties.StorageAccountSecondaryKey != null) { propertiesValue["storageAccountSecondaryKey"] = parameters.Properties.StorageAccountSecondaryKey; } if (parameters.Properties.StorageTableEndpoint != null) { propertiesValue["storageTableEndpoint"] = parameters.Properties.StorageTableEndpoint; } if (parameters.Properties.StorageAccountResourceGroupName != null) { propertiesValue["storageAccountResourceGroupName"] = parameters.Properties.StorageAccountResourceGroupName; } if (parameters.Properties.StorageAccountSubscriptionId != null) { propertiesValue["storageAccountSubscriptionId"] = parameters.Properties.StorageAccountSubscriptionId; } if (parameters.Properties.RetentionDays != null) { propertiesValue["retentionDays"] = parameters.Properties.RetentionDays; } if (parameters.Properties.AuditLogsTableName != null) { propertiesValue["auditLogsTableName"] = parameters.Properties.AuditLogsTableName; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Returns an Azure SQL Database auditing policy. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the auditing /// policy applies. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a get database auditing policy request. /// </returns> public async Task<DatabaseAuditingPolicyGetResponse> GetDatabasePolicyAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); TracingAdapter.Enter(invocationId, this, "GetDatabasePolicyAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/databases/"; url = url + Uri.EscapeDataString(databaseName); url = url + "/auditingPolicies/Default"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DatabaseAuditingPolicyGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DatabaseAuditingPolicyGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DatabaseAuditingPolicy auditingPolicyInstance = new DatabaseAuditingPolicy(); result.AuditingPolicy = auditingPolicyInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { DatabaseAuditingPolicyProperties propertiesInstance = new DatabaseAuditingPolicyProperties(); auditingPolicyInstance.Properties = propertiesInstance; JToken auditingStateValue = propertiesValue["auditingState"]; if (auditingStateValue != null && auditingStateValue.Type != JTokenType.Null) { string auditingStateInstance = ((string)auditingStateValue); propertiesInstance.AuditingState = auditingStateInstance; } JToken eventTypesToAuditValue = propertiesValue["eventTypesToAudit"]; if (eventTypesToAuditValue != null && eventTypesToAuditValue.Type != JTokenType.Null) { string eventTypesToAuditInstance = ((string)eventTypesToAuditValue); propertiesInstance.EventTypesToAudit = eventTypesToAuditInstance; } JToken storageAccountNameValue = propertiesValue["storageAccountName"]; if (storageAccountNameValue != null && storageAccountNameValue.Type != JTokenType.Null) { string storageAccountNameInstance = ((string)storageAccountNameValue); propertiesInstance.StorageAccountName = storageAccountNameInstance; } JToken storageAccountKeyValue = propertiesValue["storageAccountKey"]; if (storageAccountKeyValue != null && storageAccountKeyValue.Type != JTokenType.Null) { string storageAccountKeyInstance = ((string)storageAccountKeyValue); propertiesInstance.StorageAccountKey = storageAccountKeyInstance; } JToken storageAccountSecondaryKeyValue = propertiesValue["storageAccountSecondaryKey"]; if (storageAccountSecondaryKeyValue != null && storageAccountSecondaryKeyValue.Type != JTokenType.Null) { string storageAccountSecondaryKeyInstance = ((string)storageAccountSecondaryKeyValue); propertiesInstance.StorageAccountSecondaryKey = storageAccountSecondaryKeyInstance; } JToken storageTableEndpointValue = propertiesValue["storageTableEndpoint"]; if (storageTableEndpointValue != null && storageTableEndpointValue.Type != JTokenType.Null) { string storageTableEndpointInstance = ((string)storageTableEndpointValue); propertiesInstance.StorageTableEndpoint = storageTableEndpointInstance; } JToken storageAccountResourceGroupNameValue = propertiesValue["storageAccountResourceGroupName"]; if (storageAccountResourceGroupNameValue != null && storageAccountResourceGroupNameValue.Type != JTokenType.Null) { string storageAccountResourceGroupNameInstance = ((string)storageAccountResourceGroupNameValue); propertiesInstance.StorageAccountResourceGroupName = storageAccountResourceGroupNameInstance; } JToken storageAccountSubscriptionIdValue = propertiesValue["storageAccountSubscriptionId"]; if (storageAccountSubscriptionIdValue != null && storageAccountSubscriptionIdValue.Type != JTokenType.Null) { string storageAccountSubscriptionIdInstance = ((string)storageAccountSubscriptionIdValue); propertiesInstance.StorageAccountSubscriptionId = storageAccountSubscriptionIdInstance; } JToken retentionDaysValue = propertiesValue["retentionDays"]; if (retentionDaysValue != null && retentionDaysValue.Type != JTokenType.Null) { string retentionDaysInstance = ((string)retentionDaysValue); propertiesInstance.RetentionDays = retentionDaysInstance; } JToken useServerDefaultValue = propertiesValue["useServerDefault"]; if (useServerDefaultValue != null && useServerDefaultValue.Type != JTokenType.Null) { string useServerDefaultInstance = ((string)useServerDefaultValue); propertiesInstance.UseServerDefault = useServerDefaultInstance; } JToken auditLogsTableNameValue = propertiesValue["auditLogsTableName"]; if (auditLogsTableNameValue != null && auditLogsTableNameValue.Type != JTokenType.Null) { string auditLogsTableNameInstance = ((string)auditLogsTableNameValue); propertiesInstance.AuditLogsTableName = auditLogsTableNameInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); auditingPolicyInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); auditingPolicyInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); auditingPolicyInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); auditingPolicyInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); auditingPolicyInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Returns an Azure SQL Database server auditing policy. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a get database auditing policy request. /// </returns> public async Task<ServerAuditingPolicyGetResponse> GetServerPolicyAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); TracingAdapter.Enter(invocationId, this, "GetServerPolicyAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/auditingPolicies/Default"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerAuditingPolicyGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerAuditingPolicyGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ServerAuditingPolicy auditingPolicyInstance = new ServerAuditingPolicy(); result.AuditingPolicy = auditingPolicyInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ServerAuditingPolicyProperties propertiesInstance = new ServerAuditingPolicyProperties(); auditingPolicyInstance.Properties = propertiesInstance; JToken auditingStateValue = propertiesValue["auditingState"]; if (auditingStateValue != null && auditingStateValue.Type != JTokenType.Null) { string auditingStateInstance = ((string)auditingStateValue); propertiesInstance.AuditingState = auditingStateInstance; } JToken eventTypesToAuditValue = propertiesValue["eventTypesToAudit"]; if (eventTypesToAuditValue != null && eventTypesToAuditValue.Type != JTokenType.Null) { string eventTypesToAuditInstance = ((string)eventTypesToAuditValue); propertiesInstance.EventTypesToAudit = eventTypesToAuditInstance; } JToken storageAccountNameValue = propertiesValue["storageAccountName"]; if (storageAccountNameValue != null && storageAccountNameValue.Type != JTokenType.Null) { string storageAccountNameInstance = ((string)storageAccountNameValue); propertiesInstance.StorageAccountName = storageAccountNameInstance; } JToken storageAccountKeyValue = propertiesValue["storageAccountKey"]; if (storageAccountKeyValue != null && storageAccountKeyValue.Type != JTokenType.Null) { string storageAccountKeyInstance = ((string)storageAccountKeyValue); propertiesInstance.StorageAccountKey = storageAccountKeyInstance; } JToken storageAccountSecondaryKeyValue = propertiesValue["storageAccountSecondaryKey"]; if (storageAccountSecondaryKeyValue != null && storageAccountSecondaryKeyValue.Type != JTokenType.Null) { string storageAccountSecondaryKeyInstance = ((string)storageAccountSecondaryKeyValue); propertiesInstance.StorageAccountSecondaryKey = storageAccountSecondaryKeyInstance; } JToken storageTableEndpointValue = propertiesValue["storageTableEndpoint"]; if (storageTableEndpointValue != null && storageTableEndpointValue.Type != JTokenType.Null) { string storageTableEndpointInstance = ((string)storageTableEndpointValue); propertiesInstance.StorageTableEndpoint = storageTableEndpointInstance; } JToken storageAccountResourceGroupNameValue = propertiesValue["storageAccountResourceGroupName"]; if (storageAccountResourceGroupNameValue != null && storageAccountResourceGroupNameValue.Type != JTokenType.Null) { string storageAccountResourceGroupNameInstance = ((string)storageAccountResourceGroupNameValue); propertiesInstance.StorageAccountResourceGroupName = storageAccountResourceGroupNameInstance; } JToken storageAccountSubscriptionIdValue = propertiesValue["storageAccountSubscriptionId"]; if (storageAccountSubscriptionIdValue != null && storageAccountSubscriptionIdValue.Type != JTokenType.Null) { string storageAccountSubscriptionIdInstance = ((string)storageAccountSubscriptionIdValue); propertiesInstance.StorageAccountSubscriptionId = storageAccountSubscriptionIdInstance; } JToken retentionDaysValue = propertiesValue["retentionDays"]; if (retentionDaysValue != null && retentionDaysValue.Type != JTokenType.Null) { string retentionDaysInstance = ((string)retentionDaysValue); propertiesInstance.RetentionDays = retentionDaysInstance; } JToken auditLogsTableNameValue = propertiesValue["auditLogsTableName"]; if (auditLogsTableNameValue != null && auditLogsTableNameValue.Type != JTokenType.Null) { string auditLogsTableNameInstance = ((string)auditLogsTableNameValue); propertiesInstance.AuditLogsTableName = auditLogsTableNameInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); auditingPolicyInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); auditingPolicyInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); auditingPolicyInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); auditingPolicyInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); auditingPolicyInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
//------------------------------------------------------------------------------ // <copyright file="LinqDataSource.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System.Web.UI.WebControls.Expressions; using System.Collections; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Drawing.Design; using System.Globalization; using System.Web.DynamicData; using System.Web.Resources; using System.Web.UI; // Represents a data source that applies LINQ expressions against a business object in order to perform the Select // operation. When the Delete, Insert and Update operations are enabled the business object, specified in // ContextTypeName, must be a LINQ TO SQL DataContext. The LINQ expressions are applied in the order of Where, // OrderBy, GroupBy, OrderGroupsBy, Select. [ DefaultEvent("Selecting"), DefaultProperty("ContextTypeName"), Designer("System.Web.UI.Design.WebControls.LinqDataSourceDesigner, " + AssemblyRef.SystemWebExtensionsDesign), ParseChildren(true), PersistChildren(false), ResourceDescription("LinqDataSource_Description"), ResourceDisplayName("LinqDataSource_DisplayName"), ToolboxBitmap(typeof(LinqDataSource), "LinqDataSource.bmp") ] public class LinqDataSource : ContextDataSource, IDynamicDataSource { private const string DefaultViewName = "DefaultView"; private LinqDataSourceView _view; public LinqDataSource() { } internal LinqDataSource(LinqDataSourceView view) : base(view) { } // internal constructor that takes page mock for unit tests. internal LinqDataSource(IPage page) : base(page) { } private LinqDataSourceView View { get { if (_view == null) { _view = (LinqDataSourceView)GetView(DefaultViewName); } return _view; } } [ DefaultValue(false), Category("Behavior"), ResourceDescription("LinqDataSource_AutoGenerateOrderByClause"), ] public bool AutoGenerateOrderByClause { get { return View.AutoGenerateOrderByClause; } set { View.AutoGenerateOrderByClause = value; } } [ DefaultValue(false), Category("Behavior"), ResourceDescription("LinqDataSource_AutoGenerateWhereClause"), ] public bool AutoGenerateWhereClause { get { return View.AutoGenerateWhereClause; } set { View.AutoGenerateWhereClause = value; } } [ DefaultValue(true), Category("Behavior"), ResourceDescription("LinqDataSource_AutoPage"), ] public bool AutoPage { get { return View.AutoPage; } set { View.AutoPage = value; } } [ DefaultValue(true), Category("Behavior"), ResourceDescription("LinqDataSource_AutoSort"), ] public bool AutoSort { get { return View.AutoSort; } set { View.AutoSort = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_DeleteParameters"), Browsable(false) ] public ParameterCollection DeleteParameters { get { return View.DeleteParameters; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_ContextTypeName") ] public override string ContextTypeName { get { return View.ContextTypeName; } set { View.ContextTypeName = value; } } [ DefaultValue(false), Category("Behavior"), ResourceDescription("LinqDataSource_EnableDelete"), ] public bool EnableDelete { get { return View.EnableDelete; } set { View.EnableDelete = value; } } [ DefaultValue(false), Category("Behavior"), ResourceDescription("LinqDataSource_EnableInsert"), ] public bool EnableInsert { get { return View.EnableInsert; } set { View.EnableInsert = value; } } [ DefaultValue(true), Category("Behavior"), ResourceDescription("LinqDataSource_EnableObjectTracking"), ] public bool EnableObjectTracking { get { return View.EnableObjectTracking; } set { View.EnableObjectTracking = value; } } [ DefaultValue(false), Category("Behavior"), ResourceDescription("LinqDataSource_EnableUpdate"), ] public bool EnableUpdate { get { return View.EnableUpdate; } set { View.EnableUpdate = value; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_GroupBy"), ] public string GroupBy { get { return View.GroupBy; } set { View.GroupBy = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_GroupByParameters"), Browsable(false) ] public ParameterCollection GroupByParameters { get { return View.GroupByParameters; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_InsertParameters"), Browsable(false) ] public ParameterCollection InsertParameters { get { return View.InsertParameters; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_OrderBy"), ] public string OrderBy { get { return View.OrderBy; } set { View.OrderBy = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_OrderByParameters"), Browsable(false) ] public ParameterCollection OrderByParameters { get { return View.OrderByParameters; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_OrderGroupsBy"), ] public string OrderGroupsBy { get { return View.OrderGroupsBy; } set { View.OrderGroupsBy = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_OrderGroupsByParameters"), Browsable(false) ] public ParameterCollection OrderGroupsByParameters { get { return View.OrderGroupsByParameters; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_Select"), ] public string Select { get { return View.SelectNew; } set { View.SelectNew = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_SelectParameters"), Browsable(false) ] public ParameterCollection SelectParameters { get { return View.SelectNewParameters; } } [ DefaultValue(true), Category("Behavior"), ResourceDescription("LinqDataSource_StoreOriginalValuesInViewState"), ] public bool StoreOriginalValuesInViewState { get { return View.StoreOriginalValuesInViewState; } set { View.StoreOriginalValuesInViewState = value; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_TableName"), ] public string TableName { get { return View.TableName; } set { View.TableName = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_UpdateParameters"), Browsable(false) ] public ParameterCollection UpdateParameters { get { return View.UpdateParameters; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_Where"), ] public string Where { get { return View.Where; } set { View.Where = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_WhereParameters"), Browsable(false) ] public ParameterCollection WhereParameters { get { return View.WhereParameters; } } [ Category("Data"), ResourceDescription("LinqDataSource_ContextCreated"), ] public event EventHandler<LinqDataSourceStatusEventArgs> ContextCreated { add { View.ContextCreated += value; } remove { View.ContextCreated -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_ContextCreating"), ] public event EventHandler<LinqDataSourceContextEventArgs> ContextCreating { add { View.ContextCreating += value; } remove { View.ContextCreating -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_ContextDisposing"), ] public event EventHandler<LinqDataSourceDisposeEventArgs> ContextDisposing { add { View.ContextDisposing += value; } remove { View.ContextDisposing -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Deleted"), ] public event EventHandler<LinqDataSourceStatusEventArgs> Deleted { add { View.Deleted += value; } remove { View.Deleted -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Deleting"), ] public event EventHandler<LinqDataSourceDeleteEventArgs> Deleting { add { View.Deleting += value; } remove { View.Deleting -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Inserted"), ] public event EventHandler<LinqDataSourceStatusEventArgs> Inserted { add { View.Inserted += value; } remove { View.Inserted -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Inserting"), ] public event EventHandler<LinqDataSourceInsertEventArgs> Inserting { add { View.Inserting += value; } remove { View.Inserting -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Selected"), ] public event EventHandler<LinqDataSourceStatusEventArgs> Selected { add { View.Selected += value; } remove { View.Selected -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Selecting"), ] public event EventHandler<LinqDataSourceSelectEventArgs> Selecting { add { View.Selecting += value; } remove { View.Selecting -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Updated"), ] public event EventHandler<LinqDataSourceStatusEventArgs> Updated { add { View.Updated += value; } remove { View.Updated -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Updating"), ] public event EventHandler<LinqDataSourceUpdateEventArgs> Updating { add { View.Updating += value; } remove { View.Updating -= value; } } protected virtual LinqDataSourceView CreateView() { return new LinqDataSourceView(this, DefaultViewName, Context); } protected override QueryableDataSourceView CreateQueryableView() { return CreateView(); } public int Delete(IDictionary keys, IDictionary oldValues) { return View.Delete(keys, oldValues); } public int Insert(IDictionary values) { return View.Insert(values); } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")] protected internal override void OnInit(EventArgs e) { base.OnInit(e); if (StoreOriginalValuesInViewState && (EnableUpdate || EnableDelete)) { IPage.RegisterRequiresViewStateEncryption(); } } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")] protected internal override void OnUnload(EventArgs e) { base.OnUnload(e); // keeping the select contexts alive until Unload so that users can use deferred query evaluation. if (View != null) { View.ReleaseSelectContexts(); } } public int Update(IDictionary keys, IDictionary values, IDictionary oldValues) { return View.Update(keys, values, oldValues); } #region IDynamicDataSource members [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Property used for IDynamicDataSource abstraction that wraps the ContextTypeName.")] Type IDynamicDataSource.ContextType { get { if (String.IsNullOrEmpty(ContextTypeName)) { return null; } return View.ContextType; } set { View.ContextTypeName = value.AssemblyQualifiedName; } } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Property used for IDynamicDataSource abstraction that wraps the TableName.")] string IDynamicDataSource.EntitySetName { get { return TableName; } set { TableName = value; } } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "IDynamicDataSource abstraction for handling exceptions available to user through other events.")] event EventHandler<DynamicValidatorEventArgs> IDynamicDataSource.Exception { add { View.Exception += value; } remove { View.Exception -= value; } } #endregion } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Data; using System.Configuration; using System.Collections; using System.Collections.Specialized; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Net; using System.Collections.Generic; using System.Text; namespace WebsitePanel.Portal.ProviderControls { public partial class IIS70_Settings : WebsitePanelControlBase, IHostingServiceProviderSettings { private string FilteredAppIds; public const string WDeployEnabled = "WDeployEnabled"; public const string WDeployRepair = "WDeployRepair"; protected void Page_Load(object sender, EventArgs e) { } public void WebAppGalleryList_DataBound(object sender, EventArgs e) { SetAppsCalatolgFilter(FilteredAppIds); } public void ResetButton_Click(object sender, EventArgs e) { WebAppGalleryList.ClearSelection(); // FilterDialogButton.Text = GetLocalizedString("FilterDialogButton.Text"); } protected void SetAppsCalatolgFilter(string appsIds) { if (String.IsNullOrEmpty(appsIds)) return; // string[] filteredApps = appsIds.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); // foreach (ListItem li in WebAppGalleryList.Items) { li.Selected = Array.Exists<string>(filteredApps, x => x.Equals(li.Value.Trim(), StringComparison.InvariantCultureIgnoreCase)); } // FilterDialogButton.Text = GetLocalizedString("FilterDialogButton.AlternateText"); } protected string GetAppsCatalogFilter() { var builder = new StringBuilder(); var formatStr = "{0}"; // foreach (ListItem li in WebAppGalleryList.Items) { if (li.Selected) { builder.AppendFormat(formatStr, li.Value.Trim()); // formatStr = ",{0}"; } } // return builder.ToString(); } public void BindSettings(StringDictionary settings) { // ipAddress.AddressId = (settings["SharedIP"] != null) ? Utils.ParseInt(settings["SharedIP"], 0) : 0; ipAddress.SelectValueText = GetLocalizedString("ipAddress.SelectValueText"); txtPublicSharedIP.Text = settings["PublicSharedIP"]; txtWebGroupName.Text = settings["WebGroupName"]; chkAssignIPAutomatically.Checked = Utils.ParseBool(settings["AutoAssignDedicatedIP"], true); txtAspNet11Path.Text = settings["AspNet11Path"]; txtAspNet20Path.Text = settings["AspNet20Path"]; txtAspNet20x64Path.Text = settings["AspNet20x64Path"]; txtAspNet40Path.Text = settings["AspNet40Path"]; txtAspNet40x64Path.Text = settings["AspNet40x64Path"]; txtAspNet11Pool.Text = settings["AspNet11Pool"]; // ASP.NET 2.0 txtAspNet20Pool.Text = settings["ClassicAspNet20Pool"]; txtAspNet20IntegratedPool.Text = settings["IntegratedAspNet20Pool"]; // ASP.NET 4.0 ClassicAspNet40Pool.Text = settings[ClassicAspNet40Pool.ID]; IntegratedAspNet40Pool.Text = settings[IntegratedAspNet40Pool.ID]; // ASP.NET 2.0 & 4.0 Bitness Mode Utils.SelectListItem(AspNetBitnessMode, settings[AspNetBitnessMode.ID]); txtAspPath.Text = settings["AspPath"]; php4Path.Text = settings["Php4Path"]; txtPhpPath.Text = settings["PhpPath"]; Utils.SelectListItem(ddlPhpMode, settings["PhpMode"]); perlPath.Text = settings["PerlPath"]; txtColdFusionPath.Text = settings["ColdFusionPath"]; txtScriptsDirectory.Text = settings["CFScriptsDirectory"]; txtFlashRemotingDir.Text = settings["CFFlashRemotingDirectory"]; txtProtectedUsersFile.Text = settings["ProtectedUsersFile"]; txtProtectedGroupsFile.Text = settings["ProtectedGroupsFile"]; txtSecureFoldersModuleAsm.Text = settings["SecureFoldersModuleAssembly"]; //Helicon Ape Providers.ResultObjects.HeliconApeStatus sts = ES.Services.WebServers.GetHeliconApeStatus(int.Parse(Request.QueryString["ServiceID"])); if (sts.IsInstalled) { downloadApePanel.Visible = false; txtHeliconApeVersion.Text = sts.Version; lblHeliconRegistrationText.Text = sts.RegistrationInfo; if (sts.IsEnabled) { chkHeliconApeGlobalRegistration.Checked = true; } ViewState["HeliconApeInitiallyEnabled"] = chkHeliconApeGlobalRegistration.Checked; } else { configureApePanel.Visible = false; // Build url manually, EditUrl throws exception: module is Null // pid=Servers&mid=137&ctl=edit_platforminstaller&ServerID=1&Product=HeliconApe List<string> qsParts = new List<string>(); qsParts.Add("pid=Servers"); qsParts.Add("ctl=edit_platforminstaller"); qsParts.Add("mid=" + Request.QueryString["mid"]); qsParts.Add("ServerID=" + Request.QueryString["ServerID"]); qsParts.Add("WPIProduct=HeliconApe"); InstallHeliconApeLink.Attributes["href"] = "Default.aspx?" + String.Join("&", qsParts.ToArray()); ViewState["HeliconApeInitiallyEnabled"] = null; } // sharedSslSites.Value = settings["SharedSslSites"]; ActiveDirectoryIntegration.BindSettings(settings); // txtWmSvcServicePort.Text = settings["WmSvc.Port"]; txtWmSvcNETBIOS.Text = settings["WmSvc.NETBIOS"]; // string wmsvcServiceUrl = settings["WmSvc.ServiceUrl"]; // if (wmsvcServiceUrl == "*") wmsvcServiceUrl = String.Empty; // Set service url as is txtWmSvcServiceUrl.Text = wmsvcServiceUrl; // //if (settings["WmSvc.RequiresWindowsCredentials"] == "1") // ddlWmSvcCredentialsMode.Items.RemoveAt(1); // Utils.SelectListItem(ddlWmSvcCredentialsMode, settings["WmSvc.CredentialsMode"]); // // if (String.IsNullOrEmpty(settings[WDeployEnabled]) == false) { if (Convert.ToBoolean(settings[WDeployEnabled]) == true) { WDeployEnabledCheckBox.Checked = true; } else { WDeployDisabledCheckBox.Checked = true; } } // WPI //wpiMicrosoftFeed.Checked = Utils.ParseBool(settings["FeedEnableMicrosoft"], true); //wpiHeliconTechFeed.Checked = Utils.ParseBool(settings["FeedEnableHelicon"], true); wpiEditFeedsList.Value = settings["FeedUrls"]; FilteredAppIds = settings["GalleryAppsFilter"]; radioFilterAppsList.SelectedIndex = Utils.ParseInt(settings["GalleryAppsFilterMode"], 0); chkGalleryAppsAlwaysIgnoreDependencies.Checked = Utils.ParseBool(settings["GalleryAppsAlwaysIgnoreDependencies"], false); // If any of these exists, we assume we are running against the IIS80 provider if (settings["SSLCCSCommonPassword"] != null || settings["SSLCCSUNCPath"] != null || settings["SSLUseCCS"] != null || settings["SSLUseSNI"] != null) { IIS80SSLSettings.Visible = true; cbUseCCS.Checked = Utils.ParseBool(settings["SSLUseCCS"], false); cbUseSNI.Checked = Utils.ParseBool(settings["SSLUseSNI"], false); txtCCSUNCPath.Text = settings["SSLCCSUNCPath"]; txtCCSCommonPassword.Text = settings["SSLCCSCommonPassword"]; } } public void SaveSettings(StringDictionary settings) { // settings["SharedIP"] = ipAddress.AddressId.ToString(); settings["PublicSharedIP"] = txtPublicSharedIP.Text.Trim(); settings["WebGroupName"] = txtWebGroupName.Text.Trim(); settings["AutoAssignDedicatedIP"] = chkAssignIPAutomatically.Checked.ToString(); // paths settings["AspNet11Path"] = txtAspNet11Path.Text.Trim(); settings["AspNet20Path"] = txtAspNet20Path.Text.Trim(); settings["AspNet20x64Path"] = txtAspNet20x64Path.Text.Trim(); settings["AspNet40Path"] = txtAspNet40Path.Text.Trim(); settings["AspNet40x64Path"] = txtAspNet40x64Path.Text.Trim(); settings["AspNet11Pool"] = txtAspNet11Pool.Text.Trim(); // ASP.NET 2.0 settings["ClassicAspNet20Pool"] = txtAspNet20Pool.Text.Trim(); settings["IntegratedAspNet20Pool"] = txtAspNet20IntegratedPool.Text.Trim(); // ASP.NET 4.0 settings[ClassicAspNet40Pool.ID] = ClassicAspNet40Pool.Text.Trim(); settings[IntegratedAspNet40Pool.ID] = IntegratedAspNet40Pool.Text.Trim(); // ASP.NET 2.0 & 4.0 Bitness Mode settings[AspNetBitnessMode.ID] = AspNetBitnessMode.SelectedValue; settings["AspPath"] = txtAspPath.Text.Trim(); settings["Php4Path"] = php4Path.Text.Trim(); settings["PhpPath"] = txtPhpPath.Text.Trim(); settings["PhpMode"] = ddlPhpMode.SelectedValue; settings["PerlPath"] = perlPath.Text.Trim(); settings["ColdFusionPath"] = txtColdFusionPath.Text.Trim(); settings["CFScriptsDirectory"] = txtScriptsDirectory.Text.Trim(); settings["CFFlashRemotingDirectory"] = txtFlashRemotingDir.Text.Trim(); settings["SharedSslSites"] = sharedSslSites.Value; settings["ProtectedUsersFile"] = txtProtectedUsersFile.Text.Trim(); settings["ProtectedGroupsFile"] = txtProtectedGroupsFile.Text.Trim(); settings["SecureFoldersModuleAssembly"] = txtSecureFoldersModuleAsm.Text.Trim(); settings["WmSvc.NETBIOS"] = txtWmSvcNETBIOS.Text.Trim(); settings["WmSvc.ServiceUrl"] = txtWmSvcServiceUrl.Text.Trim(); settings["WmSvc.Port"] = Utils.ParseInt(txtWmSvcServicePort.Text.Trim(), 0).ToString(); settings["WmSvc.CredentialsMode"] = ddlWmSvcCredentialsMode.SelectedValue; ActiveDirectoryIntegration.SaveSettings(settings); // Helicon Ape if (null != ViewState["HeliconApeInitiallyEnabled"]) { bool registerHeliconApeGlobbally = chkHeliconApeGlobalRegistration.Checked; if (registerHeliconApeGlobbally != (bool)ViewState["HeliconApeInitiallyEnabled"]) { if (registerHeliconApeGlobbally) { ES.Services.WebServers.EnableHeliconApeGlobally(int.Parse(Request.QueryString["ServiceID"])); } else { ES.Services.WebServers.DisableHeliconApeGlobally(int.Parse(Request.QueryString["ServiceID"])); } } } if (WDeployEnabledCheckBox.Checked) { settings[WDeployEnabled] = Boolean.TrueString; // if (WDeployRepairSettingCheckBox.Checked) { settings[WDeployRepair] = Boolean.TrueString; } } else if (WDeployDisabledCheckBox.Checked) { settings[WDeployEnabled] = Boolean.FalseString; } //settings["FeedEnableMicrosoft"] = wpiMicrosoftFeed.Checked.ToString(); //settings["FeedEnableHelicon"] = wpiHeliconTechFeed.Checked.ToString(); settings["FeedUrls"] = wpiEditFeedsList.Value; settings["GalleryAppsFilter"] = GetAppsCatalogFilter(); settings["GalleryAppsFilterMode"] = radioFilterAppsList.SelectedIndex.ToString(); settings["GalleryAppsAlwaysIgnoreDependencies"] = chkGalleryAppsAlwaysIgnoreDependencies.Checked.ToString(); if (IIS80SSLSettings.Visible) { settings["SSLUseCCS"] = cbUseCCS.Checked.ToString(); settings["SSLUseSNI"] = cbUseSNI.Checked.ToString(); settings["SSLCCSUNCPath"] = txtCCSUNCPath.Text; settings["SSLCCSCommonPassword"] = txtCCSCommonPassword.Text; } } /* protected void DownladAndIstallApeLinkButton_Click(object sender, EventArgs e) { ES.Services.WebServers.InstallHeliconApe(PanelRequest.ServiceId); //Redirect to avoid 2-nd call Response.Redirect(this.Context.Request.Url.AbsoluteUri); } */ public string GetHttpdEditControlUrl(string ctrlKey, string name) { return HostModule.EditUrl("ItemID", PanelRequest.ItemID.ToString(), ctrlKey, "Name=" + name, PortalUtils.SPACE_ID_PARAM + "=" + int.Parse(Request.QueryString["ServiceID"]), "ReturnUrlBase64="+ EncodeTo64(Server.UrlEncode(Request.Url.PathAndQuery)), "UserID="+PanelSecurity.LoggedUserId.ToString() ); } static public string EncodeTo64(string toEncode) { return Convert.ToBase64String(Encoding.ASCII.GetBytes(toEncode)); } protected void EditHeliconApeConfButton_Click(object sender, EventArgs e) { Response.Redirect(GetHttpdEditControlUrl("edit_htaccessfolder", "httpd.conf")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.ActionConstraints; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Options; using Moq; using Xunit; namespace Microsoft.AspNetCore.Mvc.ApplicationModels { public class ControllerActionDescriptorProviderTests { [Fact] public void GetDescriptors_GetsDescriptorsOnlyForValidActions() { // Arrange var provider = GetProvider(typeof(PersonController).GetTypeInfo()); // Act var descriptors = provider.GetDescriptors(); var actionNames = descriptors.Select(ad => ad.ActionName); // Assert Assert.Equal(new[] { "GetPerson", "ShowPeople", }, actionNames); } [Fact] public void GetDescriptors_DisplayNameIncludesAssemblyName() { // Arrange var controllerTypeInfo = typeof(PersonController).GetTypeInfo(); var provider = GetProvider(controllerTypeInfo); // Act var descriptors = provider.GetDescriptors(); var descriptor = descriptors.Single(ad => ad.ActionName == nameof(PersonController.GetPerson)); // Assert Assert.Equal($"{controllerTypeInfo.FullName}.{nameof(PersonController.GetPerson)} ({controllerTypeInfo.Assembly.GetName().Name})", descriptor.DisplayName); } [Fact] public void GetDescriptors_IncludesFilters() { // Arrange var globalFilter = new MyFilterAttribute(1); var provider = GetProvider(typeof(FiltersController).GetTypeInfo(), new IFilterMetadata[] { globalFilter, }); // Act var descriptors = provider.GetDescriptors(); var descriptor = Assert.Single(descriptors); // Assert Assert.Equal(3, descriptor.FilterDescriptors.Count); var filter1 = descriptor.FilterDescriptors[0]; Assert.Same(globalFilter, filter1.Filter); Assert.Equal(FilterScope.Global, filter1.Scope); var filter2 = descriptor.FilterDescriptors[1]; Assert.Equal(2, Assert.IsType<MyFilterAttribute>(filter2.Filter).Value); Assert.Equal(FilterScope.Controller, filter2.Scope); var filter3 = descriptor.FilterDescriptors[2]; Assert.Equal(3, Assert.IsType<MyFilterAttribute>(filter3.Filter).Value); Assert.Equal(FilterScope.Action, filter3.Scope); } [Fact] public void GetDescriptors_AddsHttpMethodConstraints_ForConventionallyRoutedActions() { // Arrange var provider = GetProvider(typeof(HttpMethodController).GetTypeInfo()); // Act var descriptors = provider.GetDescriptors(); var descriptor = Assert.Single(descriptors); // Assert Assert.Equal("OnlyPost", descriptor.ActionName); var constraint = Assert.IsType<HttpMethodActionConstraint>(Assert.Single(descriptor.ActionConstraints)); Assert.Equal(new string[] { "POST" }, constraint.HttpMethods); } [Fact] public void GetDescriptors_HttpMethodConstraint_RouteOnController() { // Arrange var provider = GetProvider(typeof(AttributeRoutedHttpMethodController).GetTypeInfo()); // Act var descriptors = provider.GetDescriptors(); var descriptor = Assert.Single(descriptors); // Assert Assert.Equal("Items", descriptor.AttributeRouteInfo.Template); var constraint = Assert.IsType<HttpMethodActionConstraint>(Assert.Single(descriptor.ActionConstraints)); Assert.Equal(new string[] { "PUT", "PATCH" }, constraint.HttpMethods); } [Fact] public void GetDescriptors_AddsParameters_ToActionDescriptor() { // Arrange & Act var descriptors = GetDescriptors( typeof(ActionParametersController).GetTypeInfo()); // Assert var main = Assert.Single(descriptors.Cast<ControllerActionDescriptor>(), d => d.ActionName.Equals(nameof(ActionParametersController.RequiredInt))); Assert.NotNull(main.Parameters); var id = Assert.Single(main.Parameters); Assert.Equal("id", id.Name); Assert.Null(id.BindingInfo?.BindingSource); Assert.Equal(typeof(int), id.ParameterType); } [Fact] public void GetDescriptors_AddsMultipleParameters_ToActionDescriptor() { // Arrange & Act var descriptors = GetDescriptors( typeof(ActionParametersController).GetTypeInfo()); // Assert var main = Assert.Single(descriptors.Cast<ControllerActionDescriptor>(), d => d.ActionName.Equals(nameof(ActionParametersController.MultipleParameters))); Assert.NotNull(main.Parameters); var id = Assert.Single(main.Parameters, p => p.Name == "id"); Assert.Equal("id", id.Name); Assert.Null(id.BindingInfo?.BindingSource); Assert.Equal(typeof(int), id.ParameterType); var entity = Assert.Single(main.Parameters, p => p.Name == "entity"); Assert.Equal("entity", entity.Name); Assert.Equal(entity.BindingInfo.BindingSource, BindingSource.Body); Assert.Equal(typeof(TestActionParameter), entity.ParameterType); } [Fact] public void GetDescriptors_AddsMultipleParametersWithDifferentCasing_ToActionDescriptor() { // Arrange & Act var descriptors = GetDescriptors( typeof(ActionParametersController).GetTypeInfo()); // Assert var main = Assert.Single(descriptors.Cast<ControllerActionDescriptor>(), d => d.ActionName.Equals(nameof(ActionParametersController.DifferentCasing))); Assert.NotNull(main.Parameters); var id = Assert.Single(main.Parameters, p => p.Name == "id"); Assert.Equal("id", id.Name); Assert.Null(id.BindingInfo?.BindingSource); Assert.Equal(typeof(int), id.ParameterType); var upperCaseId = Assert.Single(main.Parameters, p => p.Name == "ID"); Assert.Equal("ID", upperCaseId.Name); Assert.Null(upperCaseId.BindingInfo?.BindingSource); Assert.Equal(typeof(int), upperCaseId.ParameterType); var pascalCaseId = Assert.Single(main.Parameters, p => p.Name == "Id"); Assert.Equal("Id", pascalCaseId.Name); Assert.Null(id.BindingInfo?.BindingSource); Assert.Equal(typeof(int), pascalCaseId.ParameterType); } [Fact] public void GetDescriptors_AddsParameters_DetectsFromBodyParameters() { // Arrange & Act var actionName = nameof(ActionParametersController.FromBodyParameter); var descriptors = GetDescriptors( typeof(ActionParametersController).GetTypeInfo()); // Assert var fromBody = Assert.Single(descriptors.Cast<ControllerActionDescriptor>(), d => d.ActionName.Equals(actionName)); Assert.NotNull(fromBody.Parameters); var entity = Assert.Single(fromBody.Parameters); Assert.Equal("entity", entity.Name); Assert.Equal(entity.BindingInfo.BindingSource, BindingSource.Body); Assert.Equal(typeof(TestActionParameter), entity.ParameterType); } [Fact] public void GetDescriptors_AddsParameters_DoesNotDetectParameterFromBody_IfNoFromBodyAttribute() { // Arrange & Act var actionName = nameof(ActionParametersController.NotFromBodyParameter); var descriptors = GetDescriptors( typeof(ActionParametersController).GetTypeInfo()); // Assert var notFromBody = Assert.Single(descriptors.Cast<ControllerActionDescriptor>(), d => d.ActionName.Equals(actionName)); Assert.NotNull(notFromBody.Parameters); var entity = Assert.Single(notFromBody.Parameters); Assert.Equal("entity", entity.Name); Assert.Null(entity.BindingInfo?.BindingSource); Assert.Equal(typeof(TestActionParameter), entity.ParameterType); } [Fact] public void GetDescriptors_AddsControllerAndActionConstraints_ToConventionallyRoutedActions() { // Arrange & Act var descriptors = GetDescriptors( typeof(ConventionallyRoutedController).GetTypeInfo()); // Assert var action = Assert.Single(descriptors); Assert.NotNull(action.RouteValues); var controller = Assert.Single(action.RouteValues, kvp => kvp.Key.Equals("controller")); Assert.Equal("ConventionallyRouted", controller.Value); var actionConstraint = Assert.Single(action.RouteValues, kvp => kvp.Key.Equals("action")); Assert.Equal(nameof(ConventionallyRoutedController.ConventionalAction), actionConstraint.Value); } [Fact] public void GetDescriptors_EndpointMetadata_ContainsAttributesFromActionAndController() { // Arrange & Act var descriptors = GetDescriptors( typeof(AuthorizeController).GetTypeInfo()); // Assert Assert.Equal(2, descriptors.Count()); var anonymousAction = Assert.Single(descriptors, a => a.RouteValues["action"] == "AllowAnonymousAction"); Assert.NotNull(anonymousAction.EndpointMetadata); Assert.Collection(anonymousAction.EndpointMetadata, metadata => Assert.IsType<AuthorizeAttribute>(metadata), metadata => Assert.IsType<AllowAnonymousAttribute>(metadata)); var authorizeAction = Assert.Single(descriptors, a => a.RouteValues["action"] == "AuthorizeAction"); Assert.NotNull(authorizeAction.EndpointMetadata); Assert.Collection(authorizeAction.EndpointMetadata, metadata => Assert.Equal("ControllerPolicy", Assert.IsType<AuthorizeAttribute>(metadata).Policy), metadata => Assert.Equal("ActionPolicy", Assert.IsType<AuthorizeAttribute>(metadata).Policy)); } [Fact] public void GetDescriptors_ActionWithHttpMethods_AddedToEndpointMetadata() { // Arrange & Act var descriptors = GetDescriptors( typeof(AttributeRoutedController).GetTypeInfo()); // Assert var action = Assert.Single(descriptors); Assert.NotNull(action.EndpointMetadata); Assert.Collection(action.EndpointMetadata, metadata => Assert.IsType<RouteAttribute>(metadata), metadata => Assert.IsType<HttpGetAttribute>(metadata), metadata => { var httpMethodMetadata = Assert.IsType<HttpMethodMetadata>(metadata); Assert.False(httpMethodMetadata.AcceptCorsPreflight); Assert.Equal("GET", Assert.Single(httpMethodMetadata.HttpMethods)); }); } [Fact] public void GetDescriptors_ActionWithMultipleHttpMethods_LastHttpMethodMetadata() { // Arrange & Act var descriptors = GetDescriptors( typeof(NonDuplicatedAttributeRouteController).GetTypeInfo()); // Assert var actions = descriptors .OfType<ControllerActionDescriptor>() .Where(d => d.ActionName == nameof(NonDuplicatedAttributeRouteController.DifferentHttpMethods)); Assert.Collection(actions, InspectElement("GET"), InspectElement("POST"), InspectElement("PUT"), InspectElement("PATCH"), InspectElement("DELETE")); Action<ControllerActionDescriptor> InspectElement(string httpMethod) { return (descriptor) => { var httpMethodAttribute = Assert.Single(descriptor.EndpointMetadata.OfType<HttpMethodAttribute>()); Assert.Equal(httpMethod, httpMethodAttribute.HttpMethods.Single(), ignoreCase: true); var lastHttpMethodMetadata = descriptor.EndpointMetadata.OfType<IHttpMethodMetadata>().Last(); Assert.Equal(httpMethod, lastHttpMethodMetadata.HttpMethods.Single(), ignoreCase: true); Assert.False(lastHttpMethodMetadata.AcceptCorsPreflight); }; } } [Fact] public void GetDescriptors_AddsControllerAndActionDefaults_ToAttributeRoutedActions() { // Arrange & Act var descriptors = GetDescriptors( typeof(AttributeRoutedController).GetTypeInfo()); // Assert var action = Assert.Single(descriptors); var controller = Assert.Single(action.RouteValues, kvp => kvp.Key.Equals("controller")); Assert.Equal("AttributeRouted", controller.Value); var actionConstraint = Assert.Single(action.RouteValues, kvp => kvp.Key.Equals("action")); Assert.Equal(nameof(AttributeRoutedController.AttributeRoutedAction), actionConstraint.Value); } [Fact] public void GetDescriptors_WithRouteValueAttribute() { // Arrange & Act var descriptors = GetDescriptors( typeof(HttpMethodController).GetTypeInfo(), typeof(RouteValueController).GetTypeInfo()).ToArray(); var descriptorWithoutValue = Assert.Single( descriptors, ad => !ad.RouteValues.ContainsKey("key")); var descriptorWithValue = Assert.Single( descriptors, ad => ad.RouteValues.ContainsKey("key")); // Assert Assert.Equal(2, descriptors.Length); Assert.Equal(3, descriptorWithValue.RouteValues.Count); Assert.Single( descriptorWithValue.RouteValues, c => c.Key == "controller" && c.Value == "RouteValue"); Assert.Single( descriptorWithValue.RouteValues, c => c.Key == "action" && c.Value == "Edit"); Assert.Single( descriptorWithValue.RouteValues, c => c.Key == "key" && c.Value == "value"); Assert.Equal(2, descriptorWithoutValue.RouteValues.Count); Assert.Single( descriptorWithoutValue.RouteValues, c => c.Key == "controller" && c.Value == "HttpMethod"); Assert.Single( descriptorWithoutValue.RouteValues, c => c.Key == "action" && c.Value == "OnlyPost"); } [Fact] public void AttributeRouting_TokenReplacement_InActionDescriptor() { // Arrange var provider = GetProvider(typeof(TokenReplacementController).GetTypeInfo()); // Act var actions = provider.GetDescriptors(); // Assert var action = Assert.Single(actions); Assert.Equal("api/Token/value/TokenReplacement/stub/ThisIsAnAction", action.AttributeRouteInfo.Template); } [Fact] public void AttributeRouting_TokenReplacement_ThrowsWithMultipleMessages() { // Arrange var controllerTypeInfo = typeof(MultipleErrorsController).GetTypeInfo(); var assemblyName = controllerTypeInfo.Assembly.GetName().Name; var provider = GetProvider(controllerTypeInfo); var expectedMessage = "The following errors occurred with attribute routing information:" + Environment.NewLine + Environment.NewLine + "Error 1:" + Environment.NewLine + $"For action: '{controllerTypeInfo.FullName}.Unknown ({assemblyName})'" + Environment.NewLine + "Error: While processing template 'stub/[action]/[unknown]', a replacement value for the token 'unknown' " + "could not be found. Available tokens: 'action, controller'. To use a '[' or ']' as a literal string in" + " a route or within a constraint, use '[[' or ']]' instead." + Environment.NewLine + Environment.NewLine + "Error 2:" + Environment.NewLine + $"For action: '{controllerTypeInfo.FullName}.Invalid ({assemblyName})'" + Environment.NewLine + "Error: The route template '[invalid/syntax' has invalid syntax. A replacement token is not closed."; // Act var ex = Assert.Throws<InvalidOperationException>(() => { provider.GetDescriptors(); }); // Assert VerifyMultiLineError(expectedMessage, ex.Message, unorderedStart: 2, unorderedLineCount: 6); } [Fact] public void AttributeRouting_CreatesOneActionDescriptor_PerControllerAndActionRouteCombination() { // Arrange var provider = GetProvider(typeof(MultiRouteAttributesController).GetTypeInfo()); // Act var descriptors = provider.GetDescriptors(); // Assert var actions = descriptors.Where(d => d.ActionName == "MultipleHttpGet"); Assert.Equal(4, actions.Count()); foreach (var action in actions) { Assert.Equal("MultipleHttpGet", action.ActionName); Assert.Equal("MultiRouteAttributes", action.ControllerName); } Assert.Single(actions, a => a.AttributeRouteInfo.Template.Equals("v1/List")); Assert.Single(actions, a => a.AttributeRouteInfo.Template.Equals("v1/All")); Assert.Single(actions, a => a.AttributeRouteInfo.Template.Equals("v2/List")); Assert.Single(actions, a => a.AttributeRouteInfo.Template.Equals("v2/All")); } [Fact] public void AttributeRouting_AcceptVerbsOnAction_CreatesActionPerControllerAttributeRouteCombination() { // Arrange var provider = GetProvider(typeof(MultiRouteAttributesController).GetTypeInfo()); // Act var descriptors = provider.GetDescriptors(); // Assert var actions = descriptors.Where(d => d.ActionName == nameof(MultiRouteAttributesController.AcceptVerbs)); Assert.Equal(2, actions.Count()); foreach (var action in actions) { Assert.Equal("MultiRouteAttributes", action.ControllerName); Assert.NotNull(action.ActionConstraints); var methodConstraint = Assert.IsType<HttpMethodActionConstraint>(Assert.Single(action.ActionConstraints)); Assert.NotNull(methodConstraint.HttpMethods); Assert.Equal(new[] { "POST" }, methodConstraint.HttpMethods); } Assert.Single(actions, a => a.AttributeRouteInfo.Template.Equals("v1/List")); Assert.Single(actions, a => a.AttributeRouteInfo.Template.Equals("v2/List")); } [Fact] public void AttributeRouting_AcceptVerbsOnActionWithOverrideTemplate_CreatesSingleAttributeRoutedAction() { // Arrange var provider = GetProvider(typeof(MultiRouteAttributesController).GetTypeInfo()); // Act var descriptors = provider.GetDescriptors(); // Assert var action = Assert.Single(descriptors, d => d.ActionName == "AcceptVerbsOverride"); Assert.Equal("MultiRouteAttributes", action.ControllerName); Assert.NotNull(action.ActionConstraints); var methodConstraint = Assert.IsType<HttpMethodActionConstraint>(Assert.Single(action.ActionConstraints)); Assert.NotNull(methodConstraint.HttpMethods); Assert.Equal(new[] { "PUT" }, methodConstraint.HttpMethods); Assert.NotNull(action.AttributeRouteInfo); Assert.Equal("Override", action.AttributeRouteInfo.Template); } [Fact] public void AttributeRouting_AcceptVerbsOnAction_WithoutTemplate_MergesVerb() { // Arrange var provider = GetProvider(typeof(MultiRouteAttributesController).GetTypeInfo()); // Act var descriptors = provider.GetDescriptors(); // Assert var actions = descriptors.Where(d => d.ActionName == "AcceptVerbsRouteAttributeAndHttpPut"); Assert.Equal(4, actions.Count()); foreach (var action in actions) { Assert.Equal("MultiRouteAttributes", action.ControllerName); Assert.NotNull(action.AttributeRouteInfo); Assert.NotNull(action.AttributeRouteInfo.Template); } var constrainedActions = actions.Where(a => a.ActionConstraints != null); Assert.Equal(4, constrainedActions.Count()); // Actions generated by PutAttribute var putActions = constrainedActions.Where( a => a.ActionConstraints.OfType<HttpMethodActionConstraint>().Single().HttpMethods.Single() == "PUT"); Assert.Equal(2, putActions.Count()); Assert.Single(putActions, a => a.AttributeRouteInfo.Template.Equals("v1/All")); Assert.Single(putActions, a => a.AttributeRouteInfo.Template.Equals("v2/All")); // Actions generated by RouteAttribute var routeActions = actions.Where( a => a.ActionConstraints.OfType<HttpMethodActionConstraint>().Single().HttpMethods.Single() == "POST"); Assert.Equal(2, routeActions.Count()); Assert.Single(routeActions, a => a.AttributeRouteInfo.Template.Equals("v1/List")); Assert.Single(routeActions, a => a.AttributeRouteInfo.Template.Equals("v2/List")); } [Fact] public void AttributeRouting_AcceptVerbsOnAction_WithTemplate_DoesNotMergeVerb() { // Arrange var provider = GetProvider(typeof(MultiRouteAttributesController).GetTypeInfo()); // Act var descriptors = provider.GetDescriptors(); // Assert var actions = descriptors.Where(d => d.ActionName == "AcceptVerbsRouteAttributeWithTemplateAndHttpPut"); Assert.Equal(6, actions.Count()); foreach (var action in actions) { Assert.Equal("MultiRouteAttributes", action.ControllerName); Assert.NotNull(action.AttributeRouteInfo); Assert.NotNull(action.AttributeRouteInfo.Template); } var constrainedActions = actions.Where(a => a.ActionConstraints != null); Assert.Equal(4, constrainedActions.Count()); // Actions generated by AcceptVerbs var postActions = constrainedActions.Where( a => a.ActionConstraints.OfType<HttpMethodActionConstraint>().Single().HttpMethods.Single() == "POST"); Assert.Equal(2, postActions.Count()); Assert.Single(postActions, a => a.AttributeRouteInfo.Template.Equals("v1")); Assert.Single(postActions, a => a.AttributeRouteInfo.Template.Equals("v2")); // Actions generated by PutAttribute var putActions = constrainedActions.Where( a => a.ActionConstraints.OfType<HttpMethodActionConstraint>().Single().HttpMethods.Single() == "PUT"); Assert.Equal(2, putActions.Count()); Assert.Single(putActions, a => a.AttributeRouteInfo.Template.Equals("v1/All")); Assert.Single(putActions, a => a.AttributeRouteInfo.Template.Equals("v2/All")); // Actions generated by RouteAttribute var unconstrainedActions = actions.Where(a => a.ActionConstraints == null); Assert.Equal(2, unconstrainedActions.Count()); Assert.Single(unconstrainedActions, a => a.AttributeRouteInfo.Template.Equals("v1/List")); Assert.Single(unconstrainedActions, a => a.AttributeRouteInfo.Template.Equals("v2/List")); } [Fact] public void AttributeRouting_AllowsDuplicateAttributeRoutedActions_WithTheSameTemplateAndSameHttpMethodsOnDifferentActions() { // Arrange var provider = GetProvider(typeof(NonDuplicatedAttributeRouteController).GetTypeInfo()); var firstActionName = nameof(NonDuplicatedAttributeRouteController.ControllerAndAction); var secondActionName = nameof(NonDuplicatedAttributeRouteController.OverrideOnAction); // Act var actions = provider.GetDescriptors(); // Assert var controllerAndAction = Assert.Single(actions, a => a.ActionName.Equals(firstActionName)); Assert.NotNull(controllerAndAction.AttributeRouteInfo); var controllerActionAndOverride = Assert.Single(actions, a => a.ActionName.Equals(secondActionName)); Assert.NotNull(controllerActionAndOverride.AttributeRouteInfo); Assert.Equal( controllerAndAction.AttributeRouteInfo.Template, controllerActionAndOverride.AttributeRouteInfo.Template, StringComparer.OrdinalIgnoreCase); } [Fact] public void AttributeRouting_AllowsDuplicateAttributeRoutedActions_WithTheSameTemplateAndDifferentHttpMethodsOnTheSameAction() { // Arrange var provider = GetProvider(typeof(NonDuplicatedAttributeRouteController).GetTypeInfo()); var actionName = nameof(NonDuplicatedAttributeRouteController.DifferentHttpMethods); // Act var descriptors = provider.GetDescriptors(); // Assert var actions = descriptors.Where(d => d.ActionName.Equals(actionName)); Assert.Equal(5, actions.Count()); foreach (var method in new[] { "GET", "POST", "PUT", "PATCH", "DELETE" }) { var action = Assert.Single( actions, a => a.ActionConstraints .OfType<HttpMethodActionConstraint>() .SelectMany(c => c.HttpMethods) .Contains(method)); Assert.NotNull(action.AttributeRouteInfo); Assert.Equal("Products/list", action.AttributeRouteInfo.Template); } } [Fact] public void AttributeRouting_ThrowsIfAttributeRoutedAndNonAttributedActions_OnTheSameMethod() { // Arrange var controllerTypeInfo = typeof(AttributeAndNonAttributeRoutedActionsOnSameMethodController).GetTypeInfo(); var assemblyName = controllerTypeInfo.Assembly.GetName().Name; var expectedMessage = "The following errors occurred with attribute routing information:" + Environment.NewLine + Environment.NewLine + "Error 1:" + Environment.NewLine + $"A method '{controllerTypeInfo.FullName}.Method ({assemblyName})'" + " must not define attribute routed actions and non attribute routed actions at the same time:" + Environment.NewLine + $"Action: '{controllerTypeInfo.FullName}.Method ({assemblyName})' " + "- Route Template: 'AttributeRouted' - " + "HTTP Verbs: 'GET'" + Environment.NewLine + $"Action: '{controllerTypeInfo.FullName}.Method ({assemblyName})' - " + "Route Template: '(none)' - HTTP Verbs: 'DELETE, PATCH, POST, PUT'" + Environment.NewLine + Environment.NewLine + "Use 'AcceptVerbsAttribute' to create a single route that allows multiple HTTP verbs and defines a " + "route, or set a route template in all attributes that constrain HTTP verbs."; var provider = GetProvider(controllerTypeInfo); // Act var exception = Assert.Throws<InvalidOperationException>(() => provider.GetDescriptors()); // Assert VerifyMultiLineError(expectedMessage, exception.Message, unorderedStart: 1, unorderedLineCount: 2); } // Verify that the expected exception and error message is thrown even when the user builds the model // incorrectly. [Fact] public void AttributeRouting_ThrowsIfAttributeRoutedAndNonAttributedActions_OnTheSameMethod_UsingCustomConvention() { // Arrange var controllerTypeInfo = typeof(UserController).GetTypeInfo(); var manager = GetApplicationManager(new[] { controllerTypeInfo }); var options = Options.Create(new MvcOptions()); var modelProvider = new DefaultApplicationModelProvider(options, new EmptyModelMetadataProvider()); var provider = new ControllerActionDescriptorProvider( manager, new ApplicationModelFactory(new[] { modelProvider }, options)); var assemblyName = controllerTypeInfo.Assembly.GetName().Name; var expectedMessage = "The following errors occurred with attribute routing information:" + Environment.NewLine + Environment.NewLine + "Error 1:" + Environment.NewLine + $"A method '{controllerTypeInfo.FullName}.GetUser ({assemblyName})'" + " must not define attribute routed actions and non attribute routed actions at the same time:" + Environment.NewLine + $"Action: '{controllerTypeInfo.FullName}.GetUser ({assemblyName})' " + "- Route Template: '(none)' - " + "HTTP Verbs: ''" + Environment.NewLine + $"Action: '{controllerTypeInfo.FullName}.GetUser ({assemblyName})' " + "- Route Template: '!!!' - " + "HTTP Verbs: ''" + Environment.NewLine + Environment.NewLine + "Use 'AcceptVerbsAttribute' to create a single route that allows multiple HTTP verbs and defines a " + "route, or set a route template in all attributes that constrain HTTP verbs."; // Act var exception = Assert.Throws<InvalidOperationException>(() => provider.GetDescriptors()); // Assert VerifyMultiLineError(expectedMessage, exception.Message, unorderedStart: 1, unorderedLineCount: 2); } [Fact] public void AttributeRouting_RouteOnControllerAndAction_CreatesActionDescriptorWithoutHttpConstraints() { // Arrange var provider = GetProvider(typeof(OnlyRouteController).GetTypeInfo()); // Act var actions = provider.GetDescriptors(); // Assert var action = Assert.Single(actions); Assert.Equal("Action", action.ActionName); Assert.Equal("OnlyRoute", action.ControllerName); Assert.NotNull(action.AttributeRouteInfo); Assert.Equal("Products/Index", action.AttributeRouteInfo.Template); Assert.Null(action.ActionConstraints); } [Fact] public void AttributeRouting_Name_ThrowsIfMultipleActions_WithDifferentTemplatesHaveTheSameName() { // Arrange var sameNameType = typeof(SameNameDifferentTemplatesController).GetTypeInfo(); var provider = GetProvider(sameNameType); var assemblyName = sameNameType.Assembly.GetName().Name; var expectedMessage = "The following errors occurred with attribute routing information:" + Environment.NewLine + Environment.NewLine + "Error 1:" + Environment.NewLine + "Attribute routes with the same name 'Products' must have the same template:" + Environment.NewLine + $"Action: '{sameNameType.FullName}.Get ({assemblyName})' - Template: 'Products'" + Environment.NewLine + $"Action: '{sameNameType.FullName}.Get ({assemblyName})' - Template: 'Products/{{id}}'" + Environment.NewLine + $"Action: '{sameNameType.FullName}.Put ({assemblyName})' - Template: 'Products/{{id}}'" + Environment.NewLine + $"Action: '{sameNameType.FullName}.Post ({assemblyName})' - Template: 'Products'" + Environment.NewLine + $"Action: '{sameNameType.FullName}.Delete ({assemblyName})' - Template: 'Products/{{id}}'" + Environment.NewLine + Environment.NewLine + "Error 2:" + Environment.NewLine + "Attribute routes with the same name 'Items' must have the same template:" + Environment.NewLine + $"Action: '{sameNameType.FullName}.GetItems ({assemblyName})' - Template: 'Items/{{id}}'" + Environment.NewLine + $"Action: '{sameNameType.FullName}.PostItems ({assemblyName})' - Template: 'Items'" + Environment.NewLine + $"Action: '{sameNameType.FullName}.PutItems ({assemblyName})' - Template: 'Items/{{id}}'" + Environment.NewLine + $"Action: '{sameNameType.FullName}.DeleteItems ({assemblyName})' - Template: 'Items/{{id}}'" + Environment.NewLine + $"Action: '{sameNameType.FullName}.PatchItems ({assemblyName})' - Template: 'Items'"; // Act var ex = Assert.Throws<InvalidOperationException>(() => { provider.GetDescriptors(); }); // Assert Assert.Equal(expectedMessage, ex.Message); } [Fact] public void AttributeRouting_Name_AllowsMultipleAttributeRoutesInDifferentActions_WithTheSameNameAndTemplate() { // Arrange var provider = GetProvider(typeof(DifferentCasingsAttributeRouteNamesController).GetTypeInfo()); // Act var descriptors = provider.GetDescriptors(); // Assert foreach (var descriptor in descriptors) { Assert.NotNull(descriptor.AttributeRouteInfo); Assert.Equal("{id}", descriptor.AttributeRouteInfo.Template, StringComparer.OrdinalIgnoreCase); Assert.Equal("Products", descriptor.AttributeRouteInfo.Name, StringComparer.OrdinalIgnoreCase); } } [Fact] public void AttributeRouting_RouteNameTokenReplace_AllowsMultipleActions_WithSameRouteNameTemplate() { // Arrange var provider = GetProvider(typeof(ActionRouteNameTemplatesController).GetTypeInfo()); var editActionName = nameof(ActionRouteNameTemplatesController.Edit); var getActionName = nameof(ActionRouteNameTemplatesController.Get); // Act var actions = provider.GetDescriptors(); // Assert var getActions = actions.Where(a => a.ActionName.Equals(getActionName)); Assert.Equal(2, getActions.Count()); foreach (var getAction in getActions) { Assert.NotNull(getAction.AttributeRouteInfo); Assert.Equal("Products/Get", getAction.AttributeRouteInfo.Template, StringComparer.OrdinalIgnoreCase); Assert.Equal("Products_Get", getAction.AttributeRouteInfo.Name, StringComparer.OrdinalIgnoreCase); } var editAction = Assert.Single(actions, a => a.ActionName.Equals(editActionName)); Assert.NotNull(editAction.AttributeRouteInfo); Assert.Equal("Products/Edit", editAction.AttributeRouteInfo.Template, StringComparer.OrdinalIgnoreCase); Assert.Equal("Products_Edit", editAction.AttributeRouteInfo.Name, StringComparer.OrdinalIgnoreCase); } [Fact] public void AttributeRouting_RouteNameTokenReplace_AreaControllerActionTokensInRoute() { // Arrange var provider = GetProvider(typeof(ControllerActionRouteNameTemplatesController).GetTypeInfo()); var editActionName = nameof(ControllerActionRouteNameTemplatesController.Edit); var getActionName = nameof(ControllerActionRouteNameTemplatesController.Get); // Act var actions = provider.GetDescriptors(); // Assert var getActions = actions.Where(a => a.ActionName.Equals(getActionName)); Assert.Equal(2, getActions.Count()); foreach (var getAction in getActions) { Assert.NotNull(getAction.AttributeRouteInfo); Assert.Equal( "ControllerActionRouteNameTemplates/Get", getAction.AttributeRouteInfo.Template, StringComparer.OrdinalIgnoreCase); Assert.Equal( "Products_ControllerActionRouteNameTemplates_Get", getAction.AttributeRouteInfo.Name, StringComparer.OrdinalIgnoreCase); } var editAction = Assert.Single(actions, a => a.ActionName.Equals(editActionName)); Assert.NotNull(editAction.AttributeRouteInfo); Assert.Equal( "ControllerActionRouteNameTemplates/Edit", editAction.AttributeRouteInfo.Template, StringComparer.OrdinalIgnoreCase); Assert.Equal( "Products_ControllerActionRouteNameTemplates_Edit", editAction.AttributeRouteInfo.Name, StringComparer.OrdinalIgnoreCase); } [Fact] public void AttributeRouting_RouteNameTokenReplace_InvalidToken() { // Arrange var controllerTypeInfo = typeof(RouteNameIncorrectTokenController).GetTypeInfo(); var assemblyName = controllerTypeInfo.Assembly.GetName().Name; var provider = GetProvider(controllerTypeInfo); var expectedMessage = "The following errors occurred with attribute routing information:" + Environment.NewLine + Environment.NewLine + "Error 1:" + Environment.NewLine + $"For action: '{controllerTypeInfo.FullName}.Get ({assemblyName})'" + Environment.NewLine + "Error: While processing template 'Products_[unknown]', a replacement value for the token 'unknown' " + "could not be found. Available tokens: 'action, controller'. To use a '[' or ']' as a literal string" + " in a route or within a constraint, use '[[' or ']]' instead."; // Act & Assert var ex = Assert.Throws<InvalidOperationException>(() => { provider.GetDescriptors(); }); Assert.Equal(expectedMessage, ex.Message); } [Fact] public void AttributeRouting_AddsDefaultRouteValues_ForAttributeRoutedActions() { // Arrange var provider = GetProvider( typeof(ConventionalAndAttributeRoutedActionsWithAreaController).GetTypeInfo(), typeof(ConstrainedController).GetTypeInfo()); // Act var actionDescriptors = provider.GetDescriptors(); // Assert Assert.NotNull(actionDescriptors); Assert.Equal(4, actionDescriptors.Count()); var indexAction = Assert.Single(actionDescriptors, ad => ad.ActionName.Equals("Index")); Assert.Equal(3, indexAction.RouteValues.Count); var controllerDefault = Assert.Single(indexAction.RouteValues, rd => rd.Key.Equals("controller", StringComparison.OrdinalIgnoreCase)); Assert.Equal("ConventionalAndAttributeRoutedActionsWithArea", controllerDefault.Value); var actionDefault = Assert.Single(indexAction.RouteValues, rd => rd.Key.Equals("action", StringComparison.OrdinalIgnoreCase)); Assert.Equal("Index", actionDefault.Value); var areaDefault = Assert.Single(indexAction.RouteValues, rd => rd.Key.Equals("area", StringComparison.OrdinalIgnoreCase)); Assert.Equal("Home", areaDefault.Value); } [Fact] public void AttributeRouting_TokenReplacement_CaseInsensitive() { // Arrange var provider = GetProvider(typeof(CaseInsensitiveController).GetTypeInfo()); // Act var actions = provider.GetDescriptors(); // Assert var action = Assert.Single(actions); Assert.Equal("stub/ThisIsAnAction", action.AttributeRouteInfo.Template); } // Parameters are validated later. This action uses the forbidden {action} and {controller} [Fact] public void AttributeRouting_DoesNotValidateParameters() { // Arrange var provider = GetProvider(typeof(InvalidParametersController).GetTypeInfo()); // Act var actions = provider.GetDescriptors(); // Assert var action = Assert.Single(actions); Assert.Equal("stub/{controller}/{action}", action.AttributeRouteInfo.Template); } [Fact] public void ApiExplorer_SetsExtensionData_WhenVisible() { // Arrange var provider = GetProvider(typeof(ApiExplorerVisibleController).GetTypeInfo()); // Act var actions = provider.GetDescriptors(); // Assert var action = Assert.Single(actions); Assert.NotNull(action.GetProperty<ApiDescriptionActionData>()); } [Fact] public void ApiExplorer_SetsExtensionData_WhenVisible_CanOverrideControllerOnAction() { // Arrange var provider = GetProvider(typeof(ApiExplorerVisibilityOverrideController).GetTypeInfo()); // Act var actions = provider.GetDescriptors(); // Assert Assert.Equal(2, actions.Count()); var action = Assert.Single(actions, a => a.ActionName == "Edit"); Assert.NotNull(action.GetProperty<ApiDescriptionActionData>()); action = Assert.Single(actions, a => a.ActionName == "Create"); Assert.Null(action.GetProperty<ApiDescriptionActionData>()); } [Theory] [InlineData(typeof(ApiExplorerNotVisibleController))] [InlineData(typeof(ApiExplorerExplicitlyNotVisibleController))] [InlineData(typeof(ApiExplorerExplicitlyNotVisibleOnActionController))] public void ApiExplorer_DoesNotSetExtensionData_WhenNotVisible(Type controllerType) { // Arrange var provider = GetProvider(controllerType.GetTypeInfo()); // Act var actions = provider.GetDescriptors(); // Assert var action = Assert.Single(actions); Assert.Null(action.GetProperty<ApiDescriptionActionData>()); } [Fact] public void ApiExplorer_SetsName_DefaultToNull() { // Arrange var provider = GetProvider(typeof(ApiExplorerNoNameController).GetTypeInfo()); // Act var actions = provider.GetDescriptors(); // Assert var action = Assert.Single(actions); Assert.Null(action.GetProperty<ApiDescriptionActionData>().GroupName); } [Fact] public void ApiExplorer_SetsName_OnController() { // Arrange var provider = GetProvider(typeof(ApiExplorerNameOnControllerController).GetTypeInfo()); // Act var actions = provider.GetDescriptors(); // Assert var action = Assert.Single(actions); Assert.Equal("Store", action.GetProperty<ApiDescriptionActionData>().GroupName); } [Fact] public void ApiExplorer_SetsName_OnAction() { // Arrange var provider = GetProvider(typeof(ApiExplorerNameOnActionController).GetTypeInfo()); // Act var actions = provider.GetDescriptors(); // Assert var action = Assert.Single(actions); Assert.Equal("Blog", action.GetProperty<ApiDescriptionActionData>().GroupName); } [Fact] public void ApiExplorer_SetsName_CanOverrideControllerOnAction() { // Arrange var provider = GetProvider(typeof(ApiExplorerNameOverrideController).GetTypeInfo()); // Act var actions = provider.GetDescriptors(); // Assert Assert.Equal(2, actions.Count()); var action = Assert.Single(actions, a => a.ActionName == "Edit"); Assert.Equal("Blog", action.GetProperty<ApiDescriptionActionData>().GroupName); action = Assert.Single(actions, a => a.ActionName == "Create"); Assert.Equal("Store", action.GetProperty<ApiDescriptionActionData>().GroupName); } [Fact] public void ApiExplorer_IsVisibleOnApplication_CanOverrideOnController() { // Arrange var convention = new ApiExplorerIsVisibleConvention(isVisible: true); var provider = GetProvider(typeof(ApiExplorerExplicitlyNotVisibleController).GetTypeInfo(), convention); // Act var actions = provider.GetDescriptors(); // Assert var action = Assert.Single(actions); Assert.Null(action.GetProperty<ApiDescriptionActionData>()); } [Fact] public void ApiExplorer_IsVisibleOnApplication_CanOverrideOnAction() { // Arrange var convention = new ApiExplorerIsVisibleConvention(isVisible: true); var provider = GetProvider( typeof(ApiExplorerExplicitlyNotVisibleOnActionController).GetTypeInfo(), convention); // Act var actions = provider.GetDescriptors(); // Assert var action = Assert.Single(actions); Assert.Null(action.GetProperty<ApiDescriptionActionData>()); } [Theory] [InlineData("A", typeof(ApiExplorerEnabledConventionalRoutedController))] [InlineData("A", typeof(ApiExplorerEnabledActionConventionalRoutedController))] public void ApiExplorer_ThrowsForConventionalRouting(string actionName, Type type) { // Arrange var assemblyName = type.GetTypeInfo().Assembly.GetName().Name; var expected = $"The action '{type.FullName}.{actionName} ({assemblyName})' has ApiExplorer enabled, but is using conventional routing. " + "Only actions which use attribute routing support ApiExplorer."; var provider = GetProvider(type.GetTypeInfo()); // Act & Assert var ex = Assert.Throws<InvalidOperationException>(() => provider.GetDescriptors()); Assert.Equal(expected, ex.Message); } [Fact] public void ApiExplorer_SkipsConventionalRoutedController_WhenConfiguredOnApplication() { // Arrange var convention = new ApiExplorerIsVisibleConvention(isVisible: true); var provider = GetProvider( typeof(ConventionallyRoutedController).GetTypeInfo(), convention); // Act var actions = provider.GetDescriptors(); // Assert var action = Assert.Single(actions); Assert.Null(action.GetProperty<ApiDescriptionActionData>()); } // Verifies the sequence of conventions running [Fact] public void ApplyConventions_RunsInOrderOfDecreasingScope() { // Arrange var sequence = 0; var applicationConvention = new Mock<IApplicationModelConvention>(); applicationConvention .Setup(c => c.Apply(It.IsAny<ApplicationModel>())) .Callback(() => { Assert.Equal(0, sequence++); }); var controllerConvention = new Mock<IControllerModelConvention>(); controllerConvention .Setup(c => c.Apply(It.IsAny<ControllerModel>())) .Callback(() => { Assert.Equal(1, sequence++); }); var actionConvention = new Mock<IActionModelConvention>(); actionConvention .Setup(c => c.Apply(It.IsAny<ActionModel>())) .Callback(() => { Assert.Equal(2, sequence++); }); var parameterConvention = new Mock<IParameterModelConvention>(); parameterConvention .Setup(c => c.Apply(It.IsAny<ParameterModel>())) .Callback(() => { Assert.Equal(3, sequence++); }); var options = Options.Create(new MvcOptions()); options.Value.Conventions.Add(applicationConvention.Object); var applicationModel = new ApplicationModel(); var controller = new ControllerModel(typeof(ConventionsController).GetTypeInfo(), new List<object>() { controllerConvention.Object }); controller.Application = applicationModel; applicationModel.Controllers.Add(controller); var methodInfo = typeof(ConventionsController).GetMethod("Create"); var actionModel = new ActionModel(methodInfo, new List<object>() { actionConvention.Object }); actionModel.Controller = controller; controller.Actions.Add(actionModel); var parameterInfo = actionModel.ActionMethod.GetParameters().Single(); var parameterModel = new ParameterModel(parameterInfo, new List<object>() { parameterConvention.Object }); parameterModel.Action = actionModel; actionModel.Parameters.Add(parameterModel); // Act ApplicationModelConventions.ApplyConventions(applicationModel, options.Value.Conventions); // Assert Assert.Equal(4, sequence); } [Fact] public void GetDescriptors_SplitsConstraintsBasedOnRoute() { // Arrange var provider = GetProvider(typeof(MultipleRouteProviderOnActionController).GetTypeInfo()); // Act var actions = provider.GetDescriptors(); // Assert Assert.Equal(2, actions.Count()); var action = Assert.Single(actions, a => a.AttributeRouteInfo.Template == "R1"); Assert.Equal(2, action.ActionConstraints.Count); Assert.Single(action.ActionConstraints, a => a is RouteAndConstraintAttribute); Assert.Single(action.ActionConstraints, a => a is ConstraintAttribute); action = Assert.Single(actions, a => a.AttributeRouteInfo.Template == "R2"); Assert.Equal(2, action.ActionConstraints.Count); Assert.Single(action.ActionConstraints, a => a is RouteAndConstraintAttribute); Assert.Single(action.ActionConstraints, a => a is ConstraintAttribute); } [Fact] public void GetDescriptors_SplitsConstraintsBasedOnControllerRoute() { // Arrange var actionName = nameof(MultipleRouteProviderOnActionAndControllerController.Edit); var provider = GetProvider(typeof(MultipleRouteProviderOnActionAndControllerController).GetTypeInfo()); // Act var actions = provider.GetDescriptors().Where(a => a.ActionName == actionName); // Assert Assert.Equal(2, actions.Count()); var action = Assert.Single(actions, a => a.AttributeRouteInfo.Template == "C1/A1"); Assert.Equal(3, action.ActionConstraints.Count); Assert.Single(action.ActionConstraints, a => (a as RouteAndConstraintAttribute)?.Template == "C1"); Assert.Single(action.ActionConstraints, a => (a as RouteAndConstraintAttribute)?.Template == "A1"); Assert.Single(action.ActionConstraints, a => a is ConstraintAttribute); action = Assert.Single(actions, a => a.AttributeRouteInfo.Template == "C2/A1"); Assert.Equal(3, action.ActionConstraints.Count); Assert.Single(action.ActionConstraints, a => (a as RouteAndConstraintAttribute)?.Template == "C2"); Assert.Single(action.ActionConstraints, a => (a as RouteAndConstraintAttribute)?.Template == "A1"); Assert.Single(action.ActionConstraints, a => a is ConstraintAttribute); } [Fact] public void GetDescriptors_SplitsConstraintsBasedOnControllerRoute_MultipleRoutesOnAction() { // Arrange var actionName = nameof(MultipleRouteProviderOnActionAndControllerController.Delete); var provider = GetProvider(typeof(MultipleRouteProviderOnActionAndControllerController).GetTypeInfo()); // Act var actions = provider.GetDescriptors().Where(a => a.ActionName == actionName); // Assert Assert.Equal(4, actions.Count()); var action = Assert.Single(actions, a => a.AttributeRouteInfo.Template == "C1/A3"); Assert.Equal(3, action.ActionConstraints.Count); Assert.Single(action.ActionConstraints, a => (a as RouteAndConstraintAttribute)?.Template == "C1"); Assert.Single(action.ActionConstraints, a => (a as RouteAndConstraintAttribute)?.Template == "A3"); Assert.Single(action.ActionConstraints, a => a is ConstraintAttribute); action = Assert.Single(actions, a => a.AttributeRouteInfo.Template == "C2/A3"); Assert.Equal(3, action.ActionConstraints.Count); Assert.Single(action.ActionConstraints, a => (a as RouteAndConstraintAttribute)?.Template == "C2"); Assert.Single(action.ActionConstraints, a => (a as RouteAndConstraintAttribute)?.Template == "A3"); Assert.Single(action.ActionConstraints, a => a is ConstraintAttribute); action = Assert.Single(actions, a => a.AttributeRouteInfo.Template == "C1/A4"); Assert.Equal(3, action.ActionConstraints.Count); Assert.Single(action.ActionConstraints, a => (a as RouteAndConstraintAttribute)?.Template == "C1"); Assert.Single(action.ActionConstraints, a => (a as RouteAndConstraintAttribute)?.Template == "A4"); Assert.Single(action.ActionConstraints, a => a is ConstraintAttribute); action = Assert.Single(actions, a => a.AttributeRouteInfo.Template == "C2/A4"); Assert.Equal(3, action.ActionConstraints.Count); Assert.Single(action.ActionConstraints, a => (a as RouteAndConstraintAttribute)?.Template == "C2"); Assert.Single(action.ActionConstraints, a => (a as RouteAndConstraintAttribute)?.Template == "A4"); Assert.Single(action.ActionConstraints, a => a is ConstraintAttribute); } // This method overrides the route from the controller, and so doesn't inherit its metadata. [Fact] public void GetDescriptors_SplitsConstraintsBasedOnControllerRoute_Override() { // Arrange var actionName = nameof(MultipleRouteProviderOnActionAndControllerController.Create); var provider = GetProvider(typeof(MultipleRouteProviderOnActionAndControllerController).GetTypeInfo()); // Act var actions = provider.GetDescriptors().Where(a => a.ActionName == actionName); // Assert Assert.Single(actions); var action = Assert.Single(actions, a => a.AttributeRouteInfo.Template == "A2"); Assert.Equal(2, action.ActionConstraints.Count); Assert.Single(action.ActionConstraints, a => (a as RouteAndConstraintAttribute)?.Template == "~/A2"); Assert.Single(action.ActionConstraints, a => a is ConstraintAttribute); } [Fact] public void OnProviderExecuted_AddsGlobalRouteValues() { // Arrange var context = new ActionDescriptorProviderContext(); context.Results.Add(new ActionDescriptor() { RouteValues = new Dictionary<string, string>() { { "controller", "Home" }, { "action", "Index" }, } }); context.Results.Add(new ActionDescriptor() { RouteValues = new Dictionary<string, string>() { { "page", "/Some/Page" } } }); var provider = GetProvider(); // Act provider.OnProvidersExecuted(context); // Assert Assert.True(context.Results[0].RouteValues.ContainsKey("page")); Assert.Null(context.Results[0].RouteValues["page"]); Assert.True(context.Results[1].RouteValues.ContainsKey("controller")); Assert.Null(context.Results[1].RouteValues["controller"]); Assert.True(context.Results[1].RouteValues.ContainsKey("action")); Assert.Null(context.Results[1].RouteValues["action"]); } private ControllerActionDescriptorProvider GetProvider( TypeInfo controllerTypeInfo, IEnumerable<IFilterMetadata> filters = null) { var options = Options.Create(new MvcOptions()); if (filters != null) { foreach (var filter in filters) { options.Value.Filters.Add(filter); } } var manager = GetApplicationManager(new[] { controllerTypeInfo }); var modelProvider = new DefaultApplicationModelProvider(options, new EmptyModelMetadataProvider()); var provider = new ControllerActionDescriptorProvider( manager, new ApplicationModelFactory(new[] { modelProvider }, options)); return provider; } private ControllerActionDescriptorProvider GetProvider( params TypeInfo[] controllerTypeInfos) { var options = Options.Create(new MvcOptions()); var manager = GetApplicationManager(controllerTypeInfos); var modelProvider = new DefaultApplicationModelProvider(options, new EmptyModelMetadataProvider()); var provider = new ControllerActionDescriptorProvider( manager, new ApplicationModelFactory(new[] { modelProvider }, options)); return provider; } private ControllerActionDescriptorProvider GetProvider( TypeInfo controllerTypeInfo, IApplicationModelConvention convention) { var options = Options.Create(new MvcOptions()); options.Value.Conventions.Add(convention); var manager = GetApplicationManager(new[] { controllerTypeInfo }); var modelProvider = new DefaultApplicationModelProvider(options, new EmptyModelMetadataProvider()); var provider = new ControllerActionDescriptorProvider( manager, new ApplicationModelFactory(new[] { modelProvider }, options)); return provider; } private static ApplicationPartManager GetApplicationManager(IEnumerable<TypeInfo> controllerTypes) { var manager = new ApplicationPartManager(); manager.ApplicationParts.Add(new TestApplicationPart(controllerTypes)); manager.FeatureProviders.Add(new TestFeatureProvider()); return manager; } private IEnumerable<ActionDescriptor> GetDescriptors(params TypeInfo[] controllerTypeInfos) { var provider = GetProvider(controllerTypeInfos); return provider.GetDescriptors(); } private static void VerifyMultiLineError( string expectedMessage, string actualMessage, int unorderedStart, int unorderedLineCount) { var expectedLines = expectedMessage .Split(new[] { Environment.NewLine }, StringSplitOptions.None) .ToArray(); var actualLines = actualMessage .Split(new[] { Environment.NewLine }, StringSplitOptions.None) .ToArray(); for (var i = 0; i < unorderedStart; i++) { Assert.Equal(expectedLines[i], actualLines[i]); } var orderedExpectedLines = expectedLines .Skip(unorderedStart) .Take(unorderedLineCount) .OrderBy(l => l, StringComparer.Ordinal) .ToArray(); var orderedActualLines = actualLines .Skip(unorderedStart) .Take(unorderedLineCount) .OrderBy(l => l, StringComparer.Ordinal) .ToArray(); for (var i = 0; i < unorderedLineCount; i++) { Assert.Equal(orderedExpectedLines[i], orderedActualLines[i]); } for (var i = unorderedStart + unorderedLineCount; i < expectedLines.Length; i++) { Assert.Equal(expectedLines[i], actualLines[i]); } Assert.Equal(expectedLines.Length, actualLines.Length); } private class HttpMethodController { [HttpPost] public void OnlyPost() { } } [Route("Items")] private class AttributeRoutedHttpMethodController { [CustomHttpMethodConstraint("PUT", "PATCH")] public void PutOrPatch() { } } private class PersonController { public void GetPerson() { } [ActionName("ShowPeople")] public void ListPeople() { } [NonAction] public void NotAnAction() { } } private class MyRouteValueAttribute : RouteValueAttribute { public MyRouteValueAttribute() : base("key", "value") { } } private class MySecondRouteValueAttribute : RouteValueAttribute { public MySecondRouteValueAttribute() : base("second", "value") { } } [MyRouteValue] private class RouteValueController { public void Edit() { } } private class MyFilterAttribute : Attribute, IFilterMetadata { public MyFilterAttribute(int value) { Value = value; } public int Value { get; private set; } } [MyFilter(2)] private class FiltersController { [MyFilter(3)] public void FilterAction() { } } [Route("api/Token/[key]/[controller]")] [MyRouteValue] private class TokenReplacementController { [HttpGet("stub/[action]")] public void ThisIsAnAction() { } } private class CaseInsensitiveController { [HttpGet("stub/[ActIon]")] public void ThisIsAnAction() { } } private class MultipleErrorsController { [HttpGet("stub/[action]/[unknown]")] public void Unknown() { } [HttpGet("[invalid/syntax")] public void Invalid() { } } private class InvalidParametersController { [HttpGet("stub/{controller}/{action}")] public void Action1() { } } private class SameGroupIdController { [HttpGet("stub/[action]")] public void Action1() { } [HttpGet("stub/Action1")] public void Action2() { } } [Area("Home")] private class ConventionalAndAttributeRoutedActionsWithAreaController { [HttpGet("Index")] public void Index() { } [HttpGet("Edit")] public void Edit() { } public void AnotherNonAttributedAction() { } } [Route("Products", Name = "Products")] private class SameNameDifferentTemplatesController { [HttpGet] public void Get() { } [HttpGet("{id}", Name = "Products")] public void Get(int id) { } [HttpPut("{id}", Name = "Products")] public void Put(int id) { } [HttpPost] public void Post() { } [HttpDelete("{id}", Name = "Products")] public void Delete(int id) { } [HttpGet("/Items/{id}", Name = "Items")] public void GetItems(int id) { } [HttpPost("/Items", Name = "Items")] public void PostItems() { } [HttpPut("/Items/{id}", Name = "Items")] public void PutItems(int id) { } [HttpDelete("/Items/{id}", Name = "Items")] public void DeleteItems(int id) { } [HttpPatch("/Items", Name = "Items")] public void PatchItems() { } } [Route("Products/[action]", Name = "Products_[action]")] private class ActionRouteNameTemplatesController { [HttpGet] public void Get() { } [HttpPost] public void Get(int id) { } public void Edit() { } } [Area("Products")] [Route("[controller]/[action]", Name = "[area]_[controller]_[action]")] private class ControllerActionRouteNameTemplatesController { [HttpGet] public void Get() { } [HttpPost] public void Get(int id) { } public void Edit() { } } [Route("Products/[action]", Name = "Products_[unknown]")] private class RouteNameIncorrectTokenController { public void Get() { } } private class DifferentCasingsAttributeRouteNamesController { [HttpGet("{id}", Name = "Products")] public void Get() { } [HttpGet("{ID}", Name = "Products")] public void Get(int id) { } [HttpPut("{id}", Name = "PRODUCTS")] public void Put(int id) { } [HttpDelete("{ID}", Order = 1, Name = "PRODUCTS")] public void Delete(int id) { } } [Route("v1")] [Route("v2")] public class MultiRouteAttributesController { [HttpGet("List")] [HttpGet("All")] public void MultipleHttpGet() { } [AcceptVerbs("POST", Route = "List")] public void AcceptVerbs() { } [AcceptVerbs("PUT", Route = "/Override")] public void AcceptVerbsOverride() { } [AcceptVerbs("POST")] [Route("List")] [HttpPut("All")] public void AcceptVerbsRouteAttributeAndHttpPut() { } [AcceptVerbs("POST", Route = "")] [Route("List")] [HttpPut("All")] public void AcceptVerbsRouteAttributeWithTemplateAndHttpPut() { } } [Route("Products")] public class OnlyRouteController { [Route("Index")] public void Action() { } } public class AttributeAndNonAttributeRoutedActionsOnSameMethodController { [HttpGet("AttributeRouted")] [HttpPost] [AcceptVerbs("PUT", "PATCH")] [CustomHttpMethodConstraint("DELETE")] public void Method() { } } [Route("Product")] [Route("/Product")] [Route("/product")] public class DuplicatedAttributeRouteController { [HttpGet("/List")] [HttpGet("/List")] public void Action() { } public void Controller() { } [HttpPut("list")] [PutOrPatch("list")] public void CommonHttpMethod() { } } [Route("Products")] public class NonDuplicatedAttributeRouteController { [HttpGet("list")] public void ControllerAndAction() { } [HttpGet("/PRODUCTS/LIST")] public void OverrideOnAction() { } [HttpGet("list")] [HttpPost("list")] [HttpPut("list")] [HttpPatch("list")] [HttpDelete("list")] public void DifferentHttpMethods() { } } [MyRouteValue] [MySecondRouteValue] private class ConstrainedController { public void ConstrainedNonAttributedAction() { } } private class ActionParametersController { public void RequiredInt(int id) { } public void FromBodyParameter([FromBody] TestActionParameter entity) { } public void NotFromBodyParameter(TestActionParameter entity) { } public void MultipleParameters(int id, [FromBody] TestActionParameter entity) { } public void DifferentCasing(int id, int ID, int Id) { } } private class ConventionallyRoutedController { public void ConventionalAction() { } } [Route("api")] private class AttributeRoutedController { [HttpGet("AttributeRoute")] public void AttributeRoutedAction() { } } [Authorize("ControllerPolicy")] private class AuthorizeController { [AllowAnonymous] public void AllowAnonymousAction() { } [Authorize("ActionPolicy")] public void AuthorizeAction() { } } private class EmptyController { } private class NonActionAttributeController { [NonAction] public void Action() { } } private class CustomHttpMethodConstraintAttribute : Attribute, IActionHttpMethodProvider { private readonly string[] _methods; public CustomHttpMethodConstraintAttribute(params string[] methods) { _methods = methods; } public IEnumerable<string> HttpMethods { get { return _methods; } } } private class PutOrPatchAttribute : HttpMethodAttribute { private static readonly string[] _httpMethods = new string[] { "PUT", "PATCH" }; public PutOrPatchAttribute(string template) : base(_httpMethods, template) { } } private class TestActionParameter { public int Id { get; set; } public int Name { get; set; } } [Route("AttributeRouting/IsRequired/ForApiExplorer")] private class ApiExplorerNotVisibleController { public void Edit() { } } [Route("AttributeRouting/IsRequired/ForApiExplorer")] [ApiExplorerSettings()] private class ApiExplorerVisibleController { public void Edit() { } } [Route("AttributeRouting/IsRequired/ForApiExplorer")] [ApiExplorerSettings(IgnoreApi = true)] private class ApiExplorerExplicitlyNotVisibleController { public void Edit() { } } [Route("AttributeRouting/IsRequired/ForApiExplorer")] private class ApiExplorerExplicitlyNotVisibleOnActionController { [ApiExplorerSettings(IgnoreApi = true)] public void Edit() { } } [Route("AttributeRouting/IsRequired/ForApiExplorer")] [ApiExplorerSettings(IgnoreApi = true)] private class ApiExplorerVisibilityOverrideController { [ApiExplorerSettings(IgnoreApi = false)] public void Edit() { } public void Create() { } } [Route("AttributeRouting/IsRequired/ForApiExplorer")] [ApiExplorerSettings(GroupName = "Store")] private class ApiExplorerNameOnControllerController { public void Edit() { } } [Route("AttributeRouting/IsRequired/ForApiExplorer")] private class ApiExplorerNameOnActionController { [ApiExplorerSettings(GroupName = "Blog")] public void Edit() { } } [Route("AttributeRouting/IsRequired/ForApiExplorer")] [ApiExplorerSettings()] private class ApiExplorerNoNameController { public void Edit() { } } [Route("AttributeRouting/IsRequired/ForApiExplorer")] [ApiExplorerSettings(GroupName = "Store")] private class ApiExplorerNameOverrideController { [ApiExplorerSettings(GroupName = "Blog")] public void Edit() { } public void Create() { } } private class ConventionsController { public void Create(int productId) { } } private class MultipleRouteProviderOnActionController { [Constraint] [RouteAndConstraint("R1")] [RouteAndConstraint("R2")] public void Edit() { } } [Constraint] [RouteAndConstraint("C1")] [RouteAndConstraint("C2")] private class MultipleRouteProviderOnActionAndControllerController { [RouteAndConstraint("A1")] public void Edit() { } [RouteAndConstraint("~/A2")] public void Create() { } [RouteAndConstraint("A3")] [RouteAndConstraint("A4")] public void Delete() { } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] private class RouteAndConstraintAttribute : Attribute, IActionConstraintMetadata, IRouteTemplateProvider { public RouteAndConstraintAttribute(string template) { Template = template; } public string Name { get; set; } public int? Order { get; set; } public string Template { get; private set; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] private class ConstraintAttribute : Attribute, IActionConstraintMetadata { } [ApiExplorerSettings(GroupName = "Default")] private class ApiExplorerEnabledConventionalRoutedController { public void A() { } } [ApiExplorerSettings(IgnoreApi = true)] private class ApiExplorerEnabledActionConventionalRoutedController { [ApiExplorerSettings(GroupName = "Default")] public void A() { } } private class ApiExplorerIsVisibleConvention : IApplicationModelConvention { private readonly bool _isVisible; public ApiExplorerIsVisibleConvention(bool isVisible) { _isVisible = isVisible; } public void Apply(ApplicationModel application) { application.ApiExplorer.IsVisible = _isVisible; } } private class MixedRoutingConventionAttribute : Attribute, IActionModelConvention { public void Apply(ActionModel action) { action.Selectors.Add(new SelectorModel() { AttributeRouteModel = new AttributeRouteModel() { Template = "/!!!", } }); } } private class UserController : ControllerBase { [MixedRoutingConvention] public string GetUser(int id) { return string.Format(CultureInfo.InvariantCulture, "User {0} retrieved successfully", id); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Rulesets.UI; using osu.Game.Screens.OnlinePlay.Multiplayer.Spectate; using osu.Game.Screens.Play; using osu.Game.Tests.Beatmaps.IO; namespace osu.Game.Tests.Visual.Multiplayer { public class TestSceneMultiSpectatorScreen : MultiplayerTestScene { [Resolved] private OsuGameBase game { get; set; } [Resolved] private BeatmapManager beatmapManager { get; set; } private MultiSpectatorScreen spectatorScreen; private readonly List<int> playingUserIds = new List<int>(); private BeatmapSetInfo importedSet; private BeatmapInfo importedBeatmap; private int importedBeatmapId; [BackgroundDependencyLoader] private void load() { importedSet = ImportBeatmapTest.LoadOszIntoOsu(game, virtualTrack: true).Result; importedBeatmap = importedSet.Beatmaps.First(b => b.RulesetID == 0); importedBeatmapId = importedBeatmap.OnlineBeatmapID ?? -1; } [SetUp] public new void Setup() => Schedule(() => playingUserIds.Clear()); [Test] public void TestDelayedStart() { AddStep("start players silently", () => { Client.CurrentMatchPlayingUserIds.Add(PLAYER_1_ID); Client.CurrentMatchPlayingUserIds.Add(PLAYER_2_ID); playingUserIds.Add(PLAYER_1_ID); playingUserIds.Add(PLAYER_2_ID); }); loadSpectateScreen(false); AddWaitStep("wait a bit", 10); AddStep("load player first_player_id", () => SpectatorClient.StartPlay(PLAYER_1_ID, importedBeatmapId)); AddUntilStep("one player added", () => spectatorScreen.ChildrenOfType<Player>().Count() == 1); AddWaitStep("wait a bit", 10); AddStep("load player second_player_id", () => SpectatorClient.StartPlay(PLAYER_2_ID, importedBeatmapId)); AddUntilStep("two players added", () => spectatorScreen.ChildrenOfType<Player>().Count() == 2); } [Test] public void TestGeneral() { int[] userIds = Enumerable.Range(0, 4).Select(i => PLAYER_1_ID + i).ToArray(); start(userIds); loadSpectateScreen(); sendFrames(userIds, 1000); AddWaitStep("wait a bit", 20); } [Test] public void TestTimeDoesNotProgressWhileAllPlayersPaused() { start(new[] { PLAYER_1_ID, PLAYER_2_ID }); loadSpectateScreen(); sendFrames(PLAYER_1_ID, 40); sendFrames(PLAYER_2_ID, 20); checkPaused(PLAYER_2_ID, true); checkPausedInstant(PLAYER_1_ID, false); AddAssert("master clock still running", () => this.ChildrenOfType<MasterGameplayClockContainer>().Single().IsRunning); checkPaused(PLAYER_1_ID, true); AddUntilStep("master clock paused", () => !this.ChildrenOfType<MasterGameplayClockContainer>().Single().IsRunning); } [Test] public void TestPlayersMustStartSimultaneously() { start(new[] { PLAYER_1_ID, PLAYER_2_ID }); loadSpectateScreen(); // Send frames for one player only, both should remain paused. sendFrames(PLAYER_1_ID, 20); checkPausedInstant(PLAYER_1_ID, true); checkPausedInstant(PLAYER_2_ID, true); // Send frames for the other player, both should now start playing. sendFrames(PLAYER_2_ID, 20); checkPausedInstant(PLAYER_1_ID, false); checkPausedInstant(PLAYER_2_ID, false); } [Test] public void TestPlayersDoNotStartSimultaneouslyIfBufferingForMaximumStartDelay() { start(new[] { PLAYER_1_ID, PLAYER_2_ID }); loadSpectateScreen(); // Send frames for one player only, both should remain paused. sendFrames(PLAYER_1_ID, 1000); checkPausedInstant(PLAYER_1_ID, true); checkPausedInstant(PLAYER_2_ID, true); // Wait for the start delay seconds... AddWaitStep("wait maximum start delay seconds", (int)(CatchUpSyncManager.MAXIMUM_START_DELAY / TimePerAction)); // Player 1 should start playing by itself, player 2 should remain paused. checkPausedInstant(PLAYER_1_ID, false); checkPausedInstant(PLAYER_2_ID, true); } [Test] public void TestPlayersContinueWhileOthersBuffer() { start(new[] { PLAYER_1_ID, PLAYER_2_ID }); loadSpectateScreen(); // Send initial frames for both players. A few more for player 1. sendFrames(PLAYER_1_ID, 20); sendFrames(PLAYER_2_ID, 10); checkPausedInstant(PLAYER_1_ID, false); checkPausedInstant(PLAYER_2_ID, false); // Eventually player 2 will pause, player 1 must remain running. checkPaused(PLAYER_2_ID, true); checkPausedInstant(PLAYER_1_ID, false); // Eventually both players will run out of frames and should pause. checkPaused(PLAYER_1_ID, true); checkPausedInstant(PLAYER_2_ID, true); // Send more frames for the first player only. Player 1 should start playing with player 2 remaining paused. sendFrames(PLAYER_1_ID, 20); checkPausedInstant(PLAYER_2_ID, true); checkPausedInstant(PLAYER_1_ID, false); // Send more frames for the second player. Both should be playing sendFrames(PLAYER_2_ID, 20); checkPausedInstant(PLAYER_2_ID, false); checkPausedInstant(PLAYER_1_ID, false); } [Test] public void TestPlayersCatchUpAfterFallingBehind() { start(new[] { PLAYER_1_ID, PLAYER_2_ID }); loadSpectateScreen(); // Send initial frames for both players. A few more for player 1. sendFrames(PLAYER_1_ID, 1000); sendFrames(PLAYER_2_ID, 30); checkPausedInstant(PLAYER_1_ID, false); checkPausedInstant(PLAYER_2_ID, false); // Eventually player 2 will run out of frames and should pause. checkPaused(PLAYER_2_ID, true); AddWaitStep("wait a few more frames", 10); // Send more frames for player 2. It should unpause. sendFrames(PLAYER_2_ID, 1000); checkPausedInstant(PLAYER_2_ID, false); // Player 2 should catch up to player 1 after unpausing. waitForCatchup(PLAYER_2_ID); AddWaitStep("wait a bit", 10); } [Test] public void TestMostInSyncUserIsAudioSource() { start(new[] { PLAYER_1_ID, PLAYER_2_ID }); loadSpectateScreen(); assertMuted(PLAYER_1_ID, true); assertMuted(PLAYER_2_ID, true); sendFrames(PLAYER_1_ID, 10); sendFrames(PLAYER_2_ID, 20); checkPaused(PLAYER_1_ID, false); assertOneNotMuted(); checkPaused(PLAYER_1_ID, true); assertMuted(PLAYER_1_ID, true); assertMuted(PLAYER_2_ID, false); sendFrames(PLAYER_1_ID, 100); waitForCatchup(PLAYER_1_ID); checkPaused(PLAYER_2_ID, true); assertMuted(PLAYER_1_ID, false); assertMuted(PLAYER_2_ID, true); sendFrames(PLAYER_2_ID, 100); waitForCatchup(PLAYER_2_ID); assertMuted(PLAYER_1_ID, false); assertMuted(PLAYER_2_ID, true); } [Test] public void TestSpectatingDuringGameplay() { var players = new[] { PLAYER_1_ID, PLAYER_2_ID }; start(players); sendFrames(players, 300); loadSpectateScreen(); sendFrames(players, 300); AddUntilStep("playing from correct point in time", () => this.ChildrenOfType<DrawableRuleset>().All(r => r.FrameStableClock.CurrentTime > 30000)); } [Test] public void TestSpectatingDuringGameplayWithLateFrames() { start(new[] { PLAYER_1_ID, PLAYER_2_ID }); sendFrames(new[] { PLAYER_1_ID, PLAYER_2_ID }, 300); loadSpectateScreen(); sendFrames(PLAYER_1_ID, 300); AddWaitStep("wait maximum start delay seconds", (int)(CatchUpSyncManager.MAXIMUM_START_DELAY / TimePerAction)); checkPaused(PLAYER_1_ID, false); sendFrames(PLAYER_2_ID, 300); AddUntilStep("player 2 playing from correct point in time", () => getPlayer(PLAYER_2_ID).ChildrenOfType<DrawableRuleset>().Single().FrameStableClock.CurrentTime > 30000); } private void loadSpectateScreen(bool waitForPlayerLoad = true) { AddStep("load screen", () => { Beatmap.Value = beatmapManager.GetWorkingBeatmap(importedBeatmap); Ruleset.Value = importedBeatmap.Ruleset; LoadScreen(spectatorScreen = new MultiSpectatorScreen(playingUserIds.ToArray())); }); AddUntilStep("wait for screen load", () => spectatorScreen.LoadState == LoadState.Loaded && (!waitForPlayerLoad || spectatorScreen.AllPlayersLoaded)); } private void start(int[] userIds, int? beatmapId = null) { AddStep("start play", () => { foreach (int id in userIds) { Client.CurrentMatchPlayingUserIds.Add(id); SpectatorClient.StartPlay(id, beatmapId ?? importedBeatmapId); playingUserIds.Add(id); } }); } private void sendFrames(int userId, int count = 10) => sendFrames(new[] { userId }, count); private void sendFrames(int[] userIds, int count = 10) { AddStep("send frames", () => { foreach (int id in userIds) SpectatorClient.SendFrames(id, count); }); } private void checkPaused(int userId, bool state) => AddUntilStep($"{userId} is {(state ? "paused" : "playing")}", () => getPlayer(userId).ChildrenOfType<GameplayClockContainer>().First().GameplayClock.IsRunning != state); private void checkPausedInstant(int userId, bool state) { checkPaused(userId, state); // Todo: The following should work, but is broken because SpectatorScreen retrieves the WorkingBeatmap via the BeatmapManager, bypassing the test scene clock and running real-time. // AddAssert($"{userId} is {(state ? "paused" : "playing")}", () => getPlayer(userId).ChildrenOfType<GameplayClockContainer>().First().GameplayClock.IsRunning != state); } private void assertOneNotMuted() => AddAssert("one player not muted", () => spectatorScreen.ChildrenOfType<PlayerArea>().Count(p => !p.Mute) == 1); private void assertMuted(int userId, bool muted) => AddAssert($"{userId} {(muted ? "is" : "is not")} muted", () => getInstance(userId).Mute == muted); private void waitForCatchup(int userId) => AddUntilStep($"{userId} not catching up", () => !getInstance(userId).GameplayClock.IsCatchingUp); private Player getPlayer(int userId) => getInstance(userId).ChildrenOfType<Player>().Single(); private PlayerArea getInstance(int userId) => spectatorScreen.ChildrenOfType<PlayerArea>().Single(p => p.UserId == userId); } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Management.Automation.Internal; using System.Management.Automation.Language; namespace System.Management.Automation { /// <summary> /// Describes how and where this command was invoked. /// </summary> [DebuggerDisplay("Command = {MyCommand}")] public class InvocationInfo { #region Constructors /// <summary> /// Constructor for InvocationInfo object when the associated command object is present. /// </summary> /// <param name="command"></param> internal InvocationInfo(InternalCommand command) : this(command.CommandInfo, command.InvocationExtent ?? PositionUtilities.EmptyExtent) { CommandOrigin = command.CommandOrigin; } /// <summary> /// Constructor for InvocationInfo object. /// </summary> /// <param name="commandInfo"> /// The command information the invocation info represents. /// </param> /// <param name="scriptPosition"> /// The position representing the invocation, or the position representing the error. /// </param> internal InvocationInfo(CommandInfo commandInfo, IScriptExtent scriptPosition) : this(commandInfo, scriptPosition, null) { // nothing to do here } /// <summary> /// Constructor for InvocationInfo object. /// </summary> /// <param name="commandInfo"> /// The command information the invocation info represents. /// </param> /// <param name="scriptPosition"> /// The position representing the invocation, or the position representing the error. /// </param> /// <param name="context"> /// The context in which the InvocationInfo is being created. /// </param> internal InvocationInfo(CommandInfo commandInfo, IScriptExtent scriptPosition, ExecutionContext context) { MyCommand = commandInfo; CommandOrigin = CommandOrigin.Internal; _scriptPosition = scriptPosition; ExecutionContext contextToUse = null; if ((commandInfo != null) && (commandInfo.Context != null)) { contextToUse = commandInfo.Context; } else if (context != null) { contextToUse = context; } // Populate the history ID of this command if (contextToUse != null) { Runspaces.LocalRunspace localRunspace = contextToUse.CurrentRunspace as Runspaces.LocalRunspace; if (localRunspace != null && localRunspace.History != null) { HistoryId = localRunspace.History.GetNextHistoryId(); } } } /// <summary> /// Creates an InformationalRecord from an instance serialized as a PSObject by ToPSObjectForRemoting. /// </summary> internal InvocationInfo(PSObject psObject) { CommandOrigin = (CommandOrigin)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_CommandOrigin"); ExpectingInput = (bool)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_ExpectingInput"); _invocationName = (string)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_InvocationName"); HistoryId = (long)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_HistoryId"); PipelineLength = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_PipelineLength"); PipelinePosition = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_PipelinePosition"); string scriptName = (string)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_ScriptName"); int scriptLineNumber = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_ScriptLineNumber"); int offsetInLine = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_OffsetInLine"); string line = (string)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_Line"); var scriptPosition = new ScriptPosition(scriptName, scriptLineNumber, offsetInLine, line); ScriptPosition scriptEndPosition; if (!string.IsNullOrEmpty(line)) { int endColumn = line.Length + 1; scriptEndPosition = new ScriptPosition(scriptName, scriptLineNumber, endColumn, line); } else { scriptEndPosition = scriptPosition; } _scriptPosition = new ScriptExtent(scriptPosition, scriptEndPosition); MyCommand = RemoteCommandInfo.FromPSObjectForRemoting(psObject); // // Arrays are de-serialized as ArrayList so we need to convert the deserialized // object into an int[] before assigning to pipelineIterationInfo. // var list = (ArrayList)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_PipelineIterationInfo"); if (list != null) { PipelineIterationInfo = (int[])list.ToArray(typeof(int)); } else { PipelineIterationInfo = Array.Empty<int>(); } // // Dictionaries are de-serialized as Hashtables so we need to convert the deserialized object into a dictionary // before assigning to CommandLineParameters. // Hashtable hashtable = (Hashtable)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_BoundParameters"); Dictionary<string, object> dictionary = new Dictionary<string, object>(); if (hashtable != null) { foreach (DictionaryEntry entry in hashtable) { dictionary.Add((string)entry.Key, entry.Value); } } _boundParameters = dictionary; // // The unbound parameters are de-serialized as an ArrayList, which we need to convert to a List // var unboundArguments = (ArrayList)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_UnboundArguments"); _unboundArguments = new List<object>(); if (unboundArguments != null) { foreach (object o in unboundArguments) { _unboundArguments.Add(o); } } object value = SerializationUtilities.GetPropertyValue(psObject, "SerializeExtent"); bool serializeExtent = false; if (value != null) serializeExtent = (bool)value; if (serializeExtent) DisplayScriptPosition = ScriptExtent.FromPSObjectForRemoting(psObject); } #endregion Constructors #region Private Data private IScriptExtent _scriptPosition; private string _invocationName; private Dictionary<string, object> _boundParameters; private List<object> _unboundArguments; #endregion Internal or Private #region Public Members /// <summary> /// Provide basic information about the command. /// </summary> /// <value>may be null</value> public CommandInfo MyCommand { get; } /// <summary> /// This member provides a dictionary of the parameters that were bound for this /// script or command. /// </summary> public Dictionary<string, object> BoundParameters { get { return _boundParameters ??= new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); } internal set { _boundParameters = value; } } /// <summary> /// This member provides a list of the arguments that were not bound to any parameter. /// </summary> public List<object> UnboundArguments { get { return _unboundArguments ??= new List<object>(); } internal set { _unboundArguments = value; } } /// <summary> /// The line number in the executing script that contained this cmdlet. /// </summary> /// <value>The script line number or -1 if not executing in a script.</value> public int ScriptLineNumber { get { return ScriptPosition.StartLineNumber; } } /// <summary> /// Command's character offset in that line. If the command was /// executed directly through the host interfaces, this will be -1. /// </summary> /// <value>The line offset or -1 if not executed from a text line.</value> public int OffsetInLine { get { return ScriptPosition.StartColumnNumber; } } /// <summary> /// History ID that represents the command. If unavailable, this will be -1. /// </summary> /// <value>The history ID or -1 if not available.</value> public long HistoryId { get; internal set; } = -1; /// <summary> /// The name of the script containing the cmdlet. /// </summary> /// <value>The script name or "" if there was no script.</value> public string ScriptName { get { return ScriptPosition.File ?? string.Empty; } } /// <summary> /// The text of the line that contained this cmdlet invocation. /// </summary> /// <value>Line that was entered to invoke this command</value> public string Line { get { if (ScriptPosition.StartScriptPosition != null) { return ScriptPosition.StartScriptPosition.Line; } return string.Empty; } } /// <summary> /// Formatted message indicating where the cmdlet appeared /// in the line. /// </summary> /// <value>Formatted string indicating the command's position in the line</value> public string PositionMessage { get { return PositionUtilities.VerboseMessage(ScriptPosition); } } /// <summary> /// This property tells you the directory from where you were being invoked. /// </summary> public string PSScriptRoot { get { if (!string.IsNullOrEmpty(ScriptPosition.File)) { return Path.GetDirectoryName(ScriptPosition.File); } else { return string.Empty; } } } /// <summary> /// This property tells you the full path to the command from where you were being invoked. /// </summary> public string PSCommandPath { get { return ScriptPosition.File; } } /// <summary> /// Command name used to invoke this string - if invoked through an alias, then /// this would be the alias name. /// </summary> /// <value>The name string.</value> public string InvocationName { get { return _invocationName ?? string.Empty; } internal set { _invocationName = value; } } /// <summary> /// How many elements are in the containing pipeline. /// </summary> /// <value>number of elements in the containing pipeline</value> public int PipelineLength { get; internal set; } /// <summary> /// Which element this command was in the containing pipeline. /// </summary> /// <value>which element this command was in the containing pipeline</value> public int PipelinePosition { get; internal set; } /// <summary> /// Is true if this command is expecting input... /// </summary> public bool ExpectingInput { get; internal set; } /// <summary> /// This property tells you if you were being invoked inside the runspace or /// if it was an external request. /// </summary> public CommandOrigin CommandOrigin { get; internal set; } /// <summary> /// The position for the invocation or error. /// </summary> public IScriptExtent DisplayScriptPosition { get; set; } /// <summary> /// Create. /// </summary> /// <param name="commandInfo"></param> /// <param name="scriptPosition"></param> /// <returns></returns> public static InvocationInfo Create( CommandInfo commandInfo, IScriptExtent scriptPosition) { var invocationInfo = new InvocationInfo(commandInfo, scriptPosition); invocationInfo.DisplayScriptPosition = scriptPosition; return invocationInfo; } #endregion Public Members #region Internal Members /// <summary> /// The position for the invocation or error. /// </summary> internal IScriptExtent ScriptPosition { get { if (DisplayScriptPosition != null) { return DisplayScriptPosition; } else { return _scriptPosition; } } set { _scriptPosition = value; } } /// <summary> /// Returns the full text of the script for this invocation info. /// </summary> internal string GetFullScript() { return (ScriptPosition != null) && (ScriptPosition.StartScriptPosition != null) ? ScriptPosition.StartScriptPosition.GetFullScript() : null; } /// <summary> /// Index of the ProcessRecord iteration for each of the commands in the pipeline. /// </summary> /// <remarks> /// All the commands in a given pipeline share the same PipelinePositionInfo. /// </remarks> internal int[] PipelineIterationInfo { get; set; } = Array.Empty<int>(); /// <summary> /// Adds the information about this informational record to a PSObject as note properties. /// The PSObject is used to serialize the record during remote operations. /// </summary> /// <remarks> /// InvocationInfos are usually serialized as part of another object, so we add "InvocationInfo_" to /// the note properties to prevent collisions with any properties set by the containing object. /// </remarks> internal void ToPSObjectForRemoting(PSObject psObject) { RemotingEncoder.AddNoteProperty<object>(psObject, "InvocationInfo_BoundParameters", () => this.BoundParameters); RemotingEncoder.AddNoteProperty<CommandOrigin>(psObject, "InvocationInfo_CommandOrigin", () => this.CommandOrigin); RemotingEncoder.AddNoteProperty<bool>(psObject, "InvocationInfo_ExpectingInput", () => this.ExpectingInput); RemotingEncoder.AddNoteProperty<string>(psObject, "InvocationInfo_InvocationName", () => this.InvocationName); RemotingEncoder.AddNoteProperty<string>(psObject, "InvocationInfo_Line", () => this.Line); RemotingEncoder.AddNoteProperty<int>(psObject, "InvocationInfo_OffsetInLine", () => this.OffsetInLine); RemotingEncoder.AddNoteProperty<long>(psObject, "InvocationInfo_HistoryId", () => this.HistoryId); RemotingEncoder.AddNoteProperty<int[]>(psObject, "InvocationInfo_PipelineIterationInfo", () => this.PipelineIterationInfo); RemotingEncoder.AddNoteProperty<int>(psObject, "InvocationInfo_PipelineLength", () => this.PipelineLength); RemotingEncoder.AddNoteProperty<int>(psObject, "InvocationInfo_PipelinePosition", () => this.PipelinePosition); RemotingEncoder.AddNoteProperty<string>(psObject, "InvocationInfo_PSScriptRoot", () => this.PSScriptRoot); RemotingEncoder.AddNoteProperty<string>(psObject, "InvocationInfo_PSCommandPath", () => this.PSCommandPath); // PositionMessage is ignored when deserializing because it is synthesized from the other position related fields, but // it is serialized for backwards compatibility. RemotingEncoder.AddNoteProperty<string>(psObject, "InvocationInfo_PositionMessage", () => this.PositionMessage); RemotingEncoder.AddNoteProperty<int>(psObject, "InvocationInfo_ScriptLineNumber", () => this.ScriptLineNumber); RemotingEncoder.AddNoteProperty<string>(psObject, "InvocationInfo_ScriptName", () => this.ScriptName); RemotingEncoder.AddNoteProperty<object>(psObject, "InvocationInfo_UnboundArguments", () => this.UnboundArguments); ScriptExtent extent = DisplayScriptPosition as ScriptExtent; if (extent != null) { extent.ToPSObjectForRemoting(psObject); RemotingEncoder.AddNoteProperty(psObject, "SerializeExtent", static () => true); } else { RemotingEncoder.AddNoteProperty(psObject, "SerializeExtent", static () => false); } RemoteCommandInfo.ToPSObjectForRemoting(this.MyCommand, psObject); } #endregion Internal Members } /// <summary> /// A CommandInfo that has been serialized/deserialized as part of an InvocationInfo during a remote invocation. /// </summary> public class RemoteCommandInfo : CommandInfo { /// <summary> /// </summary> private RemoteCommandInfo(string name, CommandTypes type) : base(name, type) { // nothing to do here } /// <summary> /// A string representing the definition of the command. /// </summary> public override string Definition { get { return _definition; } } /// <summary> /// Creates a RemoteCommandInfo from an instance serialized as a PSObject by ToPSObjectForRemoting. /// </summary> internal static RemoteCommandInfo FromPSObjectForRemoting(PSObject psObject) { RemoteCommandInfo commandInfo = null; object ctype = SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "CommandInfo_CommandType"); if (ctype != null) { CommandTypes type = RemotingDecoder.GetPropertyValue<CommandTypes>(psObject, "CommandInfo_CommandType"); string name = RemotingDecoder.GetPropertyValue<string>(psObject, "CommandInfo_Name"); commandInfo = new RemoteCommandInfo(name, type); commandInfo._definition = RemotingDecoder.GetPropertyValue<string>(psObject, "CommandInfo_Definition"); commandInfo.Visibility = RemotingDecoder.GetPropertyValue<SessionStateEntryVisibility>(psObject, "CommandInfo_Visibility"); } return commandInfo; } /// <summary> /// Adds the information about this instance to a PSObject as note properties. /// The PSObject is used to serialize the CommandInfo during remote operations. /// </summary> /// <remarks> /// CommandInfos are usually serialized as part of InvocationInfos, so we add "CommandInfo_" to /// the note properties to prevent collisions with any properties set by the containing object. /// </remarks> internal static void ToPSObjectForRemoting(CommandInfo commandInfo, PSObject psObject) { if (commandInfo != null) { RemotingEncoder.AddNoteProperty<CommandTypes>(psObject, "CommandInfo_CommandType", () => commandInfo.CommandType); RemotingEncoder.AddNoteProperty<string>(psObject, "CommandInfo_Definition", () => commandInfo.Definition); RemotingEncoder.AddNoteProperty<string>(psObject, "CommandInfo_Name", () => commandInfo.Name); RemotingEncoder.AddNoteProperty<SessionStateEntryVisibility>(psObject, "CommandInfo_Visibility", () => commandInfo.Visibility); } } /// <summary> /// NYI. /// </summary> public override ReadOnlyCollection<PSTypeName> OutputType { get { return null; } } private string _definition; } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Algorithm.Selection; using QuantConnect.Data; using QuantConnect.Data.Fundamental; using QuantConnect.Data.Market; using QuantConnect.Data.UniverseSelection; using QuantConnect.Securities; using QuantConnect.Securities.Future; using QuantConnect.Util; namespace QuantConnect.Algorithm { public partial class QCAlgorithm { // save universe additions and apply at end of time step // this removes temporal dependencies from w/in initialize method // original motivation: adding equity/options to enforce equity raw data mode private readonly object _pendingUniverseAdditionsLock = new object(); private readonly List<UserDefinedUniverseAddition> _pendingUserDefinedUniverseSecurityAdditions = new List<UserDefinedUniverseAddition>(); private readonly List<Universe> _pendingUniverseAdditions = new List<Universe>(); // this is so that later during 'UniverseSelection.CreateUniverses' we wont remove these user universes from the UniverseManager private readonly HashSet<Symbol> _userAddedUniverses = new HashSet<Symbol>(); private ConcurrentSet<Symbol> _rawNormalizationWarningSymbols = new ConcurrentSet<Symbol>(); private readonly int _rawNormalizationWarningSymbolsMaxCount = 10; /// <summary> /// Gets universe manager which holds universes keyed by their symbol /// </summary> public UniverseManager UniverseManager { get; private set; } /// <summary> /// Gets the universe settings to be used when adding securities via universe selection /// </summary> public UniverseSettings UniverseSettings { get; private set; } /// <summary> /// Invoked at the end of every time step. This allows the algorithm /// to process events before advancing to the next time step. /// </summary> public void OnEndOfTimeStep() { if (_pendingUniverseAdditions.Count + _pendingUserDefinedUniverseSecurityAdditions.Count == 0) { // no point in looping through everything if there's no pending changes return; } var requiredHistoryRequests = new Dictionary<Security, Resolution>(); // rewrite securities w/ derivatives to be in raw mode lock (_pendingUniverseAdditionsLock) { foreach (var security in Securities.Select(kvp => kvp.Value).Union( _pendingUserDefinedUniverseSecurityAdditions.Select(x => x.Security))) { // check for any derivative securities and mark the underlying as raw if (Securities.Any(skvp => skvp.Key.SecurityType != SecurityType.Base && skvp.Key.HasUnderlyingSymbol(security.Symbol))) { // set data mode raw and default volatility model ConfigureUnderlyingSecurity(security); } var configs = SubscriptionManager.SubscriptionDataConfigService .GetSubscriptionDataConfigs(security.Symbol); if (security.Symbol.HasUnderlying && security.Symbol.SecurityType != SecurityType.Base) { Security underlyingSecurity; var underlyingSymbol = security.Symbol.Underlying; var resolution = configs.GetHighestResolution(); // create the underlying security object if it doesn't already exist if (!Securities.TryGetValue(underlyingSymbol, out underlyingSecurity)) { underlyingSecurity = AddSecurity(underlyingSymbol.SecurityType, underlyingSymbol.Value, resolution, underlyingSymbol.ID.Market, false, 0, configs.IsExtendedMarketHours()); } // set data mode raw and default volatility model ConfigureUnderlyingSecurity(underlyingSecurity); if (LiveMode && underlyingSecurity.GetLastData() == null) { if (requiredHistoryRequests.ContainsKey(underlyingSecurity)) { // lets request the higher resolution var currentResolutionRequest = requiredHistoryRequests[underlyingSecurity]; if (currentResolutionRequest != Resolution.Minute // Can not be less than Minute && resolution < currentResolutionRequest) { requiredHistoryRequests[underlyingSecurity] = (Resolution)Math.Max((int)resolution, (int)Resolution.Minute); } } else { requiredHistoryRequests.Add(underlyingSecurity, (Resolution)Math.Max((int)resolution, (int)Resolution.Minute)); } } // set the underlying security on the derivative -- we do this in two places since it's possible // to do AddOptionContract w/out the underlying already added and normalized properly var derivative = security as IDerivativeSecurity; if (derivative != null) { derivative.Underlying = underlyingSecurity; } } } if (!requiredHistoryRequests.IsNullOrEmpty()) { // Create requests var historyRequests = Enumerable.Empty<HistoryRequest>(); foreach (var byResolution in requiredHistoryRequests.GroupBy(x => x.Value)) { historyRequests = historyRequests.Concat( CreateBarCountHistoryRequests(byResolution.Select(x => x.Key.Symbol), 3, byResolution.Key)); } // Request data var historicLastData = History(historyRequests); historicLastData.PushThrough(x => { var security = requiredHistoryRequests.Keys.FirstOrDefault(y => y.Symbol == x.Symbol); security?.Cache.AddData(x); }); } // add subscriptionDataConfig to their respective user defined universes foreach (var userDefinedUniverseAddition in _pendingUserDefinedUniverseSecurityAdditions) { foreach (var subscriptionDataConfig in userDefinedUniverseAddition.SubscriptionDataConfigs) { userDefinedUniverseAddition.Universe.Add(subscriptionDataConfig); } } // finally add any pending universes, this will make them available to the data feed foreach (var universe in _pendingUniverseAdditions) { UniverseManager.Add(universe.Configuration.Symbol, universe); } _pendingUniverseAdditions.Clear(); _pendingUserDefinedUniverseSecurityAdditions.Clear(); } if (!_rawNormalizationWarningSymbols.IsNullOrEmpty()) { // Log our securities being set to raw price mode Debug($"Warning: The following securities were set to raw price normalization mode to work with options: " + $"{string.Join(", ", _rawNormalizationWarningSymbols.Take(_rawNormalizationWarningSymbolsMaxCount).Select(x => x.Value))}..."); // Set our warning list to null to stop emitting these warnings after its done once _rawNormalizationWarningSymbols = null; } } /// <summary> /// Gets a helper that provides pre-defined universe definitions, such as top dollar volume /// </summary> public UniverseDefinitions Universe { get; private set; } /// <summary> /// Adds the universe to the algorithm /// </summary> /// <param name="universe">The universe to be added</param> public Universe AddUniverse(Universe universe) { // The universe will be added at the end of time step, same as the AddData user defined universes. // This is required to be independent of the start and end date set during initialize _pendingUniverseAdditions.Add(universe); _userAddedUniverses.Add(universe.Configuration.Symbol); return universe; } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. This universe will use the defaults /// of SecurityType.Equity, Resolution.Daily, Market.USA, and UniverseSettings /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="name">A unique name for this universe</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(string name, Func<IEnumerable<T>, IEnumerable<Symbol>> selector) { return AddUniverse(SecurityType.Equity, name, Resolution.Daily, Market.USA, UniverseSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. This universe will use the defaults /// of SecurityType.Equity, Resolution.Daily, Market.USA, and UniverseSettings /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="name">A unique name for this universe</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(string name, Func<IEnumerable<T>, IEnumerable<string>> selector) { return AddUniverse(SecurityType.Equity, name, Resolution.Daily, Market.USA, UniverseSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. This universe will use the defaults /// of SecurityType.Equity, Resolution.Daily, and Market.USA /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="name">A unique name for this universe</param> /// <param name="universeSettings">The settings used for securities added by this universe</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(string name, UniverseSettings universeSettings, Func<IEnumerable<T>, IEnumerable<Symbol>> selector) { return AddUniverse(SecurityType.Equity, name, Resolution.Daily, Market.USA, universeSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. This universe will use the defaults /// of SecurityType.Equity, Resolution.Daily, and Market.USA /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="name">A unique name for this universe</param> /// <param name="universeSettings">The settings used for securities added by this universe</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(string name, UniverseSettings universeSettings, Func<IEnumerable<T>, IEnumerable<string>> selector) { return AddUniverse(SecurityType.Equity, name, Resolution.Daily, Market.USA, universeSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. This universe will use the defaults /// of SecurityType.Equity, Market.USA and UniverseSettings /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The epected resolution of the universe data</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(string name, Resolution resolution, Func<IEnumerable<T>, IEnumerable<Symbol>> selector) { return AddUniverse(SecurityType.Equity, name, resolution, Market.USA, UniverseSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. This universe will use the defaults /// of SecurityType.Equity, Market.USA and UniverseSettings /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The epected resolution of the universe data</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(string name, Resolution resolution, Func<IEnumerable<T>, IEnumerable<string>> selector) { return AddUniverse(SecurityType.Equity, name, resolution, Market.USA, UniverseSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. This universe will use the defaults /// of SecurityType.Equity, and Market.USA /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The epected resolution of the universe data</param> /// <param name="universeSettings">The settings used for securities added by this universe</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(string name, Resolution resolution, UniverseSettings universeSettings, Func<IEnumerable<T>, IEnumerable<Symbol>> selector) { return AddUniverse(SecurityType.Equity, name, resolution, Market.USA, universeSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. This universe will use the defaults /// of SecurityType.Equity, and Market.USA /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The epected resolution of the universe data</param> /// <param name="universeSettings">The settings used for securities added by this universe</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(string name, Resolution resolution, UniverseSettings universeSettings, Func<IEnumerable<T>, IEnumerable<string>> selector) { return AddUniverse(SecurityType.Equity, name, resolution, Market.USA, universeSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="securityType">The security type the universe produces</param> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The epected resolution of the universe data</param> /// <param name="market">The market for selected symbols</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(SecurityType securityType, string name, Resolution resolution, string market, Func<IEnumerable<T>, IEnumerable<Symbol>> selector) { return AddUniverse(securityType, name, resolution, market, UniverseSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="securityType">The security type the universe produces</param> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The epected resolution of the universe data</param> /// <param name="market">The market for selected symbols</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(SecurityType securityType, string name, Resolution resolution, string market, Func<IEnumerable<T>, IEnumerable<string>> selector) { return AddUniverse(securityType, name, resolution, market, UniverseSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="securityType">The security type the universe produces</param> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The epected resolution of the universe data</param> /// <param name="market">The market for selected symbols</param> /// <param name="universeSettings">The subscription settings to use for newly created subscriptions</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(SecurityType securityType, string name, Resolution resolution, string market, UniverseSettings universeSettings, Func<IEnumerable<T>, IEnumerable<Symbol>> selector) { var marketHoursDbEntry = MarketHoursDatabase.GetEntry(market, name, securityType); var dataTimeZone = marketHoursDbEntry.DataTimeZone; var exchangeTimeZone = marketHoursDbEntry.ExchangeHours.TimeZone; var symbol = QuantConnect.Symbol.Create(name, securityType, market, baseDataType: typeof(T)); var config = new SubscriptionDataConfig(typeof(T), symbol, resolution, dataTimeZone, exchangeTimeZone, false, false, true, true, isFilteredSubscription: false); return AddUniverse(new FuncUniverse(config, universeSettings, d => selector(d.OfType<T>()))); } /// <summary> /// Creates a new universe and adds it to the algorithm /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="securityType">The security type the universe produces</param> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The epected resolution of the universe data</param> /// <param name="market">The market for selected symbols</param> /// <param name="universeSettings">The subscription settings to use for newly created subscriptions</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(SecurityType securityType, string name, Resolution resolution, string market, UniverseSettings universeSettings, Func<IEnumerable<T>, IEnumerable<string>> selector) { var marketHoursDbEntry = MarketHoursDatabase.GetEntry(market, name, securityType); var dataTimeZone = marketHoursDbEntry.DataTimeZone; var exchangeTimeZone = marketHoursDbEntry.ExchangeHours.TimeZone; var symbol = QuantConnect.Symbol.Create(name, securityType, market, baseDataType: typeof(T)); var config = new SubscriptionDataConfig(typeof(T), symbol, resolution, dataTimeZone, exchangeTimeZone, false, false, true, true, isFilteredSubscription: false); return AddUniverse(new FuncUniverse(config, universeSettings, d => selector(d.OfType<T>()).Select(x => QuantConnect.Symbol.Create(x, securityType, market, baseDataType: typeof(T)))) ); } /// <summary> /// Creates a new universe and adds it to the algorithm. This is for coarse fundamental US Equity data and /// will be executed on day changes in the NewYork time zone (<see cref="TimeZones.NewYork"/> /// </summary> /// <param name="selector">Defines an initial coarse selection</param> public Universe AddUniverse(Func<IEnumerable<CoarseFundamental>, IEnumerable<Symbol>> selector) { return AddUniverse(new CoarseFundamentalUniverse(UniverseSettings, selector)); } /// <summary> /// Creates a new universe and adds it to the algorithm. This is for coarse and fine fundamental US Equity data and /// will be executed on day changes in the NewYork time zone (<see cref="TimeZones.NewYork"/> /// </summary> /// <param name="coarseSelector">Defines an initial coarse selection</param> /// <param name="fineSelector">Defines a more detailed selection with access to more data</param> public Universe AddUniverse(Func<IEnumerable<CoarseFundamental>, IEnumerable<Symbol>> coarseSelector, Func<IEnumerable<FineFundamental>, IEnumerable<Symbol>> fineSelector) { var coarse = new CoarseFundamentalUniverse(UniverseSettings, coarseSelector); return AddUniverse(new FineFundamentalFilteredUniverse(coarse, fineSelector)); } /// <summary> /// Creates a new universe and adds it to the algorithm. This is for fine fundamental US Equity data and /// will be executed on day changes in the NewYork time zone (<see cref="TimeZones.NewYork"/> /// </summary> /// <param name="universe">The universe to be filtered with fine fundamental selection</param> /// <param name="fineSelector">Defines a more detailed selection with access to more data</param> public Universe AddUniverse(Universe universe, Func<IEnumerable<FineFundamental>, IEnumerable<Symbol>> fineSelector) { return AddUniverse(new FineFundamentalFilteredUniverse(universe, fineSelector)); } /// <summary> /// Creates a new universe and adds it to the algorithm. This can be used to return a list of string /// symbols retrieved from anywhere and will loads those symbols under the US Equity market. /// </summary> /// <param name="name">A unique name for this universe</param> /// <param name="selector">Function delegate that accepts a DateTime and returns a collection of string symbols</param> public Universe AddUniverse(string name, Func<DateTime, IEnumerable<string>> selector) { return AddUniverse(SecurityType.Equity, name, Resolution.Daily, Market.USA, UniverseSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This can be used to return a list of string /// symbols retrieved from anywhere and will loads those symbols under the US Equity market. /// </summary> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The resolution this universe should be triggered on</param> /// <param name="selector">Function delegate that accepts a DateTime and returns a collection of string symbols</param> public Universe AddUniverse(string name, Resolution resolution, Func<DateTime, IEnumerable<string>> selector) { return AddUniverse(SecurityType.Equity, name, resolution, Market.USA, UniverseSettings, selector); } /// <summary> /// Creates a new user defined universe that will fire on the requested resolution during market hours. /// </summary> /// <param name="securityType">The security type of the universe</param> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The resolution this universe should be triggered on</param> /// <param name="market">The market of the universe</param> /// <param name="universeSettings">The subscription settings used for securities added from this universe</param> /// <param name="selector">Function delegate that accepts a DateTime and returns a collection of string symbols</param> public Universe AddUniverse(SecurityType securityType, string name, Resolution resolution, string market, UniverseSettings universeSettings, Func<DateTime, IEnumerable<string>> selector) { var marketHoursDbEntry = MarketHoursDatabase.GetEntry(market, name, securityType); var dataTimeZone = marketHoursDbEntry.DataTimeZone; var exchangeTimeZone = marketHoursDbEntry.ExchangeHours.TimeZone; var symbol = QuantConnect.Symbol.Create(name, securityType, market); var config = new SubscriptionDataConfig(typeof(CoarseFundamental), symbol, resolution, dataTimeZone, exchangeTimeZone, false, false, true, isFilteredSubscription: false); return AddUniverse(new UserDefinedUniverse(config, universeSettings, resolution.ToTimeSpan(), selector)); } /// <summary> /// Adds a new universe that creates options of the security by monitoring any changes in the Universe the provided security is in. /// Additionally, a filter can be applied to the options generated when the universe of the security changes. /// </summary> /// <param name="underlyingSymbol">Underlying Symbol to add as an option. For Futures, the option chain constructed will be per-contract, as long as a canonical Symbol is provided.</param> /// <param name="optionFilter">User-defined filter used to select the options we want out of the option chain provided.</param> /// <exception cref="InvalidOperationException">The underlying Symbol's universe is not found.</exception> public void AddUniverseOptions(Symbol underlyingSymbol, Func<OptionFilterUniverse, OptionFilterUniverse> optionFilter) { // We need to load the universe associated with the provided Symbol and provide that universe to the option filter universe. // The option filter universe will subscribe to any changes in the universe of the underlying Symbol, // ensuring that we load the option chain for every asset found in the underlying's Universe. Universe universe; if (!UniverseManager.TryGetValue(underlyingSymbol, out universe)) { // The universe might be already added, but not registered with the UniverseManager. universe = _pendingUniverseAdditions.SingleOrDefault(u => u.Configuration.Symbol == underlyingSymbol); if (universe == null) { underlyingSymbol = AddSecurity(underlyingSymbol).Symbol; } // Recheck again, we should have a universe addition pending for the provided Symbol universe = _pendingUniverseAdditions.SingleOrDefault(u => u.Configuration.Symbol == underlyingSymbol); if (universe == null) { // Should never happen, but it could be that the subscription // created with AddSecurity is not aligned with the Symbol we're using. throw new InvalidOperationException($"Universe not found for underlying Symbol: {underlyingSymbol}."); } } // Allow all option contracts through without filtering if we're provided a null filter. AddUniverseOptions(universe, optionFilter ?? (_ => _)); } /// <summary> /// Creates a new universe selection model and adds it to the algorithm. This universe selection model will chain to the security /// changes of a given <see cref="Universe"/> selection output and create a new <see cref="OptionChainUniverse"/> for each of them /// </summary> /// <param name="universe">The universe we want to chain an option universe selection model too</param> /// <param name="optionFilter">The option filter universe to use</param> public void AddUniverseOptions(Universe universe, Func<OptionFilterUniverse, OptionFilterUniverse> optionFilter) { AddUniverseSelection(new OptionChainedUniverseSelectionModel(universe, optionFilter)); } /// <summary> /// Adds the security to the user defined universe /// </summary> /// <param name="security">The security to add</param> /// <param name="configurations">The <see cref="SubscriptionDataConfig"/> instances we want to add</param> private Security AddToUserDefinedUniverse( Security security, List<SubscriptionDataConfig> configurations) { var subscription = configurations.First(); // if we are adding a non-internal security which already has an internal feed, we remove it first Security existingSecurity; if (Securities.TryGetValue(security.Symbol, out existingSecurity)) { if (!subscription.IsInternalFeed && existingSecurity.IsInternalFeed()) { var securityUniverse = UniverseManager.Select(x => x.Value).OfType<UserDefinedUniverse>().FirstOrDefault(x => x.Members.ContainsKey(security.Symbol)); securityUniverse?.Remove(security.Symbol); Securities.Remove(security.Symbol); Securities.Add(security); } else { // we will reuse existing so we return it to the user security = existingSecurity; } } else { Securities.Add(security); } // add this security to the user defined universe Universe universe; var universeSymbol = UserDefinedUniverse.CreateSymbol(security.Type, security.Symbol.ID.Market); lock (_pendingUniverseAdditionsLock) { if (!UniverseManager.TryGetValue(universeSymbol, out universe)) { universe = _pendingUniverseAdditions.FirstOrDefault(x => x.Configuration.Symbol == universeSymbol); if (universe == null) { // create a new universe, these subscription settings don't currently get used // since universe selection proper is never invoked on this type of universe var uconfig = new SubscriptionDataConfig(subscription, symbol: universeSymbol, isInternalFeed: true, fillForward: false); if (security.Type == SecurityType.Base) { // set entry in market hours database for the universe subscription to match the custom data var symbolString = MarketHoursDatabase.GetDatabaseSymbolKey(uconfig.Symbol); MarketHoursDatabase.SetEntry(uconfig.Market, symbolString, uconfig.SecurityType, security.Exchange.Hours, uconfig.DataTimeZone); } universe = new UserDefinedUniverse(uconfig, new UniverseSettings( subscription.Resolution, security.Leverage, subscription.FillDataForward, subscription.ExtendedMarketHours, TimeSpan.Zero), QuantConnect.Time.MaxTimeSpan, new List<Symbol>()); AddUniverse(universe); } } } var userDefinedUniverse = universe as UserDefinedUniverse; if (userDefinedUniverse != null) { lock (_pendingUniverseAdditionsLock) { _pendingUserDefinedUniverseSecurityAdditions.Add( new UserDefinedUniverseAddition(userDefinedUniverse, configurations, security)); } } else { // should never happen, someone would need to add a non-user defined universe with this symbol throw new Exception("Expected universe with symbol '" + universeSymbol.Value + "' to be of type UserDefinedUniverse."); } return security; } /// <summary> /// Configures the security to be in raw data mode and ensures that a reasonable default volatility model is supplied /// </summary> /// <param name="security">The underlying security</param> private void ConfigureUnderlyingSecurity(Security security) { // force underlying securities to be raw data mode var configs = SubscriptionManager.SubscriptionDataConfigService .GetSubscriptionDataConfigs(security.Symbol); if (configs.DataNormalizationMode() != DataNormalizationMode.Raw) { // Add this symbol to our set of raw normalization warning symbols to alert the user at the end // Set a hard limit to avoid growing this collection unnecessarily large if (_rawNormalizationWarningSymbols != null && _rawNormalizationWarningSymbols.Count <= _rawNormalizationWarningSymbolsMaxCount) { _rawNormalizationWarningSymbols.Add(security.Symbol); } configs.SetDataNormalizationMode(DataNormalizationMode.Raw); // For backward compatibility we need to refresh the security DataNormalizationMode Property security.RefreshDataNormalizationModeProperty(); } // ensure a volatility model has been set on the underlying if (security.VolatilityModel == VolatilityModel.Null) { var config = configs.FirstOrDefault(); var bar = config?.Type.GetBaseDataInstance() ?? typeof(TradeBar).GetBaseDataInstance(); bar.Symbol = security.Symbol; var maxSupportedResolution = bar.SupportedResolutions().Max(); var updateFrequency = maxSupportedResolution.ToTimeSpan(); int periods; switch (maxSupportedResolution) { case Resolution.Tick: case Resolution.Second: periods = 600; break; case Resolution.Minute: periods = 60 * 24; break; case Resolution.Hour: periods = 24 * 30; break; default: periods = 30; break; } security.VolatilityModel = new StandardDeviationOfReturnsVolatilityModel(periods, maxSupportedResolution, updateFrequency); } } /// <summary> /// Helper class used to store <see cref="UserDefinedUniverse"/> additions. /// They will be consumed at <see cref="OnEndOfTimeStep"/> /// </summary> private class UserDefinedUniverseAddition { public Security Security { get; } public UserDefinedUniverse Universe { get; } public List<SubscriptionDataConfig> SubscriptionDataConfigs { get; } public UserDefinedUniverseAddition( UserDefinedUniverse universe, List<SubscriptionDataConfig> subscriptionDataConfigs, Security security) { Universe = universe; SubscriptionDataConfigs = subscriptionDataConfigs; Security = security; } } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using OpenMetaverse; using OpenMetaverse.StructuredData; using ProtoBuf; namespace OpenSim.Framework { // Soon to be dismissed public class ChildAgentDataUpdate { public Guid ActiveGroupID; public Guid AgentID; public bool alwaysrun; public float AVHeight; public sLLVector3 cameraPosition; public float drawdistance; public float godlevel; public uint GroupAccess; public sLLVector3 Position; public ulong regionHandle; public byte[] throttles; public sLLVector3 Velocity; public ChildAgentDataUpdate() { } } public interface IAgentData { UUID AgentID { get; set; } OSDMap Pack(); void Unpack(OSDMap map); } /// <summary> /// Replacement for ChildAgentDataUpdate. Used over RESTComms and LocalComms. /// </summary> public class AgentPosition : IAgentData { private UUID m_id; public UUID AgentID { get { return m_id; } set { m_id = value; } } public ulong RegionHandle; public uint CircuitCode; public UUID SessionID; public float Far; public Vector3 Position; public Vector3 Velocity; public Vector3 Center; public Vector3 Size; public Vector3 AtAxis; public Vector3 LeftAxis; public Vector3 UpAxis; public bool ChangedGrid; // This probably shouldn't be here public byte[] Throttles; public OSDMap Pack() { OSDMap args = new OSDMap(); args["message_type"] = OSD.FromString("AgentPosition"); args["region_handle"] = OSD.FromString(RegionHandle.ToString()); args["circuit_code"] = OSD.FromString(CircuitCode.ToString()); args["agent_uuid"] = OSD.FromUUID(AgentID); args["session_uuid"] = OSD.FromUUID(SessionID); args["position"] = OSD.FromString(Position.ToString()); args["velocity"] = OSD.FromString(Velocity.ToString()); args["center"] = OSD.FromString(Center.ToString()); args["size"] = OSD.FromString(Size.ToString()); args["at_axis"] = OSD.FromString(AtAxis.ToString()); args["left_axis"] = OSD.FromString(LeftAxis.ToString()); args["up_axis"] = OSD.FromString(UpAxis.ToString()); args["far"] = OSD.FromReal(Far); args["changed_grid"] = OSD.FromBoolean(ChangedGrid); if ((Throttles != null) && (Throttles.Length > 0)) args["throttles"] = OSD.FromBinary(Throttles); return args; } public void Unpack(OSDMap args) { if (args.ContainsKey("region_handle")) UInt64.TryParse(args["region_handle"].AsString(), out RegionHandle); if (args.ContainsKey("circuit_code")) UInt32.TryParse((string)args["circuit_code"].AsString(), out CircuitCode); if (args.ContainsKey("agent_uuid")) AgentID = args["agent_uuid"].AsUUID(); if (args.ContainsKey("session_uuid")) SessionID = args["session_uuid"].AsUUID(); if (args.ContainsKey("position")) Vector3.TryParse(args["position"].AsString(), out Position); if (args.ContainsKey("velocity")) Vector3.TryParse(args["velocity"].AsString(), out Velocity); if (args.ContainsKey("center")) Vector3.TryParse(args["center"].AsString(), out Center); if (args.ContainsKey("size")) Vector3.TryParse(args["size"].AsString(), out Size); if (args.ContainsKey("at_axis")) Vector3.TryParse(args["at_axis"].AsString(), out AtAxis); if (args.ContainsKey("left_axis")) Vector3.TryParse(args["left_axis"].AsString(), out AtAxis); if (args.ContainsKey("up_axis")) Vector3.TryParse(args["up_axis"].AsString(), out AtAxis); if (args.ContainsKey("changed_grid")) ChangedGrid = args["changed_grid"].AsBoolean(); if (args.ContainsKey("far")) Far = (float)(args["far"].AsReal()); if (args.ContainsKey("throttles")) Throttles = args["throttles"].AsBinary(); } /// <summary> /// Soon to be decommissioned /// </summary> /// <param name="cAgent"></param> public void CopyFrom(ChildAgentDataUpdate cAgent) { AgentID = new UUID(cAgent.AgentID); Size = new Vector3(); Size.Z = cAgent.AVHeight; Center = new Vector3(cAgent.cameraPosition.x, cAgent.cameraPosition.y, cAgent.cameraPosition.z); Far = cAgent.drawdistance; Position = new Vector3(cAgent.Position.x, cAgent.Position.y, cAgent.Position.z); RegionHandle = cAgent.regionHandle; Throttles = cAgent.throttles; Velocity = new Vector3(cAgent.Velocity.x, cAgent.Velocity.y, cAgent.Velocity.z); } } [ProtoContract] public class AgentGroupData { [ProtoMember(1)] private Guid _GroupID { get { return GroupID.Guid; } set { GroupID = new UUID(value); } } public UUID GroupID; [ProtoMember(2)] public ulong GroupPowers; [ProtoMember(3)] public bool AcceptNotices; public AgentGroupData() { //required for protobuf } public AgentGroupData(UUID id, ulong powers, bool notices) { GroupID = id; GroupPowers = powers; AcceptNotices = notices; } public AgentGroupData(OSDMap args) { UnpackUpdateMessage(args); } public OSDMap PackUpdateMessage() { OSDMap groupdata = new OSDMap(); groupdata["group_id"] = OSD.FromUUID(GroupID); groupdata["group_powers"] = OSD.FromString(GroupPowers.ToString()); groupdata["accept_notices"] = OSD.FromBoolean(AcceptNotices); return groupdata; } public void UnpackUpdateMessage(OSDMap args) { if (args.ContainsKey("group_id")) GroupID = args["group_id"].AsUUID(); if (args.ContainsKey("group_powers")) UInt64.TryParse((string)args["group_powers"].AsString(), out GroupPowers); if (args.ContainsKey("accept_notices")) AcceptNotices = args["accept_notices"].AsBoolean(); } } [Flags] public enum AgentLocomotionFlags { Teleport = (1 << 0), Crossing = (1 << 1) } [Flags] public enum PresenceFlags { DebugCrossings = (1 << 0), LimitNeighbors = (1 << 1) // when set, neighbors range is only 1 } public class AgentData : IAgentData { public ulong AgentDataCreatedOn = Util.GetLongTickCount(); private UUID m_id; public UUID AgentID { get { return m_id; } set { m_id = value; } } public ulong RegionHandle; public uint CircuitCode; public UUID SessionID; public Vector3 Position; public Vector3 Velocity; public Vector3 Center; public Vector3 Size; public Vector3 AtAxis; public Vector3 LeftAxis; public Vector3 UpAxis; public bool ChangedGrid; public float Far; public float Aspect; public byte[] Throttles; public uint LocomotionState; public Quaternion HeadRotation; public Quaternion BodyRotation; public uint ControlFlags; public float EnergyLevel; public Byte GodLevel; public bool AlwaysRun; public UUID PreyAgent; public Byte AgentAccess; public UUID ActiveGroupID; public AgentGroupData[] Groups; public Animation[] Anims; // Appearance public AvatarAppearance Appearance; // AgentPreferences from viewer public AgentPreferencesData AgentPrefs; public string CallbackURI; public UUID SatOnGroup; public UUID SatOnPrim; public Vector3 SatOnPrimOffset; public List<byte[]> SerializedAttachments; public AgentLocomotionFlags LocomotionFlags; public List<RemotePresenceInfo> RemoteAgents; public Vector3 ConstantForces; public bool ConstantForcesAreLocal; public ulong PresenceFlags; public bool AvatarAsAPrim; public virtual OSDMap Pack() { OSDMap args = new OSDMap(); args["message_type"] = OSD.FromString("AgentData"); args["region_handle"] = OSD.FromString(RegionHandle.ToString()); args["circuit_code"] = OSD.FromString(CircuitCode.ToString()); args["agent_uuid"] = OSD.FromUUID(AgentID); args["session_uuid"] = OSD.FromUUID(SessionID); args["position"] = OSD.FromString(Position.ToString()); args["velocity"] = OSD.FromString(Velocity.ToString()); args["center"] = OSD.FromString(Center.ToString()); args["size"] = OSD.FromString(Size.ToString()); args["at_axis"] = OSD.FromString(AtAxis.ToString()); args["left_axis"] = OSD.FromString(LeftAxis.ToString()); args["up_axis"] = OSD.FromString(UpAxis.ToString()); args["changed_grid"] = OSD.FromBoolean(ChangedGrid); args["far"] = OSD.FromReal(Far); args["aspect"] = OSD.FromReal(Aspect); if ((Throttles != null) && (Throttles.Length > 0)) args["throttles"] = OSD.FromBinary(Throttles); args["locomotion_state"] = OSD.FromString(LocomotionState.ToString()); args["head_rotation"] = OSD.FromString(HeadRotation.ToString()); args["body_rotation"] = OSD.FromString(BodyRotation.ToString()); args["control_flags"] = OSD.FromString(ControlFlags.ToString()); args["energy_level"] = OSD.FromReal(EnergyLevel); args["god_level"] = OSD.FromString(GodLevel.ToString()); args["always_run"] = OSD.FromBoolean(AlwaysRun); args["prey_agent"] = OSD.FromUUID(PreyAgent); args["agent_access"] = OSD.FromString(AgentAccess.ToString()); args["active_group_id"] = OSD.FromUUID(ActiveGroupID); if ((Groups != null) && (Groups.Length > 0)) { OSDArray groups = new OSDArray(Groups.Length); foreach (AgentGroupData agd in Groups) groups.Add(agd.PackUpdateMessage()); args["groups"] = groups; } if ((Anims != null) && (Anims.Length > 0)) { OSDArray anims = new OSDArray(Anims.Length); foreach (Animation aanim in Anims) anims.Add(aanim.PackUpdateMessage()); args["animations"] = anims; } if (Appearance != null) { // We might not pass this in all cases... if (Appearance.Texture != null) args["texture_entry"] = OSD.FromBinary(Appearance.Texture.GetBytes()); if ((Appearance.VisualParams != null) && (Appearance.VisualParams.Length > 0)) args["visual_params"] = OSD.FromBinary(Appearance.VisualParams); OSDArray wears = new OSDArray(AvatarWearable.MAX_WEARABLES * 2); for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++) { AvatarWearable wearable = Appearance.GetWearableOfType(i); wears.Add(OSD.FromUUID(wearable.ItemID)); wears.Add(OSD.FromUUID(wearable.AssetID)); } args["wearables"] = wears; } // AgentPreferences from viewer if (AgentPrefs != null) { args["hover_height"] = AgentPrefs.HoverHeight; args["access_prefs"] = AgentPrefs.AccessPrefs; args["perm_everyone"] = AgentPrefs.PermEveryone; args["perm_group"] = AgentPrefs.PermGroup; args["perm_next_owner"] = AgentPrefs.PermNextOwner; args["language"] = AgentPrefs.Language; args["language_is_public"] = AgentPrefs.LanguageIsPublic; args["principal_id"] = m_id; } if (!String.IsNullOrEmpty(CallbackURI)) args["callback_uri"] = OSD.FromString(CallbackURI); if (SatOnGroup != UUID.Zero) { args["sat_on_group"] = OSD.FromUUID(SatOnGroup); args["sat_on_prim"] = OSD.FromUUID(SatOnPrim); args["sit_offset"] = OSD.FromString(SatOnPrimOffset.ToString()); } args["avatar_as_a_prim"] = OSD.FromBoolean(AvatarAsAPrim); return args; } /// <summary> /// Deserialization of agent data. /// Avoiding reflection makes it painful to write, but that's the price! /// </summary> /// <param name="hash"></param> public virtual void Unpack(OSDMap args) { if (args.ContainsKey("region_handle")) UInt64.TryParse(args["region_handle"].AsString(), out RegionHandle); if (args.ContainsKey("circuit_code")) UInt32.TryParse((string)args["circuit_code"].AsString(), out CircuitCode); if (args.ContainsKey("agent_uuid")) AgentID = args["agent_uuid"].AsUUID(); if (args.ContainsKey("session_uuid")) SessionID = args["session_uuid"].AsUUID(); if (args.ContainsKey("position")) Vector3.TryParse(args["position"].AsString(), out Position); if (args.ContainsKey("velocity")) Vector3.TryParse(args["velocity"].AsString(), out Velocity); if (args.ContainsKey("center")) Vector3.TryParse(args["center"].AsString(), out Center); if (args.ContainsKey("size")) Vector3.TryParse(args["size"].AsString(), out Size); if (args.ContainsKey("at_axis")) Vector3.TryParse(args["at_axis"].AsString(), out AtAxis); if (args.ContainsKey("left_axis")) Vector3.TryParse(args["left_axis"].AsString(), out AtAxis); if (args.ContainsKey("up_axis")) Vector3.TryParse(args["up_axis"].AsString(), out AtAxis); if (args.ContainsKey("changed_grid")) ChangedGrid = args["changed_grid"].AsBoolean(); if (args.ContainsKey("far")) Far = (float)(args["far"].AsReal()); if (args.ContainsKey("aspect")) Aspect = (float)args["aspect"].AsReal(); if (args.ContainsKey("throttles")) Throttles = args["throttles"].AsBinary(); if (args.ContainsKey("locomotion_state")) UInt32.TryParse(args["locomotion_state"].AsString(), out LocomotionState); if (args.ContainsKey("head_rotation")) Quaternion.TryParse(args["head_rotation"].AsString(), out HeadRotation); if (args.ContainsKey("body_rotation")) Quaternion.TryParse(args["body_rotation"].AsString(), out BodyRotation); if (args.ContainsKey("control_flags")) UInt32.TryParse(args["control_flags"].AsString(), out ControlFlags); if (args.ContainsKey("energy_level")) EnergyLevel = (float)(args["energy_level"].AsReal()); if (args.ContainsKey("god_level")) Byte.TryParse(args["god_level"].AsString(), out GodLevel); if (args.ContainsKey("always_run")) AlwaysRun = args["always_run"].AsBoolean(); if (args.ContainsKey("prey_agent")) PreyAgent = args["prey_agent"].AsUUID(); if (args.ContainsKey("agent_access")) Byte.TryParse(args["agent_access"].AsString(), out AgentAccess); if (args.ContainsKey("active_group_id")) ActiveGroupID = args["active_group_id"].AsUUID(); if ((args.ContainsKey("groups")) && (args["groups"]).Type == OSDType.Array) { OSDArray groups = (OSDArray)(args["groups"]); Groups = new AgentGroupData[groups.Count]; int i = 0; foreach (OSD o in groups) { if (o.Type == OSDType.Map) { Groups[i++] = new AgentGroupData((OSDMap)o); } } } if ((args.ContainsKey("animations")) && (args["animations"]).Type == OSDType.Array) { OSDArray anims = (OSDArray)(args["animations"]); Anims = new Animation[anims.Count]; int i = 0; foreach (OSD o in anims) { if (o.Type == OSDType.Map) { Anims[i++] = new Animation((OSDMap)o); } } } // Initialize an Appearance Appearance = new AvatarAppearance(AgentID); if (args.ContainsKey("texture_entry")) { byte[] data = args["texture_entry"].AsBinary(); Primitive.TextureEntry textureEntries = new Primitive.TextureEntry(data, 0, data.Length); Appearance.SetTextureEntries(textureEntries); } if (args.ContainsKey("visual_params")) { byte[] visualParams = args["visual_params"].AsBinary(); Appearance.SetVisualParams(visualParams); } if ((args.ContainsKey("wearables")) && (args["wearables"]).Type == OSDType.Array) { OSDArray wears = (OSDArray)(args["wearables"]); List<AvatarWearable> wearables = new List<AvatarWearable>(); int offset = 0; for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++) { if ((offset + 1) < wears.Count) { UUID itemID = wears[offset++].AsUUID(); UUID assetID = wears[offset++].AsUUID(); wearables.Add(new AvatarWearable(i, itemID, assetID)); } else { break; } } Appearance.SetWearables(wearables); } if (args.ContainsKey("callback_uri")) CallbackURI = args["callback_uri"].AsString(); if (args.ContainsKey("avatar_as_a_prim")) AvatarAsAPrim = args["avatar_as_a_prim"].AsBoolean(); if (args.ContainsKey("sat_on_group")) { SatOnGroup = args["sat_on_group"].AsUUID(); SatOnPrim = args["sat_on_prim"].AsUUID(); try { // "sit_offset" previously used OSD.FromVector3(vec) was used to store the data. // Other Vector3 storage uses OSD.FromString(vec.ToString()). // If originating from old region code, that will still be the case // and the TryParse will trigger a format exception. Vector3.TryParse(args["sit_offset"].ToString(), out SatOnPrimOffset); } catch (Exception) { // The following is compatible with OSD.FromVector3(vec), since Vector3.TryParse is not. SatOnPrimOffset = args["sit_offset"].AsVector3(); } } // Initialize AgentPrefs from viewer AgentPrefs = new AgentPreferencesData(); if (args.ContainsKey("hover_height")) { AgentPrefs.HoverHeight = args["hover_height"]; } if (args.ContainsKey("access_prefs")) { AgentPrefs.AccessPrefs = args["access_prefs"]; } if (args.ContainsKey("perm_everyone")) { AgentPrefs.PermEveryone = args["perm_everyone"]; } if (args.ContainsKey("perm_group")) { AgentPrefs.PermGroup = args["perm_group"]; } if (args.ContainsKey("perm_next_owner")) { AgentPrefs.PermNextOwner = args["perm_next_owner"]; } if (args.ContainsKey("language")) { AgentPrefs.Language = args["language"]; } if (args.ContainsKey("language_is_public")) { AgentPrefs.LanguageIsPublic = args["language_is_public"]; } if (args.ContainsKey("principal_id")) { AgentPrefs.PrincipalID = args["principal_id"]; } } public AgentData() { } public void Dump() { System.Console.WriteLine("------------ AgentData ------------"); System.Console.WriteLine("UUID: " + AgentID); System.Console.WriteLine("Region: " + RegionHandle); System.Console.WriteLine("Position: " + Position); } } public class CompleteAgentData : AgentData { public override OSDMap Pack() { return base.Pack(); } public override void Unpack(OSDMap map) { base.Unpack(map); } } }
// <copyright file="AndroidTokenClient.cs" company="Google Inc."> // Copyright (C) 2015 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if UNITY_ANDROID namespace GooglePlayGames.Android { using GooglePlayGames.BasicApi; using GooglePlayGames.BasicApi.SavedGame; using OurUtils; using UnityEngine; using System; using System.Collections.Generic; internal class AndroidHelperFragment { private const string HelperFragmentClass = "com.google.games.bridge.HelperFragment"; public static AndroidJavaObject GetActivity() { using (var jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) { return jc.GetStatic<AndroidJavaObject>("currentActivity"); } } public static AndroidJavaObject GetDefaultPopupView() { using (var helperFragment = new AndroidJavaClass(HelperFragmentClass)) using (var activity = AndroidHelperFragment.GetActivity()) { return helperFragment.CallStatic<AndroidJavaObject>("getDecorView", activity); } } public static void ShowAchievementsUI(Action<UIStatus> cb) { using (var helperFragment = new AndroidJavaClass(HelperFragmentClass)) using (var task = helperFragment.CallStatic<AndroidJavaObject>("showAchievementUi", AndroidHelperFragment.GetActivity())) { AndroidTaskUtils.AddOnSuccessListener<int>( task, uiCode => { OurUtils.Logger.d("ShowAchievementsUI result " + uiCode); cb.Invoke((UIStatus) uiCode); }); AndroidTaskUtils.AddOnFailureListener( task, exception => { OurUtils.Logger.e("ShowAchievementsUI failed with exception"); cb.Invoke(UIStatus.InternalError); }); } } public static void ShowCaptureOverlayUI() { using (var helperFragment = new AndroidJavaClass(HelperFragmentClass)) { helperFragment.CallStatic("showCaptureOverlayUi", AndroidHelperFragment.GetActivity()); } } public static void ShowAllLeaderboardsUI(Action<UIStatus> cb) { using (var helperFragment = new AndroidJavaClass(HelperFragmentClass)) using (var task = helperFragment.CallStatic<AndroidJavaObject>("showAllLeaderboardsUi", AndroidHelperFragment.GetActivity())) { AndroidTaskUtils.AddOnSuccessListener<int>( task, uiCode => { OurUtils.Logger.d("ShowAllLeaderboardsUI result " + uiCode); cb.Invoke((UIStatus) uiCode); }); AndroidTaskUtils.AddOnFailureListener( task, exception => { OurUtils.Logger.e("ShowAllLeaderboardsUI failed with exception"); cb.Invoke(UIStatus.InternalError); }); } } public static void ShowLeaderboardUI(string leaderboardId, LeaderboardTimeSpan timeSpan, Action<UIStatus> cb) { using (var helperFragment = new AndroidJavaClass(HelperFragmentClass)) using (var task = helperFragment.CallStatic<AndroidJavaObject>("showLeaderboardUi", AndroidHelperFragment.GetActivity(), leaderboardId, AndroidJavaConverter.ToLeaderboardVariantTimeSpan(timeSpan))) { AndroidTaskUtils.AddOnSuccessListener<int>( task, uiCode => { OurUtils.Logger.d("ShowLeaderboardUI result " + uiCode); cb.Invoke((UIStatus) uiCode); }); AndroidTaskUtils.AddOnFailureListener( task, exception => { OurUtils.Logger.e("ShowLeaderboardUI failed with exception"); cb.Invoke(UIStatus.InternalError); }); } } public static void ShowCompareProfileWithAlternativeNameHintsUI( string playerId, string otherPlayerInGameName, string currentPlayerInGameName, Action<UIStatus> cb) { using (var helperFragment = new AndroidJavaClass(HelperFragmentClass)) using ( var task = helperFragment.CallStatic<AndroidJavaObject>( "showCompareProfileWithAlternativeNameHintsUI", AndroidHelperFragment.GetActivity(), playerId, otherPlayerInGameName, currentPlayerInGameName)) { AndroidTaskUtils.AddOnSuccessListener<int>(task, uiCode => { OurUtils.Logger.d("ShowCompareProfileWithAlternativeNameHintsUI result " + uiCode); cb.Invoke((UIStatus) uiCode); }); AndroidTaskUtils.AddOnFailureListener(task, exception => { OurUtils.Logger.e("ShowCompareProfileWithAlternativeNameHintsUI failed with exception"); cb.Invoke(UIStatus.InternalError); }); } } public static void IsResolutionRequired( AndroidJavaObject friendsSharingConsentException, Action<bool> cb) { using (var helperFragment = new AndroidJavaClass(HelperFragmentClass)) { var isResolutionRequired = helperFragment.CallStatic<bool>( "isResolutionRequired", friendsSharingConsentException); cb.Invoke(isResolutionRequired); } } public static void AskForLoadFriendsResolution( AndroidJavaObject friendsSharingConsentException, Action<UIStatus> cb) { using (var helperFragment = new AndroidJavaClass(HelperFragmentClass)) using ( var task = helperFragment.CallStatic<AndroidJavaObject>( "askForLoadFriendsResolution", AndroidHelperFragment.GetActivity(), friendsSharingConsentException)) { AndroidTaskUtils.AddOnSuccessListener<int>(task, uiCode => { OurUtils.Logger.d("AskForLoadFriendsResolution result " + uiCode); cb.Invoke((UIStatus) uiCode); }); AndroidTaskUtils.AddOnFailureListener(task, exception => { OurUtils.Logger.e("AskForLoadFriendsResolution failed with exception"); cb.Invoke(UIStatus.InternalError); }); } } public static void ShowSelectSnapshotUI(bool showCreateSaveUI, bool showDeleteSaveUI, int maxDisplayedSavedGames, string uiTitle, Action<SelectUIStatus, ISavedGameMetadata> cb) { using (var helperFragment = new AndroidJavaClass(HelperFragmentClass)) using (var task = helperFragment.CallStatic<AndroidJavaObject>("showSelectSnapshotUi", AndroidHelperFragment.GetActivity(), uiTitle, showCreateSaveUI, showDeleteSaveUI, maxDisplayedSavedGames)) { AndroidTaskUtils.AddOnSuccessListener<AndroidJavaObject>( task, result => { SelectUIStatus status = (SelectUIStatus) result.Get<int>("status"); OurUtils.Logger.d("ShowSelectSnapshotUI result " + status); AndroidJavaObject javaMetadata = result.Get<AndroidJavaObject>("metadata"); AndroidSnapshotMetadata metadata = javaMetadata == null ? null : new AndroidSnapshotMetadata(javaMetadata, /* contents= */null); cb.Invoke(status, metadata); }); AndroidTaskUtils.AddOnFailureListener( task, exception => { OurUtils.Logger.e("ShowSelectSnapshotUI failed with exception"); cb.Invoke(SelectUIStatus.InternalError, null); }); } } } } #endif
//========================================================================================== // // OpenNETCF.IO.Serial.Port // Copyright (c) 2003, OpenNETCF.org // // This library is free software; you can redistribute it and/or modify it under // the terms of the OpenNETCF.org Shared Source License. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License // for more details. // // You should have received a copy of the OpenNETCF.org Shared Source License // along with this library; if not, email licensing@opennetcf.org to request a copy. // // If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please // email licensing@opennetcf.org. // // For general enquiries, email enquiries@opennetcf.org or visit our website at: // http://www.opennetcf.org // //========================================================================================== // // Dec 04: Yuri Astrakhan (YuriAstrakhan at gmail dot com) // Changed access modificers from private to internal on // hPort, rxBufferSize, rxFIFO, txBufferSize, ptxBuffer, rxBufferBusy, and m_CommAPI. // using System; using System.Runtime.InteropServices; using System.Threading; using System.Text; using System.Collections; namespace OpenNETCF.IO.Serial { /// <summary> /// Exceptions throw by the OpenNETCF.IO.Serial class /// </summary> public class CommPortException : Exception { /// <summary> /// Default CommPortException /// </summary> /// <param name="desc"></param> public CommPortException(string desc) : base(desc) {} } /// <summary> /// A class wrapper for serial port communications /// </summary> public class Port : IDisposable { [DllImport("kernel32", EntryPoint="LocalAlloc", SetLastError=true)] internal static extern IntPtr LocalAlloc(int uFlags, int uBytes); [DllImport("kernel32", EntryPoint="LocalFree", SetLastError=true)] internal static extern IntPtr LocalFree(IntPtr hMem); #region delegates and events /// <summary> /// Raised on all enabled communication events /// </summary> public delegate void CommEvent(); /// <summary> /// Raised when the communication state changes /// </summary> public delegate void CommChangeEvent(bool NewState); /// <summary> /// Raised during any communication error /// </summary> public delegate void CommErrorEvent(string Description); /// <summary> /// A communication error has occurred /// </summary> public event CommErrorEvent OnError; /// <summary> /// Serial data has been received /// </summary> public event CommEvent DataReceived; // /// <summary> // /// Overrun of the transmit buffer // /// </summary> // public event CommEvent RxOverrun; /// <summary> /// Transmit complete /// </summary> public event CommEvent TxDone; /// <summary> /// Set flag character was in the receive stream /// </summary> public event CommEvent FlagCharReceived; /// <summary> /// Power change event has occurred /// </summary> public event CommEvent PowerEvent; /// <summary> /// Serial buffer's high-water level has been exceeded /// </summary> public event CommEvent HighWater; /// <summary> /// DSR state has changed /// </summary> public event CommChangeEvent DSRChange; /// <summary> /// Ring signal has been detected /// </summary> public event CommChangeEvent RingChange; /// <summary> /// CTS state has changed /// </summary> public event CommChangeEvent CTSChange; /// <summary> /// RLSD state has changed /// </summary> public event CommChangeEvent RLSDChange; #endregion #region ##### variable declarations ##### private string portName; internal IntPtr hPort = (IntPtr)CommAPI.INVALID_HANDLE_VALUE; // default Rx buffer is 1024 bytes internal int rxBufferSize = 1024; internal Queue rxFIFO; private int rthreshold = 1; // default Tx buffer is 1024 bytes internal int txBufferSize = 1024; private byte[] txBuffer; internal int ptxBuffer = 0; private int sthreshold = 1; internal Mutex rxBufferBusy = new Mutex(); private int inputLength; private DCB dcb = new DCB(); private DetailedPortSettings portSettings; private Thread eventThread; private ManualResetEvent threadStarted = new ManualResetEvent(false); private IntPtr closeEvent; private string closeEventName = "CloseEvent"; private int rts = 0; private bool rtsavail = false; private int dtr = 0; private bool dtravail = false; private int brk = 0; private int setir = 0; private bool isOpen = false; private IntPtr txOverlapped = IntPtr.Zero; private IntPtr rxOverlapped = IntPtr.Zero; internal CommAPI m_CommAPI; /// <summary> /// stores port's capabilities - capabilities can only be retreived not set /// </summary> public readonly CommCapabilities Capabilities = new CommCapabilities(); #endregion private void Init() { // create the API class based on the target if (System.Environment.OSVersion.Platform != PlatformID.WinCE) m_CommAPI=new IO.Serial.WinCommAPI(); else m_CommAPI=new IO.Serial.CECommAPI(); // create a system event for synchronizing Closing closeEvent = m_CommAPI.CreateEvent(true, false, closeEventName); rxFIFO = new Queue(rxBufferSize); txBuffer = new byte[txBufferSize]; portSettings = new DetailedPortSettings(); } #region constructors /// <summary> /// Create a serial port class. The port will be created with defualt settings. /// </summary> /// <param name="PortName">The port to open (i.e. "COM1:")</param> public Port(string PortName) { this.PortName = PortName; Init(); } /// <summary> /// Create a serial port class. /// </summary> /// <param name="PortName">The port to open (i.e. "COM1:")</param> /// <param name="InitialSettings">BasicPortSettings to apply to the new Port</param> public Port(string PortName, BasicPortSettings InitialSettings) { this.PortName = PortName; Init(); //override default ettings portSettings.BasicSettings = InitialSettings; } /// <summary> /// Create a serial port class. /// </summary> /// <param name="PortName">The port to open (i.e. "COM1:")</param> /// <param name="InitialSettings">DetailedPortSettings to apply to the new Port</param> public Port(string PortName, DetailedPortSettings InitialSettings) { this.PortName = PortName; Init(); //override default ettings portSettings = InitialSettings; } /// <summary> /// Create a serial port class. /// </summary> /// <param name="PortName">The port to open (i.e. "COM1:")</param> /// <param name="RxBufferSize">Receive buffer size, in bytes</param> /// <param name="TxBufferSize">Transmit buffer size, in bytes</param> public Port(string PortName, int RxBufferSize, int TxBufferSize) { rxBufferSize = RxBufferSize; txBufferSize = TxBufferSize; this.PortName = PortName; Init(); } /// <summary> /// Create a serial port class. /// </summary> /// <param name="PortName">The port to open (i.e. "COM1:")</param> /// <param name="InitialSettings">BasicPortSettings to apply to the new Port</param> /// <param name="RxBufferSize">Receive buffer size, in bytes</param> /// <param name="TxBufferSize">Transmit buffer size, in bytes</param> public Port(string PortName, BasicPortSettings InitialSettings, int RxBufferSize, int TxBufferSize) { rxBufferSize = RxBufferSize; txBufferSize = TxBufferSize; this.PortName = PortName; Init(); //override default ettings portSettings.BasicSettings = InitialSettings; } /// <summary> /// Create a serial port class. /// </summary> /// <param name="PortName">The port to open (i.e. "COM1:")</param> /// <param name="InitialSettings">DetailedPortSettings to apply to the new Port</param> /// <param name="RxBufferSize">Receive buffer size, in bytes</param> /// <param name="TxBufferSize">Transmit buffer size, in bytes</param> public Port(string PortName, DetailedPortSettings InitialSettings, int RxBufferSize, int TxBufferSize) { rxBufferSize = RxBufferSize; txBufferSize = TxBufferSize; this.PortName = PortName; Init(); //override default ettings portSettings = InitialSettings; } #endregion // since the event thread blocks until the port handle is closed // implement both a Dispose and destrucor to make sure that we // clean up as soon as possible /// <summary> /// Dispose the object's resources /// </summary> public void Dispose() { if(isOpen) this.Close(); } /// <summary> /// Class destructor /// </summary> ~Port() { if(isOpen) this.Close(); } /// <summary> /// The name of the Port (i.e. "COM1:") /// </summary> public string PortName { get { return portName; } set { if(! CommAPI.FullFramework) { // for CE, ensure the port name is colon terminated "COMx:" if(! value.EndsWith(":")) { portName = value + ":"; return; } } portName = value; } } /// <summary> /// Returns whether or not the port is currently open /// </summary> public bool IsOpen { get { return isOpen; } } /// <summary> /// Open the current port /// </summary> /// <returns>true if successful, false if it fails</returns> public bool Open() { if(isOpen) return false; if(CommAPI.FullFramework) { // set up the overlapped tx IO // AutoResetEvent are = new AutoResetEvent(false); OVERLAPPED o = new OVERLAPPED(); txOverlapped = LocalAlloc(0x40, Marshal.SizeOf(o)); o.Offset = 0; o.OffsetHigh = 0; o.hEvent = IntPtr.Zero; Marshal.StructureToPtr(o, txOverlapped, true); } hPort = m_CommAPI.CreateFile(portName); if(hPort == (IntPtr)CommAPI.INVALID_HANDLE_VALUE) { int e = Marshal.GetLastWin32Error(); if(e == (int)APIErrors.ERROR_ACCESS_DENIED) { // port is unavailable return false; } // ClearCommError failed! string error = String.Format("CreateFile Failed: {0}", e); throw new CommPortException(error); } isOpen = true; // set queue sizes m_CommAPI.SetupComm(hPort, rxBufferSize, txBufferSize); // transfer the port settings to a DCB structure dcb.BaudRate = (uint)portSettings.BasicSettings.BaudRate; dcb.ByteSize = portSettings.BasicSettings.ByteSize; dcb.EofChar = (sbyte)portSettings.EOFChar; dcb.ErrorChar = (sbyte)portSettings.ErrorChar; dcb.EvtChar = (sbyte)portSettings.EVTChar; dcb.fAbortOnError = portSettings.AbortOnError; dcb.fBinary = true; dcb.fDsrSensitivity = portSettings.DSRSensitive; dcb.fDtrControl = (DCB.DtrControlFlags)portSettings.DTRControl; dcb.fErrorChar = portSettings.ReplaceErrorChar; dcb.fInX = portSettings.InX; dcb.fNull = portSettings.DiscardNulls; dcb.fOutX = portSettings.OutX; dcb.fOutxCtsFlow = portSettings.OutCTS; dcb.fOutxDsrFlow = portSettings.OutDSR; dcb.fParity = (portSettings.BasicSettings.Parity == Parity.none) ? false : true; dcb.fRtsControl = (DCB.RtsControlFlags)portSettings.RTSControl; dcb.fTXContinueOnXoff = portSettings.TxContinueOnXOff; dcb.Parity = (byte)portSettings.BasicSettings.Parity; dcb.StopBits = (byte)portSettings.BasicSettings.StopBits; dcb.XoffChar = (sbyte)portSettings.XoffChar; dcb.XonChar = (sbyte)portSettings.XonChar; dcb.XonLim = dcb.XoffLim = (ushort)(rxBufferSize / 10); m_CommAPI.SetCommState(hPort, dcb); // store some state values brk = 0; dtr = dcb.fDtrControl == DCB.DtrControlFlags.Enable ? 1 : 0; rts = dcb.fRtsControl == DCB.RtsControlFlags.Enable ? 1 : 0; // set the Comm timeouts CommTimeouts ct = new CommTimeouts(); // reading we'll return immediately // this doesn't seem to work as documented ct.ReadIntervalTimeout = uint.MaxValue; // this = 0xffffffff ct.ReadTotalTimeoutConstant = 0; ct.ReadTotalTimeoutMultiplier = 0; // writing we'll give 5 seconds ct.WriteTotalTimeoutConstant = 5000; ct.WriteTotalTimeoutMultiplier = 0; m_CommAPI.SetCommTimeouts(hPort, ct); // read the ports capabilities bool status=GetPortProperties(); // start the receive thread eventThread = new Thread(new ThreadStart(CommEventThread)); eventThread.Priority = ThreadPriority.Highest; eventThread.Start(); // wait for the thread to actually get spun up threadStarted.WaitOne(); return true; } /// <summary> /// Query the current port's capabilities without accessing it. You can only call the Close() /// method after reading the capabilities. This method does neither initialize nor Open() the /// port. /// </summary> /// /// <example> /// /// </example> public bool Query() { if(isOpen) return false; hPort = m_CommAPI.QueryFile(portName); if(hPort == (IntPtr)CommAPI.INVALID_HANDLE_VALUE) { int e = Marshal.GetLastWin32Error(); if(e == (int)APIErrors.ERROR_ACCESS_DENIED) { // port is unavailable return false; } // ClearCommError failed! string error = String.Format("CreateFile Failed: {0}", e); throw new CommPortException(error); } // read the port's capabilities bool status=GetPortProperties(); return true; } // parameters without closing and reopening the port /// <summary> /// Updates communication settings of the port /// </summary> /// <returns>true if successful, false if it fails</returns> private bool UpdateSettings() { if(!isOpen) return false; // transfer the port settings to a DCB structure dcb.BaudRate = (uint)portSettings.BasicSettings.BaudRate; dcb.ByteSize = portSettings.BasicSettings.ByteSize; dcb.EofChar = (sbyte)portSettings.EOFChar; dcb.ErrorChar = (sbyte)portSettings.ErrorChar; dcb.EvtChar = (sbyte)portSettings.EVTChar; dcb.fAbortOnError = portSettings.AbortOnError; dcb.fBinary = true; dcb.fDsrSensitivity = portSettings.DSRSensitive; dcb.fDtrControl = (DCB.DtrControlFlags)portSettings.DTRControl; dcb.fErrorChar = portSettings.ReplaceErrorChar; dcb.fInX = portSettings.InX; dcb.fNull = portSettings.DiscardNulls; dcb.fOutX = portSettings.OutX; dcb.fOutxCtsFlow = portSettings.OutCTS; dcb.fOutxDsrFlow = portSettings.OutDSR; dcb.fParity = (portSettings.BasicSettings.Parity == Parity.none) ? false : true; dcb.fRtsControl = (DCB.RtsControlFlags)portSettings.RTSControl; dcb.fTXContinueOnXoff = portSettings.TxContinueOnXOff; dcb.Parity = (byte)portSettings.BasicSettings.Parity; dcb.StopBits = (byte)portSettings.BasicSettings.StopBits; dcb.XoffChar = (sbyte)portSettings.XoffChar; dcb.XonChar = (sbyte)portSettings.XonChar; dcb.XonLim = dcb.XoffLim = (ushort)(rxBufferSize / 10); return m_CommAPI.SetCommState(hPort, dcb); } /// <summary> /// Close the current serial port /// </summary> /// <returns>true indicates success, false indicated failure</returns> public bool Close() { if(txOverlapped != IntPtr.Zero) { LocalFree(txOverlapped); txOverlapped = IntPtr.Zero; } if(!isOpen) return false; isOpen = false; // to help catch intentional close if(m_CommAPI.CloseHandle(hPort)) { m_CommAPI.SetEvent(closeEvent); isOpen = false; hPort = (IntPtr)CommAPI.INVALID_HANDLE_VALUE; m_CommAPI.SetEvent(closeEvent); return true; } return false; } /// <summary> /// The Port's output buffer. Set this property to send data. /// </summary> public byte[] Output { set { if(!isOpen) throw new CommPortException("Port not open"); int written = 0; // more than threshold amount so send without buffering if(value.GetLength(0) > sthreshold) { // first send anything already in the buffer if(ptxBuffer > 0) { m_CommAPI.WriteFile(hPort, txBuffer, ptxBuffer, ref written, txOverlapped); ptxBuffer = 0; } m_CommAPI.WriteFile(hPort, value, (int)value.GetLength(0), ref written, txOverlapped); } else { // copy it to the tx buffer value.CopyTo(txBuffer, (int)ptxBuffer); ptxBuffer += (int)value.Length; // now if the buffer is above sthreshold, send it if(ptxBuffer >= sthreshold) { m_CommAPI.WriteFile(hPort, txBuffer, ptxBuffer, ref written, txOverlapped); ptxBuffer = 0; } } } } /// <summary> /// The Port's input buffer. Incoming data is read from here and a read will pull InputLen bytes from the buffer /// <seealso cref="InputLen"/> /// </summary> public byte[] Input { get { if(!isOpen) return null; int dequeueLength = 0; // lock the rx FIFO while reading rxBufferBusy.WaitOne(); // how much data are we *actually* going to return from the call? if(inputLength == 0) dequeueLength = rxFIFO.Count; // pull the entire buffer else dequeueLength = (inputLength < rxFIFO.Count) ? inputLength : rxFIFO.Count; byte[] data = new byte[dequeueLength]; // dequeue the data for(int p = 0 ; p < dequeueLength ; p++) data[p] = (byte)rxFIFO.Dequeue(); // release the mutex so the Rx thread can continue rxBufferBusy.ReleaseMutex(); return data; } } /// <summary> /// The length of the input buffer /// </summary> public int InputLen { get { return inputLength; } set { inputLength = value; } } /// <summary> /// The actual amount of data in the input buffer /// </summary> public int InBufferCount { get { if(!isOpen) return 0; return rxFIFO.Count; } } /// <summary> /// The actual amount of data in the output buffer /// </summary> public int OutBufferCount { get { if(!isOpen) return 0; return ptxBuffer; } } /// <summary> /// The number of bytes that the receive buffer must exceed to trigger a Receive event /// </summary> public int RThreshold { get { return rthreshold; } set { rthreshold = value; } } /// <summary> /// The number of bytes that the transmit buffer must exceed to trigger a Transmit event /// </summary> public int SThreshold { get { return sthreshold; } set { sthreshold = value; } } /// <summary> /// Send or check for a communications BREAK event /// </summary> public bool Break { get { if(!isOpen) return false; return (brk == 1); } set { if(!isOpen) return; if(brk < 0) return; if(hPort == (IntPtr)CommAPI.INVALID_HANDLE_VALUE) return; if (value) { if (m_CommAPI.EscapeCommFunction(hPort, CommEscapes.SETBREAK)) brk = 1; else throw new CommPortException("Failed to set break!"); } else { if (m_CommAPI.EscapeCommFunction(hPort, CommEscapes.CLRBREAK)) brk = 0; else throw new CommPortException("Failed to clear break!"); } } } /// <summary> /// Returns whether or not the current port support a DTR signal /// </summary> public bool DTRAvailable { get { return dtravail; } } /// <summary> /// Gets or sets the current DTR line state (true = 1, false = 0) /// </summary> public bool DTREnable { get { return (dtr == 1); } set { if(dtr < 0) return; if(hPort == (IntPtr)CommAPI.INVALID_HANDLE_VALUE) return; if (value) { if (m_CommAPI.EscapeCommFunction(hPort, CommEscapes.SETDTR)) dtr = 1; else throw new CommPortException("Failed to set DTR!"); } else { if (m_CommAPI.EscapeCommFunction(hPort, CommEscapes.CLRDTR)) dtr = 0; else throw new CommPortException("Failed to clear DTR!"); } } } /// <summary> /// Returns whether or not the current port support an RTS signal /// </summary> public bool RTSAvailable { get { return rtsavail; } } /// <summary> /// Gets or sets the current RTS line state (true = 1, false = 0) /// </summary> public bool RTSEnable { get { return (rts == 1); } set { if(rts < 0) return; if(hPort == (IntPtr)CommAPI.INVALID_HANDLE_VALUE) return; if (value) { if (m_CommAPI.EscapeCommFunction(hPort, CommEscapes.SETRTS)) rts = 1; else throw new CommPortException("Failed to set RTS!"); } else { if (m_CommAPI.EscapeCommFunction(hPort, CommEscapes.CLRRTS)) rts = 0; else throw new CommPortException("Failed to clear RTS!"); } } } /// <summary> /// Gets or sets the com port for IR use (true = 1, false = 0) /// </summary> public bool IREnable { get { return (setir == 1); } set { if(setir < 0) return; if(hPort == (IntPtr)CommAPI.INVALID_HANDLE_VALUE) return; if (value) { if (m_CommAPI.EscapeCommFunction(hPort, CommEscapes.SETIR)) setir = 1; else throw new CommPortException("Failed to set IR!"); } else { if (m_CommAPI.EscapeCommFunction(hPort, CommEscapes.CLRIR)) setir = 0; else throw new CommPortException("Failed to clear IR!"); } } } /// <summary> /// Get or Set the Port's DetailedPortSettings /// </summary> public DetailedPortSettings DetailedSettings { get { return portSettings; } set { portSettings = value; UpdateSettings(); } } /// <summary> /// Get or Set the Port's BasicPortSettings /// </summary> public BasicPortSettings Settings { get { return portSettings.BasicSettings; } set { portSettings.BasicSettings = value; UpdateSettings(); } } /// <summary> /// <code>GetPortProperties initializes the commprop member of the port object</code> /// </summary> /// <returns></returns> private bool GetPortProperties() { bool success; success=m_CommAPI.GetCommProperties(hPort,Capabilities); return (success); } private void CommEventThread() { CommEventFlags eventFlags = new CommEventFlags(); byte[] readbuffer = new Byte[rxBufferSize]; int bytesread = 0; AutoResetEvent rxevent = new AutoResetEvent(false); // specify the set of events to be monitored for the port. if(CommAPI.FullFramework) { m_CommAPI.SetCommMask(hPort, CommEventFlags.ALLPC); // set up the overlapped IO OVERLAPPED o = new OVERLAPPED(); rxOverlapped = LocalAlloc(0x40, Marshal.SizeOf(o)); o.Offset = 0; o.OffsetHigh = 0; o.hEvent = rxevent.Handle; Marshal.StructureToPtr(o, rxOverlapped, true); } else { m_CommAPI.SetCommMask(hPort, CommEventFlags.ALLCE); } try { // let Open() know we're started threadStarted.Set(); #region >>>> thread loop <<<< while(hPort != (IntPtr)CommAPI.INVALID_HANDLE_VALUE) { // wait for a Comm event if(!m_CommAPI.WaitCommEvent(hPort, ref eventFlags)) { int e = Marshal.GetLastWin32Error(); if(e == (int)APIErrors.ERROR_IO_PENDING) { // IO pending so just wait and try again rxevent.WaitOne(); Thread.Sleep(0); continue; } if(e == (int)APIErrors.ERROR_INVALID_HANDLE) { // Calling Port.Close() causes hPort to become invalid // Since Thread.Abort() is unsupported in the CF, we must // accept that calling Close will throw an error here. // Close signals the closeEvent, so wait on it // We wait 1 second, though Close should happen much sooner int eventResult = m_CommAPI.WaitForSingleObject(closeEvent, 1000); if(eventResult == (int)APIConstants.WAIT_OBJECT_0) { // the event was set so close was called hPort = (IntPtr)CommAPI.INVALID_HANDLE_VALUE; // reset our ResetEvent for the next call to Open threadStarted.Reset(); if(isOpen) // this should not be the case...if so, throw an exception for the owner { string error = String.Format("Wait Failed: {0}", e); throw new CommPortException(error); } return; } } // WaitCommEvent failed // 995 means an exit was requested (thread killed) if(e == 995) { return; } else { string error = String.Format("Wait Failed: {0}", e); throw new CommPortException(error); } } // Re-specify the set of events to be monitored for the port. if(CommAPI.FullFramework) { m_CommAPI.SetCommMask(hPort, CommEventFlags.ALLPC); } else { m_CommAPI.SetCommMask(hPort, CommEventFlags.ALLCE); } // check the event for errors #region >>>> error checking <<<< if(((uint)eventFlags & (uint)CommEventFlags.ERR) != 0) { CommErrorFlags errorFlags = new CommErrorFlags(); CommStat commStat = new CommStat(); // get the error status if(!m_CommAPI.ClearCommError(hPort, ref errorFlags, commStat)) { // ClearCommError failed! string error = String.Format("ClearCommError Failed: {0}", Marshal.GetLastWin32Error()); throw new CommPortException(error); } if(((uint)errorFlags & (uint)CommErrorFlags.BREAK) != 0) { // BREAK can set an error, so make sure the BREAK bit is set an continue eventFlags |= CommEventFlags.BREAK; } else { // we have an error. Build a meaningful string and throw an exception StringBuilder s = new StringBuilder("UART Error: ", 80); if ((errorFlags & CommErrorFlags.FRAME) != 0) { s = s.Append("Framing,"); } if ((errorFlags & CommErrorFlags.IOE) != 0) { s = s.Append("IO,"); } if ((errorFlags & CommErrorFlags.OVERRUN) != 0) { s = s.Append("Overrun,"); } if ((errorFlags & CommErrorFlags.RXOVER) != 0) { s = s.Append("Receive Overflow,"); } if ((errorFlags & CommErrorFlags.RXPARITY) != 0) { s = s.Append("Parity,"); } if ((errorFlags & CommErrorFlags.TXFULL) != 0) { s = s.Append("Transmit Overflow,"); } // no known bits are set if(s.Length == 12) { s = s.Append("Unknown"); } // raise an error event if(OnError != null) OnError(s.ToString()); continue; } } // if(((uint)eventFlags & (uint)CommEventFlags.ERR) != 0) #endregion #region >>>> Receive data subsection <<<< // check for RXCHAR if((eventFlags & CommEventFlags.RXCHAR) != 0) { do { // make sure the port handle is valid if(hPort == (IntPtr)CommAPI.INVALID_HANDLE_VALUE) { bytesread = 0; break; } // data came in, put it in the buffer and set the event if (!m_CommAPI.ReadFile(hPort, readbuffer, rxBufferSize, ref bytesread, rxOverlapped)) { string errString = String.Format("ReadFile Failed: {0}", Marshal.GetLastWin32Error()); if(OnError != null) OnError(errString); return; } if (bytesread >= 1) { // take the mutex rxBufferBusy.WaitOne(); // put the data into the fifo // this *may* be a perf problem and needs testing for(int b = 0 ; b < bytesread ; b++) rxFIFO.Enqueue(readbuffer[b]); // get the FIFO length int fifoLength = rxFIFO.Count; // release the mutex rxBufferBusy.ReleaseMutex(); // fire the DataReceived event every RThreshold bytes if((DataReceived != null) && (rthreshold != 0) && (fifoLength >= rthreshold)) { DataReceived(); } } } while (bytesread > 0); } // if((eventFlags & CommEventFlags.RXCHAR) != 0) #endregion #region >>>> line status checking <<<< // check for status changes uint status = 0; m_CommAPI.GetCommModemStatus(hPort, ref status); // check the CTS if(((uint)eventFlags & (uint)CommEventFlags.CTS) != 0) { if(CTSChange != null) CTSChange((status & (uint)CommModemStatusFlags.MS_CTS_ON) != 0); } // check the DSR if(((uint)eventFlags & (uint)CommEventFlags.DSR) != 0) { if(DSRChange != null) DSRChange((status & (uint)CommModemStatusFlags.MS_DSR_ON) != 0); } // check for a RING if(((uint)eventFlags & (uint)CommEventFlags.RING) != 0) { if(RingChange != null) RingChange((status & (uint)CommModemStatusFlags.MS_RING_ON) != 0); } // check for a RLSD if(((uint)eventFlags & (uint)CommEventFlags.RLSD) != 0) { if(RLSDChange != null) RLSDChange((status & (uint)CommModemStatusFlags.MS_RLSD_ON) != 0); } // check for TXEMPTY if(((uint)eventFlags & (uint)CommEventFlags.TXEMPTY) != 0) if(TxDone != null) { TxDone(); } // check for RXFLAG if(((uint)eventFlags & (uint)CommEventFlags.RXFLAG) != 0) if(FlagCharReceived != null) { FlagCharReceived(); } // check for POWER if(((uint)eventFlags & (uint)CommEventFlags.POWER) != 0) if(PowerEvent != null) { PowerEvent(); } // check for high-water state if((eventFlags & CommEventFlags.RX80FULL) != 0) if(HighWater != null) { HighWater(); } #endregion } // while(true) #endregion } // try catch(Exception e) { if(rxOverlapped != IntPtr.Zero) LocalFree(rxOverlapped); if(OnError != null) OnError(e.Message); return; } } } }
using System; namespace IxMilia.Dxf.Objects { public enum DxfUcsOrthographicType { NotOrthographic = 0, Top = 1, Bottom = 2, Front = 3, Back = 4, Left = 5, Right = 6 } public partial class DxfLayout { public string LayoutName { get => _layoutName; set { if (string.IsNullOrEmpty(value)) { throw new InvalidOperationException($"{nameof(LayoutName)} must be non-empty."); } _layoutName = value; } } public override string PlotViewName { get => string.IsNullOrEmpty(base.PlotViewName) ? LayoutName : base.PlotViewName; set => base.PlotViewName = value; } public DxfLayout(string plotViewName, string layoutName) : base(plotViewName) { LayoutName = layoutName; } public IDxfItem PaperSpaceObject { get { return Owner; } set { ((IDxfItemInternal)this).SetOwner(value); } } internal override DxfObject PopulateFromBuffer(DxfCodePairBufferReader buffer) { bool isReadingPlotSettings = true; while (buffer.ItemsRemain) { var pair = buffer.Peek(); if (pair.Code == 0) { break; } while (this.TrySetExtensionData(pair, buffer)) { pair = buffer.Peek(); } if (pair.Code == 0) { break; } if (isReadingPlotSettings) { if (pair.Code == 100 && pair.StringValue == "AcDbLayout") { isReadingPlotSettings = false; } else { if (!base.TrySetPair(pair)) { ExcessCodePairs.Add(pair); } } } else { if (!TrySetPair(pair)) { ExcessCodePairs.Add(pair); } } buffer.Advance(); } return PostParse(); } internal override bool TrySetPair(DxfCodePair pair) { switch (pair.Code) { case 1: this._layoutName = pair.StringValue; break; case 10: this.MinimumLimits = this.MinimumLimits.WithUpdatedX(pair.DoubleValue); break; case 20: this.MinimumLimits = this.MinimumLimits.WithUpdatedY(pair.DoubleValue); break; case 11: this.MaximumLimits = this.MaximumLimits.WithUpdatedX(pair.DoubleValue); break; case 21: this.MaximumLimits = this.MaximumLimits.WithUpdatedY(pair.DoubleValue); break; case 12: this.InsertionBasePoint = this.InsertionBasePoint.WithUpdatedX(pair.DoubleValue); break; case 22: this.InsertionBasePoint = this.InsertionBasePoint.WithUpdatedY(pair.DoubleValue); break; case 32: this.InsertionBasePoint = this.InsertionBasePoint.WithUpdatedZ(pair.DoubleValue); break; case 13: this.UcsOrigin = this.UcsOrigin.WithUpdatedX(pair.DoubleValue); break; case 23: this.UcsOrigin = this.UcsOrigin.WithUpdatedY(pair.DoubleValue); break; case 33: this.UcsOrigin = this.UcsOrigin.WithUpdatedZ(pair.DoubleValue); break; case 14: this.MinimumExtents = this.MinimumExtents.WithUpdatedX(pair.DoubleValue); break; case 24: this.MinimumExtents = this.MinimumExtents.WithUpdatedY(pair.DoubleValue); break; case 34: this.MinimumExtents = this.MinimumExtents.WithUpdatedZ(pair.DoubleValue); break; case 15: this.MaximumExtents = this.MaximumExtents.WithUpdatedX(pair.DoubleValue); break; case 25: this.MaximumExtents = this.MaximumExtents.WithUpdatedY(pair.DoubleValue); break; case 35: this.MaximumExtents = this.MaximumExtents.WithUpdatedZ(pair.DoubleValue); break; case 16: this.UcsXAxis = this.UcsXAxis.WithUpdatedX(pair.DoubleValue); break; case 26: this.UcsXAxis = this.UcsXAxis.WithUpdatedY(pair.DoubleValue); break; case 36: this.UcsXAxis = this.UcsXAxis.WithUpdatedZ(pair.DoubleValue); break; case 17: this.UcsYAxis = this.UcsYAxis.WithUpdatedX(pair.DoubleValue); break; case 27: this.UcsYAxis = this.UcsYAxis.WithUpdatedY(pair.DoubleValue); break; case 37: this.UcsYAxis = this.UcsYAxis.WithUpdatedZ(pair.DoubleValue); break; case 70: this.LayoutFlags = (pair.ShortValue); break; case 71: this.TabOrder = (pair.ShortValue); break; case 76: this.UcsOrthographicType = (DxfUcsOrthographicType)(pair.ShortValue); break; case 146: this.Elevation = (pair.DoubleValue); break; case 331: this.ViewportPointer.Handle = HandleString(pair.StringValue); break; case 333: this.ShadePlotObjectPointer.Handle = HandleString(pair.StringValue); break; case 345: this.TableRecordPointer.Handle = HandleString(pair.StringValue); break; case 346: this.TableRecordBasePointer.Handle = HandleString(pair.StringValue); break; default: return base.TrySetPair(pair); } return true; } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- $Pref::WorldEditor::FileSpec = "Torque Mission Files (*.mis)|*.mis|All Files (*.*)|*.*|"; ////////////////////////////////////////////////////////////////////////// // File Menu Handlers ////////////////////////////////////////////////////////////////////////// function EditorFileMenu::onMenuSelect(%this) { // don't do this since it won't exist if this is a "demo" if(!isWebDemo()) %this.enableItem(2, EditorIsDirty()); } ////////////////////////////////////////////////////////////////////////// // Package that gets temporarily activated to toggle editor after mission loading. // Deactivates itself. package BootEditor { function GameConnection::initialControlSet( %this ) { Parent::initialControlSet( %this ); toggleEditor( true ); deactivatePackage( "BootEditor" ); } }; ////////////////////////////////////////////////////////////////////////// /// Checks the various dirty flags and returns true if the /// mission or other related resources need to be saved. function EditorIsDirty() { // We kept a hard coded test here, but we could break these // into the registered tools if we wanted to. %isDirty = ( isObject( "ETerrainEditor" ) && ( ETerrainEditor.isMissionDirty || ETerrainEditor.isDirty ) ) || ( isObject( "EWorldEditor" ) && EWorldEditor.isDirty ) || ( isObject( "ETerrainPersistMan" ) && ETerrainPersistMan.hasDirty() ); // Give the editor plugins a chance to set the dirty flag. for ( %i = 0; %i < EditorPluginSet.getCount(); %i++ ) { %obj = EditorPluginSet.getObject(%i); %isDirty |= %obj.isDirty(); } return %isDirty; } /// Clears all the dirty state without saving. function EditorClearDirty() { EWorldEditor.isDirty = false; ETerrainEditor.isDirty = false; ETerrainEditor.isMissionDirty = false; ETerrainPersistMan.clearAll(); for ( %i = 0; %i < EditorPluginSet.getCount(); %i++ ) { %obj = EditorPluginSet.getObject(%i); %obj.clearDirty(); } } function EditorQuitGame() { if( EditorIsDirty() && !isWebDemo()) { MessageBoxYesNoCancel("Level Modified", "Would you like to save your changes before quitting?", "EditorSaveMissionMenu(); quit();", "quit();", "" ); } else quit(); } function EditorExitMission() { if( EditorIsDirty() && !isWebDemo() ) { MessageBoxYesNoCancel("Level Modified", "Would you like to save your changes before exiting?", "EditorDoExitMission(true);", "EditorDoExitMission(false);", ""); } else EditorDoExitMission(false); } function EditorDoExitMission(%saveFirst) { if(%saveFirst && !isWebDemo()) { EditorSaveMissionMenu(); } else { EditorClearDirty(); } if (isObject( MainMenuGui )) Editor.close("MainMenuGui"); disconnect(); } function EditorOpenTorsionProject( %projectFile ) { // Make sure we have a valid path to the Torsion installation. %torsionPath = EditorSettings.value( "WorldEditor/torsionPath" ); if( !isFile( %torsionPath ) ) { MessageBoxOK( "Torsion Not Found", "Torsion not found at '" @ %torsionPath @ "'. Please set the correct path in the preferences." ); return; } // Determine the path to the .torsion file. if( %projectFile $= "" ) { %projectName = fileBase( getExecutableName() ); %projectFile = makeFullPath( %projectName @ ".torsion" ); if( !isFile( %projectFile ) ) { %projectFile = findFirstFile( "*.torsion", false ); if( !isFile( %projectFile ) ) { MessageBoxOK( "Project File Not Found", "Cannot find .torsion project file in '" @ getMainDotCsDir() @ "'." ); return; } } } // Open the project in Torsion. shellExecute( %torsionPath, "\"" @ %projectFile @ "\"" ); } function EditorOpenFileInTorsion( %file, %line ) { // Make sure we have a valid path to the Torsion installation. %torsionPath = EditorSettings.value( "WorldEditor/torsionPath" ); if( !isFile( %torsionPath ) ) { MessageBoxOK( "Torsion Not Found", "Torsion not found at '" @ %torsionPath @ "'. Please set the correct path in the preferences." ); return; } // If no file was specified, take the current mission file. if( %file $= "" ) %file = makeFullPath( $Server::MissionFile ); // Open the file in Torsion. %args = "\"" @ %file; if( %line !$= "" ) %args = %args @ ":" @ %line; %args = %args @ "\""; shellExecute( %torsionPath, %args ); } function EditorOpenDeclarationInTorsion( %object ) { %fileName = %object.getFileName(); if( %fileName $= "" ) return; EditorOpenFileInTorsion( makeFullPath( %fileName ), %object.getDeclarationLine() ); } function EditorNewLevel( %file ) { if(isWebDemo()) return; %saveFirst = false; if ( EditorIsDirty() ) { error(knob); %saveFirst = MessageBox("Mission Modified", "Would you like to save changes to the current mission \"" @ $Server::MissionFile @ "\" before creating a new mission?", "SaveDontSave", "Question") == $MROk; } if(%saveFirst) EditorSaveMission(); // Clear dirty flags first to avoid duplicate dialog box from EditorOpenMission() if( isObject( Editor ) ) { EditorClearDirty(); Editor.getUndoManager().clearAll(); } if( %file $= "" ) %file = EditorSettings.value( "WorldEditor/newLevelFile" ); if( !$missionRunning ) { activatePackage( "BootEditor" ); StartLevel( %file ); } else EditorOpenMission(%file); //EWorldEditor.isDirty = true; //ETerrainEditor.isDirty = true; EditorGui.saveAs = true; } function EditorSaveMissionMenu() { if(!$Pref::disableSaving && !isWebDemo()) { if(EditorGui.saveAs) EditorSaveMissionAs(); else EditorSaveMission(); } else { EditorSaveMissionMenuDisableSave(); } } function EditorSaveMission() { // just save the mission without renaming it if(isFunction("getObjectLimit") && $MissionGroup.getFullCount() >= getObjectLimit()) { MessageBoxOKBuy( "Object Limit Reached", "You have exceeded the object limit of " @ getObjectLimit() @ " for this demo. You can remove objects if you would like to add more.", "", "Canvas.showPurchaseScreen(\"objectlimit\");" ); return; } // first check for dirty and read-only files: if((EWorldEditor.isDirty || ETerrainEditor.isMissionDirty) && !isWriteableFileName($Server::MissionFile)) { MessageBox("Error", "Mission file \""@ $Server::MissionFile @ "\" is read-only. Continue?", "Ok", "Stop"); return false; } if(ETerrainEditor.isDirty) { // Find all of the terrain files initContainerTypeSearch($TypeMasks::TerrainObjectType); while ((%terrainObject = containerSearchNext()) != 0) { if (!isWriteableFileName(%terrainObject.terrainFile)) { if (MessageBox("Error", "Terrain file \""@ %terrainObject.terrainFile @ "\" is read-only. Continue?", "Ok", "Stop") == $MROk) continue; else return false; } } } // now write the terrain and mission files out: if(EWorldEditor.isDirty || ETerrainEditor.isMissionDirty) $MissionGroup.save($Server::MissionFile); if(ETerrainEditor.isDirty) { // Find all of the terrain files initContainerTypeSearch($TypeMasks::TerrainObjectType); while ((%terrainObject = containerSearchNext()) != 0) %terrainObject.save(%terrainObject.terrainFile); } ETerrainPersistMan.saveDirty(); // Give EditorPlugins a chance to save. for ( %i = 0; %i < EditorPluginSet.getCount(); %i++ ) { %obj = EditorPluginSet.getObject(%i); if ( %obj.isDirty() ) %obj.onSaveMission( $Server::MissionFile ); } EditorClearDirty(); EditorGui.saveAs = false; return true; } function EditorSaveMissionMenuDisableSave() { GenericPromptDialog-->GenericPromptWindow.text = "Warning"; GenericPromptDialog-->GenericPromptText.setText("Saving disabled in demo mode."); Canvas.pushDialog( GenericPromptDialog ); } function EditorSaveMissionAs( %missionName ) { if(isFunction("getObjectLimit") && $MissionGroup.getFullCount() >= getObjectLimit()) { MessageBoxOKBuy( "Object Limit Reached", "You have exceeded the object limit of " @ getObjectLimit() @ " for this demo. You can remove objects if you would like to add more.", "", "Canvas.showPurchaseScreen(\"objectlimit\");" ); return; } if(!$Pref::disableSaving && !isWebDemo()) { // If we didn't get passed a new mission name then // prompt the user for one. if ( %missionName $= "" ) { %dlg = new SaveFileDialog() { Filters = $Pref::WorldEditor::FileSpec; DefaultPath = EditorSettings.value("LevelInformation/levelsDirectory"); ChangePath = false; OverwritePrompt = true; }; %ret = %dlg.Execute(); if(%ret) { // Immediately override/set the levelsDirectory EditorSettings.setValue( "LevelInformation/levelsDirectory", collapseFilename(filePath( %dlg.FileName )) ); %missionName = %dlg.FileName; } %dlg.delete(); if(! %ret) return; } if( fileExt( %missionName ) !$= ".mis" ) %missionName = %missionName @ ".mis"; EWorldEditor.isDirty = true; %saveMissionFile = $Server::MissionFile; $Server::MissionFile = %missionName; %copyTerrainsFailed = false; // Rename all the terrain files. Save all previous names so we can // reset them if saving fails. %newMissionName = fileBase(%missionName); %oldMissionName = fileBase(%saveMissionFile); initContainerTypeSearch( $TypeMasks::TerrainObjectType ); %savedTerrNames = new ScriptObject(); for( %i = 0;; %i ++ ) { %terrainObject = containerSearchNext(); if( !%terrainObject ) break; %savedTerrNames.array[ %i ] = %terrainObject.terrainFile; %terrainFilePath = makeRelativePath( filePath( %terrainObject.terrainFile ), getMainDotCsDir() ); %terrainFileName = fileName( %terrainObject.terrainFile ); // Workaround to have terrains created in an unsaved "New Level..." mission // moved to the correct place. if( EditorGui.saveAs && %terrainFilePath $= "tools/art/terrains" ) %terrainFilePath = "art/terrains"; // Try and follow the existing naming convention. // If we can't, use systematic terrain file names. if( strstr( %terrainFileName, %oldMissionName ) >= 0 ) %terrainFileName = strreplace( %terrainFileName, %oldMissionName, %newMissionName ); else %terrainFileName = %newMissionName @ "_" @ %i @ ".ter"; %newTerrainFile = %terrainFilePath @ "/" @ %terrainFileName; if (!isWriteableFileName(%newTerrainFile)) { if (MessageBox("Error", "Terrain file \""@ %newTerrainFile @ "\" is read-only. Continue?", "Ok", "Stop") == $MROk) continue; else { %copyTerrainsFailed = true; break; } } if( !%terrainObject.save( %newTerrainFile ) ) { error( "Failed to save '" @ %newTerrainFile @ "'" ); %copyTerrainsFailed = true; break; } %terrainObject.terrainFile = %newTerrainFile; } ETerrainEditor.isDirty = false; // Save the mission. if(%copyTerrainsFailed || !EditorSaveMission()) { // It failed, so restore the mission and terrain filenames. $Server::MissionFile = %saveMissionFile; initContainerTypeSearch( $TypeMasks::TerrainObjectType ); for( %i = 0;; %i ++ ) { %terrainObject = containerSearchNext(); if( !%terrainObject ) break; %terrainObject.terrainFile = %savedTerrNames.array[ %i ]; } } %savedTerrNames.delete(); } else { EditorSaveMissionMenuDisableSave(); } } function EditorOpenMission(%filename) { if( EditorIsDirty() && !isWebDemo() ) { // "EditorSaveBeforeLoad();", "getLoadFilename(\"*.mis\", \"EditorDoLoadMission\");" if(MessageBox("Mission Modified", "Would you like to save changes to the current mission \"" @ $Server::MissionFile @ "\" before opening a new mission?", SaveDontSave, Question) == $MROk) { if(! EditorSaveMission()) return; } } if(%filename $= "") { %dlg = new OpenFileDialog() { Filters = $Pref::WorldEditor::FileSpec; DefaultPath = EditorSettings.value("LevelInformation/levelsDirectory"); ChangePath = false; MustExist = true; }; %ret = %dlg.Execute(); if(%ret) { // Immediately override/set the levelsDirectory EditorSettings.setValue( "LevelInformation/levelsDirectory", collapseFilename(filePath( %dlg.FileName )) ); %filename = %dlg.FileName; } %dlg.delete(); if(! %ret) return; } // close the current editor, it will get cleaned up by MissionCleanup if( isObject( "Editor" ) ) Editor.close( LoadingGui ); EditorClearDirty(); // If we haven't yet connnected, create a server now. // Otherwise just load the mission. if( !$missionRunning ) { activatePackage( "BootEditor" ); StartLevel( %filename ); } else { loadMission( %filename, true ) ; pushInstantGroup(); // recreate and open the editor Editor::create(); MissionCleanup.add( Editor ); MissionCleanup.add( Editor.getUndoManager() ); EditorGui.loadingMission = true; Editor.open(); popInstantGroup(); } } function EditorExportToCollada() { if ( !$Pref::disableSaving && !isWebDemo() ) { %dlg = new SaveFileDialog() { Filters = "COLLADA Files (*.dae)|*.dae|"; DefaultPath = $Pref::WorldEditor::LastPath; DefaultFile = ""; ChangePath = false; OverwritePrompt = true; }; %ret = %dlg.Execute(); if ( %ret ) { $Pref::WorldEditor::LastPath = filePath( %dlg.FileName ); %exportFile = %dlg.FileName; } if( fileExt( %exportFile ) !$= ".dae" ) %exportFile = %exportFile @ ".dae"; %dlg.delete(); if ( !%ret ) return; if ( EditorGui.currentEditor.getId() == ShapeEditorPlugin.getId() ) ShapeEdShapeView.exportToCollada( %exportFile ); else EWorldEditor.colladaExportSelection( %exportFile ); } } function EditorMakePrefab() { // Should this be protected or not? if ( !$Pref::disableSaving && !isWebDemo() ) { %dlg = new SaveFileDialog() { Filters = "Prefab Files (*.prefab)|*.prefab|"; DefaultPath = $Pref::WorldEditor::LastPath; DefaultFile = ""; ChangePath = false; OverwritePrompt = true; }; %ret = %dlg.Execute(); if ( %ret ) { $Pref::WorldEditor::LastPath = filePath( %dlg.FileName ); %saveFile = %dlg.FileName; } if( fileExt( %saveFile ) !$= ".prefab" ) %saveFile = %saveFile @ ".prefab"; %dlg.delete(); if ( !%ret ) return; EWorldEditor.makeSelectionPrefab( %saveFile ); EditorTree.buildVisibleTree( true ); } } function EditorExplodePrefab() { //echo( "EditorExplodePrefab()" ); EWorldEditor.explodeSelectedPrefab(); EditorTree.buildVisibleTree( true ); } function EditorMount() { echo( "EditorMount" ); %size = EWorldEditor.getSelectionSize(); if ( %size != 2 ) return; %a = EWorldEditor.getSelectedObject(0); %b = EWorldEditor.getSelectedObject(1); //%a.mountObject( %b, 0 ); EWorldEditor.mountRelative( %a, %b ); } function EditorUnmount() { echo( "EditorUnmount" ); %obj = EWorldEditor.getSelectedObject(0); %obj.unmount(); } ////////////////////////////////////////////////////////////////////////// // View Menu Handlers ////////////////////////////////////////////////////////////////////////// function EditorViewMenu::onMenuSelect( %this ) { %this.checkItem( 1, EWorldEditor.renderOrthoGrid ); } ////////////////////////////////////////////////////////////////////////// // Edit Menu Handlers ////////////////////////////////////////////////////////////////////////// function EditorEditMenu::onMenuSelect( %this ) { // UndoManager is in charge of enabling or disabling the undo/redo items. Editor.getUndoManager().updateUndoMenu( %this ); // SICKHEAD: It a perfect world we would abstract // cut/copy/paste with a generic selection object // which would know how to process itself. // Give the active editor a chance at fixing up // the state of the edit menu. // Do we really need this check here? if ( isObject( EditorGui.currentEditor ) ) EditorGui.currentEditor.onEditMenuSelect( %this ); } ////////////////////////////////////////////////////////////////////////// function EditorMenuEditDelete() { if ( isObject( EditorGui.currentEditor ) ) EditorGui.currentEditor.handleDelete(); } function EditorMenuEditDeselect() { if ( isObject( EditorGui.currentEditor ) ) EditorGui.currentEditor.handleDeselect(); } function EditorMenuEditCut() { if ( isObject( EditorGui.currentEditor ) ) EditorGui.currentEditor.handleCut(); } function EditorMenuEditCopy() { if ( isObject( EditorGui.currentEditor ) ) EditorGui.currentEditor.handleCopy(); } function EditorMenuEditPaste() { if ( isObject( EditorGui.currentEditor ) ) EditorGui.currentEditor.handlePaste(); } ////////////////////////////////////////////////////////////////////////// // Window Menu Handler ////////////////////////////////////////////////////////////////////////// function EditorToolsMenu::onSelectItem(%this, %id) { %toolName = getField( %this.item[%id], 2 ); EditorGui.setEditor(%toolName, %paletteName ); %this.checkRadioItem(0, %this.getItemCount(), %id); return true; } function EditorToolsMenu::setupDefaultState(%this) { Parent::setupDefaultState(%this); } ////////////////////////////////////////////////////////////////////////// // Camera Menu Handler ////////////////////////////////////////////////////////////////////////// function EditorCameraMenu::onSelectItem(%this, %id, %text) { if(%id == 0 || %id == 1) { // Handle the Free Camera/Orbit Camera toggle %this.checkRadioItem(0, 1, %id); } return Parent::onSelectItem(%this, %id, %text); } function EditorCameraMenu::setupDefaultState(%this) { // Set the Free Camera/Orbit Camera check marks %this.checkRadioItem(0, 1, 0); Parent::setupDefaultState(%this); } function EditorFreeCameraTypeMenu::onSelectItem(%this, %id, %text) { // Handle the camera type radio %this.checkRadioItem(0, 2, %id); return Parent::onSelectItem(%this, %id, %text); } function EditorFreeCameraTypeMenu::setupDefaultState(%this) { // Set the camera type check marks %this.checkRadioItem(0, 2, 0); Parent::setupDefaultState(%this); } function EditorCameraSpeedMenu::onSelectItem(%this, %id, %text) { // Grab and set speed %speed = getField( %this.item[%id], 2 ); $Camera::movementSpeed = %speed; // Update Editor %this.checkRadioItem(0, 6, %id); // Update Toolbar TextEdit EWorldEditorCameraSpeed.setText( $Camera::movementSpeed ); // Update Toolbar Slider CameraSpeedDropdownCtrlContainer-->Slider.setValue( $Camera::movementSpeed ); return true; } function EditorCameraSpeedMenu::setupDefaultState(%this) { // Setup camera speed gui's. Both menu and editorgui %this.setupGuiControls(); //Grab and set speed %defaultSpeed = EditorSettings.value("LevelInformation/levels/" @ EditorGui.levelName @ "/cameraSpeed"); if( %defaultSpeed $= "" ) { // Update Editor with default speed %defaultSpeed = 25; } $Camera::movementSpeed = %defaultSpeed; // Update Toolbar TextEdit EWorldEditorCameraSpeed.setText( %defaultSpeed ); // Update Toolbar Slider CameraSpeedDropdownCtrlContainer-->Slider.setValue( %defaultSpeed ); Parent::setupDefaultState(%this); } function EditorCameraSpeedMenu::setupGuiControls(%this) { // Default levelInfo params %minSpeed = 5; %maxSpeed = 200; %speedA = EditorSettings.value("LevelInformation/levels/" @ EditorGui.levelName @ "/cameraSpeedMin"); %speedB = EditorSettings.value("LevelInformation/levels/" @ EditorGui.levelName @ "/cameraSpeedMax"); if( %speedA < %speedB ) { if( %speedA == 0 ) { if( %speedB > 1 ) %minSpeed = 1; else %minSpeed = 0.1; } else { %minSpeed = %speedA; } %maxSpeed = %speedB; } // Set up the camera speed items %inc = ( (%maxSpeed - %minSpeed) / (%this.getItemCount() - 1) ); for( %i = 0; %i < %this.getItemCount(); %i++) %this.item[%i] = setField( %this.item[%i], 2, (%minSpeed + (%inc * %i))); // Set up min/max camera slider range eval("CameraSpeedDropdownCtrlContainer-->Slider.range = \"" @ %minSpeed @ " " @ %maxSpeed @ "\";"); } ////////////////////////////////////////////////////////////////////////// // World Menu Handler Object Menu ////////////////////////////////////////////////////////////////////////// function EditorWorldMenu::onMenuSelect(%this) { %selSize = EWorldEditor.getSelectionSize(); %lockCount = EWorldEditor.getSelectionLockCount(); %hideCount = EWorldEditor.getSelectionHiddenCount(); %this.enableItem(0, %lockCount < %selSize); // Lock Selection %this.enableItem(1, %lockCount > 0); // Unlock Selection %this.enableItem(3, %hideCount < %selSize); // Hide Selection %this.enableItem(4, %hideCount > 0); // Show Selection %this.enableItem(6, %selSize > 1 && %lockCount == 0); // Align bounds %this.enableItem(7, %selSize > 1 && %lockCount == 0); // Align center %this.enableItem(9, %selSize > 0 && %lockCount == 0); // Reset Transforms %this.enableItem(10, %selSize > 0 && %lockCount == 0); // Reset Selected Rotation %this.enableItem(11, %selSize > 0 && %lockCount == 0); // Reset Selected Scale %this.enableItem(12, %selSize > 0 && %lockCount == 0); // Transform Selection %this.enableItem(14, %selSize > 0 && %lockCount == 0); // Drop Selection %this.enableItem(17, %selSize > 0); // Make Prefab %this.enableItem(18, %selSize > 0); // Explode Prefab %this.enableItem(20, %selSize > 1); // Mount %this.enableItem(21, %selSize > 0); // Unmount } ////////////////////////////////////////////////////////////////////////// function EditorDropTypeMenu::onSelectItem(%this, %id, %text) { // This sets up which drop script function to use when // a drop type is selected in the menu. EWorldEditor.dropType = getField(%this.item[%id], 2); %this.checkRadioItem(0, (%this.getItemCount() - 1), %id); return true; } function EditorDropTypeMenu::setupDefaultState(%this) { // Check the radio item for the currently set drop type. %numItems = %this.getItemCount(); %dropTypeIndex = 0; for( ; %dropTypeIndex < %numItems; %dropTypeIndex ++ ) if( getField( %this.item[ %dropTypeIndex ], 2 ) $= EWorldEditor.dropType ) break; // Default to screenCenter if we didn't match anything. if( %dropTypeIndex > (%numItems - 1) ) %dropTypeIndex = 4; %this.checkRadioItem( 0, (%numItems - 1), %dropTypeIndex ); Parent::setupDefaultState(%this); } ////////////////////////////////////////////////////////////////////////// function EditorAlignBoundsMenu::onSelectItem(%this, %id, %text) { // Have the editor align all selected objects by the selected bounds. EWorldEditor.alignByBounds(getField(%this.item[%id], 2)); return true; } function EditorAlignBoundsMenu::setupDefaultState(%this) { // Allow the parent to set the menu's default state Parent::setupDefaultState(%this); } ////////////////////////////////////////////////////////////////////////// function EditorAlignCenterMenu::onSelectItem(%this, %id, %text) { // Have the editor align all selected objects by the selected axis. EWorldEditor.alignByAxis(getField(%this.item[%id], 2)); return true; } function EditorAlignCenterMenu::setupDefaultState(%this) { // Allow the parent to set the menu's default state Parent::setupDefaultState(%this); }
// // Layer.cs // // Author: // Jonathan Pobst <monkey@jpobst.com> // // Copyright (c) 2010 Jonathan Pobst // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.ComponentModel; using System.Collections.Specialized; using Cairo; using Gdk; namespace Pinta.Core { public class Layer : ObservableObject { private double opacity; private bool hidden; private string name; private BlendMode blend_mode; private Matrix transform = new Matrix(); public Layer () : this (null) { } public Layer (ImageSurface surface) : this (surface, false, 1f, "") { } public Layer (ImageSurface surface, bool hidden, double opacity, string name) { Surface = surface; this.hidden = hidden; this.opacity = opacity; this.name = name; this.blend_mode = BlendMode.Normal; } public ImageSurface Surface { get; set; } public bool Tiled { get; set; } public Matrix Transform { get { return transform; } } public static readonly string OpacityProperty = "Opacity"; public static readonly string HiddenProperty = "Hidden"; public static readonly string NameProperty = "Name"; public static readonly string BlendModeProperty = "BlendMode"; public double Opacity { get { return opacity; } set { if (opacity != value) SetValue (OpacityProperty, ref opacity, value); } } public bool Hidden { get { return hidden; } set { if (hidden != value) SetValue (HiddenProperty, ref hidden, value); } } public string Name { get { return name; } set { if (name != value) SetValue (NameProperty, ref name, value); } } public BlendMode BlendMode { get { return blend_mode; } set { if (blend_mode != value) SetValue (BlendModeProperty, ref blend_mode, value); } } public void Clear () { Surface.Clear (); } public void FlipHorizontal () { Layer dest = PintaCore.Layers.CreateLayer (); using (Cairo.Context g = new Cairo.Context (dest.Surface)) { g.Matrix = new Matrix (-1, 0, 0, 1, Surface.Width, 0); g.SetSource (Surface); g.Paint (); } Surface old = Surface; Surface = dest.Surface; (old as IDisposable).Dispose (); } public void FlipVertical () { Layer dest = PintaCore.Layers.CreateLayer (); using (Cairo.Context g = new Cairo.Context (dest.Surface)) { g.Matrix = new Matrix (1, 0, 0, -1, 0, Surface.Height); g.SetSource (Surface); g.Paint (); } Surface old = Surface; Surface = dest.Surface; (old as IDisposable).Dispose (); } public void Draw(Context ctx) { Draw(ctx, Surface, Opacity); } public void Draw (Context ctx, ImageSurface surface, double opacity, bool transform = true) { ctx.Save (); if (transform) ctx.Transform (Transform); ctx.BlendSurface (surface, BlendMode, opacity); ctx.Restore (); } public virtual void ApplyTransform (Matrix xform, Size new_size) { var old_size = PintaCore.Workspace.ImageSize; var dest = new ImageSurface (Format.ARGB32, new_size.Width, new_size.Height); using (var g = new Context (dest)) { g.Transform (xform); g.SetSource (Surface); g.Paint (); } Surface old = Surface; Surface = dest; old.Dispose (); } public static Gdk.Size RotateDimensions (Gdk.Size originalSize, double angle) { double radians = (angle / 180d) * Math.PI; double cos = Math.Abs (Math.Cos (radians)); double sin = Math.Abs (Math.Sin (radians)); int w = originalSize.Width; int h = originalSize.Height; return new Gdk.Size ((int)(w * cos + h * sin), (int)(w * sin + h * cos)); } public unsafe void HueSaturation (int hueDelta, int satDelta, int lightness) { ImageSurface dest = Surface.Clone (); ColorBgra* dstPtr = (ColorBgra*)dest.DataPtr; int len = Surface.Data.Length / 4; // map the range [0,100] -> [0,100] and the range [101,200] -> [103,400] if (satDelta > 100) satDelta = ((satDelta - 100) * 3) + 100; UnaryPixelOp op; if (hueDelta == 0 && satDelta == 100 && lightness == 0) op = new UnaryPixelOps.Identity (); else op = new UnaryPixelOps.HueSaturationLightness (hueDelta, satDelta, lightness); op.Apply (dstPtr, len); using (Context g = new Context (Surface)) { g.AppendPath (PintaCore.Workspace.ActiveDocument.Selection.SelectionPath); g.FillRule = Cairo.FillRule.EvenOdd; g.Clip (); g.SetSource (dest); g.Paint (); } (dest as IDisposable).Dispose (); } public virtual void Resize (int width, int height) { ImageSurface dest = new ImageSurface (Format.Argb32, width, height); Pixbuf pb = Surface.ToPixbuf(); Pixbuf pbScaled = pb.ScaleSimple (width, height, InterpType.Bilinear); using (Context g = new Context (dest)) { CairoHelper.SetSourcePixbuf (g, pbScaled, 0, 0); g.Paint (); } (Surface as IDisposable).Dispose (); (pb as IDisposable).Dispose (); (pbScaled as IDisposable).Dispose (); Surface = dest; } public virtual void ResizeCanvas (int width, int height, Anchor anchor) { ImageSurface dest = new ImageSurface (Format.Argb32, width, height); int delta_x = Surface.Width - width; int delta_y = Surface.Height - height; using (Context g = new Context (dest)) { switch (anchor) { case Anchor.NW: g.SetSourceSurface (Surface, 0, 0); break; case Anchor.N: g.SetSourceSurface (Surface, -delta_x / 2, 0); break; case Anchor.NE: g.SetSourceSurface (Surface, -delta_x, 0); break; case Anchor.E: g.SetSourceSurface (Surface, -delta_x, -delta_y / 2); break; case Anchor.SE: g.SetSourceSurface (Surface, -delta_x, -delta_y); break; case Anchor.S: g.SetSourceSurface (Surface, -delta_x / 2, -delta_y); break; case Anchor.SW: g.SetSourceSurface (Surface, 0, -delta_y); break; case Anchor.W: g.SetSourceSurface (Surface, 0, -delta_y / 2); break; case Anchor.Center: g.SetSourceSurface (Surface, -delta_x / 2, -delta_y / 2); break; } g.Paint (); } (Surface as IDisposable).Dispose (); Surface = dest; } public virtual void Crop (Gdk.Rectangle rect, Path selection) { ImageSurface dest = new ImageSurface (Format.Argb32, rect.Width, rect.Height); using (Context g = new Context (dest)) { // Move the selected content to the upper left g.Translate (-rect.X, -rect.Y); g.Antialias = Antialias.None; // Optionally, respect the given path. if (selection != null) { g.AppendPath (selection); g.FillRule = Cairo.FillRule.EvenOdd; g.Clip (); } g.SetSource (Surface); g.Paint (); } (Surface as IDisposable).Dispose (); Surface = dest; } } }
// *********************************************************************** // Copyright (c) 2015-2018 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using NUnit.Common; using NUnit; using NUnit.Framework.Api; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Filters; namespace NUnitLite { /// <summary> /// TextRunner is a general purpose class that runs tests and /// outputs to a text-based user interface (TextUI). /// /// Call it from your Main like this: /// new TextRunner(textWriter).Execute(args); /// OR /// new TextUI().Execute(args); /// The provided TextWriter is used by default, unless the /// arguments to Execute override it using -out. The second /// form uses the Console, provided it exists on the platform. /// /// NOTE: When running on a platform without a Console, such /// as Windows Phone, the results will simply not appear if /// you fail to specify a file in the call itself or as an option. /// </summary> public class TextRunner : ITestListener { #region Runner Return Codes /// <summary>OK</summary> public const int OK = 0; /// <summary>Invalid Arguments</summary> public const int INVALID_ARG = -1; /// <summary>File not found</summary> public const int FILE_NOT_FOUND = -2; /// <summary>Test fixture not found - No longer in use</summary> //public const int FIXTURE_NOT_FOUND = -3; /// <summary>Invalid test suite</summary> public const int INVALID_TEST_FIXTURE = -4; /// <summary>Unexpected error occurred</summary> public const int UNEXPECTED_ERROR = -100; #endregion private Assembly _testAssembly; private ITestAssemblyRunner _runner; private NUnitLiteOptions _options; private ITestListener _teamCity = null; private TextUI _textUI; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="TextRunner"/> class /// without specifying an assembly. This is interpreted as allowing /// a single input file in the argument list to Execute(). /// </summary> public TextRunner() { } /// <summary> /// Initializes a new instance of the <see cref="TextRunner"/> class /// specifying a test assembly whose tests are to be run. /// </summary> /// <param name="testAssembly"></param> /// </summary> public TextRunner(Assembly testAssembly) { _testAssembly = testAssembly; } #endregion #region Properties public ResultSummary Summary { get; private set; } #endregion #region Public Methods public int Execute(string[] args) { _options = new NUnitLiteOptions(_testAssembly == null, args); ExtendedTextWriter outWriter = null; if (_options.OutFile != null) { var outFile = Path.Combine(_options.WorkDirectory, _options.OutFile); #if NETSTANDARD1_4 var textWriter = File.CreateText(outFile); #else var textWriter = TextWriter.Synchronized(new StreamWriter(outFile)); #endif outWriter = new ExtendedTextWrapper(textWriter); Console.SetOut(outWriter); } else { outWriter = new ColorConsoleWriter(!_options.NoColor); } using (outWriter) { TextWriter errWriter = null; if (_options.ErrFile != null) { var errFile = Path.Combine(_options.WorkDirectory, _options.ErrFile); #if NETSTANDARD1_4 errWriter = File.CreateText(errFile); #else errWriter = TextWriter.Synchronized(new StreamWriter(errFile)); #endif Console.SetError(errWriter); } using (errWriter) { _textUI = new TextUI(outWriter, Console.In, _options); return Execute(); } } } // Entry point called by AutoRun and by the .NET Standard nunitlite.runner public int Execute(ExtendedTextWriter writer, TextReader reader, string[] args) { _options = new NUnitLiteOptions(_testAssembly == null, args); _textUI = new TextUI(writer, reader, _options); return Execute(); } // Internal Execute depends on _textUI and _options having been set already. private int Execute() { _runner = new NUnitTestAssemblyRunner(new DefaultTestAssemblyBuilder()); InitializeInternalTrace(); try { if (!Directory.Exists(_options.WorkDirectory)) Directory.CreateDirectory(_options.WorkDirectory); if (_options.TeamCity) _teamCity = new TeamCityEventListener(_textUI.Writer); if (_options.ShowVersion || !_options.NoHeader) _textUI.DisplayHeader(); if (_options.ShowHelp) { _textUI.DisplayHelp(); return TextRunner.OK; } // We already showed version as a part of the header if (_options.ShowVersion) return TextRunner.OK; if (_options.ErrorMessages.Count > 0) { _textUI.DisplayErrors(_options.ErrorMessages); _textUI.Writer.WriteLine(); _textUI.DisplayHelp(); return TextRunner.INVALID_ARG; } if (_testAssembly == null && _options.InputFile == null) { _textUI.DisplayError("No test assembly was specified."); _textUI.Writer.WriteLine(); _textUI.DisplayHelp(); return TextRunner.OK; } _textUI.DisplayRuntimeEnvironment(); var testFile = _testAssembly != null ? AssemblyHelper.GetAssemblyPath(_testAssembly) : _options.InputFile; _textUI.DisplayTestFiles(new string[] { testFile }); if (_testAssembly == null) _testAssembly = AssemblyHelper.Load(testFile); if (_options.WaitBeforeExit && _options.OutFile != null) _textUI.DisplayWarning("Ignoring /wait option - only valid for Console"); var runSettings = MakeRunSettings(_options); LoadTests(runSettings); // We display the filters at this point so that any exception message // thrown by CreateTestFilter will be understandable. _textUI.DisplayTestFilters(); TestFilter filter = CreateTestFilter(_options); return _options.Explore ? ExploreTests(filter) : RunTests(filter, runSettings); } catch (FileNotFoundException ex) { _textUI.DisplayError(ex.Message); return FILE_NOT_FOUND; } catch (Exception ex) { _textUI.DisplayError(ex.ToString()); return UNEXPECTED_ERROR; } finally { if (_options.WaitBeforeExit) _textUI.WaitForUser("Press Enter key to continue . . ."); } } #endregion #region Helper Methods private void LoadTests(IDictionary<string, object> runSettings) { TimeStamp startTime = new TimeStamp(); _runner.Load(_testAssembly, runSettings); TimeStamp endTime = new TimeStamp(); _textUI.DisplayDiscoveryReport(startTime, endTime); } public int RunTests(TestFilter filter, IDictionary<string, object> runSettings) { var startTime = DateTime.UtcNow; ITestResult result = _runner.Run(this, filter); ReportResults(result); if (_options.ResultOutputSpecifications.Count > 0) { var outputManager = new OutputManager(_options.WorkDirectory); foreach (var spec in _options.ResultOutputSpecifications) outputManager.WriteResultFile(result, spec, runSettings, filter); } if (Summary.InvalidTestFixtures > 0) return INVALID_TEST_FIXTURE; return Summary.FailureCount + Summary.ErrorCount + Summary.InvalidCount; } public void ReportResults(ITestResult result) { Summary = new ResultSummary(result); if (Summary.ExplicitCount + Summary.SkipCount + Summary.IgnoreCount > 0) _textUI.DisplayNotRunReport(result); if (result.ResultState.Status == TestStatus.Failed || result.ResultState.Status == TestStatus.Warning) _textUI.DisplayErrorsFailuresAndWarningsReport(result); #if FULL if (_options.Full) _textUI.PrintFullReport(_result); #endif _textUI.DisplayRunSettings(); _textUI.DisplaySummaryReport(Summary); } private int ExploreTests(ITestFilter filter) { ITest testNode = _runner.ExploreTests(filter); var specs = _options.ExploreOutputSpecifications; if (specs.Count == 0) new TestCaseOutputWriter().WriteTestFile(testNode, Console.Out); else { var outputManager = new OutputManager(_options.WorkDirectory); foreach (var spec in _options.ExploreOutputSpecifications) outputManager.WriteTestFile(testNode, spec); } return OK; } /// <summary> /// Make the settings for this run - this is public for testing /// </summary> public static Dictionary<string, object> MakeRunSettings(NUnitLiteOptions options) { // Transfer command line options to run settings var runSettings = new Dictionary<string, object>(); if (options.PreFilters.Count > 0) runSettings[FrameworkPackageSettings.LOAD] = options.PreFilters; else if (options.TestList.Count > 0) { var prefilters = new List<string>(); foreach (var testName in options.TestList) { int end = testName.IndexOfAny(new char[] { '(', '<' }); if (end > 0) prefilters.Add(testName.Substring(0, end)); else prefilters.Add(testName); } runSettings[FrameworkPackageSettings.LOAD] = prefilters; } if (options.NumberOfTestWorkers >= 0) runSettings[FrameworkPackageSettings.NumberOfTestWorkers] = options.NumberOfTestWorkers; if (options.InternalTraceLevel != null) runSettings[FrameworkPackageSettings.InternalTraceLevel] = options.InternalTraceLevel; if (options.RandomSeed >= 0) runSettings[FrameworkPackageSettings.RandomSeed] = options.RandomSeed; if (options.WorkDirectory != null) runSettings[FrameworkPackageSettings.WorkDirectory] = Path.GetFullPath(options.WorkDirectory); if (options.DefaultTimeout >= 0) runSettings[FrameworkPackageSettings.DefaultTimeout] = options.DefaultTimeout; if (options.StopOnError) runSettings[FrameworkPackageSettings.StopOnError] = true; if (options.DefaultTestNamePattern != null) runSettings[FrameworkPackageSettings.DefaultTestNamePattern] = options.DefaultTestNamePattern; if (options.TestParameters.Count != 0) runSettings[FrameworkPackageSettings.TestParametersDictionary] = options.TestParameters; return runSettings; } /// <summary> /// Create the test filter for this run - public for testing /// </summary> /// <param name="options"></param> /// <returns></returns> public static TestFilter CreateTestFilter(NUnitLiteOptions options) { var filter = TestFilter.Empty; if (options.TestList.Count > 0) { var testFilters = new List<TestFilter>(); foreach (var test in options.TestList) testFilters.Add(new FullNameFilter(test)); filter = testFilters.Count > 1 ? new OrFilter(testFilters.ToArray()) : testFilters[0]; } if (options.WhereClauseSpecified) { string xmlText = new TestSelectionParser().Parse(options.WhereClause); var whereFilter = TestFilter.FromXml(TNode.FromXml(xmlText)); filter = filter.IsEmpty ? whereFilter : new AndFilter(filter, whereFilter); } return filter; } private void InitializeInternalTrace() { var traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), _options.InternalTraceLevel ?? "Off", true); if (traceLevel != InternalTraceLevel.Off) { var logName = GetLogFileName(); StreamWriter streamWriter = null; if (traceLevel > InternalTraceLevel.Off) { string logPath = Path.Combine(Directory.GetCurrentDirectory(), logName); streamWriter = new StreamWriter(new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.Write)); streamWriter.AutoFlush = true; } InternalTrace.Initialize(streamWriter, traceLevel); } } private string GetLogFileName() { const string LOG_FILE_FORMAT = "InternalTrace.{0}.{1}.{2}"; // Some mobiles don't have an Open With menu item, // so we use .txt, which is opened easily. const string ext = "log"; var baseName = _testAssembly != null ? _testAssembly.GetName().Name : _options.InputFile != null ? Path.GetFileNameWithoutExtension(_options.InputFile) : "NUnitLite"; #if NETSTANDARD1_4 var id = DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss"); #else var id = Process.GetCurrentProcess().Id; #endif return string.Format(LOG_FILE_FORMAT, id, baseName, ext); } #endregion #region ITestListener Members /// <summary> /// Called when a test or suite has just started /// </summary> /// <param name="test">The test that is starting</param> public void TestStarted(ITest test) { if (_teamCity != null) _teamCity.TestStarted(test); _textUI.TestStarted(test); } /// <summary> /// Called when a test has finished /// </summary> /// <param name="result">The result of the test</param> public void TestFinished(ITestResult result) { if (_teamCity != null) _teamCity.TestFinished(result); _textUI.TestFinished(result); } /// <summary> /// Called when a test produces output for immediate display /// </summary> /// <param name="output">A TestOutput object containing the text to display</param> public void TestOutput(TestOutput output) { _textUI.TestOutput(output); } /// <summary> /// Called when a test produces a message to be sent to listeners /// </summary> /// <param name="message">A TestMessage object containing the text to send</param> public void SendMessage(TestMessage message) { } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Microsoft.Surface; using Microsoft.Surface.Presentation; using Microsoft.Surface.Presentation.Controls; using Microsoft.Surface.Presentation.Input; using System.Threading; using Table; using System.ServiceModel; using System.Diagnostics; using Reflectable_v2; using System.IO; namespace Table { [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.Single, UseSynchronizationContext = false)] public partial class MainWindow : SurfaceWindow, ITableService { private const int MAX_CLIENTS = 4; private ServiceHost serviceHost; private Dictionary<int, ICallbackContract> tablets; private Round currentRound; private bool roundInProgress; private bool gameStarted; private CameraCapture camera; private DateTime startTime; private List<Press> presses; private PanopticonProcessor panopticonProcessor; private DateTime lastPercentageUpdate; private FileDownloadService fileDownloadService; private bool researchQuestionSet; private Dictionary<Round.RoundId, Round> rounds; public MainWindow() { rounds = new Dictionary<Round.RoundId, Round>() { { Round.RoundId.PAPER_DIVERGE, new Round(Round.RoundId.PAPER_DIVERGE, 1, Properties.Settings.Default.Round_1_Time, Properties.Settings.Default.Round_1_Instructions) }, { Round.RoundId.PAPER_CONVERGE, new Round(Round.RoundId.PAPER_CONVERGE, 2, Properties.Settings.Default.Round_2_Time, Properties.Settings.Default.Round_2_Instructions) }, { Round.RoundId.PAPER_TRANSCEND, new Round(Round.RoundId.PAPER_TRANSCEND, 3, Properties.Settings.Default.Round_3_Time, Properties.Settings.Default.Round_3_Instructions) }, { Round.RoundId.VIDEO_BROWSE, new Round(Round.RoundId.VIDEO_BROWSE, 4, Properties.Settings.Default.Round_4_Time, Properties.Settings.Default.Round_4_Instructions) }, { Round.RoundId.RESEARCH_QUESTION, new Round(Round.RoundId.RESEARCH_QUESTION, 0, TimeSpan.Zero, "") }, { Round.RoundId.VIDEO_DIVERGE, new Round(Round.RoundId.VIDEO_DIVERGE, 5, Properties.Settings.Default.Round_5_Time, Properties.Settings.Default.Round_5_Instructions) }, { Round.RoundId.VIDEO_CONVERGE, new Round(Round.RoundId.VIDEO_CONVERGE, 6, Properties.Settings.Default.Round_6_Time, Properties.Settings.Default.Round_6_Instructions) }, { Round.RoundId.COMPLETE, new Round(Round.RoundId.COMPLETE, 0, new TimeSpan(), Properties.Settings.Default.Complete_Instructions) } }; currentRound = rounds[Round.RoundId.PAPER_DIVERGE]; tablets = new Dictionary<int, ICallbackContract>(); roundInProgress = false; gameStarted = false; camera = new CameraCapture(); presses = new List<Press>(); lastPercentageUpdate = DateTime.UtcNow; fileDownloadService = new FileDownloadService(); researchQuestionSet = false; panopticonProcessor = new PanopticonProcessor(); panopticonProcessor.PercentageChanged += new PanopticonProcessor.PercentageChangedEventHandler(panopticonProcessor_PercentageChanged); panopticonProcessor.ProcessingCompleted += new PanopticonProcessor.ProcessingCompletedEventHandler(panopticonProcessor_ProcessingCompleted); panopticonProcessor.ProcessingFailed += new PanopticonProcessor.ProcessingFailedEventHandler(panopticonProcessor_ProcessingFailed); NetTcpBinding serviceBinding = new NetTcpBinding(SecurityMode.None); serviceBinding.ReceiveTimeout = TimeSpan.MaxValue; serviceBinding.SendTimeout = TimeSpan.MaxValue; serviceHost = new ServiceHost(this); serviceHost.AddServiceEndpoint(typeof(ITableService), serviceBinding, "net.tcp://localhost:8010"); serviceHost.Open(); Loaded += new RoutedEventHandler(MainWindow_Loaded); InitializeComponent(); } public void Disconnect() { serviceHost.Close(); fileDownloadService.Close(); } private void MainWindow_Loaded(object sender, RoutedEventArgs e) { Window w = App.Current.MainWindow; #if DEBUG w.WindowState = WindowState.Normal; w.WindowStyle = WindowStyle.ThreeDBorderWindow; #else w.WindowStyle = WindowStyle.None; w.WindowState = WindowState.Maximized; w.ResizeMode = ResizeMode.NoResize; w.Topmost = true; #endif } protected override void OnClosed(EventArgs e) { base.OnClosed(e); if (camera.IsCapturing) { camera.StopCapture(); } } private void StartGame() { camera.StartCapture(); startTime = DateTime.UtcNow; gameStarted = true; } private void panopticonProcessor_ProcessingCompleted(object sender) { fileDownloadService.PanopticonVideoFile = panopticonProcessor.Filename; tablets.AsParallel().ForAll((kvp) => { try { kvp.Value.PanopticonCompleted(); } catch (CommunicationObjectAbortedException) { } }); } private void panopticonProcessor_PercentageChanged(object sender, int percentage) { tablets.AsParallel().ForAll((kvp) => { try { kvp.Value.PanopticonPercentageChanged(percentage); } catch (CommunicationObjectAbortedException) { } }); } void panopticonProcessor_ProcessingFailed(object sender, Exception e) { StartPanopticonProcessing(); } private static Color CovertColor(System.Drawing.Color c) { return Color.FromArgb(c.A, c.R, c.G, c.B); } public static Color GetColorFromUser(User u) { Color c; switch (u.Id) { case 0: c = CovertColor(Properties.Settings.Default.User0Colour); break; case 1: c = CovertColor(Properties.Settings.Default.User1Colour); break; case 2: c = CovertColor(Properties.Settings.Default.User2Colour); break; case 3: c = CovertColor(Properties.Settings.Default.User3Colour); break; default: c = Colors.White; break; } return c; } private void StartPanopticonProcessing() { Thread t = new Thread(() => { camera.StopCapture(); fileDownloadService.VideoFile = camera.VideoFileName; panopticonProcessor.ProcessFile(camera.VideoFileName); }); t.Start(); } #region WebService public void Register(User u) { try { ICallbackContract tablet = OperationContext.Current.GetCallbackChannel<ICallbackContract>(); if (tablets.ContainsKey(u.Id)) { tablets.Remove(u.Id); } tablet.SetUserColor(GetColorFromUser(u)); tablets[u.Id] = tablet; tablet.SetRound(currentRound); } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public void RoundComplete(Round r) { try { if (r.Id == Round.RoundId.PAPER_TRANSCEND) { StartPanopticonProcessing(); } int i = (int)(r.Id + 1); Round.RoundId newId = (Round.RoundId)(i % Round.NUM_ROUNDS); if (newId != currentRound.Id) { currentRound = rounds[newId]; roundInProgress = false; bool restart = false; switch (currentRound.Id) { case Round.RoundId.VIDEO_BROWSE: Dispatcher.BeginInvoke(new Action(() => { Tabletop.VideoFile = camera.VideoFileName; Tabletop.Presses = presses; Tabletop.Visibility = Visibility.Visible; Screensaver.Visibility = Visibility.Hidden; })); break; case Round.RoundId.COMPLETE: restart = true; break; } tablets.AsParallel().ForAll((kvp) => { try { kvp.Value.SetRound(currentRound); } catch (CommunicationObjectAbortedException) { } }); if (restart) { Dispatcher.BeginInvoke(new Action(() => { Disconnect(); App.Restart(); })); } } } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public void RequestStartRound() { try { if (!roundInProgress) { roundInProgress = true; if (currentRound.Id == Round.RoundId.PAPER_DIVERGE && !gameStarted) { StartGame(); } DateTime startTime = DateTime.UtcNow; tablets.AsParallel().ForAll((kvp) => { try { kvp.Value.StartRound(startTime); } catch (CommunicationObjectAbortedException) { } }); } } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public void ButtonPress(User u) { try { if (gameStarted && roundInProgress) { Color c = GetColorFromUser(u); u.Color = c; TimeSpan end = DateTime.UtcNow - startTime; TimeSpan start = end - Properties.Settings.Default.PressClipLength; if (start < TimeSpan.Zero) { start = TimeSpan.Zero; } if (end < TimeSpan.Zero) { end = TimeSpan.Zero; } Press p = new Press(start, end, u); presses.Add(p); } } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public bool IsPanopticonProcessingComplete() { try { return panopticonProcessor.IsComplete; } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public string GetPanopticonFilename() { try { return panopticonProcessor.Filename; } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public string GetVideoFilename() { try { return camera.VideoFileName; } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public PanopticonInfo GetPanopticonInfo() { try { return panopticonProcessor.Info; } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public List<Press> GetPresses() { try { return presses; } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public TimeSpan GetStudyLength() { try { return camera.Length; } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public void MakeAnnotation(Annotation a) { try { Tabletop.AddAnnotation(a); } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public void SetResearchQuestion(string s) { try { if (!researchQuestionSet) { researchQuestionSet = true; Dispatcher.BeginInvoke(new Action(() => { Tabletop.SetResearchQuestion(s); })); } } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public long GetPanopticonSize() { try { string path = FileLocationUtility.GetPathInVideoFolderLocation(panopticonProcessor.Filename); FileInfo info = new FileInfo(path); return info.Length; } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public long GetVideoSize() { try { string path = FileLocationUtility.GetPathInVideoFolderLocation(camera.VideoFileName); FileInfo info = new FileInfo(path); return info.Length; } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } public DateTime GetTime() { try { return DateTime.UtcNow; } catch (Exception e) { throw new FaultException(new FaultReason(e.Message + "\r\n" + e.StackTrace)); } } #endregion } }
/***************************************************************************** * Skeleton Utility created by Mitch Thompson * Full irrevocable rights and permissions granted to Esoteric Software *****************************************************************************/ using UnityEngine; using UnityEditor; #if UNITY_4_3 //nothing #else using UnityEditor.AnimatedValues; #endif using System.Collections; using System.Collections.Generic; using Spine; using System.Reflection; namespace Spine.Unity.Editor { [CustomEditor(typeof(SkeletonUtility))] public class SkeletonUtilityInspector : UnityEditor.Editor { public static void AttachIcon (SkeletonUtilityBone utilityBone) { Skeleton skeleton = utilityBone.skeletonUtility.skeletonRenderer.skeleton; Texture2D icon; if (utilityBone.bone.Data.Length == 0) icon = SpineEditorUtilities.Icons.nullBone; else icon = SpineEditorUtilities.Icons.boneNib; foreach (IkConstraint c in skeleton.IkConstraints) { if (c.Target == utilityBone.bone) { icon = SpineEditorUtilities.Icons.constraintNib; break; } } typeof(EditorGUIUtility).InvokeMember("SetIconForObject", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic, null, null, new object[2] { utilityBone.gameObject, icon }); } static void AttachIconsToChildren (Transform root) { if (root != null) { var utilityBones = root.GetComponentsInChildren<SkeletonUtilityBone>(); foreach (var utilBone in utilityBones) { AttachIcon(utilBone); } } } static SkeletonUtilityInspector () { #if UNITY_4_3 showSlots = false; #else showSlots = new AnimBool(false); #endif } SkeletonUtility skeletonUtility; Skeleton skeleton; SkeletonRenderer skeletonRenderer; Transform transform; bool isPrefab; Dictionary<Slot, List<Attachment>> attachmentTable = new Dictionary<Slot, List<Attachment>>(); //GUI stuff #if UNITY_4_3 static bool showSlots; #else static AnimBool showSlots; #endif void OnEnable () { skeletonUtility = (SkeletonUtility)target; skeletonRenderer = skeletonUtility.GetComponent<SkeletonRenderer>(); skeleton = skeletonRenderer.skeleton; transform = skeletonRenderer.transform; if (skeleton == null) { skeletonRenderer.Initialize(false); skeletonRenderer.LateUpdate(); skeleton = skeletonRenderer.skeleton; } UpdateAttachments(); isPrefab |= PrefabUtility.GetPrefabType(this.target) == PrefabType.Prefab; } void OnSceneGUI () { if (skeleton == null) { OnEnable(); return; } foreach (Bone b in skeleton.Bones) { Vector3 pos = new Vector3(b.WorldX, b.WorldY, 0); Quaternion rot = Quaternion.Euler(0, 0, b.WorldRotationX - 90f); Vector3 scale = Vector3.one * b.Data.Length * b.WorldScaleX; SpineEditorUtilities.Icons.BoneMaterial.SetPass(0); Graphics.DrawMeshNow(SpineEditorUtilities.Icons.BoneMesh, transform.localToWorldMatrix * Matrix4x4.TRS(pos, rot, scale)); } } void UpdateAttachments () { attachmentTable = new Dictionary<Slot, List<Attachment>>(); Skin skin = skeleton.Skin; if (skin == null) { skin = skeletonRenderer.skeletonDataAsset.GetSkeletonData(true).DefaultSkin; } for (int i = skeleton.Slots.Count-1; i >= 0; i--) { List<Attachment> attachments = new List<Attachment>(); skin.FindAttachmentsForSlot(i, attachments); attachmentTable.Add(skeleton.Slots.Items[i], attachments); } } void SpawnHierarchyButton (string label, string tooltip, SkeletonUtilityBone.Mode mode, bool pos, bool rot, bool sca, params GUILayoutOption[] options) { GUIContent content = new GUIContent(label, tooltip); if (GUILayout.Button(content, options)) { if (skeletonUtility.skeletonRenderer == null) skeletonUtility.skeletonRenderer = skeletonUtility.GetComponent<SkeletonRenderer>(); if (skeletonUtility.boneRoot != null) { return; } skeletonUtility.SpawnHierarchy(mode, pos, rot, sca); SkeletonUtilityBone[] boneComps = skeletonUtility.GetComponentsInChildren<SkeletonUtilityBone>(); foreach (SkeletonUtilityBone b in boneComps) AttachIcon(b); } } public override void OnInspectorGUI () { if (isPrefab) { GUILayout.Label(new GUIContent("Cannot edit Prefabs", SpineEditorUtilities.Icons.warning)); return; } skeletonUtility.boneRoot = (Transform)EditorGUILayout.ObjectField("Bone Root", skeletonUtility.boneRoot, typeof(Transform), true); GUILayout.BeginHorizontal(); EditorGUI.BeginDisabledGroup(skeletonUtility.boneRoot != null); { if (GUILayout.Button(new GUIContent("Spawn Hierarchy", SpineEditorUtilities.Icons.skeleton), GUILayout.Width(150), GUILayout.Height(24))) SpawnHierarchyContextMenu(); } EditorGUI.EndDisabledGroup(); // if (GUILayout.Button(new GUIContent("Spawn Submeshes", SpineEditorUtilities.Icons.subMeshRenderer), GUILayout.Width(150), GUILayout.Height(24))) // skeletonUtility.SpawnSubRenderers(true); GUILayout.EndHorizontal(); EditorGUI.BeginChangeCheck(); skeleton.FlipX = EditorGUILayout.ToggleLeft("Flip X", skeleton.FlipX); skeleton.FlipY = EditorGUILayout.ToggleLeft("Flip Y", skeleton.FlipY); if (EditorGUI.EndChangeCheck()) { skeletonRenderer.LateUpdate(); SceneView.RepaintAll(); } #if UNITY_4_3 showSlots = EditorGUILayout.Foldout(showSlots, "Slots"); #else showSlots.target = EditorGUILayout.Foldout(showSlots.target, "Slots"); if (EditorGUILayout.BeginFadeGroup(showSlots.faded)) { #endif foreach (KeyValuePair<Slot, List<Attachment>> pair in attachmentTable) { Slot slot = pair.Key; EditorGUILayout.BeginHorizontal(); EditorGUI.indentLevel = 1; EditorGUILayout.LabelField(new GUIContent(slot.Data.Name, SpineEditorUtilities.Icons.slot), GUILayout.ExpandWidth(false)); EditorGUI.BeginChangeCheck(); Color c = EditorGUILayout.ColorField(new Color(slot.R, slot.G, slot.B, slot.A), GUILayout.Width(60)); if (EditorGUI.EndChangeCheck()) { slot.SetColor(c); skeletonRenderer.LateUpdate(); } EditorGUILayout.EndHorizontal(); foreach (Attachment attachment in pair.Value) { if (slot.Attachment == attachment) { GUI.contentColor = Color.white; } else { GUI.contentColor = Color.grey; } EditorGUI.indentLevel = 2; bool isAttached = attachment == slot.Attachment; Texture2D icon = null; if (attachment is MeshAttachment) icon = SpineEditorUtilities.Icons.mesh; else icon = SpineEditorUtilities.Icons.image; bool swap = EditorGUILayout.ToggleLeft(new GUIContent(attachment.Name, icon), attachment == slot.Attachment); if (!isAttached && swap) { slot.Attachment = attachment; skeletonRenderer.LateUpdate(); } else if (isAttached && !swap) { slot.Attachment = null; skeletonRenderer.LateUpdate(); } GUI.contentColor = Color.white; } } #if UNITY_4_3 #else } EditorGUILayout.EndFadeGroup(); if (showSlots.isAnimating) Repaint(); #endif } void SpawnHierarchyContextMenu () { GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("Follow"), false, SpawnFollowHierarchy); menu.AddItem(new GUIContent("Follow (Root Only)"), false, SpawnFollowHierarchyRootOnly); menu.AddSeparator(""); menu.AddItem(new GUIContent("Override"), false, SpawnOverrideHierarchy); menu.AddItem(new GUIContent("Override (Root Only)"), false, SpawnOverrideHierarchyRootOnly); menu.ShowAsContext(); } void SpawnFollowHierarchy () { Selection.activeGameObject = skeletonUtility.SpawnHierarchy(SkeletonUtilityBone.Mode.Follow, true, true, true); AttachIconsToChildren(skeletonUtility.boneRoot); } void SpawnFollowHierarchyRootOnly () { Selection.activeGameObject = skeletonUtility.SpawnRoot(SkeletonUtilityBone.Mode.Follow, true, true, true); AttachIconsToChildren(skeletonUtility.boneRoot); } void SpawnOverrideHierarchy () { Selection.activeGameObject = skeletonUtility.SpawnHierarchy(SkeletonUtilityBone.Mode.Override, true, true, true); AttachIconsToChildren(skeletonUtility.boneRoot); } void SpawnOverrideHierarchyRootOnly () { Selection.activeGameObject = skeletonUtility.SpawnRoot(SkeletonUtilityBone.Mode.Override, true, true, true); AttachIconsToChildren(skeletonUtility.boneRoot); } } }
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2015 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 16.10Release // Tag = development-akw-16.10.00-0 //////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; namespace FickleFrostbite.FIT { /// <summary> /// Implements the SegmentFile profile message. /// </summary> public class SegmentFileMesg : Mesg { #region Fields #endregion #region Constructors public SegmentFileMesg() : base(Profile.mesgs[Profile.SegmentFileIndex]) { } public SegmentFileMesg(Mesg mesg) : base(mesg) { } #endregion // Constructors #region Methods ///<summary> /// Retrieves the MessageIndex field</summary> /// <returns>Returns nullable ushort representing the MessageIndex field</returns> public ushort? GetMessageIndex() { return (ushort?)GetFieldValue(254, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set MessageIndex field</summary> /// <param name="messageIndex_">Nullable field value to be set</param> public void SetMessageIndex(ushort? messageIndex_) { SetFieldValue(254, 0, messageIndex_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the FileUuid field /// Comment: UUID of the segment file</summary> /// <returns>Returns byte[] representing the FileUuid field</returns> public byte[] GetFileUuid() { return (byte[])GetFieldValue(1, 0, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the FileUuid field /// Comment: UUID of the segment file</summary> /// <returns>Returns String representing the FileUuid field</returns> public String GetFileUuidAsString() { return Encoding.UTF8.GetString((byte[])GetFieldValue(1, 0, Fit.SubfieldIndexMainField)); } ///<summary> /// Set FileUuid field /// Comment: UUID of the segment file</summary> /// <returns>Returns String representing the FileUuid field</returns> public void SetFileUuid(String fileUuid_) { SetFieldValue(1, 0, System.Text.Encoding.UTF8.GetBytes(fileUuid_), Fit.SubfieldIndexMainField); } /// <summary> /// Set FileUuid field /// Comment: UUID of the segment file</summary> /// <param name="fileUuid_">field value to be set</param> public void SetFileUuid(byte[] fileUuid_) { SetFieldValue(1, 0, fileUuid_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Enabled field /// Comment: Enabled state of the segment file</summary> /// <returns>Returns nullable Bool enum representing the Enabled field</returns> public Bool? GetEnabled() { object obj = GetFieldValue(3, 0, Fit.SubfieldIndexMainField); Bool? value = obj == null ? (Bool?)null : (Bool)obj; return value; } /// <summary> /// Set Enabled field /// Comment: Enabled state of the segment file</summary> /// <param name="enabled_">Nullable field value to be set</param> public void SetEnabled(Bool? enabled_) { SetFieldValue(3, 0, enabled_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the UserProfilePrimaryKey field /// Comment: Primary key of the user that created the segment file</summary> /// <returns>Returns nullable uint representing the UserProfilePrimaryKey field</returns> public uint? GetUserProfilePrimaryKey() { return (uint?)GetFieldValue(4, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set UserProfilePrimaryKey field /// Comment: Primary key of the user that created the segment file</summary> /// <param name="userProfilePrimaryKey_">Nullable field value to be set</param> public void SetUserProfilePrimaryKey(uint? userProfilePrimaryKey_) { SetFieldValue(4, 0, userProfilePrimaryKey_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field LeaderType</returns> public int GetNumLeaderType() { return GetNumFieldValues(7, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the LeaderType field /// Comment: Leader type of each leader in the segment file</summary> /// <param name="index">0 based index of LeaderType element to retrieve</param> /// <returns>Returns nullable SegmentLeaderboardType enum representing the LeaderType field</returns> public SegmentLeaderboardType? GetLeaderType(int index) { object obj = GetFieldValue(7, index, Fit.SubfieldIndexMainField); SegmentLeaderboardType? value = obj == null ? (SegmentLeaderboardType?)null : (SegmentLeaderboardType)obj; return value; } /// <summary> /// Set LeaderType field /// Comment: Leader type of each leader in the segment file</summary> /// <param name="index">0 based index of leader_type</param> /// <param name="leaderType_">Nullable field value to be set</param> public void SetLeaderType(int index, SegmentLeaderboardType? leaderType_) { SetFieldValue(7, index, leaderType_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field LeaderGroupPrimaryKey</returns> public int GetNumLeaderGroupPrimaryKey() { return GetNumFieldValues(8, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the LeaderGroupPrimaryKey field /// Comment: Group primary key of each leader in the segment file</summary> /// <param name="index">0 based index of LeaderGroupPrimaryKey element to retrieve</param> /// <returns>Returns nullable uint representing the LeaderGroupPrimaryKey field</returns> public uint? GetLeaderGroupPrimaryKey(int index) { return (uint?)GetFieldValue(8, index, Fit.SubfieldIndexMainField); } /// <summary> /// Set LeaderGroupPrimaryKey field /// Comment: Group primary key of each leader in the segment file</summary> /// <param name="index">0 based index of leader_group_primary_key</param> /// <param name="leaderGroupPrimaryKey_">Nullable field value to be set</param> public void SetLeaderGroupPrimaryKey(int index, uint? leaderGroupPrimaryKey_) { SetFieldValue(8, index, leaderGroupPrimaryKey_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field LeaderActivityId</returns> public int GetNumLeaderActivityId() { return GetNumFieldValues(9, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the LeaderActivityId field /// Comment: Activity ID of each leader in the segment file</summary> /// <param name="index">0 based index of LeaderActivityId element to retrieve</param> /// <returns>Returns nullable uint representing the LeaderActivityId field</returns> public uint? GetLeaderActivityId(int index) { return (uint?)GetFieldValue(9, index, Fit.SubfieldIndexMainField); } /// <summary> /// Set LeaderActivityId field /// Comment: Activity ID of each leader in the segment file</summary> /// <param name="index">0 based index of leader_activity_id</param> /// <param name="leaderActivityId_">Nullable field value to be set</param> public void SetLeaderActivityId(int index, uint? leaderActivityId_) { SetFieldValue(9, index, leaderActivityId_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field LeaderActivityIdString</returns> public int GetNumLeaderActivityIdString() { return GetNumFieldValues(10, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the LeaderActivityIdString field /// Comment: String version of the activity ID of each leader in the segment file. 21 characters long for each ID, express in decimal</summary> /// <param name="index">0 based index of LeaderActivityIdString element to retrieve</param> /// <returns>Returns byte[] representing the LeaderActivityIdString field</returns> public byte[] GetLeaderActivityIdString(int index) { return (byte[])GetFieldValue(10, index, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the LeaderActivityIdString field /// Comment: String version of the activity ID of each leader in the segment file. 21 characters long for each ID, express in decimal</summary> /// <param name="index">0 based index of LeaderActivityIdString element to retrieve</param> /// <returns>Returns String representing the LeaderActivityIdString field</returns> public String GetLeaderActivityIdStringAsString(int index) { return Encoding.UTF8.GetString((byte[])GetFieldValue(10, index, Fit.SubfieldIndexMainField)); } ///<summary> /// Set LeaderActivityIdString field /// Comment: String version of the activity ID of each leader in the segment file. 21 characters long for each ID, express in decimal</summary> /// <param name="index">0 based index of LeaderActivityIdString element to retrieve</param> /// <returns>Returns String representing the LeaderActivityIdString field</returns> public void SetLeaderActivityIdString(int index, String leaderActivityIdString_) { SetFieldValue(10, index, System.Text.Encoding.UTF8.GetBytes(leaderActivityIdString_), Fit.SubfieldIndexMainField); } /// <summary> /// Set LeaderActivityIdString field /// Comment: String version of the activity ID of each leader in the segment file. 21 characters long for each ID, express in decimal</summary> /// <param name="index">0 based index of leader_activity_id_string</param> /// <param name="leaderActivityIdString_">field value to be set</param> public void SetLeaderActivityIdString(int index, byte[] leaderActivityIdString_) { SetFieldValue(10, index, leaderActivityIdString_, Fit.SubfieldIndexMainField); } #endregion // Methods } // Class } // namespace
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; using NPoco; using NUnit.Framework; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.Composing; using Umbraco.Cms.Core.Configuration; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Persistence.Querying; using Umbraco.Cms.Core.Persistence.Repositories; using Umbraco.Cms.Core.PropertyEditors; using Umbraco.Cms.Core.Scoping; using Umbraco.Cms.Core.Security; using Umbraco.Cms.Core.Serialization; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Infrastructure.Persistence; using Umbraco.Cms.Infrastructure.Persistence.Dtos; using Umbraco.Cms.Infrastructure.Persistence.Querying; using Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement; using Umbraco.Cms.Tests.Common.Builders; using Umbraco.Cms.Tests.Common.Testing; using Umbraco.Cms.Tests.Integration.Testing; using Umbraco.Extensions; using Constants = Umbraco.Cms.Core.Constants; namespace Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositories { [TestFixture] [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] public class MemberRepositoryTest : UmbracoIntegrationTest { private IPasswordHasher PasswordHasher => GetRequiredService<IPasswordHasher>(); private IDataTypeService DataTypeService => GetRequiredService<IDataTypeService>(); private IMemberTypeRepository MemberTypeRepository => GetRequiredService<IMemberTypeRepository>(); private IMemberGroupRepository MemberGroupRepository => GetRequiredService<IMemberGroupRepository>(); private IJsonSerializer JsonSerializer => GetRequiredService<IJsonSerializer>(); private MemberRepository CreateRepository(IScopeProvider provider) { var accessor = (IScopeAccessor)provider; ITagRepository tagRepo = GetRequiredService<ITagRepository>(); IRelationTypeRepository relationTypeRepository = GetRequiredService<IRelationTypeRepository>(); IRelationRepository relationRepository = GetRequiredService<IRelationRepository>(); var propertyEditors = new PropertyEditorCollection(new DataEditorCollection(() => Enumerable.Empty<IDataEditor>())); var dataValueReferences = new DataValueReferenceFactoryCollection(() => Enumerable.Empty<IDataValueReferenceFactory>()); return new MemberRepository( accessor, AppCaches.Disabled, LoggerFactory.CreateLogger<MemberRepository>(), MemberTypeRepository, MemberGroupRepository, tagRepo, Mock.Of<ILanguageRepository>(), relationRepository, relationTypeRepository, PasswordHasher, propertyEditors, dataValueReferences, DataTypeService, JsonSerializer, Mock.Of<IEventAggregator>(), Options.Create(new MemberPasswordConfigurationSettings())); } [Test] public void GetMember() { IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { MemberRepository repository = CreateRepository(provider); IMember member = CreateTestMember(); member = repository.Get(member.Id); Assert.That(member, Is.Not.Null); Assert.That(member.HasIdentity, Is.True); } } [Test] public void GetMembers() { IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { MemberRepository repository = CreateRepository(provider); IMemberType type = CreateTestMemberType(); IMember m1 = CreateTestMember(type, "Test 1", "test1@test.com", "pass1", "test1"); IMember m2 = CreateTestMember(type, "Test 2", "test2@test.com", "pass2", "test2"); IEnumerable<IMember> members = repository.GetMany(m1.Id, m2.Id); Assert.That(members, Is.Not.Null); Assert.That(members.Count(), Is.EqualTo(2)); Assert.That(members.Any(x => x == null), Is.False); Assert.That(members.Any(x => x.HasIdentity == false), Is.False); } } [Test] public void GetAllMembers() { IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { MemberRepository repository = CreateRepository(provider); IMemberType type = CreateTestMemberType(); for (int i = 0; i < 5; i++) { CreateTestMember(type, "Test " + i, "test" + i + "@test.com", "pass" + i, "test" + i); } IEnumerable<IMember> members = repository.GetMany(); Assert.That(members, Is.Not.Null); Assert.That(members.Any(x => x == null), Is.False); Assert.That(members.Count(), Is.EqualTo(5)); Assert.That(members.Any(x => x.HasIdentity == false), Is.False); } } [Test] public void QueryMember() { // Arrange IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { MemberRepository repository = CreateRepository(provider); var key = Guid.NewGuid(); IMember member = CreateTestMember(key: key); // Act IQuery<IMember> query = scope.SqlContext.Query<IMember>().Where(x => x.Key == key); IEnumerable<IMember> result = repository.Get(query); // Assert Assert.That(result.Count(), Is.EqualTo(1)); Assert.That(result.First().Id, Is.EqualTo(member.Id)); } } [Test] public void SaveMember() { IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { MemberRepository repository = CreateRepository(provider); IMember member = CreateTestMember(); IMember sut = repository.Get(member.Id); Assert.That(sut, Is.Not.Null); Assert.That(sut.HasIdentity, Is.True); Assert.That(sut.Name, Is.EqualTo("Johnny Hefty")); Assert.That(sut.Email, Is.EqualTo("johnny@example.com")); Assert.That(sut.RawPasswordValue, Is.EqualTo("123")); Assert.That(sut.Username, Is.EqualTo("hefty")); TestHelper.AssertPropertyValuesAreEqual(sut, member); } } [Test] public void MemberHasBuiltinProperties() { IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { MemberRepository repository = CreateRepository(provider); MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeRepository.Save(memberType); Member member = MemberBuilder.CreateSimpleMember(memberType, "Johnny Hefty", "johnny@example.com", "123", "hefty"); repository.Save(member); IMember sut = repository.Get(member.Id); Assert.That(memberType.CompositionPropertyGroups.Count(), Is.EqualTo(2)); Assert.That(memberType.CompositionPropertyTypes.Count(), Is.EqualTo(3 + ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper).Count)); Assert.That(sut.Properties.Count(), Is.EqualTo(3 + ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper).Count)); PropertyGroup grp = memberType.CompositionPropertyGroups.FirstOrDefault(x => x.Name == Constants.Conventions.Member.StandardPropertiesGroupName); Assert.IsNotNull(grp); string[] aliases = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper).Select(x => x.Key).ToArray(); foreach (IPropertyType p in memberType.CompositionPropertyTypes.Where(x => aliases.Contains(x.Alias))) { Assert.AreEqual(grp.Id, p.PropertyGroupId.Value); } } } [Test] public void SavingPreservesPassword() { IMember sut; IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { MemberRepository repository = CreateRepository(provider); MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeRepository.Save(memberType); Member member = MemberBuilder.CreateSimpleMember(memberType, "Johnny Hefty", "johnny@example.com", "123", "hefty"); repository.Save(member); sut = repository.Get(member.Id); // When the password is null it will not overwrite what is already there. sut.RawPasswordValue = null; repository.Save(sut); sut = repository.Get(member.Id); Assert.That(sut.RawPasswordValue, Is.EqualTo("123")); } } [Test] public void SavingUpdatesNameAndEmail() { IMember sut; IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { MemberRepository repository = CreateRepository(provider); MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeRepository.Save(memberType); Member member = MemberBuilder.CreateSimpleMember(memberType, "Johnny Hefty", "johnny@example.com", "123", "hefty"); repository.Save(member); sut = repository.Get(member.Id); sut.Username = "This is new"; sut.Email = "thisisnew@hello.com"; repository.Save(sut); sut = repository.Get(member.Id); Assert.That(sut.Email, Is.EqualTo("thisisnew@hello.com")); Assert.That(sut.Username, Is.EqualTo("This is new")); } } [Test] public void QueryMember_WithSubQuery() { IScopeProvider provider = ScopeProvider; IQuery<IMember> query = provider.SqlContext.Query<IMember>().Where(x => ((Member)x).LongStringPropertyValue.Contains("1095") && ((Member)x).PropertyTypeAlias == "headshot"); Sql<ISqlContext> sqlSubquery = GetSubquery(); var translator = new SqlTranslator<IMember>(sqlSubquery, query); Sql<ISqlContext> subquery = translator.Translate(); Sql<ISqlContext> sql = GetBaseQuery(false) .Append("WHERE umbracoNode.id IN (" + subquery.SQL + ")", subquery.Arguments) .OrderByDescending<ContentVersionDto>(x => x.VersionDate) .OrderBy<NodeDto>(x => x.SortOrder); Debug.Print(sql.SQL); Assert.That(sql.SQL, Is.Not.Empty); } private IMember CreateTestMember(IMemberType memberType = null, string name = null, string email = null, string password = null, string username = null, Guid? key = null) { IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { MemberRepository repository = CreateRepository(provider); if (memberType == null) { memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeRepository.Save(memberType); } Member member = MemberBuilder.CreateSimpleMember(memberType, name ?? "Johnny Hefty", email ?? "johnny@example.com", password ?? "123", username ?? "hefty", key); repository.Save(member); scope.Complete(); return member; } } private IMemberType CreateTestMemberType(string alias = null) { IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { MemberRepository repository = CreateRepository(provider); MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(alias); MemberTypeRepository.Save(memberType); scope.Complete(); return memberType; } } private Sql<ISqlContext> GetBaseQuery(bool isCount) { IScopeProvider provider = ScopeProvider; if (isCount) { Sql<ISqlContext> sqlCount = provider.SqlContext.Sql() .SelectCount() .From<NodeDto>() .InnerJoin<ContentDto>().On<ContentDto, NodeDto>(left => left.NodeId, right => right.NodeId) .InnerJoin<ContentTypeDto>().On<ContentTypeDto, ContentDto>(left => left.NodeId, right => right.ContentTypeId) .InnerJoin<ContentVersionDto>().On<ContentVersionDto, NodeDto>(left => left.NodeId, right => right.NodeId) .InnerJoin<MemberDto>().On<MemberDto, ContentDto>(left => left.NodeId, right => right.NodeId) .Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId); return sqlCount; } Sql<ISqlContext> sql = provider.SqlContext.Sql(); sql.Select( "umbracoNode.*", $"{Constants.DatabaseSchema.Tables.Content}.contentTypeId", "cmsContentType.alias AS ContentTypeAlias", $"{Constants.DatabaseSchema.Tables.ContentVersion}.versionId", $"{Constants.DatabaseSchema.Tables.ContentVersion}.versionDate", "cmsMember.Email", "cmsMember.LoginName", "cmsMember.Password", Constants.DatabaseSchema.Tables.PropertyData + ".id AS PropertyDataId", Constants.DatabaseSchema.Tables.PropertyData + ".propertytypeid", Constants.DatabaseSchema.Tables.PropertyData + ".dateValue", Constants.DatabaseSchema.Tables.PropertyData + ".intValue", Constants.DatabaseSchema.Tables.PropertyData + ".textValue", Constants.DatabaseSchema.Tables.PropertyData + ".varcharValue", "cmsPropertyType.id", "cmsPropertyType.Alias", "cmsPropertyType.Description", "cmsPropertyType.Name", "cmsPropertyType.mandatory", "cmsPropertyType.validationRegExp", "cmsPropertyType.sortOrder AS PropertyTypeSortOrder", "cmsPropertyType.propertyTypeGroupId", "cmsPropertyType.dataTypeId", "cmsDataType.propertyEditorAlias", "cmsDataType.dbType") .From<NodeDto>() .InnerJoin<ContentDto>().On<ContentDto, NodeDto>(left => left.NodeId, right => right.NodeId) .InnerJoin<ContentTypeDto>().On<ContentTypeDto, ContentDto>(left => left.NodeId, right => right.ContentTypeId) .InnerJoin<ContentVersionDto>().On<ContentVersionDto, NodeDto>(left => left.NodeId, right => right.NodeId) .InnerJoin<MemberDto>().On<MemberDto, ContentDto>(left => left.NodeId, right => right.NodeId) .LeftJoin<PropertyTypeDto>().On<PropertyTypeDto, ContentDto>(left => left.ContentTypeId, right => right.ContentTypeId) .LeftJoin<DataTypeDto>().On<DataTypeDto, PropertyTypeDto>(left => left.NodeId, right => right.DataTypeId) .LeftJoin<PropertyDataDto>().On<PropertyDataDto, PropertyTypeDto>(left => left.PropertyTypeId, right => right.Id) .Append("AND " + Constants.DatabaseSchema.Tables.PropertyData + $".versionId = {Constants.DatabaseSchema.Tables.ContentVersion}.id") .Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId); return sql; } private Sql<ISqlContext> GetSubquery() { IScopeProvider provider = ScopeProvider; Sql<ISqlContext> sql = provider.SqlContext.Sql(); sql.Select("umbracoNode.id") .From<NodeDto>() .InnerJoin<ContentDto>().On<ContentDto, NodeDto>(left => left.NodeId, right => right.NodeId) .InnerJoin<ContentTypeDto>().On<ContentTypeDto, ContentDto>(left => left.NodeId, right => right.ContentTypeId) .InnerJoin<ContentVersionDto>().On<ContentVersionDto, NodeDto>(left => left.NodeId, right => right.NodeId) .InnerJoin<MemberDto>().On<MemberDto, ContentDto>(left => left.NodeId, right => right.NodeId) .LeftJoin<PropertyTypeDto>().On<PropertyTypeDto, ContentDto>(left => left.ContentTypeId, right => right.ContentTypeId) .LeftJoin<DataTypeDto>().On<DataTypeDto, PropertyTypeDto>(left => left.NodeId, right => right.DataTypeId) .LeftJoin<PropertyDataDto>().On<PropertyDataDto, PropertyTypeDto>(left => left.PropertyTypeId, right => right.Id) .Append("AND " + Constants.DatabaseSchema.Tables.PropertyData + $".versionId = {Constants.DatabaseSchema.Tables.ContentVersion}.id") .Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId); return sql; } private Guid NodeObjectTypeId => Constants.ObjectTypes.Member; } }
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; namespace Amazon.EC2.Model { /// <summary> /// Creates a network interface in the specified subnet. /// </summary> /// <remarks> /// This action is supported only in Amazon VPC. /// </remarks> [XmlRootAttribute(IsNullable = false)] public class CreateNetworkInterfaceRequest : EC2Request { private string subnetIdField; private string descriptionField; private string privateIpAddressField; private List<string> groupIdField; private List<PrivateIpAddress> privateIpAddressesField; private int? secondaryPrivateIpAddressCountField; /// <summary> /// The ID of the subnet to associate with the network interface. /// </summary> [XmlElementAttribute(ElementName = "SubnetId")] public string SubnetId { get { return this.subnetIdField; } set { this.subnetIdField = value; } } /// <summary> /// Sets the ID of the subnet to associate with the network interface. /// </summary> /// <param name="subnetId">ID of the subnet</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateNetworkInterfaceRequest WithSubnetId(string subnetId) { this.subnetIdField = subnetId; return this; } /// <summary> /// Checks if the SubnetId property is set /// </summary> /// <returns>true if the SubnetId property is set</returns> public bool IsSetSubnetId() { return !string.IsNullOrEmpty(this.subnetIdField); } /// <summary> /// The description of the network interface. /// </summary> [XmlElementAttribute(ElementName = "Description")] public string Description { get { return this.descriptionField; } set { this.descriptionField = value; } } /// <summary> /// Sets the description of the network interface. /// </summary> /// <param name="description">Description of the network interface</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateNetworkInterfaceRequest WithDescription(string description) { this.descriptionField = description; return this; } /// <summary> /// Checks if the Description property is set /// </summary> /// <returns>true if the Description property is set</returns> public bool IsSetDescription() { return !string.IsNullOrEmpty(this.descriptionField); } /// <summary> /// The primary private IP address of the network interface. /// </summary> [XmlElementAttribute(ElementName = "PrivateIpAddress")] public string PrivateIpAddress { get { return this.privateIpAddressField; } set { this.privateIpAddressField = value; } } /// <summary> /// Sets the primary private IP address of the network interface. /// </summary> /// <param name="ipAddress">IP address of the network interface</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateNetworkInterfaceRequest WithPrivateIpAddress(string ipAddress) { this.privateIpAddressField = ipAddress; return this; } /// <summary> /// Checks if the PrivateIpAddress property is set /// </summary> /// <returns>true of the PrivateIpAddress property is set</returns> public bool IsSetPrivateIpAddress() { return !string.IsNullOrEmpty(this.privateIpAddressField); } /// <summary> /// A list of security group IDs for use by the network interface. /// </summary> [XmlElementAttribute(ElementName = "GroupId")] public List<string> GroupId { get { if (this.groupIdField == null) { this.groupIdField = new List<string>(); } return this.groupIdField; } set { this.groupIdField = value; } } /// <summary> /// Sets the list of security group IDs for use by the network interface. /// </summary> /// <param name="list">List of security group IDs</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateNetworkInterfaceRequest WithGroupId(params string[] list) { foreach (string item in list) { GroupId.Add(item); } return this; } /// <summary> /// Checks if the GroupId property is set /// </summary> /// <returns>true if the GroupId is set</returns> public bool IsSetGroupId() { return (GroupId.Count > 0); } /// <summary> /// Private IP addresses. /// </summary> [XmlElementAttribute(ElementName = "PrivateIpAddresses")] public List<PrivateIpAddress> PrivateIpAddresses { get { if (this.privateIpAddressesField == null) { this.privateIpAddressesField = new List<PrivateIpAddress>(); } return this.privateIpAddressesField; } set { this.privateIpAddressesField = value; } } /// <summary> /// Sets private IP addresses. /// </summary> /// <param name="privateIpAddresses">Private IP addresses.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateNetworkInterfaceRequest WithPrivateIpAddresses(params PrivateIpAddress[] privateIpAddresses) { foreach (PrivateIpAddress privateIpAddress in privateIpAddresses) { PrivateIpAddresses.Add(privateIpAddress); } return this; } /// <summary> /// Checks if the PrivateIpAddresses property is set /// </summary> /// <returns>true if the PrivateIpAddresses property is set</returns> public bool IsSetPrivateIpAddresses() { return PrivateIpAddresses.Count > 0; } /// <summary> /// Number of secondary private IP addresses. /// </summary> [XmlElementAttribute(ElementName = "SecondaryPrivateIpAddressCount")] public int SecondaryPrivateIpAddressCount { get { return this.secondaryPrivateIpAddressCountField.GetValueOrDefault(); } set { this.secondaryPrivateIpAddressCountField = value; } } /// <summary> /// Sets the number of secondary private IP addresses. /// </summary> /// <param name="secondaryPrivateIpAddressCount">Number of secondary private IP addresses.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public CreateNetworkInterfaceRequest WithSecondaryPrivateIpAddressCount(int secondaryPrivateIpAddressCount) { this.secondaryPrivateIpAddressCountField = secondaryPrivateIpAddressCount; return this; } /// <summary> /// Checks if the SecondaryPrivateIpAddressCount property is set /// </summary> /// <returns>true if the SecondaryPrivateIpAddressCount property is set</returns> public bool IsSetSecondaryPrivateIpAddressCount() { return this.secondaryPrivateIpAddressCountField != null; } } }
using FakeServer.Common; using FakeServer.Controllers; using JsonFlatFileDataStore; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace FakeServer.Test { public class DynamicControllerTests { [Fact] public void GetCollections() { var filePath = UTHelpers.Up(); var ds = new DataStore(filePath); var apiSettings = Options.Create(new ApiSettings()); var dsSettings = Options.Create(new DataStoreSettings()); var controller = new DynamicController(ds, apiSettings, dsSettings); var collections = controller.GetKeys(); Assert.Equal(7, collections.Count()); UTHelpers.Down(filePath); } [Fact] public async Task PutItem_NoUpsert() { var filePath = UTHelpers.Up(); var ds = new DataStore(filePath); var apiSettings = Options.Create(new ApiSettings { UpsertOnPut = false }); var dsSettings = Options.Create(new DataStoreSettings()); var controller = new DynamicController(ds, apiSettings, dsSettings); var result = await controller.ReplaceItem("my_test", "2", JToken.Parse("{ 'id': 2, 'name': 'Raymond', 'age': 32 }")); Assert.IsType<NotFoundResult>(result); UTHelpers.Down(filePath); } [Fact] public async Task PutItem_Upsert() { var filePath = UTHelpers.Up(); var ds = new DataStore(filePath); var apiSettings = Options.Create(new ApiSettings { UpsertOnPut = true }); var dsSettings = Options.Create(new DataStoreSettings()); var controller = new DynamicController(ds, apiSettings, dsSettings); var result = await controller.ReplaceItem("my_test", "2", JToken.Parse("{ 'id': 2, 'name': 'Raymond', 'age': 32 }")); Assert.IsType<NoContentResult>(result); var itemResult = controller.GetItem("my_test", "2"); Assert.IsType<OkObjectResult>(itemResult); var okObjectResult = itemResult as OkObjectResult; dynamic item = okObjectResult.Value as ExpandoObject; Assert.Equal("Raymond", item.name); UTHelpers.Down(filePath); } [Fact] public async Task PutItem_Upsert_Id_String() { var filePath = UTHelpers.Up(); var ds = new DataStore(filePath); var apiSettings = Options.Create(new ApiSettings { UpsertOnPut = true }); var dsSettings = Options.Create(new DataStoreSettings()); var controller = new DynamicController(ds, apiSettings, dsSettings); var result = await controller.ReplaceItem("my_test_string", "acdc", JToken.Parse("{ 'id': 2, 'text': 'Hello' }")) as NoContentResult; Assert.Equal(204, result.StatusCode); var itemResult = controller.GetItem("my_test_string", "acdc") as OkObjectResult; dynamic item = itemResult.Value as ExpandoObject; Assert.Equal("acdc", item.id); Assert.Equal("Hello", item.text); UTHelpers.Down(filePath); } [Fact] public void GetItems_FavouriteMovieWithQueryString() { var filePath = UTHelpers.Up(); var ds = new DataStore(filePath); var apiSettings = Options.Create(new ApiSettings()); var dsSettings = Options.Create(new DataStoreSettings()); var controller = new DynamicController(ds, apiSettings, dsSettings); controller.ControllerContext = new ControllerContext(); controller.ControllerContext.HttpContext = new DefaultHttpContext(); controller.ControllerContext.HttpContext.Request.QueryString = new QueryString("?parents.favouriteMovie=Predator"); // NOTE: Can't but skip and take to querystring with tests var result = controller.GetItems("families", 0, 100) as OkObjectResult; Assert.Equal(11, ((IEnumerable<dynamic>)result.Value).Count()); UTHelpers.Down(filePath); } [Fact] public void GetItems_FriendsWithQueryString() { var filePath = UTHelpers.Up(); var ds = new DataStore(filePath); var apiSettings = Options.Create(new ApiSettings()); var dsSettings = Options.Create(new DataStoreSettings()); var controller = new DynamicController(ds, apiSettings, dsSettings); controller.ControllerContext = new ControllerContext(); controller.ControllerContext.HttpContext = new DefaultHttpContext(); controller.ControllerContext.HttpContext.Request.QueryString = new QueryString("?children.friends.name=Castillo"); var result = controller.GetItems("families") as OkObjectResult; Assert.Equal(2, ((IEnumerable<dynamic>)result.Value).Count()); UTHelpers.Down(filePath); } [Fact] public void GetNested_ParentsSingleWork() { var filePath = UTHelpers.Up(); var ds = new DataStore(filePath); var apiSettings = Options.Create(new ApiSettings()); var dsSettings = Options.Create(new DataStoreSettings()); var controller = new DynamicController(ds, apiSettings, dsSettings); var result = controller.GetNested("families", 1, "parents/1/work") as OkObjectResult; Assert.Equal("APEXTRI", ((dynamic)result.Value).companyName); UTHelpers.Down(filePath); } [Fact] public void GetNested_ParentsSingle() { var filePath = UTHelpers.Up(); var ds = new DataStore(filePath); var apiSettings = Options.Create(new ApiSettings()); var dsSettings = Options.Create(new DataStoreSettings()); var controller = new DynamicController(ds, apiSettings, dsSettings); var result = controller.GetNested("families", 1, "parents/1") as OkObjectResult; Assert.Equal("Kim", ((dynamic)result.Value).name); UTHelpers.Down(filePath); } [Fact] public void GetNested_ParentsList() { var filePath = UTHelpers.Up(); var ds = new DataStore(filePath); var apiSettings = Options.Create(new ApiSettings()); var dsSettings = Options.Create(new DataStoreSettings()); var controller = new DynamicController(ds, apiSettings, dsSettings); var result = controller.GetNested("families", 1, "parents") as OkObjectResult; Assert.Equal(2, ((IEnumerable<dynamic>)result.Value).Count()); UTHelpers.Down(filePath); } [Fact] public void GetItems_UseResultObject() { var filePath = UTHelpers.Up(); var ds = new DataStore(filePath); var apiSettings = Options.Create(new ApiSettings { UseResultObject = true }); var dsSettings = Options.Create(new DataStoreSettings()); var controller = new DynamicController(ds, apiSettings, dsSettings); controller.ControllerContext = new ControllerContext(); controller.ControllerContext.HttpContext = new DefaultHttpContext(); controller.ControllerContext.HttpContext.Request.QueryString = new QueryString(""); var result = controller.GetItems("families", 4, 10) as OkObjectResult; dynamic resultObject = JsonConvert.DeserializeObject<dynamic>(JsonConvert.SerializeObject(result.Value)); Assert.Equal(10, resultObject.results.Count); Assert.Equal(4, resultObject.skip.Value); Assert.Equal(10, resultObject.take.Value); Assert.Equal(20, resultObject.count.Value); UTHelpers.Down(filePath); } [Fact] public void GetItems_UseResultObject_offsetlimit() { var filePath = UTHelpers.Up(); var ds = new DataStore(filePath); var apiSettings = Options.Create(new ApiSettings { UseResultObject = true }); var dsSettings = Options.Create(new DataStoreSettings()); var controller = new DynamicController(ds, apiSettings, dsSettings); controller.ControllerContext = new ControllerContext(); controller.ControllerContext.HttpContext = new DefaultHttpContext(); controller.ControllerContext.HttpContext.Request.QueryString = new QueryString("?offset=5&limit=12"); var result = controller.GetItems("families") as OkObjectResult; var resultObject = JsonConvert.DeserializeObject<dynamic>(JsonConvert.SerializeObject(result.Value)); Assert.Equal(12, resultObject.results.Count); Assert.Equal(5, resultObject.offset.Value); Assert.Equal(12, resultObject.limit.Value); Assert.Equal(20, resultObject.count.Value); UTHelpers.Down(filePath); } [Fact] public void GetItems_EmptyCollection() { var filePath = UTHelpers.Up(); var ds = new DataStore(filePath); var apiSettings = Options.Create(new ApiSettings { UseResultObject = true }); var dsSettings = Options.Create(new DataStoreSettings()); var controller = new DynamicController(ds, apiSettings, dsSettings); controller.ControllerContext = new ControllerContext(); controller.ControllerContext.HttpContext = new DefaultHttpContext(); var result = controller.GetItems("empty_collection") as OkObjectResult; var resultObject = JsonConvert.DeserializeObject<dynamic>(JsonConvert.SerializeObject(result.Value)); Assert.Equal(0, resultObject.results.Count); Assert.Equal(0, resultObject.skip.Value); Assert.Equal(512, resultObject.take.Value); Assert.Equal(0, resultObject.count.Value); UTHelpers.Down(filePath); } [Fact] public void GetItems_UseResultObject_page_and_per_page() { var filePath = UTHelpers.Up(); var ds = new DataStore(filePath); var apiSettings = Options.Create(new ApiSettings { UseResultObject = true }); var dsSettings = Options.Create(new DataStoreSettings()); var controller = new DynamicController(ds, apiSettings, dsSettings); controller.ControllerContext = new ControllerContext(); controller.ControllerContext.HttpContext = new DefaultHttpContext(); controller.ControllerContext.HttpContext.Request.QueryString = new QueryString("?page=1&per_page=12"); var result = controller.GetItems("families", 1, 12) as OkObjectResult; var resultObject = JsonConvert.DeserializeObject<dynamic>(JsonConvert.SerializeObject(result.Value)); Assert.Equal(12, resultObject.results.Count); Assert.Equal(1, resultObject.page.Value); Assert.Equal(12, resultObject.per_page.Value); Assert.Equal(20, resultObject.count.Value); UTHelpers.Down(filePath); } [Fact] public void GetItems_Single() { var filePath = UTHelpers.Up(); var ds = new DataStore(filePath); var apiSettings = Options.Create(new ApiSettings { UpsertOnPut = true }); var dsSettings = Options.Create(new DataStoreSettings()); var controller = new DynamicController(ds, apiSettings, dsSettings); var itemResult = controller.GetItems("configuration"); Assert.IsType<OkObjectResult>(itemResult); var okObjectResult = itemResult as OkObjectResult; dynamic item = okObjectResult.Value as ExpandoObject; Assert.Equal("abba", item.password); UTHelpers.Down(filePath); } [Fact] public void GetItem_Single_BadRequest() { var filePath = UTHelpers.Up(); var ds = new DataStore(filePath); var apiSettings = Options.Create(new ApiSettings { UpsertOnPut = true }); var dsSettings = Options.Create(new DataStoreSettings()); var controller = new DynamicController(ds, apiSettings, dsSettings); var itemResult = controller.GetItem("configuration", "0"); Assert.IsType<BadRequestResult>(itemResult); UTHelpers.Down(filePath); } [Fact] public void GetNested_Single_BadRequest() { var filePath = UTHelpers.Up(); var ds = new DataStore(filePath); var apiSettings = Options.Create(new ApiSettings()); var dsSettings = Options.Create(new DataStoreSettings()); var controller = new DynamicController(ds, apiSettings, dsSettings); var result = controller.GetNested("configuration", 0, "ip"); Assert.IsType<BadRequestResult>(result); UTHelpers.Down(filePath); } [Fact] public async Task AddItem_Single_Conflict() { var filePath = UTHelpers.Up(); var ds = new DataStore(filePath); var apiSettings = Options.Create(new ApiSettings()); var dsSettings = Options.Create(new DataStoreSettings()); var controller = new DynamicController(ds, apiSettings, dsSettings); var item = new { value = "hello" }; var result = await controller.AddNewItem("configuration", JToken.FromObject(item)); Assert.IsType<ConflictResult>(result); UTHelpers.Down(filePath); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.InteractiveWindow.Commands { internal sealed class Commands : IInteractiveWindowCommands { private const string _commandSeparator = ","; private readonly Dictionary<string, IInteractiveWindowCommand> _commands; private readonly int _maxCommandNameLength; private readonly IInteractiveWindow _window; private readonly IContentType _commandContentType; private readonly IStandardClassificationService _classificationRegistry; private IContentType _languageContentType; private ITextBuffer _previousBuffer; public string CommandPrefix { get; set; } public bool InCommand { get { return _window.CurrentLanguageBuffer.ContentType == _commandContentType; } } internal Commands(IInteractiveWindow window, string prefix, IEnumerable<IInteractiveWindowCommand> commands, IContentTypeRegistryService contentTypeRegistry = null, IStandardClassificationService classificationRegistry = null) { CommandPrefix = prefix; _window = window; Dictionary<string, IInteractiveWindowCommand> commandsDict = new Dictionary<string, IInteractiveWindowCommand>(); foreach (var command in commands) { int length = 0; foreach (var name in command.Names) { if (commandsDict.ContainsKey(name)) { throw new InvalidOperationException(string.Format(InteractiveWindowResources.DuplicateCommand, string.Join(", ", command.Names))); } if (length != 0) { length += _commandSeparator.Length; } length += name.Length; commandsDict[name] = command; } if (length == 0) { throw new InvalidOperationException(string.Format(InteractiveWindowResources.MissingCommandName, command.GetType().Name)); } _maxCommandNameLength = Math.Max(_maxCommandNameLength, length); } _commands = commandsDict; _classificationRegistry = classificationRegistry; if (contentTypeRegistry != null) { _commandContentType = contentTypeRegistry.GetContentType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName); } if (window != null) { window.SubmissionBufferAdded += Window_SubmissionBufferAdded; window.Properties[typeof(IInteractiveWindowCommands)] = this; } } private void Window_SubmissionBufferAdded(object sender, SubmissionBufferAddedEventArgs e) { if (_previousBuffer != null) { _previousBuffer.Changed -= NewBufferChanged; } _languageContentType = e.NewBuffer.ContentType; e.NewBuffer.Changed += NewBufferChanged; _previousBuffer = e.NewBuffer; } private void NewBufferChanged(object sender, TextContentChangedEventArgs e) { bool isCommand = IsCommand(e.After.GetExtent()); ITextBuffer buffer = e.After.TextBuffer; IContentType contentType = buffer.ContentType; IContentType newContentType = null; if (contentType == _languageContentType) { if (isCommand) { newContentType = _commandContentType; } } else { if (!isCommand) { newContentType = _languageContentType; } } if (newContentType != null) { buffer.ChangeContentType(newContentType, editTag: null); } } internal bool IsCommand(SnapshotSpan span) { SnapshotSpan prefixSpan, commandSpan, argumentsSpan; return TryParseCommand(span, out prefixSpan, out commandSpan, out argumentsSpan) != null; } internal IInteractiveWindowCommand TryParseCommand(SnapshotSpan span, out SnapshotSpan prefixSpan, out SnapshotSpan commandSpan, out SnapshotSpan argumentsSpan) { string prefix = CommandPrefix; SnapshotSpan trimmed = span.TrimStart(); if (!trimmed.StartsWith(prefix)) { prefixSpan = commandSpan = argumentsSpan = default(SnapshotSpan); return null; } prefixSpan = trimmed.SubSpan(0, prefix.Length); var nameAndArgs = trimmed.SubSpan(prefix.Length).TrimStart(); SnapshotPoint nameEnd = nameAndArgs.IndexOfAnyWhiteSpace() ?? span.End; commandSpan = new SnapshotSpan(span.Snapshot, Span.FromBounds(nameAndArgs.Start.Position, nameEnd.Position)); argumentsSpan = new SnapshotSpan(span.Snapshot, Span.FromBounds(nameEnd.Position, span.End.Position)).Trim(); return this[commandSpan.GetText()]; } public IInteractiveWindowCommand this[string name] { get { IInteractiveWindowCommand command; _commands.TryGetValue(name, out command); return command; } } public IEnumerable<IInteractiveWindowCommand> GetCommands() { return _commands.Values; } internal IEnumerable<string> Help() { string format = "{0,-" + _maxCommandNameLength + "} {1}"; return _commands.OrderBy(entry => entry.Key).Select(cmd => string.Format(format, cmd.Key, cmd.Value.Description)); } public IEnumerable<ClassificationSpan> Classify(SnapshotSpan span) { SnapshotSpan prefixSpan, commandSpan, argumentsSpan; var command = TryParseCommand(span.Snapshot.GetExtent(), out prefixSpan, out commandSpan, out argumentsSpan); if (command == null) { yield break; } if (span.OverlapsWith(prefixSpan)) { yield return Classification(span.Snapshot, prefixSpan, _classificationRegistry.Keyword); } if (span.OverlapsWith(commandSpan)) { yield return Classification(span.Snapshot, commandSpan, _classificationRegistry.Keyword); } if (argumentsSpan.Length > 0) { foreach (var classifiedSpan in command.ClassifyArguments(span.Snapshot, argumentsSpan.Span, span.Span)) { yield return classifiedSpan; } } } private ClassificationSpan Classification(ITextSnapshot snapshot, Span span, IClassificationType classificationType) { return new ClassificationSpan(new SnapshotSpan(snapshot, span), classificationType); } public Task<ExecutionResult> TryExecuteCommand() { var span = _window.CurrentLanguageBuffer.CurrentSnapshot.GetExtent(); SnapshotSpan prefixSpan, commandSpan, argumentsSpan; var command = TryParseCommand(span, out prefixSpan, out commandSpan, out argumentsSpan); if (command == null) { return null; } try { return command.Execute(_window, argumentsSpan.GetText()) ?? ExecutionResult.Failed; } catch (Exception e) { _window.ErrorOutputWriter.WriteLine(string.Format("Command '{0}' failed: {1}", command.Names.First(), e.Message)); return ExecutionResult.Failed; } } private const string HelpIndent = " "; private static readonly string[] s_shortcutDescriptions = new[] { "Enter Evaluate the current input if it appears to be complete.", "Ctrl-Enter If the caret is in current pending input submission, evaluate the entire submission.", " If the caret is in a previous input block, copy that input text to the end of the buffer.", "Shift-Enter If the caret is in the current pending input submission, insert a new line.", "Escape If the caret is in the current pending input submission, delete the entire submission.", "Alt-UpArrow Paste previous input at end of buffer, rotate through history.", "Alt-DownArrow Paste next input at end of buffer, rotate through history.", "UpArrow Normal editor buffer navigation.", "DownArrow Normal editor buffer navigation.", "Ctrl-K, Ctrl-Enter Paste the selection at the end of interactive buffer, leave caret at the end of input.", "Ctrl-E, Ctrl-Enter Paste and execute the selection before any pending input in the interactive buffer.", "Ctrl-A Alternatively select the input block containing the caret, or whole buffer.", }; public void DisplayHelp() { _window.WriteLine("Keyboard shortcuts:"); foreach (var line in s_shortcutDescriptions) { _window.Write(HelpIndent); _window.WriteLine(line); } _window.WriteLine("REPL commands:"); foreach (var line in Help()) { _window.Write(HelpIndent); _window.WriteLine(line); } } public void DisplayCommandUsage(IInteractiveWindowCommand command, TextWriter writer, bool displayDetails) { if (displayDetails) { writer.WriteLine(command.Description); writer.WriteLine(string.Empty); } writer.WriteLine("Usage:"); writer.Write(HelpIndent); writer.Write(CommandPrefix); writer.Write(string.Join(_commandSeparator, command.Names)); string commandLine = command.CommandLine; if (commandLine != null) { writer.Write(" "); writer.Write(commandLine); } if (displayDetails) { writer.WriteLine(string.Empty); var paramsDesc = command.ParametersDescription; if (paramsDesc != null && paramsDesc.Any()) { writer.WriteLine(string.Empty); writer.WriteLine("Parameters:"); int maxParamNameLength = paramsDesc.Max(entry => entry.Key.Length); string paramHelpLineFormat = HelpIndent + "{0,-" + maxParamNameLength + "} {1}"; foreach (var paramDesc in paramsDesc) { writer.WriteLine(string.Format(paramHelpLineFormat, paramDesc.Key, paramDesc.Value)); } } IEnumerable<string> details = command.DetailedDescription; if (details != null && details.Any()) { writer.WriteLine(string.Empty); foreach (var line in details) { writer.WriteLine(line); } } } } public void DisplayCommandHelp(IInteractiveWindowCommand command) { DisplayCommandUsage(command, _window.OutputWriter, displayDetails: true); } } }
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.IO; using System.Globalization; using Newtonsoft.Json.Utilities; using System.Linq; namespace Newtonsoft.Json { /// <summary> /// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data. /// </summary> public abstract class JsonReader : IDisposable { /// <summary> /// Specifies the state of the reader. /// </summary> protected internal enum State { /// <summary> /// The Read method has not been called. /// </summary> Start, /// <summary> /// The end of the file has been reached successfully. /// </summary> Complete, /// <summary> /// Reader is at a property. /// </summary> Property, /// <summary> /// Reader is at the start of an object. /// </summary> ObjectStart, /// <summary> /// Reader is in an object. /// </summary> Object, /// <summary> /// Reader is at the start of an array. /// </summary> ArrayStart, /// <summary> /// Reader is in an array. /// </summary> Array, /// <summary> /// The Close method has been called. /// </summary> Closed, /// <summary> /// Reader has just read a value. /// </summary> PostValue, /// <summary> /// Reader is at the start of a constructor. /// </summary> ConstructorStart, /// <summary> /// Reader in a constructor. /// </summary> Constructor, /// <summary> /// An error occurred that prevents the read operation from continuing. /// </summary> Error, /// <summary> /// The end of the file has been reached successfully. /// </summary> Finished } // current Token data private JsonToken _tokenType; private object _value; internal char _quoteChar; internal State _currentState; internal ReadType _readType; private JsonPosition _currentPosition; private CultureInfo _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; private readonly List<JsonPosition> _stack; /// <summary> /// Gets the current reader state. /// </summary> /// <value>The current reader state.</value> protected State CurrentState { get { return _currentState; } } /// <summary> /// Gets or sets a value indicating whether the underlying stream or /// <see cref="TextReader"/> should be closed when the reader is closed. /// </summary> /// <value> /// true to close the underlying stream or <see cref="TextReader"/> when /// the reader is closed; otherwise false. The default is true. /// </value> public bool CloseInput { get; set; } /// <summary> /// Gets the quotation mark character used to enclose the value of a string. /// </summary> public virtual char QuoteChar { get { return _quoteChar; } protected internal set { _quoteChar = value; } } /// <summary> /// Get or set how <see cref="DateTime"/> time zones are handling when reading JSON. /// </summary> public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling; } set { _dateTimeZoneHandling = value; } } /// <summary> /// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON. /// </summary> public DateParseHandling DateParseHandling { get { return _dateParseHandling; } set { _dateParseHandling = value; } } /// <summary> /// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text. /// </summary> public FloatParseHandling FloatParseHandling { get { return _floatParseHandling; } set { _floatParseHandling = value; } } /// <summary> /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>. /// </summary> public int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) throw new ArgumentException("Value must be positive.", "value"); _maxDepth = value; } } /// <summary> /// Gets the type of the current JSON token. /// </summary> public virtual JsonToken TokenType { get { return _tokenType; } } /// <summary> /// Gets the text value of the current JSON token. /// </summary> public virtual object Value { get { return _value; } } /// <summary> /// Gets The Common Language Runtime (CLR) type for the current JSON token. /// </summary> public virtual Type ValueType { get { return (_value != null) ? _value.GetType() : null; } } /// <summary> /// Gets the depth of the current token in the JSON document. /// </summary> /// <value>The depth of the current token in the JSON document.</value> public virtual int Depth { get { int depth = _stack.Count; if (IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) return depth; else return depth + 1; } } /// <summary> /// Gets the path of the current JSON token. /// </summary> public virtual string Path { get { if (_currentPosition.Type == JsonContainerType.None) return string.Empty; bool insideContainer = (_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart); IEnumerable<JsonPosition> positions = (!insideContainer) ? _stack : _stack.Concat(new[] {_currentPosition}); return JsonPosition.BuildPath(positions); } } /// <summary> /// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>. /// </summary> public CultureInfo Culture { get { return _culture ?? CultureInfo.InvariantCulture; } set { _culture = value; } } internal JsonPosition GetPosition(int depth) { if (depth < _stack.Count) return _stack[depth]; return _currentPosition; } /// <summary> /// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>. /// </summary> protected JsonReader() { _currentState = State.Start; _stack = new List<JsonPosition>(4); _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; CloseInput = true; } private void Push(JsonContainerType value) { UpdateScopeWithFinishedValue(); if (_currentPosition.Type == JsonContainerType.None) { _currentPosition = new JsonPosition(value); } else { _stack.Add(_currentPosition); _currentPosition = new JsonPosition(value); // this is a little hacky because Depth increases when first property/value is written but only testing here is faster/simpler if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth) { _hasExceededMaxDepth = true; throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); } } } private JsonContainerType Pop() { JsonPosition oldPosition; if (_stack.Count > 0) { oldPosition = _currentPosition; _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { oldPosition = _currentPosition; _currentPosition = new JsonPosition(); } if (_maxDepth != null && Depth <= _maxDepth) _hasExceededMaxDepth = false; return oldPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } /// <summary> /// Reads the next JSON token from the stream. /// </summary> /// <returns>true if the next token was read successfully; false if there are no more tokens to read.</returns> public abstract bool Read(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>. /// </summary> /// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract int? ReadAsInt32(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="String"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract string ReadAsString(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>. /// </summary> /// <returns>A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array.</returns> public abstract byte[] ReadAsBytes(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>. /// </summary> /// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract decimal? ReadAsDecimal(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract DateTime? ReadAsDateTime(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>. /// </summary> /// <returns>A <see cref="Nullable{DateTimeOffset}"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract DateTimeOffset? ReadAsDateTimeOffset(); internal virtual bool ReadInternal() { throw new NotImplementedException(); } internal DateTimeOffset? ReadAsDateTimeOffsetInternal() { _readType = ReadType.ReadAsDateTimeOffset; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (t == JsonToken.Date) { if (Value is DateTime) SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value)); return (DateTimeOffset)Value; } if (t == JsonToken.Null) return null; DateTimeOffset dt; if (t == JsonToken.String) { string s = (string)Value; if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null); return null; } if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { SetToken(JsonToken.Date, dt); return dt; } else { throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal byte[] ReadAsBytesInternal() { _readType = ReadType.ReadAsBytes; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (IsWrappedInTypeObject()) { byte[] data = ReadAsBytes(); ReadInternal(); SetToken(JsonToken.Bytes, data); return data; } // attempt to convert possible base 64 string to bytes if (t == JsonToken.String) { string s = (string)Value; byte[] data = (s.Length == 0) ? new byte[0] : Convert.FromBase64String(s); SetToken(JsonToken.Bytes, data); return data; } if (t == JsonToken.Null) return null; if (t == JsonToken.Bytes) return (byte[])Value; if (t == JsonToken.StartArray) { List<byte> data = new List<byte>(); while (ReadInternal()) { t = TokenType; switch (t) { case JsonToken.Integer: data.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); break; case JsonToken.EndArray: byte[] d = data.ToArray(); SetToken(JsonToken.Bytes, d); return d; case JsonToken.Comment: // skip break; default: throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } } throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal decimal? ReadAsDecimalInternal() { _readType = ReadType.ReadAsDecimal; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (t == JsonToken.Integer || t == JsonToken.Float) { if (!(Value is decimal)) SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture)); return (decimal)Value; } if (t == JsonToken.Null) return null; decimal d; if (t == JsonToken.String) { string s = (string)Value; if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null); return null; } if (decimal.TryParse(s, NumberStyles.Number, Culture, out d)) { SetToken(JsonToken.Float, d); return d; } else { throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal int? ReadAsInt32Internal() { _readType = ReadType.ReadAsInt32; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (t == JsonToken.Integer || t == JsonToken.Float) { if (!(Value is int)) SetToken(JsonToken.Integer, Convert.ToInt32(Value, CultureInfo.InvariantCulture)); return (int)Value; } if (t == JsonToken.Null) return null; int i; if (t == JsonToken.String) { string s = (string)Value; if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null); return null; } if (int.TryParse(s, NumberStyles.Integer, Culture, out i)) { SetToken(JsonToken.Integer, i); return i; } else { throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } internal string ReadAsStringInternal() { _readType = ReadType.ReadAsString; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (t == JsonToken.String) return (string)Value; if (t == JsonToken.Null) return null; if (IsPrimitiveToken(t)) { if (Value != null) { string s; if (Value is IFormattable) s = ((IFormattable)Value).ToString(null, Culture); else s = Value.ToString(); SetToken(JsonToken.String, s); return s; } } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal DateTime? ReadAsDateTimeInternal() { _readType = ReadType.ReadAsDateTime; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } } while (TokenType == JsonToken.Comment); if (TokenType == JsonToken.Date) return (DateTime)Value; if (TokenType == JsonToken.Null) return null; DateTime dt; if (TokenType == JsonToken.String) { string s = (string)Value; if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null); return null; } if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt); return dt; } else { throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } } if (TokenType == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } private bool IsWrappedInTypeObject() { _readType = ReadType.Read; if (TokenType == JsonToken.StartObject) { if (!ReadInternal()) throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); if (Value.ToString() == "$type") { ReadInternal(); if (Value != null && Value.ToString().StartsWith("System.Byte[]")) { ReadInternal(); if (Value.ToString() == "$value") { return true; } } } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } return false; } /// <summary> /// Skips the children of the current token. /// </summary> public void Skip() { if (TokenType == JsonToken.PropertyName) Read(); if (IsStartToken(TokenType)) { int depth = Depth; while (Read() && (depth < Depth)) { } } } /// <summary> /// Sets the current token. /// </summary> /// <param name="newToken">The new token.</param> protected void SetToken(JsonToken newToken) { SetToken(newToken, null); } /// <summary> /// Sets the current token and value. /// </summary> /// <param name="newToken">The new token.</param> /// <param name="value">The value.</param> protected void SetToken(JsonToken newToken, object value) { _tokenType = newToken; _value = value; switch (newToken) { case JsonToken.StartObject: _currentState = State.ObjectStart; Push(JsonContainerType.Object); break; case JsonToken.StartArray: _currentState = State.ArrayStart; Push(JsonContainerType.Array); break; case JsonToken.StartConstructor: _currentState = State.ConstructorStart; Push(JsonContainerType.Constructor); break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); break; case JsonToken.EndArray: ValidateEnd(JsonToken.EndArray); break; case JsonToken.EndConstructor: ValidateEnd(JsonToken.EndConstructor); break; case JsonToken.PropertyName: _currentState = State.Property; _currentPosition.PropertyName = (string) value; break; case JsonToken.Undefined: case JsonToken.Integer: case JsonToken.Float: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Date: case JsonToken.String: case JsonToken.Raw: case JsonToken.Bytes: _currentState = (Peek() != JsonContainerType.None) ? State.PostValue : State.Finished; UpdateScopeWithFinishedValue(); break; } } private void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) _currentPosition.Position++; } private void ValidateEnd(JsonToken endToken) { JsonContainerType currentObject = Pop(); if (GetTypeForCloseToken(endToken) != currentObject) throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject)); _currentState = (Peek() != JsonContainerType.None) ? State.PostValue : State.Finished; } /// <summary> /// Sets the state based on current token type. /// </summary> protected void SetStateBasedOnCurrent() { JsonContainerType currentObject = Peek(); switch (currentObject) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Constructor; break; case JsonContainerType.None: _currentState = State.Finished; break; default: throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject)); } } internal static bool IsPrimitiveToken(JsonToken token) { switch (token) { case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Undefined: case JsonToken.Null: case JsonToken.Date: case JsonToken.Bytes: return true; default: return false; } } internal static bool IsStartToken(JsonToken token) { switch (token) { case JsonToken.StartObject: case JsonToken.StartArray: case JsonToken.StartConstructor: return true; default: return false; } } private JsonContainerType GetTypeForCloseToken(JsonToken token) { switch (token) { case JsonToken.EndObject: return JsonContainerType.Object; case JsonToken.EndArray: return JsonContainerType.Array; case JsonToken.EndConstructor: return JsonContainerType.Constructor; default: throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> void IDisposable.Dispose() { Dispose(true); } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) Close(); } /// <summary> /// Changes the <see cref="State"/> to Closed. /// </summary> public virtual void Close() { _currentState = State.Closed; _tokenType = JsonToken.None; _value = null; } } } #endif
#pragma warning disable 1591 using Braintree.Exceptions; using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Xml; namespace Braintree { /// <summary> /// Provides operations for sales, credits, refunds, voids, submitting for settlement, and searching for transactions in the vault /// </summary> public class TransactionGateway : ITransactionGateway { private readonly BraintreeService service; private readonly IBraintreeGateway gateway; protected internal TransactionGateway(IBraintreeGateway gateway) { gateway.Configuration.AssertHasAccessTokenOrKeys(); this.gateway = gateway; service = gateway.Service; } public virtual Result<Transaction> AdjustAuthorization(string id, decimal amount) { var request = new TransactionRequest { Amount = amount }; XmlNode response = service.Put(service.MerchantPath() + "/transactions/" + id + "/adjust_authorization", request); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual async Task<Result<Transaction>> AdjustAuthorizationAsync(string id, decimal amount) { var request = new TransactionRequest { Amount = amount }; XmlNode response = await service.PutAsync(service.MerchantPath() + "/transactions/" + id + "/adjust_authorization", request).ConfigureAwait(false); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual Result<Transaction> CancelRelease(string id) { var request = new TransactionRequest(); XmlNode response = service.Put(service.MerchantPath() + "/transactions/" + id + "/cancel_release", request); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual async Task<Result<Transaction>> CancelReleaseAsync(string id) { var request = new TransactionRequest(); XmlNode response = await service.PutAsync(service.MerchantPath() + "/transactions/" + id + "/cancel_release", request).ConfigureAwait(false); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual Result<Transaction> HoldInEscrow(string id) { var request = new TransactionRequest(); XmlNode response = service.Put(service.MerchantPath() + "/transactions/" + id + "/hold_in_escrow", request); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual async Task<Result<Transaction>> HoldInEscrowAsync(string id) { var request = new TransactionRequest(); XmlNode response = await service.PutAsync(service.MerchantPath() + "/transactions/" + id + "/hold_in_escrow", request).ConfigureAwait(false); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual Result<Transaction> Credit(TransactionRequest request) { request.Type = TransactionType.CREDIT; XmlNode response = service.Post(service.MerchantPath() + "/transactions", request); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual async Task<Result<Transaction>> CreditAsync(TransactionRequest request) { request.Type = TransactionType.CREDIT; XmlNode response = await service.PostAsync(service.MerchantPath() + "/transactions", request).ConfigureAwait(false); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual Transaction Find(string id) { if(id == null || id.Trim().Equals("")) throw new NotFoundException(); XmlNode response = service.Get(service.MerchantPath() + "/transactions/" + id); return new Transaction(new NodeWrapper(response), gateway); } public virtual async Task<Transaction> FindAsync(string id) { if(id == null || id.Trim().Equals("")) throw new NotFoundException(); XmlNode response = await service.GetAsync(service.MerchantPath() + "/transactions/" + id).ConfigureAwait(false); return new Transaction(new NodeWrapper(response), gateway); } public virtual Result<Transaction> Refund(string id) { XmlNode response = service.Post(service.MerchantPath() + "/transactions/" + id + "/refund"); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual async Task<Result<Transaction>> RefundAsync(string id) { XmlNode response = await service.PostAsync(service.MerchantPath() + "/transactions/" + id + "/refund").ConfigureAwait(false); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual Result<Transaction> Refund(string id, decimal amount) { var request = new TransactionRefundRequest { Amount = amount }; return Refund(id, request); } public virtual Task<Result<Transaction>> RefundAsync(string id, decimal amount) { var request = new TransactionRefundRequest { Amount = amount }; return RefundAsync(id, request); } public virtual Result<Transaction> Refund(string id, TransactionRefundRequest refundRequest) { XmlNode response = service.Post(service.MerchantPath() + "/transactions/" + id + "/refund", refundRequest); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual async Task<Result<Transaction>> RefundAsync(string id, TransactionRefundRequest refundRequest) { XmlNode response = await service.PostAsync(service.MerchantPath() + "/transactions/" + id + "/refund", refundRequest).ConfigureAwait(false); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual Result<Transaction> Sale(TransactionRequest request) { request.Type = TransactionType.SALE; XmlNode response = service.Post(service.MerchantPath() + "/transactions", request); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual async Task<Result<Transaction>> SaleAsync(TransactionRequest request) { request.Type = TransactionType.SALE; XmlNode response = await service.PostAsync(service.MerchantPath() + "/transactions", request).ConfigureAwait(false); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual Result<Transaction> ReleaseFromEscrow(string id) { var request = new TransactionRequest(); XmlNode response = service.Put(service.MerchantPath() + "/transactions/" + id + "/release_from_escrow", request); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual async Task<Result<Transaction>> ReleaseFromEscrowAsync(string id) { var request = new TransactionRequest(); XmlNode response = await service.PutAsync(service.MerchantPath() + "/transactions/" + id + "/release_from_escrow", request).ConfigureAwait(false); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual Result<Transaction> SubmitForSettlement(string id) { return SubmitForSettlement(id, 0); } public virtual Task<Result<Transaction>> SubmitForSettlementAsync(string id) { return SubmitForSettlementAsync(id, 0); } public virtual Result<Transaction> SubmitForSettlement(string id, decimal amount) { var request = new TransactionRequest { Amount = amount }; return SubmitForSettlement(id, request); } public virtual async Task<Result<Transaction>> SubmitForSettlementAsync(string id, decimal amount) { var request = new TransactionRequest { Amount = amount }; return await SubmitForSettlementAsync(id, request); } public virtual Result<Transaction> SubmitForSettlement(string id, TransactionRequest request) { XmlNode response = service.Put(service.MerchantPath() + "/transactions/" + id + "/submit_for_settlement", request); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual async Task<Result<Transaction>> SubmitForSettlementAsync(string id, TransactionRequest request) { XmlNode response = await service.PutAsync(service.MerchantPath() + "/transactions/" + id + "/submit_for_settlement", request).ConfigureAwait(false); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual Result<Transaction> UpdateDetails(string id, TransactionRequest request) { XmlNode response = service.Put(service.MerchantPath() + "/transactions/" + id + "/update_details", request); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual Result<Transaction> SubmitForPartialSettlement(string id, decimal amount) { var request = new TransactionRequest(); request.Amount = amount; return SubmitForPartialSettlement(id, request); } public virtual Result<Transaction> SubmitForPartialSettlement(string id, TransactionRequest request) { XmlNode response = service.Post(service.MerchantPath() + "/transactions/" + id + "/submit_for_partial_settlement", request); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual Result<Transaction> Void(string id) { XmlNode response = service.Put(service.MerchantPath() + "/transactions/" + id + "/void"); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual async Task<Result<Transaction>> VoidAsync(string id) { XmlNode response = await service.PutAsync(service.MerchantPath() + "/transactions/" + id + "/void").ConfigureAwait(false); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual ResourceCollection<Transaction> Search(TransactionSearchRequest query) { var response = new NodeWrapper(service.Post(service.MerchantPath() + "/transactions/advanced_search_ids", query)); if (response.GetName() == "search-results") { return new ResourceCollection<Transaction>(response, ids => FetchTransactions(query, ids)); } else { throw new UnexpectedException(); } } public virtual async Task<ResourceCollection<Transaction>> SearchAsync(TransactionSearchRequest query) { var response = new NodeWrapper(await service.PostAsync(service.MerchantPath() + "/transactions/advanced_search_ids", query).ConfigureAwait(false)); if (response.GetName() == "search-results") { return new ResourceCollection<Transaction>(response, ids => FetchTransactions(query, ids)); } else { throw new UnexpectedException(); } } public virtual Result<Transaction> CloneTransaction(string id, TransactionCloneRequest cloneRequest) { XmlNode response = service.Post(service.MerchantPath() + "/transactions/" + id + "/clone", cloneRequest); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } public virtual async Task<Result<Transaction>> CloneTransactionAsync(string id, TransactionCloneRequest cloneRequest) { XmlNode response = await service.PostAsync(service.MerchantPath() + "/transactions/" + id + "/clone", cloneRequest).ConfigureAwait(false); return new ResultImpl<Transaction>(new NodeWrapper(response), gateway); } private List<Transaction> FetchTransactions(TransactionSearchRequest query, string[] ids) { query.Ids.IncludedIn(ids); var response = new NodeWrapper(service.Post(service.MerchantPath() + "/transactions/advanced_search", query)); if (response.GetName() == "credit-card-transactions") { var transactions = new List<Transaction>(); foreach (var node in response.GetList("transaction")) { transactions.Add(new Transaction(node, gateway)); } return transactions; } else { throw new UnexpectedException(); } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public abstract class BiomeTile : MonoBehaviour { public GameObject[] groundTiles; public GameObject[] blockingTiles; public Spawn[] enemies; private Tile[,] myTileMap = null; protected Tile[,] tileMap { get { if (this.myTileMap == null) { this.myTileMap = this.GetComponent<RoomManager>().tileMap; } return this.myTileMap; } } private int myWidth = 0; protected int width { get { if (this.myWidth == 0) { this.myWidth = this.tileMap.GetLength(1); } return this.myWidth; } } private int myHeight = 0; protected int height { get { if (this.myHeight == 0) { this.myHeight = this.tileMap.GetLength(0); } return this.myHeight; } } //protected Tile[,] tileMap; //protected int width; //protected int height; public RoomManager.Count treasureCount = new RoomManager.Count(1, 2); public RoomManager.Count chestCount = new RoomManager.Count(1, 2); public RoomManager.Count tentCount = new RoomManager.Count(1, 2); [System.Serializable] public class Spawn { public float chance; public GameObject enemy; } /* void Start() { this.tileMap = this.GetComponent<RoomManager>().tileMap; this.height = this.tileMap.GetLength(0); this.width = this.tileMap.GetLength(1); }*/ public delegate void TilePlacer(int x, int y); // Blooms are great for making irregular, but roundish shapes like bodies of water public void BlockingExplosion(int x, int y, int level, TilePlacer spritePlacer) { if (Random.Range (0, level) < 1 || x < 0 || y < 0 || x >= this.width || y >= this.height) { return; } Tile tile = this.tileMap[x, y]; if (tile.biome != this.getBiomeNumber() || tile.blocking || tile.path) { return; } if (tile.item == null) { spritePlacer(x, y); tile.blocking = true; } for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (Random.Range(0, 10) > 3 && (j != 0 || i == 1)) { BlockingExplosion(x + i, y + j, level - 1, spritePlacer); } } } } // Perlin is faster than blooms and creates a maze-like structure, which is great for forests // blockingRatio: float between 0f and 1f; 1f is no blocking and 0f is all blocking // blockingSize: how large thick the walls of the maze are, recommended .2f public void PerlinGenerator(List<Tile> tiles, TilePlacer spritePlacer, float blockingRatio, float blockingSize) { foreach (Tile tile in tiles) { float noise = Mathf.PerlinNoise((float)tile.x * blockingSize, (float)tile.y * blockingSize); if (noise > blockingRatio && !tile.path && tile.item == null) { tile.blocking = true; spritePlacer(tile.x, tile.y); } } } public virtual GameObject getGroundTile() { return this.groundTiles[Random.Range(0, this.groundTiles.Length)]; } public GameObject getBlockingTile() { return this.blockingTiles[Random.Range(0, this.blockingTiles.Length)]; } public void placeBlockingTile(int x, int y) { this.GetComponent<RoomManager>().PlaceItem(this.getBlockingTile(), x, y); } public void placeTreasureTiles(List<Tile> tiles) { int treasureNum = Random.Range(this.treasureCount.minimum, this.treasureCount.maximum); for (int i = 0; i < treasureNum; i++) { Tile treasureTile = tiles[Random.Range(0, tiles.Count)]; while (treasureTile.item != null) { treasureTile = tiles[Random.Range(0, tiles.Count)]; } this.GetComponent<RoomManager>().PlaceItem(this.GetComponent<ElevationTile>().xMarksTheSpot, treasureTile.x, treasureTile.y); } } public void placeChestTiles(List<Tile> tiles) { int chestNum = Random.Range(this.chestCount.minimum, this.chestCount.maximum); for (int i = 0; i < chestNum; i++) { Tile chestTile = tiles[Random.Range(0, tiles.Count)]; while (chestTile.item != null) { chestTile = tiles[Random.Range(0, tiles.Count)]; } this.GetComponent<RoomManager>().PlaceItem(this.GetComponent<ElevationTile>().chest, chestTile.x, chestTile.y); } } public void placeCamps(List<Tile> tiles) { int tentNum = Random.Range(this.tentCount.minimum, this.tentCount.maximum + 1); for (int i = 0; i < tentNum; i++) { Tile tentTile = tiles[Random.Range(0, tiles.Count)]; while (tentTile.item != null) { tentTile = tiles[Random.Range(0, tiles.Count)]; } this.GetComponent<RoomManager>().PlaceItem(this.GetComponent<ElevationTile>().tent, tentTile.x, tentTile.y); // place enemies and item nearby if there is room int enemyMax = Random.Range(3, 5); int enemies = 0; for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { int enemyX = x + tentTile.x; int enemyY = y + tentTile.y; if (this.inMap(enemyX, enemyY) && !tileMap[enemyX, enemyY].blocking && enemies < enemyMax) { // place item for first open spot, then place enemies if (enemies == 0) { this.GetComponent<RoomManager>().PlaceItem(this.GetComponent<ElevationTile>().randomItem, enemyX, enemyY); } else { this.GetComponent<RoomManager>().PlaceItem(this.getEnemy(), enemyX, enemyY); } enemies++; } } } // place reward item in front of tent } } public Tile GetOpenArea(List<Tile> tiles) { int biome = tiles[0].biome; foreach (Tile tile in tiles) { bool open = true; for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { int xPos = tile.x + x; int yPos = tile.y + y; if (xPos < 0 || yPos < 0 || xPos >= width || yPos >= height || this.tileMap[xPos, yPos].blocking || biome != tile.biome) { open = false; } } } if (open) { return tile; } } return null; } public void RandomFlip(GameObject item) { if (Random.Range(0, 2) == 1) { item.transform.localScale = new Vector3(-1f, 1f, 1f); } } public GameObject makeEnemy(List<Tile> tiles) { GameObject enemy = this.getEnemy(); Tile enemyTile = tiles[Random.Range(0, tiles.Count)]; while (enemyTile.item != null || enemyTile.blocking || this.GetComponent<RoomManager>().PlayerIsNear(enemyTile.x, enemyTile.y)) { enemyTile = tiles[Random.Range(0, tiles.Count)]; } // TODO: change 32 to be whatever the column, row amount is. return GameObject.Instantiate (enemy, new Vector3(enemyTile.x - 32 / 2 + .5f, enemyTile.y - 32 / 2 + .5f, 0f), Quaternion.identity) as GameObject; } public GameObject getEnemy() { float total = 0f; foreach (Spawn enemy in this.enemies) { total += enemy.chance; } float selected = Random.Range (0f, total); total = 0f; foreach (Spawn enemy in this.enemies) { total += enemy.chance; if (selected < total) { return enemy.enemy; } } // this line should never run if this function works correctly return this.enemies[Random.Range(0, this.enemies.Length)].enemy; } public virtual void RandomBlocking(List<Tile> tiles) { this.GetComponent<ElevationTile>().placeCliffTiles(tiles); this.placeTreasureTiles(tiles); this.placeChestTiles(tiles); this.placeCamps(tiles); } public abstract int getBiomeNumber(); public bool inMap(int x, int y) { return x >= 0 && y >= 0 && x < this.width && y < this.height; } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.Security.Cryptography.X509Certificates { public static class __X509Certificate { public static IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> CreateFromCertFile( IObservable<System.String> filename) { return Observable.Select(filename, (filenameLambda) => System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile(filenameLambda)); } public static IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> CreateFromSignedFile( IObservable<System.String> filename) { return Observable.Select(filename, (filenameLambda) => System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromSignedFile(filenameLambda)); } public static IObservable<System.String> GetName( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.GetName()); } public static IObservable<System.String> GetIssuerName( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.GetIssuerName()); } public static IObservable<System.Byte[]> GetSerialNumber( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.GetSerialNumber()); } public static IObservable<System.String> GetSerialNumberString( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.GetSerialNumberString()); } public static IObservable<System.Byte[]> GetKeyAlgorithmParameters( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.GetKeyAlgorithmParameters()); } public static IObservable<System.String> GetKeyAlgorithmParametersString( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.GetKeyAlgorithmParametersString()); } public static IObservable<System.String> GetKeyAlgorithm( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.GetKeyAlgorithm()); } public static IObservable<System.Byte[]> GetPublicKey( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.GetPublicKey()); } public static IObservable<System.String> GetPublicKeyString( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.GetPublicKeyString()); } public static IObservable<System.Byte[]> GetRawCertData( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.GetRawCertData()); } public static IObservable<System.String> GetRawCertDataString( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.GetRawCertDataString()); } public static IObservable<System.Byte[]> GetCertHash( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.GetCertHash()); } public static IObservable<System.String> GetCertHashString( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.GetCertHashString()); } public static IObservable<System.String> GetEffectiveDateString( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.GetEffectiveDateString()); } public static IObservable<System.String> GetExpirationDateString( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.GetExpirationDateString()); } public static IObservable<System.Boolean> Equals( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue, IObservable<System.Object> obj) { return Observable.Zip(X509CertificateValue, obj, (X509CertificateValueLambda, objLambda) => X509CertificateValueLambda.Equals(objLambda)); } public static IObservable<System.Boolean> Equals( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue, IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> other) { return Observable.Zip(X509CertificateValue, other, (X509CertificateValueLambda, otherLambda) => X509CertificateValueLambda.Equals(otherLambda)); } public static IObservable<System.Int32> GetHashCode( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.GetHashCode()); } public static IObservable<System.String> ToString( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.ToString()); } public static IObservable<System.String> ToString( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue, IObservable<System.Boolean> fVerbose) { return Observable.Zip(X509CertificateValue, fVerbose, (X509CertificateValueLambda, fVerboseLambda) => X509CertificateValueLambda.ToString(fVerboseLambda)); } public static IObservable<System.String> GetFormat( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.GetFormat()); } public static IObservable<System.Reactive.Unit> Import( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue, IObservable<System.Byte[]> rawData) { return ObservableExt.ZipExecute(X509CertificateValue, rawData, (X509CertificateValueLambda, rawDataLambda) => X509CertificateValueLambda.Import(rawDataLambda)); } public static IObservable<System.Reactive.Unit> Import( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue, IObservable<System.Byte[]> rawData, IObservable<System.String> password, IObservable<System.Security.Cryptography.X509Certificates.X509KeyStorageFlags> keyStorageFlags) { return ObservableExt.ZipExecute(X509CertificateValue, rawData, password, keyStorageFlags, (X509CertificateValueLambda, rawDataLambda, passwordLambda, keyStorageFlagsLambda) => X509CertificateValueLambda.Import(rawDataLambda, passwordLambda, keyStorageFlagsLambda)); } public static IObservable<System.Reactive.Unit> Import( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue, IObservable<System.Byte[]> rawData, IObservable<System.Security.SecureString> password, IObservable<System.Security.Cryptography.X509Certificates.X509KeyStorageFlags> keyStorageFlags) { return ObservableExt.ZipExecute(X509CertificateValue, rawData, password, keyStorageFlags, (X509CertificateValueLambda, rawDataLambda, passwordLambda, keyStorageFlagsLambda) => X509CertificateValueLambda.Import(rawDataLambda, passwordLambda, keyStorageFlagsLambda)); } public static IObservable<System.Reactive.Unit> Import( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue, IObservable<System.String> fileName) { return ObservableExt.ZipExecute(X509CertificateValue, fileName, (X509CertificateValueLambda, fileNameLambda) => X509CertificateValueLambda.Import(fileNameLambda)); } public static IObservable<System.Reactive.Unit> Import( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue, IObservable<System.String> fileName, IObservable<System.String> password, IObservable<System.Security.Cryptography.X509Certificates.X509KeyStorageFlags> keyStorageFlags) { return ObservableExt.ZipExecute(X509CertificateValue, fileName, password, keyStorageFlags, (X509CertificateValueLambda, fileNameLambda, passwordLambda, keyStorageFlagsLambda) => X509CertificateValueLambda.Import(fileNameLambda, passwordLambda, keyStorageFlagsLambda)); } public static IObservable<System.Reactive.Unit> Import( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue, IObservable<System.String> fileName, IObservable<System.Security.SecureString> password, IObservable<System.Security.Cryptography.X509Certificates.X509KeyStorageFlags> keyStorageFlags) { return ObservableExt.ZipExecute(X509CertificateValue, fileName, password, keyStorageFlags, (X509CertificateValueLambda, fileNameLambda, passwordLambda, keyStorageFlagsLambda) => X509CertificateValueLambda.Import(fileNameLambda, passwordLambda, keyStorageFlagsLambda)); } public static IObservable<System.Byte[]> Export( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue, IObservable<System.Security.Cryptography.X509Certificates.X509ContentType> contentType) { return Observable.Zip(X509CertificateValue, contentType, (X509CertificateValueLambda, contentTypeLambda) => X509CertificateValueLambda.Export(contentTypeLambda)); } public static IObservable<System.Byte[]> Export( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue, IObservable<System.Security.Cryptography.X509Certificates.X509ContentType> contentType, IObservable<System.String> password) { return Observable.Zip(X509CertificateValue, contentType, password, (X509CertificateValueLambda, contentTypeLambda, passwordLambda) => X509CertificateValueLambda.Export(contentTypeLambda, passwordLambda)); } public static IObservable<System.Byte[]> Export( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue, IObservable<System.Security.Cryptography.X509Certificates.X509ContentType> contentType, IObservable<System.Security.SecureString> password) { return Observable.Zip(X509CertificateValue, contentType, password, (X509CertificateValueLambda, contentTypeLambda, passwordLambda) => X509CertificateValueLambda.Export(contentTypeLambda, passwordLambda)); } public static IObservable<System.Reactive.Unit> Reset( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Do(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.Reset()) .ToUnit(); } public static IObservable<System.Reactive.Unit> Dispose( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Do(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.Dispose()) .ToUnit(); } public static IObservable<System.IntPtr> get_Handle( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.Handle); } public static IObservable<System.String> get_Issuer( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.Issuer); } public static IObservable<System.String> get_Subject( this IObservable<System.Security.Cryptography.X509Certificates.X509Certificate> X509CertificateValue) { return Observable.Select(X509CertificateValue, (X509CertificateValueLambda) => X509CertificateValueLambda.Subject); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection.PortableExecutable; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Microsoft.DotNet.Cli.Compiler.Common; using Microsoft.DotNet.PlatformAbstractions; using Microsoft.DotNet.ProjectModel.Compilation; using Microsoft.DotNet.ProjectModel.Files; using NuGet.Frameworks; using RoslynWorkspace = Microsoft.CodeAnalysis.Workspace; namespace Microsoft.DotNet.ProjectModel.Workspaces { public class ProjectJsonWorkspace : RoslynWorkspace { private Dictionary<string, AssemblyMetadata> _cache = new Dictionary<string, AssemblyMetadata>(); public ProjectJsonWorkspace(ProjectContext context) : base(MefHostServices.DefaultHost, "Custom") { AddProject(context); } public ProjectJsonWorkspace(string projectPath) : this(new[] { projectPath }) { } public ProjectJsonWorkspace(IEnumerable<string> projectPaths) : base(MefHostServices.DefaultHost, "Custom") { Initialize(projectPaths); } private void Initialize(IEnumerable<string> projectPaths) { foreach (var projectPath in projectPaths) { AddProject(projectPath); } } private void AddProject(string projectPath) { // Get all of the specific projects (there is a project per framework) foreach (var p in ProjectContext.CreateContextForEachFramework(projectPath)) { AddProject(p); } } private ProjectId AddProject(ProjectContext project) { // Create the framework specific project and add it to the workspace var projectInfo = ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), project.ProjectFile.Name + "+" + project.TargetFramework, project.ProjectFile.Name, LanguageNames.CSharp, project.ProjectFile.ProjectFilePath); OnProjectAdded(projectInfo); // TODO: ctor argument? var configuration = "Debug"; var compilerOptions = project.GetLanguageSpecificCompilerOptions(project.TargetFramework, configuration); var compilationSettings = ToCompilationSettings(compilerOptions, project.TargetFramework, project.ProjectFile.ProjectDirectory); OnParseOptionsChanged(projectInfo.Id, new CSharpParseOptions(compilationSettings.LanguageVersion, preprocessorSymbols: compilationSettings.Defines)); OnCompilationOptionsChanged(projectInfo.Id, compilationSettings.CompilationOptions); IEnumerable<string> sourceFiles = null; if (compilerOptions.CompileInclude == null) { sourceFiles = project.ProjectFile.Files.SourceFiles; } else { var includeFiles = IncludeFilesResolver.GetIncludeFiles(compilerOptions.CompileInclude, "/", diagnostics: null); sourceFiles = includeFiles.Select(f => f.SourcePath); } foreach (var file in sourceFiles) { using (var stream = File.OpenRead(file)) { AddSourceFile(projectInfo, file, stream); } } var exporter = project.CreateExporter(configuration); foreach (var dependency in exporter.GetDependencies()) { var projectDependency = dependency.Library as ProjectDescription; if (projectDependency != null) { var projectDependencyContext = ProjectContext.Create(projectDependency.Project.ProjectFilePath, projectDependency.Framework); var id = AddProject(projectDependencyContext); OnProjectReferenceAdded(projectInfo.Id, new ProjectReference(id)); } else { foreach (var asset in dependency.CompilationAssemblies) { OnMetadataReferenceAdded(projectInfo.Id, GetMetadataReference(asset.ResolvedPath)); } } foreach (var file in dependency.SourceReferences) { using (var stream = file.GetTransformedStream()) { AddSourceFile(projectInfo, file.ResolvedPath, stream); } } } return projectInfo.Id; } private void AddSourceFile(ProjectInfo projectInfo, string file, Stream stream) { var sourceText = SourceText.From(stream, encoding: Encoding.UTF8); var id = DocumentId.CreateNewId(projectInfo.Id); var version = VersionStamp.Create(); var loader = TextLoader.From(TextAndVersion.Create(sourceText, version)); OnDocumentAdded(DocumentInfo.Create(id, file, filePath: file, loader: loader)); } private MetadataReference GetMetadataReference(string path) { AssemblyMetadata assemblyMetadata; if (!_cache.TryGetValue(path, out assemblyMetadata)) { using (var stream = File.OpenRead(path)) { var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata); assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); _cache[path] = assemblyMetadata; } } return assemblyMetadata.GetReference(); } private static CompilationSettings ToCompilationSettings(CommonCompilerOptions compilerOptions, NuGetFramework targetFramework, string projectDirectory) { var options = GetCompilationOptions(compilerOptions, projectDirectory); options = options.WithSpecificDiagnosticOptions(compilerOptions.SuppressWarnings.ToDictionary( suppress => suppress, _ => ReportDiagnostic.Suppress)); AssemblyIdentityComparer assemblyIdentityComparer = targetFramework.IsDesktop() ? DesktopAssemblyIdentityComparer.Default : null; options = options.WithAssemblyIdentityComparer(assemblyIdentityComparer); LanguageVersion languageVersion; if (!Enum.TryParse<LanguageVersion>(value: compilerOptions.LanguageVersion, ignoreCase: true, result: out languageVersion)) { languageVersion = LanguageVersion.CSharp6; } var settings = new CompilationSettings { LanguageVersion = languageVersion, Defines = compilerOptions.Defines ?? Enumerable.Empty<string>(), CompilationOptions = options }; return settings; } private static CSharpCompilationOptions GetCompilationOptions(CommonCompilerOptions compilerOptions, string projectDirectory) { var outputKind = compilerOptions.EmitEntryPoint.GetValueOrDefault() ? OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary; var options = new CSharpCompilationOptions(outputKind); string platformValue = compilerOptions.Platform; bool allowUnsafe = compilerOptions.AllowUnsafe ?? false; bool optimize = compilerOptions.Optimize ?? false; bool warningsAsErrors = compilerOptions.WarningsAsErrors ?? false; Microsoft.CodeAnalysis.Platform platform; if (!Enum.TryParse(value: platformValue, ignoreCase: true, result: out platform)) { platform = Microsoft.CodeAnalysis.Platform.AnyCpu; } options = options .WithAllowUnsafe(allowUnsafe) .WithPlatform(platform) .WithGeneralDiagnosticOption(warningsAsErrors ? ReportDiagnostic.Error : ReportDiagnostic.Default) .WithOptimizationLevel(optimize ? OptimizationLevel.Release : OptimizationLevel.Debug); return AddSigningOptions(options, compilerOptions, projectDirectory); } private static CSharpCompilationOptions AddSigningOptions(CSharpCompilationOptions options, CommonCompilerOptions compilerOptions, string projectDirectory) { var useOssSigning = compilerOptions.PublicSign == true; var keyFile = compilerOptions.KeyFile; if (!string.IsNullOrEmpty(keyFile)) { keyFile = Path.GetFullPath(Path.Combine(projectDirectory, compilerOptions.KeyFile)); if (RuntimeEnvironment.OperatingSystemPlatform != PlatformAbstractions.Platform.Windows || useOssSigning) { return options.WithCryptoPublicKey( SnkUtils.ExtractPublicKey(File.ReadAllBytes(keyFile))); } options = options.WithCryptoKeyFile(keyFile); return options.WithDelaySign(compilerOptions.DelaySign); } return options; } private class CompilationSettings { public LanguageVersion LanguageVersion { get; set; } public IEnumerable<string> Defines { get; set; } public CSharpCompilationOptions CompilationOptions { get; set; } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using NodaTime; using NUnit.Framework; using QuantConnect.Data.Consolidators; using QuantConnect.Data.Market; using QuantConnect.Lean.Engine.DataFeeds; using QuantConnect.Lean.Engine.DataFeeds.Enumerators; namespace QuantConnect.Tests.Engine.DataFeeds.Enumerators { [TestFixture, Parallelizable(ParallelScope.All)] public class ScannableEnumeratorTests { [Test] public void PassesTicksStraightThrough() { var currentTime = new DateTime(2000, 01, 01); var enumerator = new ScannableEnumerator<Tick>( new IdentityDataConsolidator<Tick>(), DateTimeZone.ForOffset(Offset.FromHours(-5)), new ManualTimeProvider(currentTime), (s, e) => { } ); // returns true even if no data present until stop is called Assert.IsTrue(enumerator.MoveNext()); Assert.IsNull(enumerator.Current); var tick1 = new Tick(currentTime, Symbols.SPY, 199.55m, 199, 200) { Quantity = 10 }; enumerator.Update(tick1); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(tick1, enumerator.Current); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNull(enumerator.Current); var tick2 = new Tick(currentTime, Symbols.SPY, 199.56m, 199.21m, 200.02m) { Quantity = 5 }; enumerator.Update(tick2); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(tick2, enumerator.Current); enumerator.Dispose(); } [Test] public void NewDataAvailableShouldFire() { var currentTime = new DateTime(2000, 01, 01); var available = false; var enumerator = new ScannableEnumerator<Tick>( new IdentityDataConsolidator<Tick>(), DateTimeZone.ForOffset(Offset.FromHours(-5)), new ManualTimeProvider(currentTime), (s, e) => { available = true; } ); // returns true even if no data present until stop is called Assert.IsTrue(enumerator.MoveNext()); Assert.IsNull(enumerator.Current); Assert.IsFalse(available); var tick1 = new Tick(currentTime, Symbols.SPY, 199.55m, 199, 200) { Quantity = 10 }; enumerator.Update(tick1); Assert.IsTrue(available); enumerator.Dispose(); } [Test] public void AggregatesNewQuoteBarProperly() { var reference = DateTime.Today; var enumerator = new ScannableEnumerator<Data.BaseData>( new TickQuoteBarConsolidator(4), DateTimeZone.ForOffset(Offset.FromHours(-5)), new ManualTimeProvider(reference), (s, e) => { } ); var tick1 = new Tick { Symbol = Symbols.SPY, Time = reference, BidPrice = 10, BidSize = 20, TickType = TickType.Quote }; enumerator.Update(tick1); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNull(enumerator.Current); var tick2 = new Tick { Symbol = Symbols.SPY, Time = reference.AddMinutes(1), AskPrice = 20, AskSize = 10, TickType = TickType.Quote }; var badTick = new Tick { Symbol = Symbols.SPY, Time = reference.AddMinutes(1), AskPrice = 25, AskSize = 100, BidPrice = -100, BidSize = 2, Value = 50, Quantity = 1234, TickType = TickType.Trade }; enumerator.Update(badTick); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNull(enumerator.Current); enumerator.Update(tick2); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNull(enumerator.Current); var tick3 = new Tick { Symbol = Symbols.SPY, Time = reference.AddMinutes(2), BidPrice = 12, BidSize = 50, TickType = TickType.Quote }; enumerator.Update(tick3); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNull(enumerator.Current); var tick4 = new Tick { Symbol = Symbols.SPY, Time = reference.AddMinutes(3), AskPrice = 17, AskSize = 15, TickType = TickType.Quote }; enumerator.Update(tick4); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNotNull(enumerator.Current); QuoteBar quoteBar = enumerator.Current as QuoteBar; Assert.IsNotNull(quoteBar); Assert.AreEqual(Symbols.SPY, quoteBar.Symbol); Assert.AreEqual(tick1.Time, quoteBar.Time); Assert.AreEqual(tick4.EndTime, quoteBar.EndTime); Assert.AreEqual(tick1.BidPrice, quoteBar.Bid.Open); Assert.AreEqual(tick1.BidPrice, quoteBar.Bid.Low); Assert.AreEqual(tick3.BidPrice, quoteBar.Bid.High); Assert.AreEqual(tick3.BidPrice, quoteBar.Bid.Close); Assert.AreEqual(tick3.BidSize, quoteBar.LastBidSize); Assert.AreEqual(tick2.AskPrice, quoteBar.Ask.Open); Assert.AreEqual(tick4.AskPrice, quoteBar.Ask.Low); Assert.AreEqual(tick2.AskPrice, quoteBar.Ask.High); Assert.AreEqual(tick4.AskPrice, quoteBar.Ask.Close); Assert.AreEqual(tick4.AskSize, quoteBar.LastAskSize); } [Test] public void ForceScanQuoteBar() { var reference = new DateTime(2020, 2, 2, 1, 0, 0); var timeProvider = new ManualTimeProvider(reference); var dateTimeZone = DateTimeZone.ForOffset(Offset.FromHours(-5)); var enumerator = new ScannableEnumerator<Data.BaseData>( new TickQuoteBarConsolidator(TimeSpan.FromMinutes(1)), dateTimeZone, timeProvider, (s, e) => { } ); var tick1 = new Tick { Symbol = Symbols.SPY, Time = reference.ConvertFromUtc(dateTimeZone), BidPrice = 10, BidSize = 20, TickType = TickType.Quote }; enumerator.Update(tick1); var tick2 = new Tick { Symbol = Symbols.SPY, Time = reference.AddSeconds(1).ConvertFromUtc(dateTimeZone), AskPrice = 20, AskSize = 10, TickType = TickType.Quote }; enumerator.Update(tick2); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNull(enumerator.Current); var tick3 = new Tick { Symbol = Symbols.SPY, Time = reference.AddSeconds(2).ConvertFromUtc(dateTimeZone), BidPrice = 12, BidSize = 50, TickType = TickType.Quote }; enumerator.Update(tick3); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNull(enumerator.Current); var tick4 = new Tick { Symbol = Symbols.SPY, Time = reference.AddSeconds(3).ConvertFromUtc(dateTimeZone), AskPrice = 17, AskSize = 15, TickType = TickType.Quote }; enumerator.Update(tick4); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNull(enumerator.Current); timeProvider.AdvanceSeconds(120); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNotNull(enumerator.Current); QuoteBar quoteBar = enumerator.Current as QuoteBar; Assert.IsNotNull(quoteBar); Assert.AreEqual(Symbols.SPY, quoteBar.Symbol); Assert.AreEqual(tick1.Time, quoteBar.Time); Assert.AreNotEqual(tick4.EndTime, quoteBar.EndTime); Assert.AreEqual(tick1.BidPrice, quoteBar.Bid.Open); Assert.AreEqual(tick1.BidPrice, quoteBar.Bid.Low); Assert.AreEqual(tick3.BidPrice, quoteBar.Bid.High); Assert.AreEqual(tick3.BidPrice, quoteBar.Bid.Close); Assert.AreEqual(tick3.BidSize, quoteBar.LastBidSize); Assert.AreEqual(tick2.AskPrice, quoteBar.Ask.Open); Assert.AreEqual(tick4.AskPrice, quoteBar.Ask.Low); Assert.AreEqual(tick2.AskPrice, quoteBar.Ask.High); Assert.AreEqual(tick4.AskPrice, quoteBar.Ask.Close); Assert.AreEqual(tick4.AskSize, quoteBar.LastAskSize); } [Test] public void MoveNextScanQuoteBar() { var offset = Offset.FromHours(-5); var timeZone = DateTimeZone.ForOffset(offset); var utc = new DateTimeOffset(DateTime.Today); var reference = utc.ToOffset(offset.ToTimeSpan()); var timeProvider = new ManualTimeProvider(reference.DateTime, timeZone); var enumerator = new ScannableEnumerator<Data.BaseData>( new TickQuoteBarConsolidator(TimeSpan.FromMinutes(1)), timeZone, timeProvider, (s, e) => { } ); var tick1 = new Tick { Symbol = Symbols.SPY, Time = reference.DateTime, BidPrice = 10, BidSize = 20, TickType = TickType.Quote }; enumerator.Update(tick1); var tick2 = new Tick { Symbol = Symbols.SPY, Time = reference.DateTime.AddSeconds(1), AskPrice = 20, AskSize = 10, TickType = TickType.Quote }; enumerator.Update(tick2); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNull(enumerator.Current); var tick3 = new Tick { Symbol = Symbols.SPY, Time = reference.DateTime.AddSeconds(2), BidPrice = 12, BidSize = 50, TickType = TickType.Quote }; enumerator.Update(tick3); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNull(enumerator.Current); var tick4 = new Tick { Symbol = Symbols.SPY, Time = reference.DateTime.AddSeconds(3), AskPrice = 17, AskSize = 15, TickType = TickType.Quote }; enumerator.Update(tick4); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNull(enumerator.Current); timeProvider.SetCurrentTime(reference.DateTime.AddMinutes(2)); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNotNull(enumerator.Current); QuoteBar quoteBar = enumerator.Current as QuoteBar; Assert.IsNotNull(quoteBar); Assert.AreEqual(Symbols.SPY, quoteBar.Symbol); Assert.AreEqual(tick1.Time, quoteBar.Time); Assert.AreNotEqual(tick4.EndTime, quoteBar.EndTime); Assert.AreEqual(tick1.BidPrice, quoteBar.Bid.Open); Assert.AreEqual(tick1.BidPrice, quoteBar.Bid.Low); Assert.AreEqual(tick3.BidPrice, quoteBar.Bid.High); Assert.AreEqual(tick3.BidPrice, quoteBar.Bid.Close); Assert.AreEqual(tick3.BidSize, quoteBar.LastBidSize); Assert.AreEqual(tick2.AskPrice, quoteBar.Ask.Open); Assert.AreEqual(tick4.AskPrice, quoteBar.Ask.Low); Assert.AreEqual(tick2.AskPrice, quoteBar.Ask.High); Assert.AreEqual(tick4.AskPrice, quoteBar.Ask.Close); Assert.AreEqual(tick4.AskSize, quoteBar.LastAskSize); } } }
using System; using System.Collections; using System.Data; using PCSComUtils.PCSExc; using PCSComUtils.Common; using PCSComUtils.Framework.ReportFrame.DS; namespace PCSComUtils.Framework.ReportFrame.BO { public class GroupPropertiesBO { private const string THIS = "PCSComUtils.Framework.ReportFrame.BO.GroupPropertiesBO"; public GroupPropertiesBO() { } /// <summary> /// Insert a new record into database /// </summary> public void Add(object pObjectDetail) { throw new NotImplementedException(); } /// <summary> /// Insert a new record into database /// </summary> public int AddAndReturnID(object pobjFieldGroup, ArrayList parrSelectedItem) { try { Sys_FieldGroupVO voFieldGroup = (Sys_FieldGroupVO)pobjFieldGroup; Sys_FieldGroupDS dsFieldGroup = new Sys_FieldGroupDS(); sys_ReportFieldsDS dsReportField = new sys_ReportFieldsDS(); Sys_FieldGroupDetailDS dsFieldGroupDetail = new Sys_FieldGroupDetailDS(); // get current field group order voFieldGroup.GroupOrder = dsFieldGroup.GetFieldGroupOrder(voFieldGroup.ReportID, voFieldGroup.ParentFieldGroupID) + 1; // save new field group to database int intNewID = dsFieldGroup.AddAndReturnID(voFieldGroup); // save all selected sub group/field to database if any for (int i = 0; i < parrSelectedItem.Count; i++) { switch (voFieldGroup.GroupLevel) { case (int)GroupFieldLevel.One: // update sub group Sys_FieldGroupVO voSubGroup = (Sys_FieldGroupVO)parrSelectedItem[i]; // parent field group id voSubGroup.ParentFieldGroupID = intNewID; // new order in group voSubGroup.GroupOrder = i + 1; // save to database dsFieldGroup.Update(voSubGroup); break; case (int)GroupFieldLevel.Two: // update report field sys_ReportFieldsVO voReportField = (sys_ReportFieldsVO)parrSelectedItem[i]; // new field order in group voReportField.FieldOrder = i + 1; dsReportField.UpdateByName(voReportField); // create new Field Group Detail Sys_FieldGroupDetailVO voFieldGroupDetail = new Sys_FieldGroupDetailVO(); voFieldGroupDetail.FieldGroupID = intNewID; voFieldGroupDetail.ReportID = voFieldGroup.ReportID; voFieldGroupDetail.FieldName = voReportField.FieldName; // save to database dsFieldGroupDetail.Add(voFieldGroupDetail); break; } } return intNewID; } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } /// <summary> /// Delete record by condition /// </summary> public void Delete(object pObjectVO) { throw new NotImplementedException(); } /// <summary> /// Delete record by condition /// </summary> public void Delete(object pObjectVO, ArrayList parrSelected) { try { Sys_FieldGroupVO voFieldGroup = (Sys_FieldGroupVO)pObjectVO; Sys_FieldGroupDS dsFieldGroup = new Sys_FieldGroupDS(); sys_ReportFieldsDS dsReportField = new sys_ReportFieldsDS(); Sys_FieldGroupDetailDS dsFieldGroupDetail = new Sys_FieldGroupDetailDS(); int intCurrentGroupOrder = dsFieldGroup.GetFieldGroupOrder(voFieldGroup.ReportID, 0); int intCurrentFieldOrder = dsReportField.GetMaxFieldOrder(voFieldGroup.ReportID); for (int i = 0; i < parrSelected.Count; i++) { switch (voFieldGroup.GroupLevel) { case (int)GroupFieldLevel.One: // update sub group (order and parent id) Sys_FieldGroupVO voSubGroup = (Sys_FieldGroupVO)parrSelected[i]; voSubGroup.ParentFieldGroupID = 0; voSubGroup.GroupOrder = intCurrentGroupOrder + i + 1; dsFieldGroup.Update(voSubGroup); break; case (int)GroupFieldLevel.Two: // update report field sys_ReportFieldsVO voReportField = (sys_ReportFieldsVO)parrSelected[i]; // new field order in group voReportField.FieldOrder = intCurrentFieldOrder + i + 1; dsReportField.UpdateByName(voReportField); // delete field group detail records first dsFieldGroupDetail.Delete(voFieldGroup.FieldGroupID, voFieldGroup.ReportID); break; } } // delete field group dsFieldGroup.Delete(voFieldGroup.FieldGroupID); } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } /// <summary> /// Get the object information by ID of VO class /// </summary> public object GetObjectVO(int pintID, string VOclass) { throw new NotImplementedException(); } /// <summary> /// Return the DataSet (list of record) by inputing the FieldList and Condition /// </summary> public void UpdateDataSet(DataSet dstData) { throw new NotImplementedException(); } /// <summary> /// Update into Database /// </summary> public void Update(object pObjectDetail) { throw new NotImplementedException(); } /// <summary> /// Update into Database /// </summary> public void Update(object pobjFieldGroup, ArrayList parrSelectedItem, ArrayList parrAvailableItem) { try { Sys_FieldGroupVO voFieldGroup = (Sys_FieldGroupVO)pobjFieldGroup; Sys_FieldGroupDS dsFieldGroup = new Sys_FieldGroupDS(); sys_ReportFieldsDS dsReportField = new sys_ReportFieldsDS(); Sys_FieldGroupDetailDS dsFieldGroupDetail = new Sys_FieldGroupDetailDS(); // update Field Group dsFieldGroup.Update(voFieldGroup); int intCurrentGroupOrder = dsFieldGroup.GetFieldGroupOrder(voFieldGroup.ReportID, 0); int intCurrentFieldOrder = dsReportField.GetMaxFieldOrder(voFieldGroup.ReportID); for (int i = 0; i < parrAvailableItem.Count; i++) { switch (voFieldGroup.GroupLevel) { case (int)GroupFieldLevel.One: Sys_FieldGroupVO voSubGroup = (Sys_FieldGroupVO)parrAvailableItem[i]; // remove parent field group voSubGroup.ParentFieldGroupID = 0; voSubGroup.GroupOrder = intCurrentGroupOrder + 1 + i; dsFieldGroup.Update(voSubGroup); break; case (int)GroupFieldLevel.Two: // update report field sys_ReportFieldsVO voReportField = (sys_ReportFieldsVO)parrSelectedItem[i]; // new field order in group voReportField.FieldOrder = intCurrentFieldOrder + i + 1; dsReportField.UpdateByName(voReportField); // create new Field Group Detail Sys_FieldGroupDetailVO voFieldGroupDetail = new Sys_FieldGroupDetailVO(); voFieldGroupDetail.FieldGroupID = voFieldGroup.FieldGroupID; voFieldGroupDetail.ReportID = voFieldGroup.ReportID; voFieldGroupDetail.FieldName = voReportField.FieldName; // save to database dsFieldGroupDetail.Add(voFieldGroupDetail); break; } } // delete old field group detail dsFieldGroupDetail.Delete(voFieldGroup.FieldGroupID, voFieldGroup.ReportID); // update selected group/field for (int i = 0; i < parrSelectedItem.Count; i++) { switch (voFieldGroup.GroupLevel) { case (int)GroupFieldLevel.One: Sys_FieldGroupVO voSubGroup = (Sys_FieldGroupVO)parrSelectedItem[i]; voSubGroup.ParentFieldGroupID = voFieldGroup.FieldGroupID; voSubGroup.GroupOrder = i + 1; dsFieldGroup.Update(voSubGroup); break; case (int)GroupFieldLevel.Two: // update report field sys_ReportFieldsVO voReportField = (sys_ReportFieldsVO)parrSelectedItem[i]; // new field order in group voReportField.FieldOrder = i + 1; dsReportField.UpdateByName(voReportField); // create new Field Group Detail Sys_FieldGroupDetailVO voFieldGroupDetail = new Sys_FieldGroupDetailVO(); voFieldGroupDetail.FieldGroupID = voFieldGroup.FieldGroupID; voFieldGroupDetail.ReportID = voFieldGroup.ReportID; voFieldGroupDetail.FieldName = voReportField.FieldName; // save to database dsFieldGroupDetail.Add(voFieldGroupDetail); break; } } } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } /// <summary> /// List all Field Group of Report /// </summary> /// <param name="pstrReportID">Report ID</param> /// <returns>DataTable</returns> public DataTable List(string pstrReportID) { try { Sys_FieldGroupDS dsFieldGroup = new Sys_FieldGroupDS(); return dsFieldGroup.List(pstrReportID); } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } /// <summary> /// Get all lower group of a Group /// </summary> /// <param name="pintFieldGroupID">Field Group</param> /// <returns>DataTable</returns> public DataTable GetLowerGroup(int pintFieldGroupID) { try { Sys_FieldGroupDS dsFieldGroup = new Sys_FieldGroupDS(); return dsFieldGroup.GetLowerGroup(pintFieldGroupID); } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } /// <summary> /// Get all field belong to field group /// </summary> /// <param name="pintFieldGroupID">Field Group Id</param> /// <param name="pstrReportID">Report ID</param> /// <returns>DataTable</returns> public DataTable GetFields(int pintFieldGroupID, string pstrReportID) { try { Sys_FieldGroupDS dsFieldGroup = new Sys_FieldGroupDS(); return dsFieldGroup.GetFields(pintFieldGroupID, pstrReportID); } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } /// <summary> /// Get all field which not belong to any field group /// </summary> /// <param name="pstrReportID">Report ID</param> /// <returns>DataTable</returns> public DataTable GetAvailableFields(string pstrReportID) { try { Sys_FieldGroupDS dsFieldGroup = new Sys_FieldGroupDS(); return dsFieldGroup.GetAvailableFields(pstrReportID); } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } /// <summary> /// Switch two group order /// </summary> /// <param name="pobjGroup1">Field Group 1</param> /// <param name="pobjGroup2">Field Group 2</param> public void SwitchFieldGroup (object pobjGroup1, object pobjGroup2) { try { Sys_FieldGroupDS dsFieldGroup = new Sys_FieldGroupDS(); dsFieldGroup.Update(pobjGroup1); dsFieldGroup.Update(pobjGroup2); } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics; namespace IntelHardwareIntrinsicTest { class Program { const int Pass = 100; const int Fail = 0; static unsafe int Main(string[] args) { int testResult = Pass; if (Avx.IsSupported) { using (TestTable<int> intTable = new TestTable<int>(new int[8] { 1, -5, 100, 0, 1, 2, 3, 4 }, new int[8])) { var vf = Avx.LoadDquVector256((int*)(intTable.inArrayPtr)); Unsafe.Write(intTable.outArrayPtr, vf); if (!intTable.CheckResult((x, y) => x == y)) { Console.WriteLine("AVX LoadDquVector256 failed on int:"); foreach (var item in intTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<uint> intTable = new TestTable<uint>(new uint[8] { 1, 5, 100, 0, 1, 2, 3, 4 }, new uint[8])) { var vf = Avx.LoadDquVector256((uint*)(intTable.inArrayPtr)); Unsafe.Write(intTable.outArrayPtr, vf); if (!intTable.CheckResult((x, y) => x == y)) { Console.WriteLine("AVX LoadDquVector256 failed on uint:"); foreach (var item in intTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<long> intTable = new TestTable<long>(new long[4] { 1, -5, 100, 0 }, new long[4])) { var vf = Avx.LoadDquVector256((long*)(intTable.inArrayPtr)); Unsafe.Write(intTable.outArrayPtr, vf); if (!intTable.CheckResult((x, y) => x == y)) { Console.WriteLine("AVX LoadDquVector256 failed on long:"); foreach (var item in intTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<ulong> intTable = new TestTable<ulong>(new ulong[4] { 1, 5, 100, 0 }, new ulong[4])) { var vf = Avx.LoadDquVector256((ulong*)(intTable.inArrayPtr)); Unsafe.Write(intTable.outArrayPtr, vf); if (!intTable.CheckResult((x, y) => x == y)) { Console.WriteLine("AVX LoadDquVector256 failed on ulong:"); foreach (var item in intTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<short> intTable = new TestTable<short>(new short[16] { 1, -5, 100, 0, 1, 2, 3, 4, 1, -5, 100, 0, 1, 2, 3, 4 }, new short[16])) { var vf = Avx.LoadDquVector256((short*)(intTable.inArrayPtr)); Unsafe.Write(intTable.outArrayPtr, vf); if (!intTable.CheckResult((x, y) => x == y)) { Console.WriteLine("AVX LoadDquVector256 failed on short:"); foreach (var item in intTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<ushort> intTable = new TestTable<ushort>(new ushort[16] { 1, 5, 100, 0, 1, 2, 3, 4, 1, 5, 100, 0, 1, 2, 3, 4 }, new ushort[16])) { var vf = Avx.LoadDquVector256((ushort*)(intTable.inArrayPtr)); Unsafe.Write(intTable.outArrayPtr, vf); if (!intTable.CheckResult((x, y) => x == y)) { Console.WriteLine("AVX LoadDquVector256 failed on ushort:"); foreach (var item in intTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<byte> intTable = new TestTable<byte>(new byte[32] { 1, 5, 100, 0, 1, 2, 3, 4, 1, 5, 100, 0, 1, 2, 3, 4, 1, 5, 100, 0, 1, 2, 3, 4, 1, 5, 100, 0, 1, 2, 3, 4 }, new byte[32])) { var vf = Avx.LoadDquVector256((byte*)(intTable.inArrayPtr)); Unsafe.Write(intTable.outArrayPtr, vf); if (!intTable.CheckResult((x, y) => x == y)) { Console.WriteLine("AVX LoadDquVector256 failed on byte:"); foreach (var item in intTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<sbyte> intTable = new TestTable<sbyte>(new sbyte[32] { 1, -5, 100, 0, 1, 2, 3, 4, 1, -5, 100, 0, 1, 2, 3, 4, 1, -5, 100, 0, 1, 2, 3, 4, 1, -5, 100, 0, 1, 2, 3, 4 }, new sbyte[32])) { var vf = Avx.LoadDquVector256((sbyte*)(intTable.inArrayPtr)); Unsafe.Write(intTable.outArrayPtr, vf); if (!intTable.CheckResult((x, y) => x == y)) { Console.WriteLine("AVX LoadDquVector256 failed on sbyte:"); foreach (var item in intTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } } return testResult; } public unsafe struct TestTable<T> : IDisposable where T : struct { public T[] inArray; public T[] outArray; public void* inArrayPtr => inHandle.AddrOfPinnedObject().ToPointer(); public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer(); GCHandle inHandle; GCHandle outHandle; public TestTable(T[] a, T[] b) { this.inArray = a; this.outArray = b; inHandle = GCHandle.Alloc(inArray, GCHandleType.Pinned); outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned); } public bool CheckResult(Func<T, T, bool> check) { for (int i = 0; i < inArray.Length; i++) { if (!check(inArray[i], outArray[i])) { return false; } } return true; } public void Dispose() { inHandle.Free(); outHandle.Free(); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace ODataValidator.Rule { using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using ODataValidator.Rule.Helper; using ODataValidator.RuleEngine; using ODataValidator.RuleEngine.Common; using System.Net; /// <summary> /// Class of extension rule /// </summary> [Export(typeof(ExtensionRule))] public class MetadataCore4204 : ExtensionRule { private List<AliasNamespacePair> aliasNamespacePairList = new List<AliasNamespacePair>(); /// <summary> /// Gets Category property /// </summary> public override string Category { get { return "core"; } } /// <summary> /// Gets rule name /// </summary> public override string Name { get { return "Metadata.Core.4204"; } } /// <summary> /// Gets rule description /// </summary> public override string Description { get { return "A complex type MUST NOT introduce an inheritance cycle via the base type attribute."; } } /// <summary> /// Gets rule specification in OData document /// </summary> public override string SpecificationSection { get { return "9.1.2"; } } /// <summary> /// Gets location of help information of the rule /// </summary> public override string HelpLink { get { return null; } } /// <summary> /// Gets the error message for validation failure /// </summary> public override string ErrorMessage { get { return this.Description; } } /// <summary> /// Gets the requirement level. /// </summary> public override RequirementLevel RequirementLevel { get { return RequirementLevel.Must; } } /// <summary> /// Gets the version. /// </summary> public override ODataVersion? Version { get { return ODataVersion.V4; } } /// <summary> /// Gets the payload type to which the rule applies. /// </summary> public override PayloadType? PayloadType { get { return RuleEngine.PayloadType.Metadata; } } /// <summary> /// Gets the flag whether the rule requires metadata document /// </summary> public override bool? RequireMetadata { get { return true; } } /// <summary> /// Gets the offline context to which the rule applies /// </summary> public override bool? IsOfflineContext { get { return false; } } /// <summary> /// Gets the payload format to which the rule applies. /// </summary> public override PayloadFormat? PayloadFormat { get { return RuleEngine.PayloadFormat.Xml; } } /// <summary> /// Verify Metadata.Core.4204 /// </summary> /// <param name="context">Service context</param> /// <param name="info">out parameter to return violation information when rule fail</param> /// <returns>true if rule passes; false otherwise</returns> public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool? passed = null; info = null; // Load MetadataDocument into XMLDOM XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(context.MetadataDocument); string xpath = "//*[local-name()='Reference']"; XmlNodeList refNodeList = xmlDoc.SelectNodes(xpath); // Add all included reference namespace alias pair in aliasNamespacePairList. foreach (XmlNode reference in refNodeList) { foreach (XmlNode child in reference.ChildNodes) { if (child.Attributes == null) continue; // the comment nodes do not contain Attributes collection. if (child.Name.Equals("edmx:Include")) { string namespaceString = string.Empty; string aliasString = string.Empty; if (child.Attributes == null) continue; // the comment nodes do not contain Attributes collection. if (child.Attributes["Namespace"] != null) { namespaceString = child.Attributes["Namespace"].Value; } if (child.Attributes["Alias"] != null) { aliasString = child.Attributes["Alias"].Value; } AliasNamespacePair referenceAliasNamespace = new AliasNamespacePair(aliasString, namespaceString); aliasNamespacePairList.Add(referenceAliasNamespace); } } } XElement metaXml = XElement.Parse(context.MetadataDocument); xpath = "//*[local-name()='ComplexType']"; IEnumerable<XElement> complexTypeElements = metaXml.XPathSelectElements(xpath, ODataNamespaceManager.Instance); foreach (XElement complexTypeElement in complexTypeElements) { passed = true; HashSet<string> descendantsSet = new HashSet<string>(StringComparer.Ordinal); AliasNamespacePair aliasNameSpace = complexTypeElement.GetAliasAndNamespace(); if (!string.IsNullOrEmpty(aliasNameSpace.Namespace)) { descendantsSet.Add(aliasNameSpace.Namespace+ "." + complexTypeElement.Attribute("Name").Value); } if (!string.IsNullOrEmpty(aliasNameSpace.Alias)) { descendantsSet.Add(aliasNameSpace.Alias + "." + complexTypeElement.Attribute("Name").Value); } if (!aliasNamespacePairList.Contains(aliasNameSpace)) { aliasNamespacePairList.Add(aliasNameSpace); } if (this.IsComplextTypeBaseDeadCycled(complexTypeElement, context, ref descendantsSet)) { passed = true; } else { passed = false; info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload); break; } } return passed; } /// <summary> /// See whether there is a complex type base type cycled to one of its desendants. /// </summary> /// <param name="complexTypeElement">The XElement of a complext type.</param> /// <param name="context">The ODataValidation Service context.</param> /// <param name="descendantsSet">The set of the qualified names of the </param> /// <returns></returns> private bool IsComplextTypeBaseDeadCycled(XElement complexTypeElement, ServiceContext context, ref HashSet<string> descendantsSet) { XElement baseType = null; string baseTypeQulifiedName = string.Empty; string baseTypeSimpleName = string.Empty; string baseTypePrefix = string.Empty; if(complexTypeElement.Attribute("BaseType")!=null) { baseTypeQulifiedName = complexTypeElement.Attribute("BaseType").Value; baseTypeSimpleName = baseTypeQulifiedName.GetLastSegment(); baseTypePrefix = baseTypeQulifiedName.Substring(0, baseTypeQulifiedName.IndexOf(baseTypeSimpleName) - 1); baseType= MetadataHelper.GetTypeDefinitionEleByDoc("ComplexType", baseTypeQulifiedName, context.MetadataDocument); if(baseType == null) { string doc = MetadataHelper.GetReferenceDocByDefinedType(baseTypeQulifiedName, context); if(!string.IsNullOrEmpty(doc)) { baseType = MetadataHelper.GetTypeDefinitionEleByDoc("ComplexType", baseTypeQulifiedName, doc); } } } if (baseType != null) { string baseTypeAnotherQualifiedName = string.Empty; foreach(AliasNamespacePair aliasNspair in aliasNamespacePairList) { if (baseTypePrefix.Equals(aliasNspair.Alias) && !string.IsNullOrEmpty(aliasNspair.Namespace)) { baseTypeAnotherQualifiedName = aliasNspair.Namespace + "." + baseTypeSimpleName; break; } else if (baseTypePrefix.Equals(aliasNspair.Namespace) && !string.IsNullOrEmpty(aliasNspair.Alias)) { baseTypeAnotherQualifiedName = aliasNspair.Alias + "." + baseTypeSimpleName; break; } } if (descendantsSet.Add(baseTypeQulifiedName) && (string.IsNullOrEmpty(baseTypeAnotherQualifiedName) ? true : descendantsSet.Add(baseTypeAnotherQualifiedName))) { return IsComplextTypeBaseDeadCycled(baseType, context, ref descendantsSet); } else { return false; } } return true; } } }
// // Copyright (c) 2003-2006 Jaroslaw Kowalski <jaak@jkowalski.net> // Copyright (c) 2006-2014 Piotr Fusik <piotr@fusik.info> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using Sooda.Caching; using Sooda.Logging; using Sooda.QL; using Sooda.Schema; using System; using System.Collections; using System.Collections.Generic; using System.Data; namespace Sooda.ObjectMapper { enum CollectionChange { Added, Removed } public class SoodaObjectOneToManyCollection : SoodaObjectCollectionBase, ISoodaObjectList, ISoodaObjectListInternal { static readonly Logger logger = LogManager.GetLogger("Sooda.OneToManyCollection"); Dictionary<SoodaObject, CollectionChange> tempItems = null; readonly SoodaObject parentObject; readonly string childRefField; readonly Type childType; readonly SoodaWhereClause additionalWhereClause; readonly bool cached; public SoodaObjectOneToManyCollection(SoodaTransaction tran, Type childType, SoodaObject parentObject, string childRefField, Sooda.Schema.ClassInfo classInfo, SoodaWhereClause additionalWhereClause, bool cached) : base(tran, classInfo) { this.childType = childType; this.parentObject = parentObject; this.childRefField = childRefField; this.additionalWhereClause = additionalWhereClause; this.cached = cached; } public override int Add(object obj) { if (obj == null) throw new ArgumentNullException("obj"); Type t = childType; System.Reflection.PropertyInfo prop = t.GetProperty(childRefField); prop.SetValue(obj, parentObject, null); return 0; } public override void Remove(object obj) { if (obj == null) throw new ArgumentNullException("obj"); Type t = childType; System.Reflection.PropertyInfo prop = t.GetProperty(childRefField); prop.SetValue(obj, null, null); } public override bool Contains(object obj) { if (obj == null) return false; Type t = childType; System.Reflection.PropertyInfo prop = t.GetProperty(childRefField); return parentObject == prop.GetValue(obj, null); } public void InternalAdd(SoodaObject c) { if (!childType.IsInstanceOfType(c)) return; if (items == null) { if (tempItems == null) tempItems = new Dictionary<SoodaObject, CollectionChange>(); tempItems[c] = CollectionChange.Added; return; } if (items.ContainsKey(c)) return; items.Add(c, itemsArray.Count); itemsArray.Add(c); } public void InternalRemove(SoodaObject c) { if (!childType.IsInstanceOfType(c)) return; if (items == null) { if (tempItems == null) tempItems = new Dictionary<SoodaObject, CollectionChange>(); tempItems[c] = CollectionChange.Removed; return; } int pos; if (!items.TryGetValue(c, out pos)) throw new InvalidOperationException("Attempt to remove object not in collection"); SoodaObject lastObj = itemsArray[itemsArray.Count - 1]; if (lastObj != c) { itemsArray[pos] = lastObj; items[lastObj] = pos; } itemsArray.RemoveAt(itemsArray.Count - 1); items.Remove(c); } protected override void LoadData() { SoodaDataSource ds = transaction.OpenDataSource(classInfo.GetDataSource()); TableInfo[] loadedTables; items = new Dictionary<SoodaObject, int>(); itemsArray = new List<SoodaObject>(); ISoodaObjectFactory factory = transaction.GetFactory(classInfo); SoodaWhereClause whereClause = new SoodaWhereClause(Soql.FieldEqualsParam(childRefField, 0), parentObject.GetPrimaryKeyValue()); if (additionalWhereClause != null) whereClause = whereClause.Append(additionalWhereClause); string cacheKey = null; if (cached) { // cache makes sense only on clean database if (!transaction.HasBeenPrecommitted(classInfo.GetRootClass())) { cacheKey = SoodaCache.GetCollectionKey(classInfo, whereClause); } } IEnumerable keysCollection = transaction.LoadCollectionFromCache(cacheKey, logger); if (keysCollection != null) { foreach (object o in keysCollection) { SoodaObject obj = factory.GetRef(transaction, o); // this binds to cache obj.EnsureFieldsInited(); if (tempItems != null) { CollectionChange change; if (tempItems.TryGetValue(obj, out change) && change == CollectionChange.Removed) continue; } items.Add(obj, itemsArray.Count); itemsArray.Add(obj); } } else { using (IDataReader reader = ds.LoadObjectList(transaction.Schema, classInfo, whereClause, null, 0, -1, SoodaSnapshotOptions.Default, out loadedTables)) { List<SoodaObject> readObjects = null; if (cached) readObjects = new List<SoodaObject>(); while (reader.Read()) { SoodaObject obj = SoodaObject.GetRefFromRecordHelper(transaction, factory, reader, 0, loadedTables, 0); if (readObjects != null) readObjects.Add(obj); if (tempItems != null) { CollectionChange change; if (tempItems.TryGetValue(obj, out change) && change == CollectionChange.Removed) continue; } items.Add(obj, itemsArray.Count); itemsArray.Add(obj); } if (cached) { TimeSpan expirationTimeout; bool slidingExpiration; if (transaction.CachingPolicy.GetExpirationTimeout( classInfo, whereClause, null, 0, -1, readObjects.Count, out expirationTimeout, out slidingExpiration)) { transaction.StoreCollectionInCache(cacheKey, classInfo, readObjects, null, true, expirationTimeout, slidingExpiration); } } } } if (tempItems != null) { foreach (KeyValuePair<SoodaObject, CollectionChange> entry in tempItems) { if (entry.Value == CollectionChange.Added) { SoodaObject obj = (SoodaObject) entry.Key; if (!items.ContainsKey(obj)) { items.Add(obj, itemsArray.Count); itemsArray.Add(obj); } } } } } } }
namespace InControl { using UnityEngine; public class TouchButtonControl : TouchControl { [Header( "Position" )] [SerializeField] TouchControlAnchor anchor = TouchControlAnchor.BottomRight; [SerializeField] TouchUnitType offsetUnitType = TouchUnitType.Percent; [SerializeField] Vector2 offset = new Vector2( -10.0f, 10.0f ); [SerializeField] bool lockAspectRatio = true; [Header( "Options" )] public ButtonTarget target = ButtonTarget.Action1; public bool allowSlideToggle = true; public bool toggleOnLeave = false; [Header( "Sprites" )] public TouchSprite button = new TouchSprite( 15.0f ); bool buttonState; Touch currentTouch; bool dirty; public override void CreateControl() { button.Create( "Button", transform, 1000 ); } public override void DestroyControl() { button.Delete(); if (currentTouch != null) { TouchEnded( currentTouch ); currentTouch = null; } } public override void ConfigureControl() { transform.position = OffsetToWorldPosition( anchor, offset, offsetUnitType, lockAspectRatio ); button.Update( true ); } public override void DrawGizmos() { button.DrawGizmos( ButtonPosition, Color.yellow ); } void Update() { if (dirty) { ConfigureControl(); dirty = false; } else { button.Update(); } } public override void SubmitControlState( ulong updateTick, float deltaTime ) { if (currentTouch == null && allowSlideToggle) { ButtonState = false; var touchCount = TouchManager.TouchCount; for (var i = 0; i < touchCount; i++) { ButtonState = ButtonState || button.Contains( TouchManager.GetTouch( i ) ); } } SubmitButtonState( target, ButtonState, updateTick, deltaTime ); } public override void CommitControlState( ulong updateTick, float deltaTime ) { CommitButton( target ); } public override void TouchBegan( Touch touch ) { if (currentTouch != null) { return; } if (button.Contains( touch )) { ButtonState = true; currentTouch = touch; } } public override void TouchMoved( Touch touch ) { if (currentTouch != touch) { return; } if (toggleOnLeave && !button.Contains( touch )) { ButtonState = false; currentTouch = null; } } public override void TouchEnded( Touch touch ) { if (currentTouch != touch) { return; } ButtonState = false; currentTouch = null; } bool ButtonState { get { return buttonState; } set { if (buttonState != value) { buttonState = value; button.State = value; } } } public Vector3 ButtonPosition { get { return button.Ready ? button.Position : transform.position; } set { if (button.Ready) { button.Position = value; } } } public TouchControlAnchor Anchor { get { return anchor; } set { if (anchor != value) { anchor = value; dirty = true; } } } public Vector2 Offset { get { return offset; } set { if (offset != value) { offset = value; dirty = true; } } } public TouchUnitType OffsetUnitType { get { return offsetUnitType; } set { if (offsetUnitType != value) { offsetUnitType = value; dirty = true; } } } } }
using System; using NUnit.Framework; using ServiceStack.Common.Tests.Models; namespace ServiceStack.OrmLite.MySql.Tests { [TestFixture] public class OrmLiteCreateTableWithNamigStrategyTests : OrmLiteTestBase { [Test] public void Can_create_TableWithNamigStrategy_table_prefix() { OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = new PrefixNamingStrategy { TablePrefix ="tab_", ColumnPrefix = "col_", }; using (var db = ConnectionString.OpenDbConnection()) using (var dbCmd = db.CreateCommand()) { dbCmd.CreateTable<ModelWithOnlyStringFields>(true); } OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase(); } [Test] public void Can_create_TableWithNamigStrategy_table_lowered() { OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = new LowercaseNamingStrategy(); using (var db = ConnectionString.OpenDbConnection()) using (var dbCmd = db.CreateCommand()) { dbCmd.CreateTable<ModelWithOnlyStringFields>(true); } OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase(); } [Test] public void Can_create_TableWithNamigStrategy_table_nameUnderscoreCoumpound() { OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = new UnderscoreSeparatedCompoundNamingStrategy(); using (var db = ConnectionString.OpenDbConnection()) using (var dbCmd = db.CreateCommand()) { dbCmd.CreateTable<ModelWithOnlyStringFields>(true); } OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase(); } [Test] public void Can_get_data_from_TableWithNamigStrategy_with_GetById() { OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = new PrefixNamingStrategy { TablePrefix = "tab_", ColumnPrefix = "col_", }; using (var db = ConnectionString.OpenDbConnection()) using (var dbCmd = db.CreateCommand()) { dbCmd.CreateTable<ModelWithOnlyStringFields>(true); ModelWithOnlyStringFields m = new ModelWithOnlyStringFields() { Id= "999", AlbumId = "112", AlbumName="ElectroShip", Name = "MyNameIsBatman"}; dbCmd.Save<ModelWithOnlyStringFields>(m); var modelFromDb = dbCmd.GetById<ModelWithOnlyStringFields>("999"); Assert.AreEqual(m.Name, modelFromDb.Name); } OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase(); } [Test] public void Can_get_data_from_TableWithNamigStrategy_with_query_by_example() { OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = new PrefixNamingStrategy { TablePrefix = "tab_", ColumnPrefix = "col_", }; using (var db = ConnectionString.OpenDbConnection()) using (var dbCmd = db.CreateCommand()) { dbCmd.CreateTable<ModelWithOnlyStringFields>(true); ModelWithOnlyStringFields m = new ModelWithOnlyStringFields() { Id = "998", AlbumId = "112", AlbumName = "ElectroShip", Name = "QueryByExample" }; dbCmd.Save<ModelWithOnlyStringFields>(m); var modelFromDb = dbCmd.Where<ModelWithOnlyStringFields>(new { Name = "QueryByExample" })[0]; Assert.AreEqual(m.Name, modelFromDb.Name); } OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase(); } [Test] public void Can_get_data_from_TableWithNamigStrategy_AfterChangingNamingStrategy() { OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = new PrefixNamingStrategy { TablePrefix = "tab_", ColumnPrefix = "col_", }; using (var db = ConnectionString.OpenDbConnection()) using (var dbCmd = db.CreateCommand()) { dbCmd.CreateTable<ModelWithOnlyStringFields>(true); ModelWithOnlyStringFields m = new ModelWithOnlyStringFields() { Id = "998", AlbumId = "112", AlbumName = "ElectroShip", Name = "QueryByExample" }; dbCmd.Save<ModelWithOnlyStringFields>(m); var modelFromDb = dbCmd.Where<ModelWithOnlyStringFields>(new { Name = "QueryByExample" })[0]; Assert.AreEqual(m.Name, modelFromDb.Name); modelFromDb = dbCmd.GetById<ModelWithOnlyStringFields>("998"); Assert.AreEqual(m.Name, modelFromDb.Name); } OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase(); using (var db = ConnectionString.OpenDbConnection()) using (var dbCmd = db.CreateCommand()) { dbCmd.CreateTable<ModelWithOnlyStringFields>(true); ModelWithOnlyStringFields m = new ModelWithOnlyStringFields() { Id = "998", AlbumId = "112", AlbumName = "ElectroShip", Name = "QueryByExample" }; dbCmd.Save<ModelWithOnlyStringFields>(m); var modelFromDb = dbCmd.Where<ModelWithOnlyStringFields>(new { Name = "QueryByExample" })[0]; Assert.AreEqual(m.Name, modelFromDb.Name); modelFromDb = dbCmd.GetById<ModelWithOnlyStringFields>("998"); Assert.AreEqual(m.Name, modelFromDb.Name); } OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy = new PrefixNamingStrategy { TablePrefix = "tab_", ColumnPrefix = "col_", }; using (var db = ConnectionString.OpenDbConnection()) using (var dbCmd = db.CreateCommand()) { dbCmd.CreateTable<ModelWithOnlyStringFields>(true); ModelWithOnlyStringFields m = new ModelWithOnlyStringFields() { Id = "998", AlbumId = "112", AlbumName = "ElectroShip", Name = "QueryByExample" }; dbCmd.Save<ModelWithOnlyStringFields>(m); var modelFromDb = dbCmd.Where<ModelWithOnlyStringFields>(new { Name = "QueryByExample" })[0]; Assert.AreEqual(m.Name, modelFromDb.Name); modelFromDb = dbCmd.GetById<ModelWithOnlyStringFields>("998"); Assert.AreEqual(m.Name, modelFromDb.Name); } OrmLite.OrmLiteConfig.DialectProvider.NamingStrategy= new OrmLiteNamingStrategyBase(); } } public class PrefixNamingStrategy : OrmLiteNamingStrategyBase { public string TablePrefix { get; set; } public string ColumnPrefix { get; set; } public override string GetTableName(string name) { return TablePrefix + name; } public override string GetColumnName(string name) { return ColumnPrefix + name; } } public class LowercaseNamingStrategy : OrmLiteNamingStrategyBase { public override string GetTableName(string name) { return name.ToLower(); } public override string GetColumnName(string name) { return name.ToLower(); } } public class UnderscoreSeparatedCompoundNamingStrategy : OrmLiteNamingStrategyBase { public override string GetTableName(string name) { return toUnderscoreSeparatedCompound(name); } public override string GetColumnName(string name) { return toUnderscoreSeparatedCompound(name); } string toUnderscoreSeparatedCompound(string name) { string r = char.ToLower(name[0]).ToString(); for (int i = 1; i < name.Length; i++) { char c = name[i]; if (char.IsUpper(name[i])) { r += "_"; r += char.ToLower(name[i]); } else { r += name[i]; } } return r; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Configuration.Install; using System.Reflection; using Microsoft.Win32; using System.IO; using System.Text; using System.Threading; using System.Globalization; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation { /// <summary> /// /// PSInstaller is a class for facilitating installation /// of monad engine and monad PSSnapin's. /// /// This class implements installer api from CLR. At install /// time, installation utilities (like InstallUtil.exe) will /// call api implementation functions in this class automatically. /// This includes functions like Install, Uninstall, Rollback /// and Commit. /// /// This class is an abstract class for handling installation needs /// that are common for all monad components, which include, /// /// 1. accessing system registry /// 2. support of additional command line parameters. /// 3. writing registry files /// 4. automatically extract informaton like vender, version, etc. /// /// Different monad component will derive from this class. Two common /// components that need install include, /// /// 1. PSSnapin. Installation of PSSnapin will require information /// about PSSnapin assembly, version, vendor, etc to be /// written to registry. /// /// 2. Engine. Installation of monad engine will require information /// about engine assembly, version, CLR information to be /// written to registry. /// /// </summary> /// /// <remarks> /// This is an abstract class to be derived by monad engine and PSSnapin installers /// only. Developer should not directly derive from this class. /// </remarks> public abstract class PSInstaller : Installer { private static string[] MshRegistryRoots { get { // For 3.0 PowerShell, we use "3" as the registry version key only for Engine // related data like ApplicationBase. // For 3.0 PowerShell, we still use "1" as the registry version key for // Snapin and Custom shell lookup/discovery. return new string[] { "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\PowerShell\\" + PSVersionInfo.RegistryVersion1Key + "\\" }; } } /// <summary> /// /// </summary> internal abstract string RegKey { get; } /// <summary> /// /// </summary> internal abstract Dictionary<String, object> RegValues { get; } /// <summary> /// /// </summary> /// <param name="stateSaver"></param> public sealed override void Install(IDictionary stateSaver) { base.Install(stateSaver); WriteRegistry(); return; } private void WriteRegistry() { foreach (string root in MshRegistryRoots) { RegistryKey key = GetRegistryKey(root + RegKey); foreach (var pair in RegValues) { key.SetValue(pair.Key, pair.Value); } } } private RegistryKey GetRegistryKey(string keyPath) { RegistryKey root = GetRootHive(keyPath); if (root == null) return null; return root.CreateSubKey(GetSubkeyPath(keyPath)); } private static string GetSubkeyPath(string keyPath) { int index = keyPath.IndexOf('\\'); if (index > 0) { return keyPath.Substring(index + 1); } return null; } private static RegistryKey GetRootHive(string keyPath) { string root; int index = keyPath.IndexOf('\\'); if (index > 0) { root = keyPath.Substring(0, index); } else { root = keyPath; } switch (root.ToUpperInvariant()) { case "HKEY_CURRENT_USER": return Registry.CurrentUser; case "HKEY_LOCAL_MACHINE": return Registry.LocalMachine; case "HKEY_CLASSES_ROOT": return Registry.ClassesRoot; case "HKEY_CURRENT_CONFIG": return Registry.CurrentConfig; case "HKEY_PERFORMANCE_DATA": return Registry.PerformanceData; case "HKEY_USERS": return Registry.Users; } return null; } /// <summary> /// Uninstall this msh component /// </summary> /// <param name="savedState"></param> public sealed override void Uninstall(IDictionary savedState) { base.Uninstall(savedState); if (this.Context != null && this.Context.Parameters != null && this.Context.Parameters.ContainsKey("RegFile")) { string regFile = this.Context.Parameters["RegFile"]; // If regfile is specified. Don't uninstall. if (!String.IsNullOrEmpty(regFile)) return; } string keyName; string parentKey; int index = RegKey.LastIndexOf('\\'); if (index >= 0) { parentKey = RegKey.Substring(0, index); keyName = RegKey.Substring(index + 1); } else { parentKey = ""; keyName = RegKey; } foreach (string root in MshRegistryRoots) { RegistryKey key = GetRegistryKey(root + parentKey); key.DeleteSubKey(keyName); } return; } /// <summary> /// Rollback this msh component /// </summary> /// <param name="savedState"></param> public sealed override void Rollback(IDictionary savedState) { Uninstall(savedState); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System { //Only contains static methods. Does not require serialization using System; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; using System.Runtime; #if BIT64 using nuint = System.UInt64; #else // BIT64 using nuint = System.UInt32; #endif // BIT64 [System.Runtime.InteropServices.ComVisible(true)] public static class Buffer { // Copies from one primitive array to another primitive array without // respecting types. This calls memmove internally. The count and // offset parameters here are in bytes. If you want to use traditional // array element indices and counts, use Array.Copy. [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count); // A very simple and efficient memmove that assumes all of the // parameter validation has already been done. The count and offset // parameters here are in bytes. If you want to use traditional // array element indices and counts, use Array.Copy. [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void InternalBlockCopy(Array src, int srcOffsetBytes, Array dst, int dstOffsetBytes, int byteCount); // This is ported from the optimized CRT assembly in memchr.asm. The JIT generates // pretty good code here and this ends up being within a couple % of the CRT asm. // It is however cross platform as the CRT hasn't ported their fast version to 64-bit // platforms. // internal unsafe static int IndexOfByte(byte* src, byte value, int index, int count) { Debug.Assert(src != null, "src should not be null"); byte* pByte = src + index; // Align up the pointer to sizeof(int). while (((int)pByte & 3) != 0) { if (count == 0) return -1; else if (*pByte == value) return (int) (pByte - src); count--; pByte++; } // Fill comparer with value byte for comparisons // // comparer = 0/0/value/value uint comparer = (((uint)value << 8) + (uint)value); // comparer = value/value/value/value comparer = (comparer << 16) + comparer; // Run through buffer until we hit a 4-byte section which contains // the byte we're looking for or until we exhaust the buffer. while (count > 3) { // Test the buffer for presence of value. comparer contains the byte // replicated 4 times. uint t1 = *(uint*)pByte; t1 = t1 ^ comparer; uint t2 = 0x7efefeff + t1; t1 = t1 ^ 0xffffffff; t1 = t1 ^ t2; t1 = t1 & 0x81010100; // if t1 is zero then these 4-bytes don't contain a match if (t1 != 0) { // We've found a match for value, figure out which position it's in. int foundIndex = (int) (pByte - src); if (pByte[0] == value) return foundIndex; else if (pByte[1] == value) return foundIndex + 1; else if (pByte[2] == value) return foundIndex + 2; else if (pByte[3] == value) return foundIndex + 3; } count -= 4; pByte += 4; } // Catch any bytes that might be left at the tail of the buffer while (count > 0) { if (*pByte == value) return (int) (pByte - src); count--; pByte++; } // If we don't have a match return -1; return -1; } // Returns a bool to indicate if the array is of primitive data types // or not. [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool IsPrimitiveTypeArray(Array array); // Gets a particular byte out of the array. The array must be an // array of primitives. // // This essentially does the following: // return ((byte*)array) + index. // [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern byte _GetByte(Array array, int index); public static byte GetByte(Array array, int index) { // Is the array present? if (array == null) throw new ArgumentNullException(nameof(array)); // Is it of primitive types? if (!IsPrimitiveTypeArray(array)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), nameof(array)); // Is the index in valid range of the array? if (index < 0 || index >= _ByteLength(array)) throw new ArgumentOutOfRangeException(nameof(index)); return _GetByte(array, index); } // Sets a particular byte in an the array. The array must be an // array of primitives. // // This essentially does the following: // *(((byte*)array) + index) = value. // [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _SetByte(Array array, int index, byte value); public static void SetByte(Array array, int index, byte value) { // Is the array present? if (array == null) throw new ArgumentNullException(nameof(array)); // Is it of primitive types? if (!IsPrimitiveTypeArray(array)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), nameof(array)); // Is the index in valid range of the array? if (index < 0 || index >= _ByteLength(array)) throw new ArgumentOutOfRangeException(nameof(index)); // Make the FCall to do the work _SetByte(array, index, value); } // Gets a particular byte out of the array. The array must be an // array of primitives. // // This essentially does the following: // return array.length * sizeof(array.UnderlyingElementType). // [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int _ByteLength(Array array); public static int ByteLength(Array array) { // Is the array present? if (array == null) throw new ArgumentNullException(nameof(array)); // Is it of primitive types? if (!IsPrimitiveTypeArray(array)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), nameof(array)); return _ByteLength(array); } internal unsafe static void ZeroMemory(byte* src, long len) { while(len-- > 0) *(src + len) = 0; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal unsafe static void Memcpy(byte[] dest, int destIndex, byte* src, int srcIndex, int len) { Debug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!"); Debug.Assert(dest.Length - destIndex >= len, "not enough bytes in dest"); // If dest has 0 elements, the fixed statement will throw an // IndexOutOfRangeException. Special-case 0-byte copies. if (len==0) return; fixed(byte* pDest = dest) { Memcpy(pDest + destIndex, src + srcIndex, len); } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal unsafe static void Memcpy(byte* pDest, int destIndex, byte[] src, int srcIndex, int len) { Debug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!"); Debug.Assert(src.Length - srcIndex >= len, "not enough bytes in src"); // If dest has 0 elements, the fixed statement will throw an // IndexOutOfRangeException. Special-case 0-byte copies. if (len==0) return; fixed(byte* pSrc = src) { Memcpy(pDest + destIndex, pSrc + srcIndex, len); } } // This is tricky to get right AND fast, so lets make it useful for the whole Fx. // E.g. System.Runtime.WindowsRuntime!WindowsRuntimeBufferExtensions.MemCopy uses it. // This method has a slightly different behavior on arm and other platforms. // On arm this method behaves like memcpy and does not handle overlapping buffers. // While on other platforms it behaves like memmove and handles overlapping buffers. // This behavioral difference is unfortunate but intentional because // 1. This method is given access to other internal dlls and this close to release we do not want to change it. // 2. It is difficult to get this right for arm and again due to release dates we would like to visit it later. [FriendAccessAllowed] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if ARM [MethodImplAttribute(MethodImplOptions.InternalCall)] internal unsafe static extern void Memcpy(byte* dest, byte* src, int len); #else // ARM [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] internal unsafe static void Memcpy(byte* dest, byte* src, int len) { Debug.Assert(len >= 0, "Negative length in memcopy!"); Memmove(dest, src, (uint)len); } #endif // ARM // This method has different signature for x64 and other platforms and is done for performance reasons. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal unsafe static void Memmove(byte* dest, byte* src, nuint len) { // P/Invoke into the native version when the buffers are overlapping and the copy needs to be performed backwards // This check can produce false positives for lengths greater than Int32.MaxInt. It is fine because we want to use PInvoke path for the large lengths anyway. if ((nuint)dest - (nuint)src < len) goto PInvoke; // This is portable version of memcpy. It mirrors what the hand optimized assembly versions of memcpy typically do. // // Ideally, we would just use the cpblk IL instruction here. Unfortunately, cpblk IL instruction is not as efficient as // possible yet and so we have this implementation here for now. // Note: It's important that this switch handles lengths at least up to 22. // See notes below near the main loop for why. // The switch will be very fast since it can be implemented using a jump // table in assembly. See http://stackoverflow.com/a/449297/4077294 for more info. switch (len) { case 0: return; case 1: *dest = *src; return; case 2: *(short*)dest = *(short*)src; return; case 3: *(short*)dest = *(short*)src; *(dest + 2) = *(src + 2); return; case 4: *(int*)dest = *(int*)src; return; case 5: *(int*)dest = *(int*)src; *(dest + 4) = *(src + 4); return; case 6: *(int*)dest = *(int*)src; *(short*)(dest + 4) = *(short*)(src + 4); return; case 7: *(int*)dest = *(int*)src; *(short*)(dest + 4) = *(short*)(src + 4); *(dest + 6) = *(src + 6); return; case 8: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif return; case 9: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(dest + 8) = *(src + 8); return; case 10: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(short*)(dest + 8) = *(short*)(src + 8); return; case 11: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(short*)(dest + 8) = *(short*)(src + 8); *(dest + 10) = *(src + 10); return; case 12: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); return; case 13: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); *(dest + 12) = *(src + 12); return; case 14: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); *(short*)(dest + 12) = *(short*)(src + 12); return; case 15: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); *(short*)(dest + 12) = *(short*)(src + 12); *(dest + 14) = *(src + 14); return; case 16: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif return; case 17: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif *(dest + 16) = *(src + 16); return; case 18: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif *(short*)(dest + 16) = *(short*)(src + 16); return; case 19: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif *(short*)(dest + 16) = *(short*)(src + 16); *(dest + 18) = *(src + 18); return; case 20: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif *(int*)(dest + 16) = *(int*)(src + 16); return; case 21: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif *(int*)(dest + 16) = *(int*)(src + 16); *(dest + 20) = *(src + 20); return; case 22: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif *(int*)(dest + 16) = *(int*)(src + 16); *(short*)(dest + 20) = *(short*)(src + 20); return; } // P/Invoke into the native version for large lengths if (len >= 512) goto PInvoke; nuint i = 0; // byte offset at which we're copying if (((int)dest & 3) != 0) { if (((int)dest & 1) != 0) { *(dest + i) = *(src + i); i += 1; if (((int)dest & 2) != 0) goto IntAligned; } *(short*)(dest + i) = *(short*)(src + i); i += 2; } IntAligned: #if BIT64 // On 64-bit IntPtr.Size == 8, so we want to advance to the next 8-aligned address. If // (int)dest % 8 is 0, 5, 6, or 7, we will already have advanced by 0, 3, 2, or 1 // bytes to the next aligned address (respectively), so do nothing. On the other hand, // if it is 1, 2, 3, or 4 we will want to copy-and-advance another 4 bytes until // we're aligned. // The thing 1, 2, 3, and 4 have in common that the others don't is that if you // subtract one from them, their 3rd lsb will not be set. Hence, the below check. if ((((int)dest - 1) & 4) == 0) { *(int*)(dest + i) = *(int*)(src + i); i += 4; } #endif // BIT64 nuint end = len - 16; len -= i; // lower 4 bits of len represent how many bytes are left *after* the unrolled loop // We know due to the above switch-case that this loop will always run 1 iteration; max // bytes we copy before checking is 23 (7 to align the pointers, 16 for 1 iteration) so // the switch handles lengths 0-22. Debug.Assert(end >= 7 && i <= end); // This is separated out into a different variable, so the i + 16 addition can be // performed at the start of the pipeline and the loop condition does not have // a dependency on the writes. nuint counter; do { counter = i + 16; // This loop looks very costly since there appear to be a bunch of temporary values // being created with the adds, but the jit (for x86 anyways) will convert each of // these to use memory addressing operands. // So the only cost is a bit of code size, which is made up for by the fact that // we save on writes to dest/src. #if BIT64 *(long*)(dest + i) = *(long*)(src + i); *(long*)(dest + i + 8) = *(long*)(src + i + 8); #else *(int*)(dest + i) = *(int*)(src + i); *(int*)(dest + i + 4) = *(int*)(src + i + 4); *(int*)(dest + i + 8) = *(int*)(src + i + 8); *(int*)(dest + i + 12) = *(int*)(src + i + 12); #endif i = counter; // See notes above for why this wasn't used instead // i += 16; } while (counter <= end); if ((len & 8) != 0) { #if BIT64 *(long*)(dest + i) = *(long*)(src + i); #else *(int*)(dest + i) = *(int*)(src + i); *(int*)(dest + i + 4) = *(int*)(src + i + 4); #endif i += 8; } if ((len & 4) != 0) { *(int*)(dest + i) = *(int*)(src + i); i += 4; } if ((len & 2) != 0) { *(short*)(dest + i) = *(short*)(src + i); i += 2; } if ((len & 1) != 0) { *(dest + i) = *(src + i); // We're not using i after this, so not needed // i += 1; } return; PInvoke: _Memmove(dest, src, len); } // Non-inlinable wrapper around the QCall that avoids poluting the fast path // with P/Invoke prolog/epilog. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [MethodImplAttribute(MethodImplOptions.NoInlining)] private unsafe static void _Memmove(byte* dest, byte* src, nuint len) { __Memmove(dest, src, len); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] extern private unsafe static void __Memmove(byte* dest, byte* src, nuint len); // The attributes on this method are chosen for best JIT performance. // Please do not edit unless intentional. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static unsafe void MemoryCopy(void* source, void* destination, long destinationSizeInBytes, long sourceBytesToCopy) { if (sourceBytesToCopy > destinationSizeInBytes) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sourceBytesToCopy); } Memmove((byte*)destination, (byte*)source, checked((nuint)sourceBytesToCopy)); } // The attributes on this method are chosen for best JIT performance. // Please do not edit unless intentional. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static unsafe void MemoryCopy(void* source, void* destination, ulong destinationSizeInBytes, ulong sourceBytesToCopy) { if (sourceBytesToCopy > destinationSizeInBytes) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sourceBytesToCopy); } #if BIT64 Memmove((byte*)destination, (byte*)source, sourceBytesToCopy); #else // BIT64 Memmove((byte*)destination, (byte*)source, checked((uint)sourceBytesToCopy)); #endif // BIT64 } } }
namespace Oculus.Platform.Samples.VrBoardGame { using UnityEngine; using Oculus.Platform; using Oculus.Platform.Models; using UnityEngine.UI; using System.Collections.Generic; using System; using UnityEngine.Assertions; // This classes uses the Oculus Matchmaking Service to find opponents of a similar // skill and play a match with them. A skill pool is used with the matchmaking pool // to coordinate the skill matching. Follow the instructions in the Readme to setup // the matchmaking pools. // The Datastore for the Room is used to communicate between the clients. This only // works for relatively simple games with tolerance for latency. For more complex // or realtime requirements, you'll want to use the Oculus.Platform.Net API. public class MatchmakingManager : MonoBehaviour { // GameController to notify about match completions or early endings [SerializeField] private GameController m_gameController = null; // Text for the button that controls matchmaking [SerializeField] private Text m_matchButtonText = null; // Test widget to render matmaking statistics [SerializeField] private Text m_infoText = null; // name of the Quckmatch Pool configured on the Oculus Developer Dashboard // which is expected to have an associated skill pool private const string POOL = "VR_BOARD_GAME_POOL"; // the ID of the room for the current match private ulong m_matchRoom; // opponent User data private User m_remotePlayer; // last time we've received a room update private float m_lastUpdateTime; // how long to wait before polling for updates private const float POLL_FREQUENCY = 30.0f; private enum MatchRoomState { None, Queued, Configuring, MyTurn, RemoteTurn } private MatchRoomState m_state; void Start() { Matchmaking.SetMatchFoundNotificationCallback(MatchFoundCallback); Rooms.SetUpdateNotificationCallback(MatchmakingRoomUpdateCallback); TransitionToState(MatchRoomState.None); } void Update() { switch (m_state) { case MatchRoomState.Configuring: case MatchRoomState.MyTurn: case MatchRoomState.RemoteTurn: // if we're expecting an update form the remote player and we haven't // heard from them in a while, check the datastore just-in-case if (POLL_FREQUENCY < (Time.time - m_lastUpdateTime)) { Debug.Log("Polling Room"); m_lastUpdateTime = Time.time; Rooms.Get(m_matchRoom).OnComplete(MatchmakingRoomUpdateCallback); } break; } } public void MatchButtonPressed() { switch (m_state) { case MatchRoomState.None: TransitionToState(MatchRoomState.Queued); break; default: TransitionToState(MatchRoomState.None); break; } } public void EndMatch(int localScore, int remoteScore) { switch (m_state) { case MatchRoomState.MyTurn: case MatchRoomState.RemoteTurn: var myID = PlatformManager.MyID.ToString(); var remoteID = m_remotePlayer.ID.ToString(); var rankings = new Dictionary<string, int>(); if (localScore > remoteScore) { rankings[myID] = 1; rankings[remoteID] = 2; } else if (localScore < remoteScore) { rankings[myID] = 2; rankings[remoteID] = 1; } else { rankings[myID] = 1; rankings[remoteID] = 1; } // since there is no secure server to simulate the game and report // verifiable results, each client needs to independently report their // results for the service to compate for inconsistencies Matchmaking.ReportResultsInsecure(m_matchRoom, rankings) .OnComplete(GenericErrorCheckCallback); break; } TransitionToState(MatchRoomState.None); } void OnApplicationQuit() { // be a good matchmaking citizen and leave any queue immediately Matchmaking.Cancel(); if (m_matchRoom != 0) { Rooms.Leave(m_matchRoom); } } private void TransitionToState(MatchRoomState state) { var m_oldState = m_state; m_state = state; switch (m_state) { case MatchRoomState.None: m_matchButtonText.text = "Find Match"; // the player can abort from any of the other states to the None state // so we need to be careful to clean up all state variables m_remotePlayer = null; Matchmaking.Cancel(); if (m_matchRoom != 0) { Rooms.Leave(m_matchRoom); m_matchRoom = 0; } break; case MatchRoomState.Queued: Assert.AreEqual(MatchRoomState.None, m_oldState); m_matchButtonText.text = "Leave Queue"; Matchmaking.Enqueue2(POOL).OnComplete(MatchmakingEnqueueCallback); break; case MatchRoomState.Configuring: Assert.AreEqual(MatchRoomState.Queued, m_oldState); m_matchButtonText.text = "Cancel Match"; break; case MatchRoomState.MyTurn: case MatchRoomState.RemoteTurn: Assert.AreNotEqual(MatchRoomState.None, m_oldState); Assert.AreNotEqual(MatchRoomState.Queued, m_oldState); m_matchButtonText.text = "Cancel Match"; break; } } void MatchmakingEnqueueCallback(Message untyped_msg) { if (untyped_msg.IsError) { Debug.Log(untyped_msg.GetError().Message); TransitionToState(MatchRoomState.None); return; } Message<MatchmakingEnqueueResult> msg = (Message<MatchmakingEnqueueResult>)untyped_msg; MatchmakingEnqueueResult info = msg.Data; m_infoText.text = string.Format( "Avg Wait Time: {0}s\n" + "Max Expected Wait: {1}s\n" + "In Last Hour: {2}\n" + "Recent Percentage: {3}%", info.AverageWait, info.MaxExpectedWait, info.MatchesInLastHourCount, info.RecentMatchPercentage); } void MatchFoundCallback(Message<Room> msg) { if (msg.IsError) { Debug.Log(msg.GetError().Message); TransitionToState(MatchRoomState.None); return; } if (m_state != MatchRoomState.Queued) { // ignore callback - user already cancelled return; } // since this example communicates via updates to the datastore, it's vital that // we subscribe to room updates Matchmaking.JoinRoom(msg.Data.ID, true /* subscribe to update notifications */) .OnComplete(MatchmakingJoinRoomCallback); m_matchRoom = msg.Data.ID; } void MatchmakingJoinRoomCallback(Message<Room> msg) { if (msg.IsError) { Debug.Log(msg.GetError().Message); TransitionToState(MatchRoomState.None); return; } if (m_state != MatchRoomState.Queued) { // ignore callback - user already cancelled return; } int numUsers = (msg.Data.UsersOptional != null) ? msg.Data.UsersOptional.Count : 0; Debug.Log ("Match room joined: " + m_matchRoom + " count: " + numUsers); TransitionToState(MatchRoomState.Configuring); // only process the room data if the other user has already joined if (msg.Data.UsersOptional != null && msg.Data.UsersOptional.Count == 2) { ProcessRoomData(msg.Data); } } // Room Datastore updates are used to send moves between players. So if the MatchRoomState // is RemoteTurn I'm looking for the other player's move in the Datastore. If the // MatchRoomState is MyTurn I'm waiting for the room ownership to change so that // I have authority to write to the datastore. void MatchmakingRoomUpdateCallback(Message<Room> msg) { if (msg.IsError) { Debug.Log(msg.GetError().Message); TransitionToState(MatchRoomState.None); return; } string ownerOculusID = msg.Data.OwnerOptional != null ? msg.Data.OwnerOptional.OculusID : ""; int numUsers = (msg.Data.UsersOptional != null) ? msg.Data.UsersOptional.Count : 0; Debug.LogFormat( "Room Update {0}\n" + " Owner {1}\n" + " User Count {2}\n" + " Datastore Count {3}\n", msg.Data.ID, ownerOculusID, numUsers, msg.Data.DataStore.Count); // check to make sure the room is valid as there are a few odd timing issues (for // example when leaving a room) that can trigger an uninteresting update if (msg.Data.ID != m_matchRoom) { Debug.Log("Unexpected room update from: " + msg.Data.ID); return; } ProcessRoomData(msg.Data); } private void ProcessRoomData(Room room) { m_lastUpdateTime = Time.time; if (m_state == MatchRoomState.Configuring) { // get the User info for the other player if (room.UsersOptional != null) { foreach (var user in room.UsersOptional) { if (PlatformManager.MyID != user.ID) { Debug.Log("Found remote user: " + user.OculusID); m_remotePlayer = user; break; } } } if (m_remotePlayer == null) return; bool i_go_first = DoesLocalUserGoFirst(); TransitionToState(i_go_first ? MatchRoomState.MyTurn : MatchRoomState.RemoteTurn); Matchmaking.StartMatch(m_matchRoom).OnComplete(GenericErrorCheckCallback); m_gameController.StartOnlineMatch(m_remotePlayer.OculusID, i_go_first); } // if it's the remote player's turn, look for their move in the datastore if (m_state == MatchRoomState.RemoteTurn && room.DataStore.ContainsKey(m_remotePlayer.OculusID) && room.DataStore[m_remotePlayer.OculusID] != "") { // process remote move ProcessRemoteMove(room.DataStore[m_remotePlayer.OculusID]); TransitionToState(MatchRoomState.MyTurn); } // If the room ownership transferred to me, we can mark the remote turn complete. // We don't do this when the remote move comes in if we aren't yet the owner because // the local user will not be able to write to the datastore if they aren't the // owner of the room. if (m_state == MatchRoomState.MyTurn && room.OwnerOptional != null && room.OwnerOptional.ID == PlatformManager.MyID) { m_gameController.MarkRemoteTurnComplete(); } if (room.UsersOptional == null || (room.UsersOptional != null && room.UsersOptional.Count != 2)) { Debug.Log("Other user quit the room"); m_gameController.RemoteMatchEnded(); } } private void ProcessRemoteMove(string moveString) { Debug.Log("Processing remote move string: " + moveString); string[] tokens = moveString.Split(':'); GamePiece.Piece piece = (GamePiece.Piece)Enum.Parse(typeof(GamePiece.Piece), tokens[0]); int x = Int32.Parse(tokens[1]); int y = Int32.Parse(tokens[2]); // swap the coordinates since each player assumes they are player 0 x = GameBoard.LENGTH_X-1 - x; y = GameBoard.LENGTH_Y-1 - y; m_gameController.MakeRemoteMove(piece, x, y); } public void SendLocalMove(GamePiece.Piece piece, int boardX, int boardY) { string moveString = string.Format("{0}:{1}:{2}", piece.ToString(), boardX, boardY); Debug.Log("Sending move: " + moveString); var dict = new Dictionary<string, string>(); dict[PlatformManager.MyOculusID] = moveString; dict[m_remotePlayer.OculusID] = ""; Rooms.UpdateDataStore(m_matchRoom, dict).OnComplete(UpdateDataStoreCallback); TransitionToState(MatchRoomState.RemoteTurn); } private void UpdateDataStoreCallback(Message<Room> msg) { if (m_state != MatchRoomState.RemoteTurn) { // ignore calback - user already quit the match return; } // after I've updated the datastore with my move, change ownership so the other // user can perform their move Rooms.UpdateOwner(m_matchRoom, m_remotePlayer.ID); } // deterministic but somewhat random selection for who goes first private bool DoesLocalUserGoFirst() { // if the room ID is even, the lower ID goes first if (m_matchRoom % 2 == 0) { return PlatformManager.MyID < m_remotePlayer.ID; } // otherwise the higher ID goes first { return PlatformManager.MyID > m_remotePlayer.ID; } } private void GenericErrorCheckCallback(Message msg) { if (msg.IsError) { Debug.Log(msg.GetError().Message); TransitionToState(MatchRoomState.None); return; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Threading; namespace System.Transactions { // The volatile Demultiplexer is a fanout point for promoted volatile enlistments. // When a transaction is promoted a single volatile enlistment is created in the new // transaction for all volitile enlistments on the transaction. When the VolatileDemux // receives a preprepare it will fan that notification out to all of the enlistments // on the transaction. When it has gathered all of the responses it will send a // single vote back to the DistributedTransactionManager. internal abstract class VolatileDemultiplexer : IEnlistmentNotificationInternal { // Reference the transactions so that we have access to it's enlistments protected InternalTransaction _transaction; // Store the IVolatileEnlistment interface to call back to the Distributed TM internal IPromotedEnlistment _promotedEnlistment; internal IPromotedEnlistment _preparingEnlistment; public VolatileDemultiplexer(InternalTransaction transaction) { _transaction = transaction; } internal void BroadcastCommitted(ref VolatileEnlistmentSet volatiles) { // Broadcast preprepare to the volatile subordinates for (int i = 0; i < volatiles._volatileEnlistmentCount; i++) { volatiles._volatileEnlistments[i]._twoPhaseState.InternalCommitted( volatiles._volatileEnlistments[i]); } } // This broadcast is used by the state machines and therefore must be internal. internal void BroadcastRollback(ref VolatileEnlistmentSet volatiles) { // Broadcast preprepare to the volatile subordinates for (int i = 0; i < volatiles._volatileEnlistmentCount; i++) { volatiles._volatileEnlistments[i]._twoPhaseState.InternalAborted( volatiles._volatileEnlistments[i]); } } internal void BroadcastInDoubt(ref VolatileEnlistmentSet volatiles) { // Broadcast preprepare to the volatile subordinates for (int i = 0; i < volatiles._volatileEnlistmentCount; i++) { volatiles._volatileEnlistments[i]._twoPhaseState.InternalIndoubt( volatiles._volatileEnlistments[i]); } } // Object for synchronizing access to the entire class( avoiding lock( typeof( ... )) ) private static object s_classSyncObject; internal static object ClassSyncObject { get { if (s_classSyncObject == null) { object o = new object(); Interlocked.CompareExchange(ref s_classSyncObject, o, null); } return s_classSyncObject; } } private static WaitCallback s_prepareCallback; private static WaitCallback PrepareCallback => LazyInitializer.EnsureInitialized(ref s_prepareCallback, ref s_classSyncObject, () => new WaitCallback(PoolablePrepare)); protected static void PoolablePrepare(object state) { VolatileDemultiplexer demux = (VolatileDemultiplexer)state; // Don't block an enlistment thread (or a thread pool thread). So // try to get the transaction lock but if unsuccessfull give up and // queue this operation to try again later. bool tookLock = false; try { Monitor.TryEnter(demux._transaction, 250, ref tookLock); if (tookLock) { demux.InternalPrepare(); } else { if (!ThreadPool.QueueUserWorkItem(PrepareCallback, demux)) { throw TransactionException.CreateInvalidOperationException( TraceSourceType.TraceSourceLtm, SR.UnexpectedFailureOfThreadPool, null ); } } } finally { if (tookLock) { Monitor.Exit(demux._transaction); } } } private static WaitCallback s_commitCallback; private static WaitCallback CommitCallback => LazyInitializer.EnsureInitialized(ref s_commitCallback, ref s_classSyncObject, () => new WaitCallback(PoolableCommit)); protected static void PoolableCommit(object state) { VolatileDemultiplexer demux = (VolatileDemultiplexer)state; // Don't block an enlistment thread (or a thread pool thread). So // try to get the transaction lock but if unsuccessfull give up and // queue this operation to try again later. bool tookLock = false; try { Monitor.TryEnter(demux._transaction, 250, ref tookLock); if (tookLock) { demux.InternalCommit(); } else { if (!ThreadPool.QueueUserWorkItem(CommitCallback, demux)) { throw TransactionException.CreateInvalidOperationException( TraceSourceType.TraceSourceLtm, SR.UnexpectedFailureOfThreadPool, null ); } } } finally { if (tookLock) { Monitor.Exit(demux._transaction); } } } private static WaitCallback s_rollbackCallback; private static WaitCallback RollbackCallback => LazyInitializer.EnsureInitialized(ref s_rollbackCallback, ref s_classSyncObject, () => new WaitCallback(PoolableRollback)); protected static void PoolableRollback(object state) { VolatileDemultiplexer demux = (VolatileDemultiplexer)state; // Don't block an enlistment thread (or a thread pool thread). So // try to get the transaction lock but if unsuccessfull give up and // queue this operation to try again later. bool tookLock = false; try { Monitor.TryEnter(demux._transaction, 250, ref tookLock); if (tookLock) { demux.InternalRollback(); } else { if (!ThreadPool.QueueUserWorkItem(RollbackCallback, demux)) { throw TransactionException.CreateInvalidOperationException( TraceSourceType.TraceSourceLtm, SR.UnexpectedFailureOfThreadPool, null ); } } } finally { if (tookLock) { Monitor.Exit(demux._transaction); } } } private static WaitCallback s_inDoubtCallback; private static WaitCallback InDoubtCallback => LazyInitializer.EnsureInitialized(ref s_inDoubtCallback, ref s_classSyncObject, () => new WaitCallback(PoolableInDoubt)); protected static void PoolableInDoubt(object state) { VolatileDemultiplexer demux = (VolatileDemultiplexer)state; // Don't block an enlistment thread (or a thread pool thread). So // try to get the transaction lock but if unsuccessfull give up and // queue this operation to try again later. bool tookLock = false; try { Monitor.TryEnter(demux._transaction, 250, ref tookLock); if (tookLock) { demux.InternalInDoubt(); } else { if (!ThreadPool.QueueUserWorkItem(InDoubtCallback, demux)) { throw TransactionException.CreateInvalidOperationException( TraceSourceType.TraceSourceLtm, SR.UnexpectedFailureOfThreadPool, null ); } } } finally { if (tookLock) { Monitor.Exit(demux._transaction); } } } protected abstract void InternalPrepare(); protected abstract void InternalCommit(); protected abstract void InternalRollback(); protected abstract void InternalInDoubt(); #region IEnlistmentNotification Members // Fanout Preprepare notifications public abstract void Prepare(IPromotedEnlistment en); public abstract void Commit(IPromotedEnlistment en); public abstract void Rollback(IPromotedEnlistment en); public abstract void InDoubt(IPromotedEnlistment en); #endregion } // This class implements the phase 0 version of a volatile demux. internal class Phase0VolatileDemultiplexer : VolatileDemultiplexer { public Phase0VolatileDemultiplexer(InternalTransaction transaction) : base(transaction) { } protected override void InternalPrepare() { try { _transaction.State.ChangeStatePromotedPhase0(_transaction); } catch (TransactionAbortedException e) { _promotedEnlistment.ForceRollback(e); TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.ExceptionConsumed(e); } } catch (TransactionInDoubtException e) { _promotedEnlistment.EnlistmentDone(); TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.ExceptionConsumed(e); } } } protected override void InternalCommit() { // Respond immediately to the TM _promotedEnlistment.EnlistmentDone(); _transaction.State.ChangeStatePromotedCommitted(_transaction); } protected override void InternalRollback() { // Respond immediately to the TM _promotedEnlistment.EnlistmentDone(); _transaction.State.ChangeStatePromotedAborted(_transaction); } protected override void InternalInDoubt() { _transaction.State.InDoubtFromDtc(_transaction); } #region IEnlistmentNotification Members // Fanout Preprepare notifications public override void Prepare(IPromotedEnlistment en) { _preparingEnlistment = en; PoolablePrepare(this); } public override void Commit(IPromotedEnlistment en) { _promotedEnlistment = en; PoolableCommit(this); } public override void Rollback(IPromotedEnlistment en) { _promotedEnlistment = en; PoolableRollback(this); } public override void InDoubt(IPromotedEnlistment en) { _promotedEnlistment = en; PoolableInDoubt(this); } #endregion } // This class implements the phase 1 version of a volatile demux. internal class Phase1VolatileDemultiplexer : VolatileDemultiplexer { public Phase1VolatileDemultiplexer(InternalTransaction transaction) : base(transaction) { } protected override void InternalPrepare() { try { _transaction.State.ChangeStatePromotedPhase1(_transaction); } catch (TransactionAbortedException e) { _promotedEnlistment.ForceRollback(e); TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.ExceptionConsumed(e); } } catch (TransactionInDoubtException e) { _promotedEnlistment.EnlistmentDone(); TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.ExceptionConsumed(e); } } } protected override void InternalCommit() { // Respond immediately to the TM _promotedEnlistment.EnlistmentDone(); _transaction.State.ChangeStatePromotedCommitted(_transaction); } protected override void InternalRollback() { // Respond immediately to the TM _promotedEnlistment.EnlistmentDone(); _transaction.State.ChangeStatePromotedAborted(_transaction); } protected override void InternalInDoubt() { _transaction.State.InDoubtFromDtc(_transaction); } // Fanout Preprepare notifications public override void Prepare(IPromotedEnlistment en) { _preparingEnlistment = en; PoolablePrepare(this); } public override void Commit(IPromotedEnlistment en) { _promotedEnlistment = en; PoolableCommit(this); } public override void Rollback(IPromotedEnlistment en) { _promotedEnlistment = en; PoolableRollback(this); } public override void InDoubt(IPromotedEnlistment en) { _promotedEnlistment = en; PoolableInDoubt(this); } } internal struct VolatileEnlistmentSet { internal InternalEnlistment[] _volatileEnlistments; internal int _volatileEnlistmentCount; internal int _volatileEnlistmentSize; internal int _dependentClones; // Track the number of volatile enlistments that have prepared. internal int _preparedVolatileEnlistments; // This is a single pinpoint enlistment to represent all volatile enlistments that // may exist on a promoted transaction. This member should only be initialized if // a transaction is promoted. private VolatileDemultiplexer _volatileDemux; internal VolatileDemultiplexer VolatileDemux { get { return _volatileDemux; } set { Debug.Assert(_volatileDemux == null, "volatileDemux can only be set once."); _volatileDemux = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace ILCompiler.DependencyAnalysis.X86 { public struct X86Emitter { public X86Emitter(NodeFactory factory, bool relocsOnly) { Builder = new ObjectDataBuilder(factory, relocsOnly); TargetRegister = new TargetRegisterMap(factory.Target.OperatingSystem); } public ObjectDataBuilder Builder; public TargetRegisterMap TargetRegister; public void EmitADD(ref AddrMode addrMode, sbyte immediate) { if (addrMode.Size == AddrModeSize.Int16) Builder.EmitByte(0x66); EmitIndirInstruction((byte)((addrMode.Size != AddrModeSize.Int8) ? 0x83 : 0x80), (byte)0, ref addrMode); Builder.EmitByte((byte)immediate); } public void EmitJMP(ISymbolNode symbol) { if (symbol.RepresentsIndirectionCell) { Builder.EmitByte(0xff); Builder.EmitByte(0x25); Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_HIGHLOW); } else { Builder.EmitByte(0xE9); Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_REL32); } } public void EmitXOR(Register register1, Register register2) { Builder.EmitByte(0x33); Builder.EmitByte((byte)(0xC0 | ((byte)register1 << 3) | (byte)register2)); } public void EmitPUSH(sbyte imm8) { Builder.EmitByte(0x6A); Builder.EmitByte(unchecked((byte)imm8)); } public void EmitPUSH(ISymbolNode node) { if (node.RepresentsIndirectionCell) { // push eax (arbitrary value) Builder.EmitByte(0x50); // mov eax, [node address] Builder.EmitByte(0x8B); Builder.EmitByte(0x00 | ((byte)Register.EAX << 3) | 0x5); Builder.EmitReloc(node, RelocType.IMAGE_REL_BASED_HIGHLOW); // xchg [esp], eax; this also restores the previous value of eax Builder.EmitByte(0x87); Builder.EmitByte(0x04); Builder.EmitByte(0x24); } else { // push <node address> Builder.EmitByte(0x68); Builder.EmitReloc(node, RelocType.IMAGE_REL_BASED_HIGHLOW); } } public void EmitMOV(Register register, ISymbolNode node) { if (node.RepresentsIndirectionCell) { // mov register, [node address] Builder.EmitByte(0x8B); Builder.EmitByte((byte)(0x00 | ((byte)register << 3) | 0x5)); } else { // mov register, immediate Builder.EmitByte((byte)(0xB8 + (byte)register)); } Builder.EmitReloc(node, RelocType.IMAGE_REL_BASED_HIGHLOW); } public void EmitINT3() { Builder.EmitByte(0xCC); } private bool InSignedByteRange(int i) { return i == (int)(sbyte)i; } private void EmitImmediate(int immediate, int size) { switch (size) { case 0: break; case 1: Builder.EmitByte((byte)immediate); break; case 2: Builder.EmitShort((short)immediate); break; case 4: Builder.EmitInt(immediate); break; default: throw new NotImplementedException(); } } private void EmitModRM(byte subOpcode, ref AddrMode addrMode) { byte modRM = (byte)((subOpcode & 0x07) << 3); if (addrMode.BaseReg > Register.None) { Debug.Assert(addrMode.BaseReg >= Register.RegDirect); Register reg = (Register)(addrMode.BaseReg - Register.RegDirect); Builder.EmitByte((byte)(0xC0 | modRM | ((int)reg & 0x07))); } else { byte lowOrderBitsOfBaseReg = (byte)((int)addrMode.BaseReg & 0x07); modRM |= lowOrderBitsOfBaseReg; int offsetSize = 0; if (addrMode.Offset == 0 && (lowOrderBitsOfBaseReg != (byte)Register.EBP)) { offsetSize = 0; } else if (InSignedByteRange(addrMode.Offset)) { offsetSize = 1; modRM |= 0x40; } else { offsetSize = 4; modRM |= 0x80; } bool emitSibByte = false; Register sibByteBaseRegister = addrMode.BaseReg; if (addrMode.BaseReg == Register.None) { emitSibByte = (addrMode.IndexReg != Register.NoIndex); modRM &= 0x38; // set Mod bits to 00 and clear out base reg offsetSize = 4; // this forces 32-bit displacement if (emitSibByte) { // EBP in SIB byte means no base // ModRM base register forced to ESP in SIB code below sibByteBaseRegister = Register.EBP; } else { // EBP in ModRM means no base modRM |= (byte)(Register.EBP); } } else if (lowOrderBitsOfBaseReg == (byte)Register.ESP || addrMode.IndexReg.HasValue) { emitSibByte = true; } if (!emitSibByte) { Builder.EmitByte(modRM); } else { modRM = (byte)((modRM & 0xF8) | (int)Register.ESP); Builder.EmitByte(modRM); int indexRegAsInt = (int)(addrMode.IndexReg.HasValue ? addrMode.IndexReg.Value : Register.ESP); Builder.EmitByte((byte)((addrMode.Scale << 6) + ((indexRegAsInt & 0x07) << 3) + ((int)sibByteBaseRegister & 0x07))); } EmitImmediate(addrMode.Offset, offsetSize); } } private void EmitExtendedOpcode(int opcode) { if ((opcode >> 16) != 0) { if ((opcode >> 24) != 0) { Builder.EmitByte((byte)(opcode >> 24)); } Builder.EmitByte((byte)(opcode >> 16)); } Builder.EmitByte((byte)(opcode >> 8)); } private void EmitIndirInstruction(int opcode, byte subOpcode, ref AddrMode addrMode) { if ((opcode >> 8) != 0) { EmitExtendedOpcode(opcode); } Builder.EmitByte((byte)opcode); EmitModRM(subOpcode, ref addrMode); } } }
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ using System; using System.Collections.Generic; using Lucene.Net.Analysis; using Lucene.Net.Codecs; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Index.Extensions; using Lucene.Net.Queries.Function; using Lucene.Net.Queries.Function.ValueSources; using Lucene.Net.Search; using Lucene.Net.Search.Similarities; using Lucene.Net.Store; using Lucene.Net.Util; using NUnit.Framework; namespace Lucene.Net.Tests.Queries.Function { // TODO: add separate docvalues test /// <summary> /// barebones tests for function queries. /// </summary> public class TestValueSources : LuceneTestCase { internal static Directory dir; internal static IndexReader reader; internal static IndexSearcher searcher; internal static readonly IList<string[]> documents = new[] { /* id, byte, double, float, int, long, short, string, text */ new[] { "0", "5", "3.63", "5.2", "35", "4343", "945", "test", "this is a test test test" }, new[] { "1", "12", "5.65", "9.3", "54", "1954", "123", "bar", "second test" } }; [SetUp] public override void SetUp() { base.SetUp(); dir = NewDirectory(); IndexWriterConfig iwConfig = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); iwConfig.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwConfig); Document document = new Document(); Field idField = new StringField("id", "", Field.Store.NO); document.Add(idField); Field byteField = new StringField("byte", "", Field.Store.NO); document.Add(byteField); Field doubleField = new StringField("double", "", Field.Store.NO); document.Add(doubleField); Field floatField = new StringField("float", "", Field.Store.NO); document.Add(floatField); Field intField = new StringField("int", "", Field.Store.NO); document.Add(intField); Field longField = new StringField("long", "", Field.Store.NO); document.Add(longField); Field shortField = new StringField("short", "", Field.Store.NO); document.Add(shortField); Field stringField = new StringField("string", "", Field.Store.NO); document.Add(stringField); Field textField = new TextField("text", "", Field.Store.NO); document.Add(textField); foreach (string[] doc in documents) { idField.SetStringValue(doc[0]); byteField.SetStringValue(doc[1]); doubleField.SetStringValue(doc[2]); floatField.SetStringValue(doc[3]); intField.SetStringValue(doc[4]); longField.SetStringValue(doc[5]); shortField.SetStringValue(doc[6]); stringField.SetStringValue(doc[7]); textField.SetStringValue(doc[8]); iw.AddDocument(document); } reader = iw.GetReader(); searcher = NewSearcher(reader); iw.Dispose(); } [TearDown] public override void TearDown() { searcher = null; reader.Dispose(); reader = null; dir.Dispose(); dir = null; base.TearDown(); } [Test] public void TestByte() { #pragma warning disable 612, 618 AssertHits(new FunctionQuery(new ByteFieldSource("byte")), new[] { 5f, 12f }); #pragma warning restore 612, 618 } [Test] public void TestConst() { AssertHits(new FunctionQuery(new ConstValueSource(0.3f)), new[] { 0.3f, 0.3f }); } [Test] public void TestDiv() { AssertHits(new FunctionQuery(new DivSingleFunction(new ConstValueSource(10f), new ConstValueSource(5f))), new[] { 2f, 2f }); } [Test] public void TestDocFreq() { AssertHits(new FunctionQuery(new DocFreqValueSource("bogus", "bogus", "text", new BytesRef("test"))), new[] { 2f, 2f }); } [Test] public void TestDoubleConst() { AssertHits(new FunctionQuery(new DoubleConstValueSource(0.3d)), new[] { 0.3f, 0.3f }); } [Test] public void TestDouble() { AssertHits(new FunctionQuery(new DoubleFieldSource("double")), new[] { 3.63f, 5.65f }); } [Test] public void TestFloat() { AssertHits(new FunctionQuery(new SingleFieldSource("float")), new[] { 5.2f, 9.3f }); } [Test] public void TestIDF() { Similarity saved = searcher.Similarity; try { searcher.Similarity = new DefaultSimilarity(); AssertHits(new FunctionQuery(new IDFValueSource("bogus", "bogus", "text", new BytesRef("test"))), new[] { 0.5945349f, 0.5945349f }); } finally { searcher.Similarity = saved; } } [Test] public void TestIf() { AssertHits(new FunctionQuery(new IfFunction(new BytesRefFieldSource("id"), new ConstValueSource(1.0f), new ConstValueSource(2.0f) )), new[] { 1f, 1f }); // true just if a value exists... AssertHits(new FunctionQuery(new IfFunction(new LiteralValueSource("false"), new ConstValueSource(1.0f), new ConstValueSource(2.0f) )), new[] { 1f, 1f }); } [Test] public void TestInt() { AssertHits(new FunctionQuery(new Int32FieldSource("int")), new[] { 35f, 54f }); } [Test] public void TestJoinDocFreq() { AssertHits(new FunctionQuery(new JoinDocFreqValueSource("string", "text")), new[] { 2f, 0f }); } [Test] public void TestLinearFloat() { AssertHits(new FunctionQuery(new LinearSingleFunction(new ConstValueSource(2.0f), 3, 1)), new[] { 7f, 7f }); } [Test] public void TestLong() { AssertHits(new FunctionQuery(new Int64FieldSource("long")), new[] { 4343f, 1954f }); } [Test] public void TestMaxDoc() { AssertHits(new FunctionQuery(new MaxDocValueSource()), new[] { 2f, 2f }); } [Test] public void TestMaxFloat() { AssertHits(new FunctionQuery(new MaxSingleFunction(new ValueSource[] { new ConstValueSource(1f), new ConstValueSource(2f) })), new[] { 2f, 2f }); } [Test] public void TestMinFloat() { AssertHits(new FunctionQuery(new MinSingleFunction(new ValueSource[] { new ConstValueSource(1f), new ConstValueSource(2f) })), new[] { 1f, 1f }); } [Test] public void TestNorm() { Similarity saved = searcher.Similarity; try { // no norm field (so agnostic to indexed similarity) searcher.Similarity = new DefaultSimilarity(); AssertHits(new FunctionQuery(new NormValueSource("byte")), new[] { 0f, 0f }); } finally { searcher.Similarity = saved; } } [Test] public void TestNumDocs() { AssertHits(new FunctionQuery(new NumDocsValueSource()), new[] { 2f, 2f }); } [Test] public void TestPow() { AssertHits(new FunctionQuery(new PowSingleFunction(new ConstValueSource(2f), new ConstValueSource(3f))), new[] { 8f, 8f }); } [Test] public void TestProduct() { AssertHits(new FunctionQuery(new ProductSingleFunction(new ValueSource[] { new ConstValueSource(2f), new ConstValueSource(3f) })), new[] { 6f, 6f }); } [Test] public void TestQuery() { AssertHits(new FunctionQuery(new QueryValueSource(new FunctionQuery(new ConstValueSource(2f)), 0f)), new[] { 2f, 2f }); } [Test] public void TestRangeMap() { AssertHits(new FunctionQuery(new RangeMapSingleFunction(new SingleFieldSource("float"), 5, 6, 1, 0f)), new[] { 1f, 0f }); AssertHits(new FunctionQuery(new RangeMapSingleFunction(new SingleFieldSource("float"), 5, 6, new SumSingleFunction(new ValueSource[] { new ConstValueSource(1f), new ConstValueSource(2f) }), new ConstValueSource(11f))), new[] { 3f, 11f }); } [Test] public void TestReciprocal() { AssertHits(new FunctionQuery(new ReciprocalSingleFunction(new ConstValueSource(2f), 3, 1, 4)), new[] { 0.1f, 0.1f }); } [Test] public void TestScale() { AssertHits(new FunctionQuery(new ScaleSingleFunction(new Int32FieldSource("int"), 0, 1)), new[] { 0.0f, 1.0f }); } [Test] public void TestShort() { #pragma warning disable 612, 618 AssertHits(new FunctionQuery(new Int16FieldSource("short")), new[] { 945f, 123f }); #pragma warning restore 612, 618 } [Test] public void TestSumFloat() { AssertHits(new FunctionQuery(new SumSingleFunction(new ValueSource[] { new ConstValueSource(1f), new ConstValueSource(2f) })), new[] { 3f, 3f }); } [Test] public void TestSumTotalTermFreq() { if (Codec.Default.Name.Equals("Lucene3x", StringComparison.Ordinal)) { AssertHits(new FunctionQuery(new SumTotalTermFreqValueSource("text")), new[] { -1f, -1f }); } else { AssertHits(new FunctionQuery(new SumTotalTermFreqValueSource("text")), new[] { 8f, 8f }); } } [Test] public void TestTermFreq() { AssertHits(new FunctionQuery(new TermFreqValueSource("bogus", "bogus", "text", new BytesRef("test"))), new[] { 3f, 1f }); AssertHits(new FunctionQuery(new TermFreqValueSource("bogus", "bogus", "string", new BytesRef("bar"))), new[] { 0f, 1f }); } [Test] public void TestTF() { Similarity saved = searcher.Similarity; try { // no norm field (so agnostic to indexed similarity) searcher.Similarity = new DefaultSimilarity(); AssertHits(new FunctionQuery(new TFValueSource("bogus", "bogus", "text", new BytesRef("test"))), new[] { (float)Math.Sqrt(3d), (float)Math.Sqrt(1d) }); AssertHits(new FunctionQuery(new TFValueSource("bogus", "bogus", "string", new BytesRef("bar"))), new[] { 0f, 1f }); } finally { searcher.Similarity = saved; } } [Test] public void TestTotalTermFreq() { if (Codec.Default.Name.Equals("Lucene3x", StringComparison.Ordinal)) { AssertHits(new FunctionQuery(new TotalTermFreqValueSource("bogus", "bogus", "text", new BytesRef("test"))), new[] { -1f, -1f }); } else { AssertHits(new FunctionQuery(new TotalTermFreqValueSource("bogus", "bogus", "text", new BytesRef("test"))), new[] { 4f, 4f }); } } private void AssertHits(Query q, float[] scores) { ScoreDoc[] expected = new ScoreDoc[scores.Length]; int[] expectedDocs = new int[scores.Length]; for (int i = 0; i < expected.Length; i++) { expectedDocs[i] = i; expected[i] = new ScoreDoc(i, scores[i]); } TopDocs docs = searcher.Search(q, null, documents.Count, new Sort(new SortField("id", SortFieldType.STRING)), true, false); CheckHits.DoCheckHits( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, q, "", searcher, expectedDocs); CheckHits.CheckHitsQuery(q, expected, docs.ScoreDocs, expectedDocs); CheckHits.CheckExplanations(q, "", searcher); } } }
using System.Collections.Generic; using System.Text; namespace Lucene.Net.Search.Spans { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using IBits = Lucene.Net.Util.IBits; using IndexReader = Lucene.Net.Index.IndexReader; using Term = Lucene.Net.Index.Term; using TermContext = Lucene.Net.Index.TermContext; /// <summary> /// Wraps any <see cref="MultiTermQuery"/> as a <see cref="SpanQuery"/>, /// so it can be nested within other <see cref="SpanQuery"/> classes. /// <para/> /// The query is rewritten by default to a <see cref="SpanOrQuery"/> containing /// the expanded terms, but this can be customized. /// <para/> /// Example: /// <code> /// WildcardQuery wildcard = new WildcardQuery(new Term("field", "bro?n")); /// SpanQuery spanWildcard = new SpanMultiTermQueryWrapper&lt;WildcardQuery&gt;(wildcard); /// // do something with spanWildcard, such as use it in a SpanFirstQuery /// </code> /// </summary> public class SpanMultiTermQueryWrapper<Q> : SpanQuery, ISpanMultiTermQueryWrapper where Q : MultiTermQuery { protected readonly Q m_query; /// <summary> /// Create a new <see cref="SpanMultiTermQueryWrapper{Q}"/>. /// </summary> /// <param name="query"> Query to wrap. /// <para/> /// NOTE: This will set <see cref="MultiTermQuery.MultiTermRewriteMethod"/> /// on the wrapped <paramref name="query"/>, changing its rewrite method to a suitable one for spans. /// Be sure to not change the rewrite method on the wrapped query afterwards! Doing so will /// throw <see cref="System.NotSupportedException"/> on rewriting this query! </param> public SpanMultiTermQueryWrapper(Q query) { this.m_query = query; MultiTermQuery.RewriteMethod method = this.m_query.MultiTermRewriteMethod; if (method is ITopTermsRewrite) { int pqsize = ((ITopTermsRewrite)method).Count; MultiTermRewriteMethod = new TopTermsSpanBooleanQueryRewrite(pqsize); } else { MultiTermRewriteMethod = SCORING_SPAN_QUERY_REWRITE; } } /// <summary> /// Expert: Gets or Sets the rewrite method. This only makes sense /// to be a span rewrite method. /// </summary> public SpanRewriteMethod MultiTermRewriteMethod { get { MultiTermQuery.RewriteMethod m = m_query.MultiTermRewriteMethod; if (!(m is SpanRewriteMethod)) { throw new System.NotSupportedException("You can only use SpanMultiTermQueryWrapper with a suitable SpanRewriteMethod."); } return (SpanRewriteMethod)m; } set { m_query.MultiTermRewriteMethod = value; } } public override Spans GetSpans(AtomicReaderContext context, IBits acceptDocs, IDictionary<Term, TermContext> termContexts) { throw new System.NotSupportedException("Query should have been rewritten"); } public override string Field { get { return m_query.Field; } } /// <summary> /// Returns the wrapped query </summary> public virtual Query WrappedQuery { get { return m_query; } } public override string ToString(string field) { StringBuilder builder = new StringBuilder(); builder.Append("SpanMultiTermQueryWrapper("); builder.Append(m_query.ToString(field)); builder.Append(")"); if (Boost != 1F) { builder.Append('^'); builder.Append(Boost); } return builder.ToString(); } public override Query Rewrite(IndexReader reader) { Query q = m_query.Rewrite(reader); if (!(q is SpanQuery)) { throw new System.NotSupportedException("You can only use SpanMultiTermQueryWrapper with a suitable SpanRewriteMethod."); } q.Boost = q.Boost * Boost; // multiply boost return q; } public override int GetHashCode() { const int prime = 31; int result = base.GetHashCode(); result = prime * result + m_query.GetHashCode(); return result; } public override bool Equals(object obj) { if (this == obj) { return true; } if (!base.Equals(obj)) { return false; } if (this.GetType() != obj.GetType()) { return false; } var other = (SpanMultiTermQueryWrapper<Q>)obj; if (!m_query.Equals(other.m_query)) { return false; } return true; } // LUCENENET NOTE: Moved SpanRewriteMethod outside of this class /// <summary> /// A rewrite method that first translates each term into a <see cref="SpanTermQuery"/> in a /// <see cref="Occur.SHOULD"/> clause in a <see cref="BooleanQuery"/>, and keeps the /// scores as computed by the query. /// </summary> /// <seealso cref="MultiTermRewriteMethod"/> public static readonly SpanRewriteMethod SCORING_SPAN_QUERY_REWRITE = new SpanRewriteMethodAnonymousInnerClassHelper(); private class SpanRewriteMethodAnonymousInnerClassHelper : SpanRewriteMethod { public SpanRewriteMethodAnonymousInnerClassHelper() { } private readonly ScoringRewrite<SpanOrQuery> @delegate = new ScoringRewriteAnonymousInnerClassHelper(); private class ScoringRewriteAnonymousInnerClassHelper : ScoringRewrite<SpanOrQuery> { public ScoringRewriteAnonymousInnerClassHelper() { } protected override SpanOrQuery GetTopLevelQuery() { return new SpanOrQuery(); } protected override void CheckMaxClauseCount(int count) { // we accept all terms as SpanOrQuery has no limits } protected override void AddClause(SpanOrQuery topLevel, Term term, int docCount, float boost, TermContext states) { // TODO: would be nice to not lose term-state here. // we could add a hack option to SpanOrQuery, but the hack would only work if this is the top-level Span // (if you put this thing in another span query, it would extractTerms/double-seek anyway) SpanTermQuery q = new SpanTermQuery(term); q.Boost = boost; topLevel.AddClause(q); } } public override Query Rewrite(IndexReader reader, MultiTermQuery query) { return @delegate.Rewrite(reader, query); } } /// <summary> /// A rewrite method that first translates each term into a <see cref="SpanTermQuery"/> in a /// <see cref="Occur.SHOULD"/> clause in a <see cref="BooleanQuery"/>, and keeps the /// scores as computed by the query. /// /// <para/> /// This rewrite method only uses the top scoring terms so it will not overflow /// the boolean max clause count. /// </summary> /// <seealso cref="MultiTermRewriteMethod"/> public sealed class TopTermsSpanBooleanQueryRewrite : SpanRewriteMethod { private readonly TopTermsRewrite<SpanOrQuery> @delegate; /// <summary> /// Create a <see cref="TopTermsSpanBooleanQueryRewrite"/> for /// at most <paramref name="size"/> terms. /// </summary> public TopTermsSpanBooleanQueryRewrite(int size) { @delegate = new TopTermsRewriteAnonymousInnerClassHelper(this, size); } private class TopTermsRewriteAnonymousInnerClassHelper : TopTermsRewrite<SpanOrQuery> { private readonly TopTermsSpanBooleanQueryRewrite outerInstance; public TopTermsRewriteAnonymousInnerClassHelper(TopTermsSpanBooleanQueryRewrite outerInstance, int size) : base(size) { this.outerInstance = outerInstance; } protected override int MaxSize { get { return int.MaxValue; } } protected override SpanOrQuery GetTopLevelQuery() { return new SpanOrQuery(); } protected override void AddClause(SpanOrQuery topLevel, Term term, int docFreq, float boost, TermContext states) { SpanTermQuery q = new SpanTermQuery(term); q.Boost = boost; topLevel.AddClause(q); } } /// <summary> /// return the maximum priority queue size. /// <para/> /// NOTE: This was size() in Lucene. /// </summary> public int Count { get { return @delegate.Count; } } public override Query Rewrite(IndexReader reader, MultiTermQuery query) { return @delegate.Rewrite(reader, query); } public override int GetHashCode() { return 31 * @delegate.GetHashCode(); } public override bool Equals(object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.GetType() != obj.GetType()) { return false; } TopTermsSpanBooleanQueryRewrite other = (TopTermsSpanBooleanQueryRewrite)obj; return @delegate.Equals(other.@delegate); } } } /// <summary> /// Abstract class that defines how the query is rewritten. </summary> // LUCENENET specific - moved this class outside of SpanMultiTermQueryWrapper<Q> public abstract class SpanRewriteMethod : MultiTermQuery.RewriteMethod { public override abstract Query Rewrite(IndexReader reader, MultiTermQuery query); } /// <summary> /// LUCENENET specific interface for referring to/identifying a <see cref="Search.Spans.SpanMultiTermQueryWrapper{Q}"/> without /// referring to its generic closing type. /// </summary> public interface ISpanMultiTermQueryWrapper { /// <summary> /// Expert: Gets or Sets the rewrite method. This only makes sense /// to be a span rewrite method. /// </summary> SpanRewriteMethod MultiTermRewriteMethod { get; } Spans GetSpans(AtomicReaderContext context, IBits acceptDocs, IDictionary<Term, TermContext> termContexts); string Field { get; } /// <summary> /// Returns the wrapped query </summary> Query WrappedQuery { get; } Query Rewrite(IndexReader reader); } }