context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.IO; using System.Runtime.InteropServices; using NDesk.Options; namespace SteamBot { public class Program { private static OptionSet opts = new OptionSet() { {"bot=", "launch a configured bot given that bots index in the configuration array.", b => botIndex = Convert.ToInt32(b) } , { "help", "shows this help text", p => showHelp = (p != null) } }; private static bool showHelp; private static int botIndex = -1; private static BotManager manager; private static bool isclosing = false; [STAThread] public static void Main(string[] args) { opts.Parse(args); if (showHelp) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("If no options are given SteamBot defaults to Bot Manager mode."); opts.WriteOptionDescriptions(Console.Out); Console.Write("Press Enter to exit..."); Console.ReadLine(); return; } if (args.Length == 0) { BotManagerMode(); } else if (botIndex > -1) { BotMode(botIndex); } } #region SteamBot Operational Modes // This mode is to run a single Bot until it's terminated. private static void BotMode(int botIndex) { if (!File.Exists("settings.json")) { Console.WriteLine("No settings.json file found."); return; } Configuration configObject; try { configObject = Configuration.LoadConfiguration("settings.json"); } catch (Newtonsoft.Json.JsonReaderException) { // handle basic json formatting screwups Console.WriteLine("settings.json file is corrupt or improperly formatted."); return; } if (botIndex >= configObject.Bots.Length) { Console.WriteLine("Invalid bot index."); return; } Bot b = new Bot(configObject.Bots[botIndex], configObject.ApiKey, BotManager.UserHandlerCreator, true, true); Console.Title = "Bot Manager"; b.StartBot(); string AuthSet = "auth"; string ExecCommand = "exec"; string InputCommand = "input"; // this loop is needed to keep the botmode console alive. // instead of just sleeping, this loop will handle console input while (true) { string inputText = Console.ReadLine(); if (String.IsNullOrEmpty(inputText)) continue; // Small parse for console input var c = inputText.Trim(); var cs = c.Split(' '); if (cs.Length > 1) { if (cs[0].Equals(AuthSet, StringComparison.CurrentCultureIgnoreCase)) { b.AuthCode = cs[1].Trim(); } else if (cs[0].Equals(ExecCommand, StringComparison.CurrentCultureIgnoreCase)) { b.HandleBotCommand(c.Remove(0, cs[0].Length + 1)); } else if (cs[0].Equals(InputCommand, StringComparison.CurrentCultureIgnoreCase)) { b.HandleInput(c.Remove(0, cs[0].Length + 1)); } } } } // This mode is to manage child bot processes and take use command line inputs private static void BotManagerMode() { Console.Title = "Bot Manager"; manager = new BotManager(); var loadedOk = manager.LoadConfiguration("settings.json"); if (!loadedOk) { Console.WriteLine( "Configuration file Does not exist or is corrupt. Please rename 'settings-template.json' to 'settings.json' and modify the settings to match your environment"); Console.Write("Press Enter to exit..."); Console.ReadLine(); } else { if (manager.ConfigObject.UseSeparateProcesses) SetConsoleCtrlHandler(ConsoleCtrlCheck, true); if (manager.ConfigObject.AutoStartAllBots) { var startedOk = manager.StartBots(); if (!startedOk) { Console.WriteLine( "Error starting the bots because either the configuration was bad or because the log file was not opened."); Console.Write("Press Enter to exit..."); Console.ReadLine(); } } else { foreach (var botInfo in manager.ConfigObject.Bots) { if (botInfo.AutoStart) { // auto start this particual bot... manager.StartBot(botInfo.Username); } } } Console.WriteLine("Type help for bot manager commands. "); Console.Write("botmgr > "); var bmi = new BotManagerInterpreter(manager); // command interpreter loop. do { string inputText = Console.ReadLine(); if (String.IsNullOrEmpty(inputText)) continue; bmi.CommandInterpreter(inputText); Console.Write("botmgr > "); } while (!isclosing); } } #endregion Bot Modes private static bool ConsoleCtrlCheck(CtrlTypes ctrlType) { // Put your own handler here switch (ctrlType) { case CtrlTypes.CTRL_C_EVENT: case CtrlTypes.CTRL_BREAK_EVENT: case CtrlTypes.CTRL_CLOSE_EVENT: case CtrlTypes.CTRL_LOGOFF_EVENT: case CtrlTypes.CTRL_SHUTDOWN_EVENT: if (manager != null) { manager.StopBots(); } isclosing = true; break; } return true; } #region Console Control Handler Imports // Declare the SetConsoleCtrlHandler function // as external and receiving a delegate. [DllImport("Kernel32")] public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add); // A delegate type to be used as the handler routine // for SetConsoleCtrlHandler. public delegate bool HandlerRoutine(CtrlTypes CtrlType); // An enumerated type for the control messages // sent to the handler routine. public enum CtrlTypes { CTRL_C_EVENT = 0, CTRL_BREAK_EVENT, CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT = 5, CTRL_SHUTDOWN_EVENT } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.Threading.Tasks; using Android.Support.V4.App; using Android.Support.V4.Content; using WindowsAzure.Messaging; using Shopping.DemoApp.Droid.Activities; using Gcm; namespace Shopping.DemoApp.Droid.Services { public static class AndroidPushService { private const int VibrateTimeInMillis = 300; private const string PushTitle = "Shopping Demo App"; private static TaskCompletionSource<string> registrationTaskCompletionSource; private static TaskCompletionSource<string> unRegistrationTaskCompletionSource; private static Context initContext; private static bool gmsAvailabilable; private static NotificationHub hub; public static void Initialize(Context context) { initContext = context; gmsAvailabilable = CheckAvailability(); //hub = new NotificationHub(AppSettings.NotificationHubPath, AppSettings.NotificationHubConnectionString, context); } public static async Task Register(string[] tags) { if (gmsAvailabilable) { var registrationId = await RegisterInternal(); try { await Task.Run(() => hub.Register(registrationId, tags)); Console.WriteLine($"Registered to channel with registrationId {registrationId}"); } catch (Exception ex) { Console.WriteLine(ex); } } } public static async Task UnRegister(string[] tags) { if (gmsAvailabilable) { var registrationId = await UnRegisterInternal(); try { await Task.Run(() => hub.UnregisterAll(registrationId)); Console.WriteLine($"UnRegistered to channel with registrationId {registrationId}"); } catch (Exception ex) { Console.WriteLine(ex); } } } public static void SetRegisterRegistrationId(string rRegistrationId) { registrationTaskCompletionSource?.TrySetResult(rRegistrationId); Console.WriteLine($"Current rRegistrationId {rRegistrationId}"); } public static void SetUnRegisterRegistrationId(string unrRegistrationId) { unRegistrationTaskCompletionSource?.TrySetResult(unrRegistrationId); Console.WriteLine($"Current unrRegistrationId {unrRegistrationId}"); } public static void ShowInAppToast(Context context, string msg) { Console.WriteLine($"Toast received: {msg}"); var toastMsg = msg; if (!string.IsNullOrEmpty(toastMsg)) { Toast.MakeText(context, toastMsg, ToastLength.Long).Show(); var vibrator = (Vibrator)context.GetSystemService(Context.VibratorService); vibrator.Vibrate(VibrateTimeInMillis); } } public static void ShowLocalPush(Context context, string msg) { Console.WriteLine($"Toast received: {msg}"); var pushMsg = msg; if (!string.IsNullOrEmpty(pushMsg)) { var pendingIntent = GeneratePendingIntent(context, msg); var currentMillis = Java.Lang.JavaSystem.CurrentTimeMillis(); var builder = new NotificationCompat.Builder(context) .SetContentIntent(pendingIntent) .SetContentTitle(PushTitle) .SetContentText(pushMsg) .SetAutoCancel(true) .SetStyle(new NotificationCompat.BigTextStyle().BigText(pushMsg)) .SetDefaults((int)(NotificationDefaults.Sound | NotificationDefaults.Vibrate)) .SetWhen(currentMillis) .SetSmallIcon(GetNotificationIcon()); builder = SetNotificationColor(context, builder); var notification = builder.Build(); var notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService); notificationManager.Notify((int)currentMillis, notification); } } private static PendingIntent GeneratePendingIntent(Context context, string msg) { var notificationIntent = new Intent(context, typeof(MainActivity)); notificationIntent.SetFlags(ActivityFlags.SingleTop); var pendingIntent = PendingIntent.GetActivity(context, 0, notificationIntent, PendingIntentFlags.UpdateCurrent); return pendingIntent; } private static Task<string> RegisterInternal() { registrationTaskCompletionSource = new TaskCompletionSource<string>(); try { GcmClient.Register(initContext, GcmBroadcastReceiver.SENDER_IDS); } catch (Exception ex) { Console.WriteLine(ex); registrationTaskCompletionSource.TrySetResult(string.Empty); } return registrationTaskCompletionSource.Task; } private static Task<string> UnRegisterInternal() { unRegistrationTaskCompletionSource = new TaskCompletionSource<string>(); try { GcmClient.UnRegister(initContext); } catch (Exception ex) { Console.WriteLine(ex); unRegistrationTaskCompletionSource.TrySetResult(string.Empty); } return unRegistrationTaskCompletionSource.Task; } private static bool CheckAvailability() { try { GcmClient.CheckDevice(initContext); GcmClient.CheckManifest(initContext); return true; } catch (Exception ex) { Console.WriteLine(ex); return false; } } private static NotificationCompat.Builder SetNotificationColor(Context context, NotificationCompat.Builder builder) { if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.Lollipop) { var blueDocks = ContextCompat.GetColor(context, Resource.Color.blue); builder = builder.SetColor(blueDocks); } return builder; } private static int GetNotificationIcon() { var useWhiteIcon = global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.Lollipop; return useWhiteIcon ? Resource.Drawable.Icon : Resource.Drawable.Icon; } } }
// 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 Microsoft.Build.Framework; using Microsoft.Build.Utilities; using NuGet.Frameworks; using NuGet.Packaging; using NuGet.Packaging.Core; using NuGet.Versioning; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Microsoft.DotNet.Build.Tasks.Packaging { public class CreateTrimDependencyGroups : PackagingTask { private const string PlaceHolderDependency = "_._"; [Required] public ITaskItem[] Dependencies { get; set; } [Required] public ITaskItem[] Files { get; set; } /// <summary> /// Package index files used to define stable package list. /// </summary> [Required] public ITaskItem[] PackageIndexes { get; set; } [Output] public ITaskItem[] TrimmedDependencies { get; set; } /* Given a set of available frameworks ("InboxOnTargetFrameworks"), and a list of desired frameworks, reduce the set of frameworks to the minimum set of frameworks which is compatible (preferring inbox frameworks. */ public override bool Execute() { if (null == Dependencies) { Log.LogError("Dependencies argument must be specified"); return false; } if (PackageIndexes == null && PackageIndexes.Length == 0) { Log.LogError("PackageIndexes argument must be specified"); return false; } var index = PackageIndex.Load(PackageIndexes.Select(pi => pi.GetMetadata("FullPath"))); // Retrieve the list of dependency group TFM's var dependencyGroups = Dependencies .Select(dependencyItem => new TaskItemPackageDependency(dependencyItem)) .GroupBy(dependency => dependency.TargetFramework) .Select(dependencyGrouping => new TaskItemPackageDependencyGroup(dependencyGrouping.Key, dependencyGrouping)) .ToArray(); // Prepare a resolver for evaluating if candidate frameworks are actually supported by the package PackageItem[] packageItems = Files.Select(f => new PackageItem(f)).ToArray(); var packagePaths = packageItems.Select(pi => pi.TargetPath); NuGetAssetResolver resolver = new NuGetAssetResolver(null, packagePaths); // Determine all inbox frameworks which are supported by this package var supportedInboxFrameworks = index.GetAlllInboxFrameworks().Where(fx => IsSupported(fx, resolver)); var newDependencyGroups = new Queue<TaskItemPackageDependencyGroup>(); // For each inbox framework determine its best compatible dependency group foreach(var supportedInboxFramework in supportedInboxFrameworks) { var nearestDependencyGroup = dependencyGroups.GetNearest(supportedInboxFramework); // We found a compatible dependency group that is not the same as this framework if (nearestDependencyGroup != null && nearestDependencyGroup.TargetFramework != supportedInboxFramework) { // remove all dependencies which are inbox on supportedInboxFramework var filteredDependencies = nearestDependencyGroup.Packages.Where(d => !index.IsInbox(d.Id, supportedInboxFramework, d.AssemblyVersion)).ToArray(); // only create the new group if we removed some inbox dependencies if (filteredDependencies.Length != nearestDependencyGroup.Packages.Count) { // copy remaining dependencies newDependencyGroups.Enqueue(new TaskItemPackageDependencyGroup(supportedInboxFramework, filteredDependencies)); } } } // Remove any redundant groups from the added set (EG: net45 and net46 with the same set of dependencies) int groupsToCheck = newDependencyGroups.Count; for(int i = 0; i < groupsToCheck; i++) { // to determine if this is a redundant group, we dequeue so that it won't be considered in the following check for nearest group. var group = newDependencyGroups.Dequeue(); // of the remaining groups, find the most compatible one var nearestGroup = newDependencyGroups.Concat(dependencyGroups).GetNearest(group.TargetFramework); // either we found no compatible group, // or the closest compatible group has different dependencies, // or the closest compatible group is portable and this is not (Portable profiles have different framework precedence, https://github.com/NuGet/Home/issues/6483), // keep it in the set of additions if (nearestGroup == null || !group.Packages.SetEquals(nearestGroup.Packages) || FrameworkUtilities.IsPortableMoniker(group.TargetFramework) != FrameworkUtilities.IsPortableMoniker(nearestGroup.TargetFramework)) { // not redundant, keep it in the queue newDependencyGroups.Enqueue(group); } } // Build the items representing added dependency groups. List<ITaskItem> trimmedDependencies = new List<ITaskItem>(); foreach (var newDependencyGroup in newDependencyGroups) { if (newDependencyGroup.Packages.Count == 0) { // no dependencies (all inbox), use a placeholder dependency. var item = new TaskItem(PlaceHolderDependency); item.SetMetadata("TargetFramework", newDependencyGroup.TargetFramework.GetShortFolderName()); trimmedDependencies.Add(item); } else { foreach(var dependency in newDependencyGroup.Packages) { var item = new TaskItem(dependency.Item); // emit CopiedFromTargetFramework to aide in debugging. item.SetMetadata("CopiedFromTargetFramework", item.GetMetadata("TargetFramework")); item.SetMetadata("TargetFramework", newDependencyGroup.TargetFramework.GetShortFolderName()); trimmedDependencies.Add(item); } } } TrimmedDependencies = trimmedDependencies.ToArray(); return !Log.HasLoggedErrors; } private bool IsSupported(NuGetFramework inboxFx, NuGetAssetResolver resolver) { var compileAssets = resolver.ResolveCompileAssets(inboxFx); // We assume that packages will only support inbox frameworks with lib/tfm assets and not runtime specific assets. // This effectively means we'll never reduce dependencies if a package happens to support an inbox framework with // a RID asset, but that is OK because RID assets can only be used by nuget3 + project.json // and we don't care about reducing dependencies for project.json because indirect dependencies are hidden. var runtimeAssets = resolver.ResolveRuntimeAssets(inboxFx, null); foreach (var compileAsset in compileAssets.Where(c => !NuGetAssetResolver.IsPlaceholder(c))) { string fileName = Path.GetFileName(compileAsset); if (!runtimeAssets.Any(r => Path.GetFileName(r).Equals(fileName, StringComparison.OrdinalIgnoreCase))) { // ref with no matching lib return false; } } // Either all compile assets had matching runtime assets, or all were placeholders, make sure we have at // least one runtime asset to cover the placeholder case return runtimeAssets.Any(); } /// <summary> /// Similar to NuGet.Packaging.Core.PackageDependency but also allows for flowing the original ITaskItem. /// </summary> class TaskItemPackageDependency : PackageDependency { public TaskItemPackageDependency(ITaskItem item) : base(item.ItemSpec, TryParseVersionRange(item.GetMetadata("Version"))) { Item = item; TargetFramework = NuGetFramework.Parse(item.GetMetadata(nameof(TargetFramework))); AssemblyVersion = GetAssemblyVersion(item); } private static VersionRange TryParseVersionRange(string versionString) { VersionRange value; return VersionRange.TryParse(versionString, out value) ? value : null; } private static Version GetAssemblyVersion(ITaskItem dependency) { // If we don't have the AssemblyVersion metadata (4 part version string), fall back and use Version (3 part version string) string versionString = dependency.GetMetadata("AssemblyVersion"); if (string.IsNullOrEmpty(versionString)) { versionString = dependency.GetMetadata("Version"); int prereleaseIndex = versionString.IndexOf('-'); if (prereleaseIndex != -1) { versionString = versionString.Substring(0, prereleaseIndex); } } Version assemblyVersion = FrameworkUtilities.Ensure4PartVersion( String.IsNullOrEmpty(versionString) ? new Version(0, 0, 0, 0) : new Version(versionString)); return assemblyVersion; } public ITaskItem Item { get; } public NuGetFramework TargetFramework { get; } public Version AssemblyVersion { get; } } /// <summary> /// An IFrameworkSpecific type that can be used with FrameworkUtilties.GetNearest. /// This differs from NuGet.Packaging.PackageDependencyGroup in that it exposes the package dependencies as an ISet which can /// undergo an unordered comparison with another ISet. /// </summary> class TaskItemPackageDependencyGroup : IFrameworkSpecific { public TaskItemPackageDependencyGroup(NuGetFramework targetFramework, IEnumerable<TaskItemPackageDependency> packages) { TargetFramework = targetFramework; Packages = new HashSet<TaskItemPackageDependency>(packages.Where(d => d.Id != PlaceHolderDependency)); } public NuGetFramework TargetFramework { get; } public ISet<TaskItemPackageDependency> Packages { get; } } } }
using System; using System.Data; using Csla; using Csla.Data; using Invoices.DataAccess; namespace Invoices.Business { /// <summary> /// InvoiceView (read only object).<br/> /// This is a generated base class of <see cref="InvoiceView"/> business object. /// This class is a root object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="InvoiceLines"/> of type <see cref="InvoiceLineList"/> (1:M relation to <see cref="InvoiceLineInfo"/>) /// </remarks> [Serializable] public partial class InvoiceView : ReadOnlyBase<InvoiceView> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="InvoiceId"/> property. /// </summary> public static readonly PropertyInfo<Guid> InvoiceIdProperty = RegisterProperty<Guid>(p => p.InvoiceId, "Invoice Id", Guid.NewGuid()); /// <summary> /// The invoice internal identification /// </summary> /// <value>The Invoice Id.</value> public Guid InvoiceId { get { return GetProperty(InvoiceIdProperty); } } /// <summary> /// Maintains metadata about <see cref="InvoiceNumber"/> property. /// </summary> public static readonly PropertyInfo<string> InvoiceNumberProperty = RegisterProperty<string>(p => p.InvoiceNumber, "Invoice Number"); /// <summary> /// The public invoice number /// </summary> /// <value>The Invoice Number.</value> public string InvoiceNumber { get { return GetProperty(InvoiceNumberProperty); } } /// <summary> /// Maintains metadata about <see cref="CustomerId"/> property. /// </summary> public static readonly PropertyInfo<string> CustomerIdProperty = RegisterProperty<string>(p => p.CustomerId, "Customer Id"); /// <summary> /// Gets the Customer Id. /// </summary> /// <value>The Customer Id.</value> public string CustomerId { get { return GetProperty(CustomerIdProperty); } } /// <summary> /// Maintains metadata about <see cref="InvoiceDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> InvoiceDateProperty = RegisterProperty<SmartDate>(p => p.InvoiceDate, "Invoice Date"); /// <summary> /// Gets the Invoice Date. /// </summary> /// <value>The Invoice Date.</value> public string InvoiceDate { get { return GetPropertyConvert<SmartDate, string>(InvoiceDateProperty); } } /// <summary> /// Maintains metadata about <see cref="TotalAmount"/> property. /// </summary> public static readonly PropertyInfo<decimal> TotalAmountProperty = RegisterProperty<decimal>(p => p.TotalAmount, "Total Amount"); /// <summary> /// Computed invoice total amount /// </summary> /// <value>The Total Amount.</value> public decimal TotalAmount { get { return GetProperty(TotalAmountProperty); } } /// <summary> /// Maintains metadata about <see cref="IsActive"/> property. /// </summary> public static readonly PropertyInfo<bool> IsActiveProperty = RegisterProperty<bool>(p => p.IsActive, "Is Active"); /// <summary> /// Gets the Is Active. /// </summary> /// <value><c>true</c> if Is Active; otherwise, <c>false</c>.</value> public bool IsActive { get { return GetProperty(IsActiveProperty); } } /// <summary> /// Maintains metadata about <see cref="CreateDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate, "Create Date", new SmartDate(DateTime.Now)); /// <summary> /// Gets the Create Date. /// </summary> /// <value>The Create Date.</value> public SmartDate CreateDate { get { return GetProperty(CreateDateProperty); } } /// <summary> /// Maintains metadata about <see cref="CreateUser"/> property. /// </summary> public static readonly PropertyInfo<int> CreateUserProperty = RegisterProperty<int>(p => p.CreateUser, "Create User", Security.UserInformation.UserId); /// <summary> /// Gets the Create User. /// </summary> /// <value>The Create User.</value> public int CreateUser { get { return GetProperty(CreateUserProperty); } } /// <summary> /// Maintains metadata about <see cref="ChangeDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate, "Change Date"); /// <summary> /// Gets the Change Date. /// </summary> /// <value>The Change Date.</value> public SmartDate ChangeDate { get { return GetProperty(ChangeDateProperty); } } /// <summary> /// Maintains metadata about <see cref="ChangeUser"/> property. /// </summary> public static readonly PropertyInfo<int> ChangeUserProperty = RegisterProperty<int>(p => p.ChangeUser, "Change User"); /// <summary> /// Gets the Change User. /// </summary> /// <value>The Change User.</value> public int ChangeUser { get { return GetProperty(ChangeUserProperty); } } /// <summary> /// Maintains metadata about <see cref="RowVersion"/> property. /// </summary> public static readonly PropertyInfo<byte[]> RowVersionProperty = RegisterProperty<byte[]>(p => p.RowVersion, "Row Version"); /// <summary> /// Gets the Row Version. /// </summary> /// <value>The Row Version.</value> public byte[] RowVersion { get { return GetProperty(RowVersionProperty); } } /// <summary> /// Maintains metadata about child <see cref="InvoiceLines"/> property. /// </summary> public static readonly PropertyInfo<InvoiceLineList> InvoiceLinesProperty = RegisterProperty<InvoiceLineList>(p => p.InvoiceLines, "Invoice Lines"); /// <summary> /// Gets the Invoice Lines ("parent load" child property). /// </summary> /// <value>The Invoice Lines.</value> public InvoiceLineList InvoiceLines { get { return GetProperty(InvoiceLinesProperty); } private set { LoadProperty(InvoiceLinesProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="InvoiceView"/> object, based on given parameters. /// </summary> /// <param name="invoiceId">The InvoiceId parameter of the InvoiceView to fetch.</param> /// <returns>A reference to the fetched <see cref="InvoiceView"/> object.</returns> public static InvoiceView GetInvoiceView(Guid invoiceId) { return DataPortal.Fetch<InvoiceView>(invoiceId); } /// <summary> /// Factory method. Asynchronously loads a <see cref="InvoiceView"/> object, based on given parameters. /// </summary> /// <param name="invoiceId">The InvoiceId parameter of the InvoiceView to fetch.</param> /// <param name="callback">The completion callback method.</param> public static void GetInvoiceView(Guid invoiceId, EventHandler<DataPortalResult<InvoiceView>> callback) { DataPortal.BeginFetch<InvoiceView>(invoiceId, callback); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="InvoiceView"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public InvoiceView() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads a <see cref="InvoiceView"/> object from the database, based on given criteria. /// </summary> /// <param name="invoiceId">The Invoice Id.</param> protected void DataPortal_Fetch(Guid invoiceId) { var args = new DataPortalHookArgs(invoiceId); OnFetchPre(args); using (var dalManager = DalFactoryInvoices.GetManager()) { var dal = dalManager.GetProvider<IInvoiceViewDal>(); var data = dal.Fetch(invoiceId); Fetch(data); } OnFetchPost(args); } private void Fetch(IDataReader data) { using (var dr = new SafeDataReader(data)) { if (dr.Read()) { Fetch(dr); FetchChildren(dr); } } } /// <summary> /// Loads a <see cref="InvoiceView"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(InvoiceIdProperty, dr.GetGuid("InvoiceId")); LoadProperty(InvoiceNumberProperty, dr.GetString("InvoiceNumber")); LoadProperty(CustomerIdProperty, dr.GetString("CustomerId")); LoadProperty(InvoiceDateProperty, dr.GetSmartDate("InvoiceDate", true)); LoadProperty(IsActiveProperty, dr.GetBoolean("IsActive")); LoadProperty(CreateDateProperty, dr.GetSmartDate("CreateDate", true)); LoadProperty(CreateUserProperty, dr.GetInt32("CreateUser")); LoadProperty(ChangeDateProperty, dr.GetSmartDate("ChangeDate", true)); LoadProperty(ChangeUserProperty, dr.GetInt32("ChangeUser")); LoadProperty(RowVersionProperty, dr.GetValue("RowVersion") as byte[]); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void FetchChildren(SafeDataReader dr) { dr.NextResult(); LoadProperty(InvoiceLinesProperty, DataPortal.FetchChild<InvoiceLineList>(dr)); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); #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. //////////////////////////////////////////////////////////////////////////// // // // // Purpose: This class implements a set of methods for comparing // strings. // // //////////////////////////////////////////////////////////////////////////// using System.Reflection; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.Serialization; namespace System.Globalization { [Flags] public enum CompareOptions { None = 0x00000000, IgnoreCase = 0x00000001, IgnoreNonSpace = 0x00000002, IgnoreSymbols = 0x00000004, IgnoreKanaType = 0x00000008, // ignore kanatype IgnoreWidth = 0x00000010, // ignore width OrdinalIgnoreCase = 0x10000000, // This flag can not be used with other flags. StringSort = 0x20000000, // use string sort method Ordinal = 0x40000000, // This flag can not be used with other flags. } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public partial class CompareInfo : IDeserializationCallback { // Mask used to check if IndexOf()/LastIndexOf()/IsPrefix()/IsPostfix() has the right flags. private const CompareOptions ValidIndexMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType); // Mask used to check if Compare() has the right flags. private const CompareOptions ValidCompareMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort); // Mask used to check if GetHashCodeOfString() has the right flags. private const CompareOptions ValidHashCodeOfStringMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType); // Mask used to check if we have the right flags. private const CompareOptions ValidSortkeyCtorMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort); // Cache the invariant CompareInfo internal static readonly CompareInfo Invariant = CultureInfo.InvariantCulture.CompareInfo; // // CompareInfos have an interesting identity. They are attached to the locale that created them, // ie: en-US would have an en-US sort. For haw-US (custom), then we serialize it as haw-US. // The interesting part is that since haw-US doesn't have its own sort, it has to point at another // locale, which is what SCOMPAREINFO does. [OptionalField(VersionAdded = 2)] private string m_name; // The name used to construct this CompareInfo. Do not rename (binary serialization) [NonSerialized] private string _sortName; // The name that defines our behavior [OptionalField(VersionAdded = 3)] private SortVersion m_SortVersion; // Do not rename (binary serialization) // _invariantMode is defined for the perf reason as accessing the instance field is faster than access the static property GlobalizationMode.Invariant [NonSerialized] private readonly bool _invariantMode = GlobalizationMode.Invariant; private int culture; // Do not rename (binary serialization). The fields sole purpose is to support Desktop serialization. internal CompareInfo(CultureInfo culture) { m_name = culture._name; InitSort(culture); } /*=================================GetCompareInfo========================== **Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture. ** Warning: The assembly versioning mechanism is dead! **Returns: The CompareInfo for the specified culture. **Arguments: ** culture the ID of the culture ** assembly the assembly which contains the sorting table. **Exceptions: ** ArugmentNullException when the assembly is null ** ArgumentException if culture is invalid. ============================================================================*/ // Assembly constructor should be deprecated, we don't act on the assembly information any more public static CompareInfo GetCompareInfo(int culture, Assembly assembly) { // Parameter checking. if (assembly == null) { throw new ArgumentNullException(nameof(assembly)); } if (assembly != typeof(Object).Module.Assembly) { throw new ArgumentException(SR.Argument_OnlyMscorlib); } return GetCompareInfo(culture); } /*=================================GetCompareInfo========================== **Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture. ** The purpose of this method is to provide version for CompareInfo tables. **Returns: The CompareInfo for the specified culture. **Arguments: ** name the name of the culture ** assembly the assembly which contains the sorting table. **Exceptions: ** ArugmentNullException when the assembly is null ** ArgumentException if name is invalid. ============================================================================*/ // Assembly constructor should be deprecated, we don't act on the assembly information any more public static CompareInfo GetCompareInfo(string name, Assembly assembly) { if (name == null || assembly == null) { throw new ArgumentNullException(name == null ? nameof(name) : nameof(assembly)); } if (assembly != typeof(Object).Module.Assembly) { throw new ArgumentException(SR.Argument_OnlyMscorlib); } return GetCompareInfo(name); } /*=================================GetCompareInfo========================== **Action: Get the CompareInfo for the specified culture. ** This method is provided for ease of integration with NLS-based software. **Returns: The CompareInfo for the specified culture. **Arguments: ** culture the ID of the culture. **Exceptions: ** ArgumentException if culture is invalid. ============================================================================*/ // People really shouldn't be calling LCID versions, no custom support public static CompareInfo GetCompareInfo(int culture) { if (CultureData.IsCustomCultureId(culture)) { // Customized culture cannot be created by the LCID. throw new ArgumentException(SR.Argument_CustomCultureCannotBePassedByNumber, nameof(culture)); } return CultureInfo.GetCultureInfo(culture).CompareInfo; } /*=================================GetCompareInfo========================== **Action: Get the CompareInfo for the specified culture. **Returns: The CompareInfo for the specified culture. **Arguments: ** name the name of the culture. **Exceptions: ** ArgumentException if name is invalid. ============================================================================*/ public static CompareInfo GetCompareInfo(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } return CultureInfo.GetCultureInfo(name).CompareInfo; } public static unsafe bool IsSortable(char ch) { if (GlobalizationMode.Invariant) { return true; } char *pChar = &ch; return IsSortable(pChar, 1); } public static unsafe bool IsSortable(string text) { if (text == null) { // A null param is invalid here. throw new ArgumentNullException(nameof(text)); } if (text.Length == 0) { // A zero length string is not invalid, but it is also not sortable. return (false); } if (GlobalizationMode.Invariant) { return true; } fixed (char *pChar = text) { return IsSortable(pChar, text.Length); } } [OnDeserializing] private void OnDeserializing(StreamingContext ctx) { m_name = null; } void IDeserializationCallback.OnDeserialization(object sender) { OnDeserialized(); } [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { OnDeserialized(); } private void OnDeserialized() { // If we didn't have a name, use the LCID if (m_name == null) { // From whidbey, didn't have a name CultureInfo ci = CultureInfo.GetCultureInfo(this.culture); m_name = ci._name; } else { InitSort(CultureInfo.GetCultureInfo(m_name)); } } [OnSerializing] private void OnSerializing(StreamingContext ctx) { // This is merely for serialization compatibility with Whidbey/Orcas, it can go away when we don't want that compat any more. culture = CultureInfo.GetCultureInfo(this.Name).LCID; // This is the lcid of the constructing culture (still have to dereference to get target sort) Debug.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already"); } ///////////////////////////----- Name -----///////////////////////////////// // // Returns the name of the culture (well actually, of the sort). // Very important for providing a non-LCID way of identifying // what the sort is. // // Note that this name isn't dereferenced in case the CompareInfo is a different locale // which is consistent with the behaviors of earlier versions. (so if you ask for a sort // and the locale's changed behavior, then you'll get changed behavior, which is like // what happens for a version update) // //////////////////////////////////////////////////////////////////////// public virtual string Name { get { Debug.Assert(m_name != null, "CompareInfo.Name Expected _name to be set"); if (m_name == "zh-CHT" || m_name == "zh-CHS") { return m_name; } return _sortName; } } //////////////////////////////////////////////////////////////////////// // // Compare // // Compares the two strings with the given options. Returns 0 if the // two strings are equal, a number less than 0 if string1 is less // than string2, and a number greater than 0 if string1 is greater // than string2. // //////////////////////////////////////////////////////////////////////// public virtual int Compare(string string1, string string2) { return (Compare(string1, string2, CompareOptions.None)); } public unsafe virtual int Compare(string string1, string string2, CompareOptions options) { if (options == CompareOptions.OrdinalIgnoreCase) { return String.Compare(string1, string2, StringComparison.OrdinalIgnoreCase); } // Verify the options before we do any real comparison. if ((options & CompareOptions.Ordinal) != 0) { if (options != CompareOptions.Ordinal) { throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options)); } return String.CompareOrdinal(string1, string2); } if ((options & ValidCompareMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } //Our paradigm is that null sorts less than any other string and //that two nulls sort as equal. if (string1 == null) { if (string2 == null) { return (0); // Equal } return (-1); // null < non-null } if (string2 == null) { return (1); // non-null > null } if (_invariantMode) { if ((options & CompareOptions.IgnoreCase) != 0) return CompareOrdinalIgnoreCase(string1, 0, string1.Length, string2, 0, string2.Length); return String.CompareOrdinal(string1, string2); } return CompareString(string1.AsReadOnlySpan(), string2.AsReadOnlySpan(), options); } // TODO https://github.com/dotnet/coreclr/issues/13827: // This method shouldn't be necessary, as we should be able to just use the overload // that takes two spans. But due to this issue, that's adding significant overhead. internal unsafe int Compare(ReadOnlySpan<char> string1, string string2, CompareOptions options) { if (options == CompareOptions.OrdinalIgnoreCase) { return CompareOrdinalIgnoreCase(string1, string2.AsReadOnlySpan()); } // Verify the options before we do any real comparison. if ((options & CompareOptions.Ordinal) != 0) { if (options != CompareOptions.Ordinal) { throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options)); } return string.CompareOrdinal(string1, string2.AsReadOnlySpan()); } if ((options & ValidCompareMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } // null sorts less than any other string. if (string2 == null) { return 1; } if (_invariantMode) { return (options & CompareOptions.IgnoreCase) != 0 ? CompareOrdinalIgnoreCase(string1, string2.AsReadOnlySpan()) : string.CompareOrdinal(string1, string2.AsReadOnlySpan()); } return CompareString(string1, string2, options); } // TODO https://github.com/dotnet/corefx/issues/21395: Expose this publicly? internal unsafe virtual int Compare(ReadOnlySpan<char> string1, ReadOnlySpan<char> string2, CompareOptions options) { if (options == CompareOptions.OrdinalIgnoreCase) { return CompareOrdinalIgnoreCase(string1, string2); } // Verify the options before we do any real comparison. if ((options & CompareOptions.Ordinal) != 0) { if (options != CompareOptions.Ordinal) { throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options)); } return string.CompareOrdinal(string1, string2); } if ((options & ValidCompareMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } if (_invariantMode) { return (options & CompareOptions.IgnoreCase) != 0 ? CompareOrdinalIgnoreCase(string1, string2) : string.CompareOrdinal(string1, string2); } return CompareString(string1, string2, options); } //////////////////////////////////////////////////////////////////////// // // Compare // // Compares the specified regions of the two strings with the given // options. // Returns 0 if the two strings are equal, a number less than 0 if // string1 is less than string2, and a number greater than 0 if // string1 is greater than string2. // //////////////////////////////////////////////////////////////////////// public unsafe virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2) { return Compare(string1, offset1, length1, string2, offset2, length2, 0); } public virtual int Compare(string string1, int offset1, string string2, int offset2, CompareOptions options) { return Compare(string1, offset1, string1 == null ? 0 : string1.Length - offset1, string2, offset2, string2 == null ? 0 : string2.Length - offset2, options); } public virtual int Compare(string string1, int offset1, string string2, int offset2) { return Compare(string1, offset1, string2, offset2, 0); } public virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options) { if (options == CompareOptions.OrdinalIgnoreCase) { int result = String.Compare(string1, offset1, string2, offset2, length1 < length2 ? length1 : length2, StringComparison.OrdinalIgnoreCase); if ((length1 != length2) && result == 0) return (length1 > length2 ? 1 : -1); return (result); } // Verify inputs if (length1 < 0 || length2 < 0) { throw new ArgumentOutOfRangeException((length1 < 0) ? nameof(length1) : nameof(length2), SR.ArgumentOutOfRange_NeedPosNum); } if (offset1 < 0 || offset2 < 0) { throw new ArgumentOutOfRangeException((offset1 < 0) ? nameof(offset1) : nameof(offset2), SR.ArgumentOutOfRange_NeedPosNum); } if (offset1 > (string1 == null ? 0 : string1.Length) - length1) { throw new ArgumentOutOfRangeException(nameof(string1), SR.ArgumentOutOfRange_OffsetLength); } if (offset2 > (string2 == null ? 0 : string2.Length) - length2) { throw new ArgumentOutOfRangeException(nameof(string2), SR.ArgumentOutOfRange_OffsetLength); } if ((options & CompareOptions.Ordinal) != 0) { if (options != CompareOptions.Ordinal) { throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options)); } } else if ((options & ValidCompareMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } // // Check for the null case. // if (string1 == null) { if (string2 == null) { return (0); } return (-1); } if (string2 == null) { return (1); } if (options == CompareOptions.Ordinal) { return CompareOrdinal(string1, offset1, length1, string2, offset2, length2); } if (_invariantMode) { if ((options & CompareOptions.IgnoreCase) != 0) return CompareOrdinalIgnoreCase(string1, offset1, length1, string2, offset2, length2); return CompareOrdinal(string1, offset1, length1, string2, offset2, length2); } return CompareString( string1.AsReadOnlySpan().Slice(offset1, length1), string2.AsReadOnlySpan().Slice(offset2, length2), options); } private static int CompareOrdinal(string string1, int offset1, int length1, string string2, int offset2, int length2) { int result = String.CompareOrdinal(string1, offset1, string2, offset2, (length1 < length2 ? length1 : length2)); if ((length1 != length2) && result == 0) { return (length1 > length2 ? 1 : -1); } return (result); } // // CompareOrdinalIgnoreCase compare two string ordinally with ignoring the case. // it assumes the strings are Ascii string till we hit non Ascii character in strA or strB and then we continue the comparison by // calling the OS. // internal static unsafe int CompareOrdinalIgnoreCase(string strA, int indexA, int lengthA, string strB, int indexB, int lengthB) { Debug.Assert(indexA + lengthA <= strA.Length); Debug.Assert(indexB + lengthB <= strB.Length); return CompareOrdinalIgnoreCase(strA.AsReadOnlySpan().Slice(indexA, lengthA), strB.AsReadOnlySpan().Slice(indexB, lengthB)); } internal static unsafe int CompareOrdinalIgnoreCase(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB) { int length = Math.Min(strA.Length, strB.Length); int range = length; fixed (char* ap = &MemoryMarshal.GetReference(strA)) fixed (char* bp = &MemoryMarshal.GetReference(strB)) { char* a = ap; char* b = bp; // in InvariantMode we support all range and not only the ascii characters. char maxChar = (char) (GlobalizationMode.Invariant ? 0xFFFF : 0x80); while (length != 0 && (*a <= maxChar) && (*b <= maxChar)) { int charA = *a; int charB = *b; if (charA == charB) { a++; b++; length--; continue; } // uppercase both chars - notice that we need just one compare per char if ((uint)(charA - 'a') <= 'z' - 'a') charA -= 0x20; if ((uint)(charB - 'a') <= 'z' - 'a') charB -= 0x20; // Return the (case-insensitive) difference between them. if (charA != charB) return charA - charB; // Next char a++; b++; length--; } if (length == 0) return strA.Length - strB.Length; Debug.Assert(!GlobalizationMode.Invariant); range -= length; return CompareStringOrdinalIgnoreCase(a, strA.Length - range, b, strB.Length - range); } } //////////////////////////////////////////////////////////////////////// // // IsPrefix // // Determines whether prefix is a prefix of string. If prefix equals // String.Empty, true is returned. // //////////////////////////////////////////////////////////////////////// public virtual bool IsPrefix(string source, string prefix, CompareOptions options) { if (source == null || prefix == null) { throw new ArgumentNullException((source == null ? nameof(source) : nameof(prefix)), SR.ArgumentNull_String); } if (prefix.Length == 0) { return (true); } if (source.Length == 0) { return false; } if (options == CompareOptions.OrdinalIgnoreCase) { return source.StartsWith(prefix, StringComparison.OrdinalIgnoreCase); } if (options == CompareOptions.Ordinal) { return source.StartsWith(prefix, StringComparison.Ordinal); } if ((options & ValidIndexMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } if (_invariantMode) { return source.StartsWith(prefix, (options & CompareOptions.IgnoreCase) != 0 ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } return StartsWith(source, prefix, options); } internal bool IsPrefix(ReadOnlySpan<char> source, ReadOnlySpan<char> prefix, CompareOptions options) { Debug.Assert(prefix.Length != 0); Debug.Assert(source.Length != 0); Debug.Assert((options & ValidIndexMaskOffFlags) == 0); Debug.Assert(!_invariantMode); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return StartsWith(source, prefix, options); } public virtual bool IsPrefix(string source, string prefix) { return (IsPrefix(source, prefix, 0)); } //////////////////////////////////////////////////////////////////////// // // IsSuffix // // Determines whether suffix is a suffix of string. If suffix equals // String.Empty, true is returned. // //////////////////////////////////////////////////////////////////////// public virtual bool IsSuffix(string source, string suffix, CompareOptions options) { if (source == null || suffix == null) { throw new ArgumentNullException((source == null ? nameof(source) : nameof(suffix)), SR.ArgumentNull_String); } if (suffix.Length == 0) { return (true); } if (source.Length == 0) { return false; } if (options == CompareOptions.OrdinalIgnoreCase) { return source.EndsWith(suffix, StringComparison.OrdinalIgnoreCase); } if (options == CompareOptions.Ordinal) { return source.EndsWith(suffix, StringComparison.Ordinal); } if ((options & ValidIndexMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } if (_invariantMode) { return source.EndsWith(suffix, (options & CompareOptions.IgnoreCase) != 0 ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } return EndsWith(source, suffix, options); } internal bool IsSuffix(ReadOnlySpan<char> source, ReadOnlySpan<char> suffix, CompareOptions options) { Debug.Assert(suffix.Length != 0); Debug.Assert(source.Length != 0); Debug.Assert((options & ValidIndexMaskOffFlags) == 0); Debug.Assert(!_invariantMode); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return EndsWith(source, suffix, options); } public virtual bool IsSuffix(string source, string suffix) { return (IsSuffix(source, suffix, 0)); } //////////////////////////////////////////////////////////////////////// // // IndexOf // // Returns the first index where value is found in string. The // search starts from startIndex and ends at endIndex. Returns -1 if // the specified value is not found. If value equals String.Empty, // startIndex is returned. Throws IndexOutOfRange if startIndex or // endIndex is less than zero or greater than the length of string. // Throws ArgumentException if value is null. // //////////////////////////////////////////////////////////////////////// public virtual int IndexOf(string source, char value) { if (source == null) throw new ArgumentNullException(nameof(source)); return IndexOf(source, value, 0, source.Length, CompareOptions.None); } public virtual int IndexOf(string source, string value) { if (source == null) throw new ArgumentNullException(nameof(source)); return IndexOf(source, value, 0, source.Length, CompareOptions.None); } public virtual int IndexOf(string source, char value, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); return IndexOf(source, value, 0, source.Length, options); } public virtual int IndexOf(string source, string value, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); return IndexOf(source, value, 0, source.Length, options); } public virtual int IndexOf(string source, char value, int startIndex) { if (source == null) throw new ArgumentNullException(nameof(source)); return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None); } public virtual int IndexOf(string source, string value, int startIndex) { if (source == null) throw new ArgumentNullException(nameof(source)); return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None); } public virtual int IndexOf(string source, char value, int startIndex, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); return IndexOf(source, value, startIndex, source.Length - startIndex, options); } public virtual int IndexOf(string source, string value, int startIndex, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); return IndexOf(source, value, startIndex, source.Length - startIndex, options); } public virtual int IndexOf(string source, char value, int startIndex, int count) { return IndexOf(source, value, startIndex, count, CompareOptions.None); } public virtual int IndexOf(string source, string value, int startIndex, int count) { return IndexOf(source, value, startIndex, count, CompareOptions.None); } public unsafe virtual int IndexOf(string source, char value, int startIndex, int count, CompareOptions options) { // Validate inputs if (source == null) throw new ArgumentNullException(nameof(source)); if (startIndex < 0 || startIndex > source.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (count < 0 || startIndex > source.Length - count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); if (options == CompareOptions.OrdinalIgnoreCase) { return source.IndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase); } // Validate CompareOptions // Ordinal can't be selected with other flags if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal)) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); if (_invariantMode) return IndexOfOrdinal(source, new string(value, 1), startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0); return IndexOfCore(source, new string(value, 1), startIndex, count, options, null); } public unsafe virtual int IndexOf(string source, string value, int startIndex, int count, CompareOptions options) { // Validate inputs if (source == null) throw new ArgumentNullException(nameof(source)); if (value == null) throw new ArgumentNullException(nameof(value)); if (startIndex > source.Length) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); } // In Everett we used to return -1 for empty string even if startIndex is negative number so we keeping same behavior here. // We return 0 if both source and value are empty strings for Everett compatibility too. if (source.Length == 0) { if (value.Length == 0) { return 0; } return -1; } if (startIndex < 0) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); } if (count < 0 || startIndex > source.Length - count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); if (options == CompareOptions.OrdinalIgnoreCase) { return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true); } // Validate CompareOptions // Ordinal can't be selected with other flags if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal)) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); if (_invariantMode) return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0); return IndexOfCore(source, value, startIndex, count, options, null); } // The following IndexOf overload is mainly used by String.Replace. This overload assumes the parameters are already validated // and the caller is passing a valid matchLengthPtr pointer. internal unsafe int IndexOf(string source, string value, int startIndex, int count, CompareOptions options, int* matchLengthPtr) { Debug.Assert(source != null); Debug.Assert(value != null); Debug.Assert(startIndex >= 0); Debug.Assert(matchLengthPtr != null); *matchLengthPtr = 0; if (source.Length == 0) { if (value.Length == 0) { return 0; } return -1; } if (startIndex >= source.Length) { return -1; } if (options == CompareOptions.OrdinalIgnoreCase) { int res = IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true); if (res >= 0) { *matchLengthPtr = value.Length; } return res; } if (_invariantMode) { int res = IndexOfOrdinal(source, value, startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0); if (res >= 0) { *matchLengthPtr = value.Length; } return res; } return IndexOfCore(source, value, startIndex, count, options, matchLengthPtr); } internal int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { if (_invariantMode) { return InvariantIndexOf(source, value, startIndex, count, ignoreCase); } return IndexOfOrdinalCore(source, value, startIndex, count, ignoreCase); } //////////////////////////////////////////////////////////////////////// // // LastIndexOf // // Returns the last index where value is found in string. The // search starts from startIndex and ends at endIndex. Returns -1 if // the specified value is not found. If value equals String.Empty, // endIndex is returned. Throws IndexOutOfRange if startIndex or // endIndex is less than zero or greater than the length of string. // Throws ArgumentException if value is null. // //////////////////////////////////////////////////////////////////////// public virtual int LastIndexOf(String source, char value) { if (source == null) throw new ArgumentNullException(nameof(source)); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, source.Length, CompareOptions.None); } public virtual int LastIndexOf(string source, string value) { if (source == null) throw new ArgumentNullException(nameof(source)); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, source.Length, CompareOptions.None); } public virtual int LastIndexOf(string source, char value, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, source.Length, options); } public virtual int LastIndexOf(string source, string value, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, source.Length, options); } public virtual int LastIndexOf(string source, char value, int startIndex) { return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None); } public virtual int LastIndexOf(string source, string value, int startIndex) { return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None); } public virtual int LastIndexOf(string source, char value, int startIndex, CompareOptions options) { return LastIndexOf(source, value, startIndex, startIndex + 1, options); } public virtual int LastIndexOf(string source, string value, int startIndex, CompareOptions options) { return LastIndexOf(source, value, startIndex, startIndex + 1, options); } public virtual int LastIndexOf(string source, char value, int startIndex, int count) { return LastIndexOf(source, value, startIndex, count, CompareOptions.None); } public virtual int LastIndexOf(string source, string value, int startIndex, int count) { return LastIndexOf(source, value, startIndex, count, CompareOptions.None); } public virtual int LastIndexOf(string source, char value, int startIndex, int count, CompareOptions options) { // Verify Arguments if (source == null) throw new ArgumentNullException(nameof(source)); // Validate CompareOptions // Ordinal can't be selected with other flags if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal) && (options != CompareOptions.OrdinalIgnoreCase)) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); // Special case for 0 length input strings if (source.Length == 0 && (startIndex == -1 || startIndex == 0)) return -1; // Make sure we're not out of range if (startIndex < 0 || startIndex > source.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); // Make sure that we allow startIndex == source.Length if (startIndex == source.Length) { startIndex--; if (count > 0) count--; } // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); if (options == CompareOptions.OrdinalIgnoreCase) { return source.LastIndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase); } if (_invariantMode) return InvariantLastIndexOf(source, new string(value, 1), startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0); return LastIndexOfCore(source, value.ToString(), startIndex, count, options); } public virtual int LastIndexOf(string source, string value, int startIndex, int count, CompareOptions options) { // Verify Arguments if (source == null) throw new ArgumentNullException(nameof(source)); if (value == null) throw new ArgumentNullException(nameof(value)); // Validate CompareOptions // Ordinal can't be selected with other flags if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal) && (options != CompareOptions.OrdinalIgnoreCase)) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); // Special case for 0 length input strings if (source.Length == 0 && (startIndex == -1 || startIndex == 0)) return (value.Length == 0) ? 0 : -1; // Make sure we're not out of range if (startIndex < 0 || startIndex > source.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); // Make sure that we allow startIndex == source.Length if (startIndex == source.Length) { startIndex--; if (count > 0) count--; // If we are looking for nothing, just return 0 if (value.Length == 0 && count >= 0 && startIndex - count + 1 >= 0) return startIndex; } // 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); if (options == CompareOptions.OrdinalIgnoreCase) { return LastIndexOfOrdinal(source, value, startIndex, count, ignoreCase: true); } if (_invariantMode) return InvariantLastIndexOf(source, value, startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0); return LastIndexOfCore(source, value, startIndex, count, options); } internal int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { if (_invariantMode) { return InvariantLastIndexOf(source, value, startIndex, count, ignoreCase); } return LastIndexOfOrdinalCore(source, value, startIndex, count, ignoreCase); } //////////////////////////////////////////////////////////////////////// // // GetSortKey // // Gets the SortKey for the given string with the given options. // //////////////////////////////////////////////////////////////////////// public virtual SortKey GetSortKey(string source, CompareOptions options) { if (_invariantMode) return InvariantCreateSortKey(source, options); return CreateSortKey(source, options); } public virtual SortKey GetSortKey(string source) { if (_invariantMode) return InvariantCreateSortKey(source, CompareOptions.None); return CreateSortKey(source, CompareOptions.None); } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same CompareInfo as the current // instance. // //////////////////////////////////////////////////////////////////////// public override bool Equals(Object value) { CompareInfo that = value as CompareInfo; if (that != null) { return this.Name == that.Name; } return (false); } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // CompareInfo. The hash code is guaranteed to be the same for // CompareInfo A and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return (this.Name.GetHashCode()); } //////////////////////////////////////////////////////////////////////// // // GetHashCodeOfString // // This internal method allows a method that allows the equivalent of creating a Sortkey for a // string from CompareInfo, and generate a hashcode value from it. It is not very convenient // to use this method as is and it creates an unnecessary Sortkey object that will be GC'ed. // // The hash code is guaranteed to be the same for string A and B where A.Equals(B) is true and both // the CompareInfo and the CompareOptions are the same. If two different CompareInfo objects // treat the string the same way, this implementation will treat them differently (the same way that // Sortkey does at the moment). // // This method will never be made public itself, but public consumers of it could be created, e.g.: // // string.GetHashCode(CultureInfo) // string.GetHashCode(CompareInfo) // string.GetHashCode(CultureInfo, CompareOptions) // string.GetHashCode(CompareInfo, CompareOptions) // etc. // // (the methods above that take a CultureInfo would use CultureInfo.CompareInfo) // //////////////////////////////////////////////////////////////////////// internal int GetHashCodeOfString(string source, CompareOptions options) { // // Parameter validation // if (null == source) { throw new ArgumentNullException(nameof(source)); } if ((options & ValidHashCodeOfStringMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } return GetHashCodeOfStringCore(source, options); } public virtual int GetHashCode(string source, CompareOptions options) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (options == CompareOptions.Ordinal) { return source.GetHashCode(); } if (options == CompareOptions.OrdinalIgnoreCase) { return TextInfo.GetHashCodeOrdinalIgnoreCase(source); } // // GetHashCodeOfString does more parameters validation. basically will throw when // having Ordinal, OrdinalIgnoreCase and StringSort // return GetHashCodeOfString(source, options); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns a string describing the // CompareInfo. // //////////////////////////////////////////////////////////////////////// public override string ToString() { return ("CompareInfo - " + this.Name); } public SortVersion Version { get { if (m_SortVersion == null) { if (_invariantMode) { m_SortVersion = new SortVersion(0, CultureInfo.LOCALE_INVARIANT, new Guid(0, 0, 0, 0, 0, 0, 0, (byte) (CultureInfo.LOCALE_INVARIANT >> 24), (byte) ((CultureInfo.LOCALE_INVARIANT & 0x00FF0000) >> 16), (byte) ((CultureInfo.LOCALE_INVARIANT & 0x0000FF00) >> 8), (byte) (CultureInfo.LOCALE_INVARIANT & 0xFF))); } else { m_SortVersion = GetSortVersion(); } } return m_SortVersion; } } public int LCID { get { return CultureInfo.GetCultureInfo(Name).LCID; } } } }
using System; using System.Collections.Generic; 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 System.Collections.ObjectModel; using System.Net.Sockets; using System.Threading; using System.Net; using System.IO; using System.Windows.Threading; using Profiler.Data; using Frame = Profiler.Data.Frame; using Microsoft.Win32; using System.Xml; using System.Net.Cache; using System.Reflection; using System.Diagnostics; using System.Web; using System.Net.NetworkInformation; using System.ComponentModel; using System.IO.Compression; using System.Threading.Tasks; using System.Security; using Profiler.Controls; namespace Profiler { public delegate void ClearAllFramesHandler(); /// <summary> /// Interaction logic for TimeLine.xaml /// </summary> public partial class TimeLine : UserControl { FrameCollection frames = new FrameCollection(); Thread socketThread = null; Object criticalSection = new Object(); public FrameCollection Frames { get { return frames; } } public TimeLine() { this.InitializeComponent(); this.DataContext = frames; statusToError.Add(TracerStatus.TRACER_ERROR_ACCESS_DENIED, new KeyValuePair<string, string>("ETW can't start: launch your Game/VisualStudio/UE4Editor as administrator to collect context switches", "https://github.com/bombomby/optick/wiki/Event-Tracing-for-Windows")); statusToError.Add(TracerStatus.TRACER_ERROR_ALREADY_EXISTS, new KeyValuePair<string, string>("ETW session already started (Reboot should help)", "https://github.com/bombomby/optick/wiki/Event-Tracing-for-Windows")); statusToError.Add(TracerStatus.TRACER_FAILED, new KeyValuePair<string, string>("ETW session failed (Run your Game or Visual Studio as Administrator to get ETW data)", "https://github.com/bombomby/optick/wiki/Event-Tracing-for-Windows")); statusToError.Add(TracerStatus.TRACER_INVALID_PASSWORD, new KeyValuePair<string, string>("Tracing session failed: invalid root password. Run the game as a root or pass a valid password through Optick GUI", "https://github.com/bombomby/optick/wiki/Event-Tracing-for-Windows")); statusToError.Add(TracerStatus.TRACER_NOT_IMPLEMENTED, new KeyValuePair<string, string>("Tracing sessions are not supported yet on the selected platform! Stay tuned!", "https://github.com/bombomby/optick")); ProfilerClient.Get().ConnectionChanged += TimeLine_ConnectionChanged; socketThread = new Thread(RecieveMessage); socketThread.Start(); } private void TimeLine_ConnectionChanged(IPAddress address, UInt16 port, ProfilerClient.State state, String message) { switch (state) { case ProfilerClient.State.Connecting: StatusText.Text = String.Format("Connecting {0}:{1} ...", address.ToString(), port); StatusText.Visibility = System.Windows.Visibility.Visible; break; case ProfilerClient.State.Disconnected: RaiseEvent(new ShowWarningEventArgs("Connection Failed! " + message, String.Empty)); StatusText.Visibility = System.Windows.Visibility.Collapsed; break; case ProfilerClient.State.Connected: break; } } public bool LoadFile(string file) { if (File.Exists(file)) { using (new WaitCursor()) { if (System.IO.Path.GetExtension(file) == ".trace") { return OpenTrace<FTraceGroup>(file); } else if (System.IO.Path.GetExtension(file) == ".json") { return OpenTrace<ChromeTracingGroup>(file); } else { using (Stream stream = Data.Capture.Open(file)) { return Open(file, stream); } } } } return false; } private bool Open(String name, Stream stream) { DataResponse response = DataResponse.Create(stream); while (response != null) { if (!ApplyResponse(response)) return false; response = DataResponse.Create(stream); } frames.UpdateName(name); frames.Flush(); ScrollToEnd(); return true; } private bool OpenTrace<T>(String path) where T : ITrace, new() { if (File.Exists(path)) { using (Stream stream = File.OpenRead(path)) { T trace = new T(); trace.Init(path, stream); frames.AddGroup(trace.MainGroup); frames.Add(trace.MainFrame); FocusOnFrame(trace.MainFrame); } return true; } return false; } Dictionary<DataResponse.Type, int> testResponses = new Dictionary<DataResponse.Type, int>(); private void SaveTestResponse(DataResponse response) { if (!testResponses.ContainsKey(response.ResponseType)) testResponses.Add(response.ResponseType, 0); int count = testResponses[response.ResponseType]++; String data = response.SerializeToBase64(); String path = response.ResponseType.ToString() + "_" + String.Format("{0:000}", count) + ".bin"; File.WriteAllText(path, data); } public class ThreadDescription { public UInt32 ThreadID { get; set; } public String Name { get; set; } public override string ToString() { return String.Format("[{0}] {1}", ThreadID, Name); } } enum TracerStatus { TRACER_OK = 0, TRACER_ERROR_ALREADY_EXISTS = 1, TRACER_ERROR_ACCESS_DENIED = 2, TRACER_FAILED = 3, TRACER_INVALID_PASSWORD = 4, TRACER_NOT_IMPLEMENTED = 5, } Dictionary<TracerStatus, KeyValuePair<String, String>> statusToError = new Dictionary<TracerStatus, KeyValuePair<String, String>>(); private bool ApplyResponse(DataResponse response) { if (response.Version >= NetworkProtocol.NETWORK_PROTOCOL_MIN_VERSION) { //SaveTestResponse(response); switch (response.ResponseType) { case DataResponse.Type.ReportProgress: Int32 length = response.Reader.ReadInt32(); StatusText.Text = new String(response.Reader.ReadChars(length)); break; case DataResponse.Type.NullFrame: RaiseEvent(new CancelConnectionEventArgs()); StatusText.Visibility = System.Windows.Visibility.Collapsed; lock (frames) { frames.Flush(); ScrollToEnd(); } break; case DataResponse.Type.Handshake: TracerStatus status = (TracerStatus)response.Reader.ReadUInt32(); KeyValuePair<string, string> warning; if (statusToError.TryGetValue(status, out warning)) { RaiseEvent(new ShowWarningEventArgs(warning.Key, warning.Value)); } if (response.Version >= NetworkProtocol.NETWORK_PROTOCOL_VERSION_23) { Platform.Connection connection = new Platform.Connection() { Address = response.Source.Address.ToString(), Port = response.Source.Port }; Platform.Type target = Platform.Type.Unknown; String targetName = Utils.ReadBinaryString(response.Reader); Enum.TryParse(targetName, true, out target); connection.Target = target; connection.Name = Utils.ReadBinaryString(response.Reader); RaiseEvent(new NewConnectionEventArgs(connection)); } break; default: lock (frames) { frames.Add(response); //ScrollToEnd(); } break; } } else { RaiseEvent(new ShowWarningEventArgs("Invalid NETWORK_PROTOCOL_VERSION", String.Empty)); return false; } return true; } private void ScrollToEnd() { if (frames.Count > 0) { frameList.SelectedItem = frames[frames.Count - 1]; frameList.ScrollIntoView(frames[frames.Count - 1]); } } public void RecieveMessage() { while (true) { DataResponse response = ProfilerClient.Get().RecieveMessage(); if (response != null) Application.Current.Dispatcher.BeginInvoke(new Action(() => ApplyResponse(response))); else Thread.Sleep(1000); } } #region FocusFrame private void FocusOnFrame(Data.Frame frame) { FocusFrameEventArgs args = new FocusFrameEventArgs(GlobalEvents.FocusFrameEvent, frame); RaiseEvent(args); } public class ShowWarningEventArgs : RoutedEventArgs { public String Message { get; set; } public String URL { get; set; } public ShowWarningEventArgs(String message, String url) : base(ShowWarningEvent) { Message = message; URL = url; } } public class NewConnectionEventArgs : RoutedEventArgs { public Platform.Connection Connection { get; set; } public NewConnectionEventArgs(Platform.Connection connection) : base(NewConnectionEvent) { Connection = connection; } } public class CancelConnectionEventArgs : RoutedEventArgs { public CancelConnectionEventArgs() : base(CancelConnectionEvent) { } } public delegate void ShowWarningEventHandler(object sender, ShowWarningEventArgs e); public delegate void NewConnectionEventHandler(object sender, NewConnectionEventArgs e); public delegate void CancelConnectionEventHandler(object sender, CancelConnectionEventArgs e); public static readonly RoutedEvent ShowWarningEvent = EventManager.RegisterRoutedEvent("ShowWarning", RoutingStrategy.Bubble, typeof(ShowWarningEventArgs), typeof(TimeLine)); public static readonly RoutedEvent NewConnectionEvent = EventManager.RegisterRoutedEvent("NewConnection", RoutingStrategy.Bubble, typeof(NewConnectionEventHandler), typeof(TimeLine)); public static readonly RoutedEvent CancelConnectionEvent = EventManager.RegisterRoutedEvent("CancelConnection", RoutingStrategy.Bubble, typeof(CancelConnectionEventHandler), typeof(TimeLine)); public event RoutedEventHandler FocusFrame { add { AddHandler(GlobalEvents.FocusFrameEvent, value); } remove { RemoveHandler(GlobalEvents.FocusFrameEvent, value); } } public event RoutedEventHandler ShowWarning { add { AddHandler(ShowWarningEvent, value); } remove { RemoveHandler(ShowWarningEvent, value); } } public event RoutedEventHandler NewConnection { add { AddHandler(NewConnectionEvent, value); } remove { RemoveHandler(NewConnectionEvent, value); } } public event RoutedEventHandler CancelConnection { add { AddHandler(CancelConnectionEvent, value); } remove { RemoveHandler(CancelConnectionEvent, value); } } #endregion private void frameList_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (frameList.SelectedItem is Data.Frame) { FocusOnFrame((Data.Frame)frameList.SelectedItem); } } public void ForEachResponse(Action<FrameGroup, DataResponse> action) { FrameGroup currentGroup = null; foreach (Frame frame in frames) { if (frame is EventFrame) { EventFrame eventFrame = frame as EventFrame; if (eventFrame.Group != currentGroup && currentGroup != null) { currentGroup.Responses.ForEach(response => action(currentGroup, response)); } currentGroup = eventFrame.Group; } else if (frame is SamplingFrame) { if (currentGroup != null) { currentGroup.Responses.ForEach(response => action(currentGroup, response)); currentGroup = null; } action(null, (frame as SamplingFrame).Response); } } currentGroup?.Responses.ForEach(response => action(currentGroup, response)); } public void Save(Stream stream) { ForEachResponse((group, response) => response.Serialize(stream)); } public String Save() { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Optick Performance Capture (*.opt)|*.opt"; dlg.Title = "Where should I save profiler results?"; if (dlg.ShowDialog() == true) { lock (frames) { using (Stream stream = Capture.Create(dlg.FileName)) Save(stream); frames.UpdateName(dlg.FileName, true); } return dlg.FileName; } return null; } public void Close() { if (socketThread != null) { socketThread.Abort(); socketThread = null; } } public void Clear() { lock (frames) { frames.Clear(); } } //private void FrameFilterSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) //{ // ICollectionView view = CollectionViewSource.GetDefaultView(frameList.ItemsSource); // view.Filter = new Predicate<object>((item) => { return (item is Frame) ? (item as Frame).Duration >= FrameFilterSlider.Value : true; }); //} public void StartCapture(IPAddress address, UInt16 port, CaptureSettings settings, SecureString password) { ProfilerClient.Get().IpAddress = address; ProfilerClient.Get().Port = port; Application.Current.Dispatcher.BeginInvoke(new Action(() => { StatusText.Text = "Connecting..."; StatusText.Visibility = System.Windows.Visibility.Visible; })); Task.Run(() => { ProfilerClient.Get().SendMessage(new StartMessage() { Settings = settings, Password = password } , true); }); } } public class FrameHeightConverter : IValueConverter { public static double Convert(double value) { return 2.775 * value; } public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return Convert((double)value); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return null; } } public class WaitCursor : IDisposable { private Cursor _previousCursor; public WaitCursor() { _previousCursor = Mouse.OverrideCursor; Mouse.OverrideCursor = Cursors.Wait; } public void Dispose() { Mouse.OverrideCursor = _previousCursor; } } }
// 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.Collections.Immutable; using System.Collections.ObjectModel; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DynamicTests : ExpressionCompilerTestBase { [Fact] public void Local_Simple() { var source = @"class C { static void M() { dynamic d = 1; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; Assert.NotNull(GetDynamicAttributeIfAny(method)); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (dynamic V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Local_Array() { var source = @"class C { static void M() { dynamic[] d = new dynamic[1]; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; Assert.NotNull(GetDynamicAttributeIfAny(method)); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (dynamic[] V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Local_Generic() { var source = @"class C { static void M() { System.Collections.Generic.List<dynamic> d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; Assert.NotNull(GetDynamicAttributeIfAny(method)); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments.Single().TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Collections.Generic.List<dynamic> V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void LocalConstant_Simple() { var source = @"class C { static void M() { const dynamic d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; Assert.NotNull(GetDynamicAttributeIfAny(method)); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); locals.Free(); }); } [Fact] public void LocalConstant_Array() { var source = @"class C { static void M() { const dynamic[] d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; Assert.NotNull(GetDynamicAttributeIfAny(method)); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); locals.Free(); }); } [Fact] public void LocalConstant_Generic() { var source = @"class C { static void M() { const Generic<dynamic> d = null; } static dynamic ForceDynamicAttribute() { return null; } } class Generic<T> { } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; Assert.NotNull(GetDynamicAttributeIfAny(method)); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments.Single().TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndNonConstantDynamic() { var source = @"class C { static void M() { { #line 799 dynamic a = null; const dynamic b = null; } { const dynamic[] a = null; #line 899 dynamic[] b = null; } } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[0], "a", 0x01); } else { VerifyCustomTypeInfo(locals[0], "a", null); // Dynamic info ignored because ambiguous. } VerifyCustomTypeInfo(locals[1], "b", 0x01); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "b", 0x02); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x02); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndNonConstantNonDynamic() { var source = @"class C { static void M() { { #line 799 object a = null; const dynamic b = null; } { const dynamic[] a = null; #line 899 object[] b = null; } } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "a", null); VerifyCustomTypeInfo(locals[1], "b", 0x01); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "b", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x02); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndConstantDynamic() { var source = @"class C { static void M() { { const dynamic a = null; const dynamic b = null; #line 799 object e = null; } { const dynamic[] a = null; const dynamic[] c = null; #line 899 object[] e = null; } { #line 999 object e = null; const dynamic a = null; const dynamic c = null; } } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x01); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } VerifyCustomTypeInfo(locals[2], "b", 0x01); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x02); VerifyCustomTypeInfo(locals[2], "c", 0x02); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. VerifyCustomTypeInfo(locals[2], "c", null); // Dynamic info ignored because ambiguous. } locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 999); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x01); VerifyCustomTypeInfo(locals[2], "c", 0x01); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. VerifyCustomTypeInfo(locals[2], "c", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndConstantNonDynamic() { var source = @"class C { static void M() { { const dynamic a = null; const object c = null; #line 799 object e = null; } { const dynamic[] b = null; #line 899 object[] e = null; } { const object[] a = null; #line 999 object e = null; const dynamic[] c = null; } } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x01); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } VerifyCustomTypeInfo(locals[2], "c", null); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); VerifyCustomTypeInfo(locals[1], "b", 0x02); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 999); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); VerifyCustomTypeInfo(locals[1], "a", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[2], "c", 0x02); } else { VerifyCustomTypeInfo(locals[2], "c", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [Fact] public void LocalsWithLongAndShortNames() { var source = @"class C { static void M() { const dynamic a123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars const dynamic b = null; dynamic c123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars dynamic d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(4, locals.Count); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[0], "c123456789012345678901234567890123456789012345678901234567890123", 0x01); VerifyCustomTypeInfo(locals[2], "a123456789012345678901234567890123456789012345678901234567890123", 0x01); } else { VerifyCustomTypeInfo(locals[0], "c123456789012345678901234567890123456789012345678901234567890123", null); // dynamic info dropped VerifyCustomTypeInfo(locals[2], "a123456789012345678901234567890123456789012345678901234567890123", null); // dynamic info dropped } VerifyCustomTypeInfo(locals[1], "d", 0x01); VerifyCustomTypeInfo(locals[3], "b", 0x01); locals.Free(); }); } [Fact] public void Parameter_Simple() { var source = @"class C { static void M(dynamic d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; Assert.NotNull(GetDynamicAttributeIfAny(method)); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Parameter_Array() { var source = @"class C { static void M(dynamic[] d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; Assert.NotNull(GetDynamicAttributeIfAny(method)); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Parameter_Generic() { var source = @"class C { static void M(System.Collections.Generic.List<dynamic> d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; Assert.NotNull(GetDynamicAttributeIfAny(method)); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments.Single().TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); locals.Free(); }); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void ComplexDynamicType() { var source = @"class C { static void M(Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic> d) { } static dynamic ForceDynamicAttribute() { return null; } } public class Outer<T, U> { public class Inner<V, W> { } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; Assert.NotNull(GetDynamicAttributeIfAny(method)); VerifyCustomTypeInfo(locals[0], "d", 0x04, 0x03); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); string error; var result = context.CompileExpression("d", out error); Assert.Null(error); VerifyCustomTypeInfo(result, 0x04, 0x03); // Note that the method produced by CompileAssignment returns void // so there is never custom type info. result = context.CompileAssignment("d", "d", out error); Assert.Null(error); VerifyCustomTypeInfo(result, null); ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; testData = new CompilationTestData(); result = context.CompileExpression( "var dd = d;", DkmEvaluationFlags.None, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Null(error); VerifyCustomTypeInfo(result, null); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 60 (0x3c) .maxstack 6 IL_0000: ldtoken ""Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic>"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""dd"" IL_000f: ldstr ""108766ce-df68-46ee-b761-0dcb7ac805f1"" IL_0014: newobj ""System.Guid..ctor(string)"" IL_0019: ldc.i4.3 IL_001a: newarr ""byte"" IL_001f: dup IL_0020: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=3 <PrivateImplementationDetails>.A4E591DA7617172655FE45FC3878ECC8CC0D44B3"" IL_0025: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_002a: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])"" IL_002f: ldstr ""dd"" IL_0034: call ""Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic> Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic>>(string)"" IL_0039: ldarg.0 IL_003a: stind.ref IL_003b: ret }"); locals.Free(); }); } [Fact] public void DynamicAliases() { var source = @"class C { static void M() { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext( runtime, "C.M"); var aliases = ImmutableArray.Create( Alias( DkmClrAliasKind.Variable, "d1", "d1", typeof(object).AssemblyQualifiedName, MakeCustomTypeInfo(true)), Alias( DkmClrAliasKind.Variable, "d2", "d2", typeof(Dictionary<Dictionary<dynamic, Dictionary<object[], dynamic[]>>, object>).AssemblyQualifiedName, MakeCustomTypeInfo(false, false, true, false, false, false, false, true, false))); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var diagnostics = DiagnosticBag.GetInstance(); var testData = new CompilationTestData(); context.CompileGetLocals( locals, argumentsOnly: false, aliases: aliases, diagnostics: diagnostics, typeName: out typeName, testData: testData); diagnostics.Free(); Assert.Equal(locals.Count, 2); VerifyCustomTypeInfo(locals[0], "d1", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d1", expectedILOpt: @"{ // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""d1"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: ret }"); VerifyCustomTypeInfo(locals[1], "d2", 0x84, 0x00); // Note: read flags right-to-left in each byte: 0010 0001 0(000 0000) VerifyLocal(testData, typeName, locals[1], "<>m1", "d2", expectedILOpt: @"{ // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr ""d2"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""System.Collections.Generic.Dictionary<System.Collections.Generic.Dictionary<dynamic, System.Collections.Generic.Dictionary<object[], dynamic[]>>, object>"" IL_000f: ret }"); locals.Free(); }); } private static ReadOnlyCollection<byte> MakeCustomTypeInfo(params bool[] flags) { Assert.NotNull(flags); var builder = ArrayBuilder<bool>.GetInstance(); builder.AddRange(flags); var bytes = DynamicFlagsCustomTypeInfo.ToBytes(builder); builder.Free(); return CustomTypeInfo.Encode(bytes, null); } [Fact] public void DynamicAttribute_NotAvailable() { var source = @"class C { static void M() { dynamic d = 1; } }"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; Assert.Null(GetDynamicAttributeIfAny(method)); VerifyCustomTypeInfo(locals[0], "d", null); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (dynamic V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void DynamicCall() { var source = @" class C { void M() { dynamic d = this; d.M(); } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var result = context.CompileExpression("d.M()", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(TypeKind.Dynamic, methodData.Method.ReturnType.TypeKind); methodData.VerifyIL(@" { // Code size 77 (0x4d) .maxstack 9 .locals init (dynamic V_0) //d IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0037 IL_0007: ldc.i4.0 IL_0008: ldstr ""M"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.1 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0032: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_003c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0041: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0046: ldloc.0 IL_0047: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004c: ret } "); }); } [WorkItem(1160855, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1160855")] [Fact] public void AwaitDynamic() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class C { dynamic d; void M(int p) { d.Test(); // Force reference to runtime binder. } static void G(Func<Task<object>> f) { } } "; var comp = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var result = context.CompileExpression("G(async () => await d())", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, null); var methodData = testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()"); methodData.VerifyIL(@" { // Code size 539 (0x21b) .maxstack 10 .locals init (int V_0, object V_1, object V_2, System.Runtime.CompilerServices.ICriticalNotifyCompletion V_3, System.Runtime.CompilerServices.INotifyCompletion V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse IL_0185 IL_000d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_0012: brtrue.s IL_0044 IL_0014: ldc.i4.0 IL_0015: ldstr ""GetAwaiter"" IL_001a: ldnull IL_001b: ldtoken ""C"" IL_0020: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0025: ldc.i4.1 IL_0026: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldc.i4.0 IL_002e: ldnull IL_002f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0034: stelem.ref IL_0035: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003a: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003f: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_0044: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_0049: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_004e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0058: brtrue.s IL_0084 IL_005a: ldc.i4.0 IL_005b: ldtoken ""C"" IL_0060: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0065: ldc.i4.1 IL_0066: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_006b: dup IL_006c: ldc.i4.0 IL_006d: ldc.i4.0 IL_006e: ldnull IL_006f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0074: stelem.ref IL_0075: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_007a: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007f: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0084: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0089: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_008e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0093: ldarg.0 IL_0094: ldfld ""<>x.<>c__DisplayClass0_0 <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>4__this"" IL_0099: ldfld ""C <>x.<>c__DisplayClass0_0.<>4__this"" IL_009e: ldfld ""dynamic C.d"" IL_00a3: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00a8: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00ad: stloc.2 IL_00ae: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00b3: brtrue.s IL_00da IL_00b5: ldc.i4.s 16 IL_00b7: ldtoken ""bool"" IL_00bc: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00c1: ldtoken ""C"" IL_00c6: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00cb: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_00d0: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d5: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00da: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00df: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Target"" IL_00e4: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00e9: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_00ee: brtrue.s IL_011f IL_00f0: ldc.i4.0 IL_00f1: ldstr ""IsCompleted"" IL_00f6: ldtoken ""C"" IL_00fb: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0100: ldc.i4.1 IL_0101: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0106: dup IL_0107: ldc.i4.0 IL_0108: ldc.i4.0 IL_0109: ldnull IL_010a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_010f: stelem.ref IL_0110: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0115: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_011a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_011f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_0124: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0129: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_012e: ldloc.2 IL_012f: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_0134: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_0139: brtrue.s IL_019c IL_013b: ldarg.0 IL_013c: ldc.i4.0 IL_013d: dup IL_013e: stloc.0 IL_013f: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_0144: ldarg.0 IL_0145: ldloc.2 IL_0146: stfld ""object <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>u__1"" IL_014b: ldloc.2 IL_014c: isinst ""System.Runtime.CompilerServices.ICriticalNotifyCompletion"" IL_0151: stloc.3 IL_0152: ldloc.3 IL_0153: brtrue.s IL_0170 IL_0155: ldloc.2 IL_0156: castclass ""System.Runtime.CompilerServices.INotifyCompletion"" IL_015b: stloc.s V_4 IL_015d: ldarg.0 IL_015e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_0163: ldloca.s V_4 IL_0165: ldarg.0 IL_0166: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.AwaitOnCompleted<System.Runtime.CompilerServices.INotifyCompletion, <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d>(ref System.Runtime.CompilerServices.INotifyCompletion, ref <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d)"" IL_016b: ldnull IL_016c: stloc.s V_4 IL_016e: br.s IL_017e IL_0170: ldarg.0 IL_0171: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_0176: ldloca.s V_3 IL_0178: ldarg.0 IL_0179: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ICriticalNotifyCompletion, <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d>(ref System.Runtime.CompilerServices.ICriticalNotifyCompletion, ref <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d)"" IL_017e: ldnull IL_017f: stloc.3 IL_0180: leave IL_021a IL_0185: ldarg.0 IL_0186: ldfld ""object <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>u__1"" IL_018b: stloc.2 IL_018c: ldarg.0 IL_018d: ldnull IL_018e: stfld ""object <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>u__1"" IL_0193: ldarg.0 IL_0194: ldc.i4.m1 IL_0195: dup IL_0196: stloc.0 IL_0197: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_019c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01a1: brtrue.s IL_01d3 IL_01a3: ldc.i4.0 IL_01a4: ldstr ""GetResult"" IL_01a9: ldnull IL_01aa: ldtoken ""C"" IL_01af: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01b4: ldc.i4.1 IL_01b5: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_01ba: dup IL_01bb: ldc.i4.0 IL_01bc: ldc.i4.0 IL_01bd: ldnull IL_01be: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01c3: stelem.ref IL_01c4: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_01c9: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_01ce: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01d3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01d8: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_01dd: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01e2: ldloc.2 IL_01e3: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_01e8: ldnull IL_01e9: stloc.2 IL_01ea: stloc.1 IL_01eb: leave.s IL_0206 } catch System.Exception { IL_01ed: stloc.s V_5 IL_01ef: ldarg.0 IL_01f0: ldc.i4.s -2 IL_01f2: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_01f7: ldarg.0 IL_01f8: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_01fd: ldloc.s V_5 IL_01ff: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)"" IL_0204: leave.s IL_021a } IL_0206: ldarg.0 IL_0207: ldc.i4.s -2 IL_0209: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_020e: ldarg.0 IL_020f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_0214: ldloc.1 IL_0215: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)"" IL_021a: ret } "); }); } [WorkItem(1072296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072296")] [Fact] public void InvokeStaticMemberInLambda() { var source = @" class C { static dynamic x; static void Foo(dynamic y) { System.Action a = () => Foo(x); } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.Foo"); var testData = new CompilationTestData(); string error; var result = context.CompileAssignment("a", "() => Foo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, null); testData.GetMethodData("<>x.<>c.<<>m0>b__0_0").VerifyIL(@" { // Code size 106 (0x6a) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""Foo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0055: ldtoken ""<>x"" IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005f: ldsfld ""dynamic C.x"" IL_0064: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0069: ret }"); context = CreateMethodContext(runtime, "C.<>c.<Foo>b__1_0"); testData = new CompilationTestData(); result = context.CompileExpression("Foo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL(@" { // Code size 102 (0x66) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0042 IL_0007: ldc.i4.0 IL_0008: ldstr ""Foo"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.s 33 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: dup IL_002a: ldc.i4.1 IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0051: ldtoken ""<>x"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldsfld ""dynamic C.x"" IL_0060: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0065: ret }"); }); } [WorkItem(1095613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1095613")] [Fact] public void HoistedLocalsLoseDynamicAttribute() { var source = @" class C { static void M(dynamic x) { dynamic y = 3; System.Func<dynamic> a = () => x + y; } static void Foo(int x) { M(x); } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var result = context.CompileExpression("Foo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 103 (0x67) .maxstack 9 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Func<dynamic> V_1) //a IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0042 IL_0007: ldc.i4.0 IL_0008: ldstr ""Foo"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.s 33 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: dup IL_002a: ldc.i4.1 IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0051: ldtoken ""<>x"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldloc.0 IL_005c: ldfld ""dynamic C.<>c__DisplayClass0_0.x"" IL_0061: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0066: ret }"); testData = new CompilationTestData(); result = context.CompileExpression("Foo(y)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 103 (0x67) .maxstack 9 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Func<dynamic> V_1) //a IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0042 IL_0007: ldc.i4.0 IL_0008: ldstr ""Foo"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.s 33 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: dup IL_002a: ldc.i4.1 IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0051: ldtoken ""<>x"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldloc.0 IL_005c: ldfld ""dynamic C.<>c__DisplayClass0_0.y"" IL_0061: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0066: ret }"); }); } private static void VerifyCustomTypeInfo(LocalAndMethod localAndMethod, string expectedName, params byte[] expectedBytes) { Assert.Equal(localAndMethod.LocalName, expectedName); ReadOnlyCollection<byte> customTypeInfo; Guid customTypeInfoId = localAndMethod.GetCustomTypeInfo(out customTypeInfo); VerifyCustomTypeInfo(customTypeInfoId, customTypeInfo, expectedBytes); } private static void VerifyCustomTypeInfo(CompileResult compileResult, params byte[] expectedBytes) { ReadOnlyCollection<byte> customTypeInfo; Guid customTypeInfoId = compileResult.GetCustomTypeInfo(out customTypeInfo); VerifyCustomTypeInfo(customTypeInfoId, customTypeInfo, expectedBytes); } private static void VerifyCustomTypeInfo(Guid customTypeInfoId, ReadOnlyCollection<byte> customTypeInfo, params byte[] expectedBytes) { if (expectedBytes == null) { Assert.Equal(Guid.Empty, customTypeInfoId); Assert.Null(customTypeInfo); } else { Assert.Equal(CustomTypeInfo.PayloadTypeId, customTypeInfoId); // Include leading count byte. var builder = ArrayBuilder<byte>.GetInstance(); builder.Add((byte)expectedBytes.Length); builder.AddRange(expectedBytes); expectedBytes = builder.ToArrayAndFree(); Assert.Equal(expectedBytes, customTypeInfo); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Text { internal static class IntegerFormatter { // TODO: format should be ReadOnlySpan<char> internal static bool TryFormatInt64(long value, byte numberOfBytes, Span<byte> buffer, ReadOnlySpan<char> format, EncodingData formattingData, out int bytesWritten) { Precondition.Require(numberOfBytes <= sizeof(long)); Format.Parsed parsedFormat = Format.Parse(format); return TryFormatInt64(value, numberOfBytes, buffer, parsedFormat, formattingData, out bytesWritten); } internal static bool TryFormatInt64(long value, byte numberOfBytes, Span<byte> buffer, Format.Parsed format, EncodingData formattingData, out int bytesWritten) { Precondition.Require(numberOfBytes <= sizeof(long)); if (value >= 0) { return TryFormatUInt64(unchecked((ulong)value), numberOfBytes, buffer, format, formattingData, out bytesWritten); } else if (format.IsHexadecimal) { ulong bitMask = GetBitMask(numberOfBytes); return TryFormatUInt64(unchecked((ulong)value) & bitMask, numberOfBytes, buffer, format, formattingData, out bytesWritten); } else { int minusSignBytes = 0; if(!formattingData.TryWriteSymbol(EncodingData.Symbol.MinusSign, buffer, out minusSignBytes)) { bytesWritten = 0; return false; } int digitBytes = 0; if(!TryFormatUInt64(unchecked((ulong)-value), numberOfBytes, buffer.Slice(minusSignBytes), format, formattingData, out digitBytes)) { bytesWritten = 0; return false; } bytesWritten = digitBytes + minusSignBytes; return true; } } internal static bool TryFormatUInt64(ulong value, byte numberOfBytes, Span<byte> buffer, ReadOnlySpan<char> format, EncodingData formattingData, out int bytesWritten) { Format.Parsed parsedFormat = Format.Parse(format); return TryFormatUInt64(value, numberOfBytes, buffer, parsedFormat, formattingData, out bytesWritten); } internal static bool TryFormatUInt64(ulong value, byte numberOfBytes, Span<byte> buffer, Format.Parsed format, EncodingData formattingData, out int bytesWritten) { if(format.Symbol == 'g') { format.Symbol = 'G'; } if (format.IsHexadecimal && formattingData.IsUtf16) { return TryFormatHexadecimalInvariantCultureUtf16(value, buffer, format, out bytesWritten); } if (format.IsHexadecimal && formattingData.IsUtf8) { return TryFormatHexadecimalInvariantCultureUtf8(value, buffer, format, out bytesWritten); } if ((formattingData.IsInvariantUtf16) && (format.Symbol == 'D' || format.Symbol == 'G')) { return TryFormatDecimalInvariantCultureUtf16(value, buffer, format, out bytesWritten); } if ((formattingData.IsInvariantUtf8) && (format.Symbol == 'D' || format.Symbol == 'G')) { return TryFormatDecimalInvariantCultureUtf8(value, buffer, format, out bytesWritten); } return TryFormatDecimal(value, buffer, format, formattingData, out bytesWritten); } private static bool TryFormatDecimalInvariantCultureUtf16(ulong value, Span<byte> buffer, Format.Parsed format, out int bytesWritten) { Precondition.Require(format.Symbol == 'D' || format.Symbol == 'G'); // Count digits var valueToCountDigits = value; var digitsCount = 1; while (valueToCountDigits >= 10UL) { valueToCountDigits = valueToCountDigits / 10UL; digitsCount++; } var index = 0; var bytesCount = digitsCount * 2; // If format is D and precision is greater than digits count, append leading zeros if (format.Symbol == 'D' && format.HasPrecision) { var leadingZerosCount = format.Precision - digitsCount; if (leadingZerosCount > 0) { bytesCount += leadingZerosCount * 2; } if (bytesCount > buffer.Length) { bytesWritten = 0; return false; } while (leadingZerosCount-- > 0) { buffer[index++] = (byte)'0'; buffer[index++] = 0; } } else if (bytesCount > buffer.Length) { bytesWritten = 0; return false; } index = bytesCount; while (digitsCount-- > 0) { ulong digit = value % 10UL; value /= 10UL; buffer[--index] = 0; buffer[--index] = (byte)(digit + (ulong)'0'); } bytesWritten = bytesCount; return true; } private static bool TryFormatDecimalInvariantCultureUtf8(ulong value, Span<byte> buffer, Format.Parsed format, out int bytesWritten) { Precondition.Require(format.Symbol == 'D' || format.Symbol == 'G'); // Count digits var valueToCountDigits = value; var digitsCount = 1; while (valueToCountDigits >= 10UL) { valueToCountDigits = valueToCountDigits / 10UL; digitsCount++; } var index = 0; var bytesCount = digitsCount; // If format is D and precision is greater than digits count, append leading zeros if (format.Symbol == 'D' && format.HasPrecision) { var leadingZerosCount = format.Precision - digitsCount; if (leadingZerosCount > 0) { bytesCount += leadingZerosCount; } if (bytesCount > buffer.Length) { bytesWritten = 0; return false; } while (leadingZerosCount-- > 0) { buffer[index++] = (byte)'0'; } } else if (bytesCount > buffer.Length) { bytesWritten = 0; return false; } index = bytesCount; while (digitsCount-- > 0) { ulong digit = value % 10UL; value /= 10UL; buffer[--index] = (byte)(digit + (ulong)'0'); } bytesWritten = bytesCount; return true; } private static bool TryFormatHexadecimalInvariantCultureUtf16(ulong value, Span<byte> buffer, Format.Parsed format, out int bytesWritten) { Precondition.Require(format.Symbol == 'X' || format.Symbol == 'x'); byte firstDigitOffset = (byte)'0'; byte firstHexCharOffset = format.Symbol == 'x' ? (byte)'a' : (byte)'A'; firstHexCharOffset -= 10; // Count amount of hex digits var hexDigitsCount = 1; ulong valueToCount = value; if (valueToCount > 0xFFFFFFFF) { hexDigitsCount += 8; valueToCount >>= 0x20; } if (valueToCount > 0xFFFF) { hexDigitsCount += 4; valueToCount >>= 0x10; } if (valueToCount > 0xFF) { hexDigitsCount += 2; valueToCount >>= 0x8; } if (valueToCount > 0xF) { hexDigitsCount++; } var bytesCount = hexDigitsCount * 2; // Count leading zeros var leadingZerosCount = format.HasPrecision ? format.Precision - hexDigitsCount : 0; bytesCount += leadingZerosCount > 0 ? leadingZerosCount * 2 : 0; if (bytesCount > buffer.Length) { bytesWritten = 0; return false; } var index = bytesCount; while (hexDigitsCount-- > 0) { byte digit = (byte)(value & 0xF); value >>= 0x4; digit += digit < 10 ? firstDigitOffset : firstHexCharOffset; buffer[--index] = 0; buffer[--index] = digit; } // Write leading zeros if any while (leadingZerosCount-- > 0) { buffer[--index] = 0; buffer[--index] = firstDigitOffset; } bytesWritten = bytesCount; return true; } private static bool TryFormatHexadecimalInvariantCultureUtf8(ulong value, Span<byte> buffer, Format.Parsed format, out int bytesWritten) { Precondition.Require(format.Symbol == 'X' || format.Symbol == 'X'); byte firstDigitOffset = (byte)'0'; byte firstHexCharOffset = format.Symbol == 'X' ? (byte)'a' : (byte)'A'; firstHexCharOffset -= 10; // Count amount of hex digits var hexDigitsCount = 1; ulong valueToCount = value; if (valueToCount > 0xFFFFFFFF) { hexDigitsCount += 8; valueToCount >>= 0x20; } if (valueToCount > 0xFFFF) { hexDigitsCount += 4; valueToCount >>= 0x10; } if (valueToCount > 0xFF) { hexDigitsCount += 2; valueToCount >>= 0x8; } if (valueToCount > 0xF) { hexDigitsCount++; } var bytesCount = hexDigitsCount; // Count leading zeros var leadingZerosCount = format.HasPrecision ? format.Precision - hexDigitsCount : 0; bytesCount += leadingZerosCount > 0 ? leadingZerosCount : 0; if (bytesCount > buffer.Length) { bytesWritten = 0; return false; } var index = bytesCount; while (hexDigitsCount-- > 0) { byte digit = (byte)(value & 0xF); value >>= 0x4; digit += digit < 10 ? firstDigitOffset : firstHexCharOffset; buffer[--index] = digit; } // Write leading zeros if any while (leadingZerosCount-- > 0) { buffer[--index] = firstDigitOffset; } bytesWritten = bytesCount; return true; } // TODO: this whole routine is too slow. It does div and mod twice, which are both costly (especially that some JITs cannot optimize it). // It does it twice to avoid reversing the formatted buffer, which can be tricky given it should handle arbitrary cultures. // One optimization I thought we could do is to do div/mod once and store digits in a temp buffer (but that would allocate). Modification to the idea would be to store the digits in a local struct // Another idea possibly worth tying would be to special case cultures that have constant digit size, and go back to the format + reverse buffer approach. private static bool TryFormatDecimal(ulong value, Span<byte> buffer, Format.Parsed format, EncodingData formattingData, out int bytesWritten) { if(format.IsDefault) { format.Symbol = 'G'; } format.Symbol = Char.ToUpperInvariant(format.Symbol); // TODO: this is costly. I think the transformation should happen in Parse Precondition.Require(format.Symbol == 'D' || format.Symbol == 'G' || format.Symbol == 'N'); // Reverse value on decimal basis, count digits and trailing zeros before the decimal separator ulong reversedValueExceptFirst = 0; var digitsCount = 1; var trailingZerosCount = 0; // We reverse the digits in numeric form because reversing encoded digits is hard and/or costly. // If value contains 20 digits, its reversed value will not fit into ulong size. // So reverse it till last digit (reversedValueExceptFirst will have all the digits except the first one). while (value >= 10) { var digit = value % 10UL; value = value / 10UL; if (reversedValueExceptFirst == 0 && digit == 0) { trailingZerosCount++; } else { reversedValueExceptFirst = reversedValueExceptFirst * 10UL + digit; digitsCount++; } } bytesWritten = 0; int digitBytes; // If format is D and precision is greater than digitsCount + trailingZerosCount, append leading zeros if (format.Symbol == 'D' && format.HasPrecision) { var leadingZerosCount = format.Precision - digitsCount - trailingZerosCount; while (leadingZerosCount-- > 0) { if (!formattingData.TryWriteDigitOrSymbol(0, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; } } // Append first digit if (!formattingData.TryWriteDigit(value, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; digitsCount--; if (format.Symbol == 'N') { const int GroupSize = 3; // Count amount of digits before first group separator. It will be reset to groupSize every time digitsLeftInGroup == zero var digitsLeftInGroup = (digitsCount + trailingZerosCount) % GroupSize; if (digitsLeftInGroup == 0) { if (digitsCount + trailingZerosCount > 0) { // There is a new group immediately after the first digit if (!formattingData.TryWriteSymbol(EncodingData.Symbol.GroupSeparator, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; } digitsLeftInGroup = GroupSize; } // Append digits while (reversedValueExceptFirst > 0) { if (digitsLeftInGroup == 0) { if (!formattingData.TryWriteSymbol(EncodingData.Symbol.GroupSeparator, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; digitsLeftInGroup = GroupSize; } var nextDigit = reversedValueExceptFirst % 10UL; reversedValueExceptFirst = reversedValueExceptFirst / 10UL; if (!formattingData.TryWriteDigit(nextDigit, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; digitsLeftInGroup--; } // Append trailing zeros if any while (trailingZerosCount-- > 0) { if (digitsLeftInGroup == 0) { if (!formattingData.TryWriteSymbol(EncodingData.Symbol.GroupSeparator, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; digitsLeftInGroup = GroupSize; } if (!formattingData.TryWriteDigitOrSymbol(0, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; digitsLeftInGroup--; } } else { while (reversedValueExceptFirst > 0) { var bufferSlice = buffer.Slice(bytesWritten); var nextDigit = reversedValueExceptFirst % 10UL; reversedValueExceptFirst = reversedValueExceptFirst / 10UL; if (!formattingData.TryWriteDigit(nextDigit, bufferSlice, out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; } // Append trailing zeros if any while (trailingZerosCount-- > 0) { if (!formattingData.TryWriteDigitOrSymbol(0, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; } } // If format is N and precision is not defined or is greater than zero, append trailing zeros after decimal point if (format.Symbol == 'N') { int trailingZerosAfterDecimalCount = format.HasPrecision ? format.Precision : 2; if (trailingZerosAfterDecimalCount > 0) { if (!formattingData.TryWriteSymbol(EncodingData.Symbol.DecimalSeparator, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; while (trailingZerosAfterDecimalCount-- > 0) { if (!formattingData.TryWriteDigitOrSymbol(0, buffer.Slice(bytesWritten), out digitBytes)) { bytesWritten = 0; return false; } bytesWritten += digitBytes; } } } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ulong GetBitMask(byte numberOfBytes) { Precondition.Require(numberOfBytes == 1 || numberOfBytes == 2 || numberOfBytes == 4 || numberOfBytes == 8); switch (numberOfBytes) { case 1: return 0xFF; case 2: return 0xFFFF; case 4: return 0xFFFFFFFF; case 8: return 0xFFFFFFFFFFFFFFFF; default: throw new Exception(); // I would like this to fail fast. } } } }
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace XControls.TextBox { /// <summary> /// This class defines a textbox which can be editable. /// </summary> public partial class EditableInPlaceTextBox : UserControl { #region Fields /// <summary> /// We keep the old text when we go into editmode in case the user aborts with the escape key /// </summary> private string mOldText; #endregion // Fields. #region Constructor /// <summary> /// This class define a text box that is editable /// </summary> public EditableInPlaceTextBox() { this.InitializeComponent(); this.Focusable = true; } #endregion // Constructor. #region Dependency properties /// <summary> /// Property associated to Text property /// </summary> public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(EditableInPlaceTextBox), new PropertyMetadata(string.Empty, OnTextChanged)); /// <summary> /// Property associated to IsEditable property /// </summary> public static readonly DependencyProperty IsEditableProperty = DependencyProperty.Register("IsEditable", typeof(bool), typeof(EditableInPlaceTextBox), new PropertyMetadata(false)); /// <summary> /// Property associated to IsInEditMode property /// </summary> public static readonly DependencyProperty IsInEditModeProperty = DependencyProperty.Register("IsInEditMode", typeof(bool), typeof(EditableInPlaceTextBox), new PropertyMetadata(false, OnEditModeChanged, CoerceEditMode)); /// <summary> /// Property associated to the TextFormat property /// </summary> public static readonly DependencyProperty TextFormatProperty = DependencyProperty.Register("TextFormat", typeof(string), typeof(EditableInPlaceTextBox), new PropertyMetadata("{0}")); #endregion // Dependency properties. #region Properties /// <summary> /// The editable text displayed to the user /// </summary> public string Text { get { // Save the text as the old text when it changes this.mOldText = (string) this.GetValue(TextProperty); return this.mOldText; } set => this.SetValue(TextProperty, value); } /// <summary> /// Tells if the item is editable /// </summary> public bool IsEditable { get => (bool) this.GetValue(IsEditableProperty); set => this.SetValue(IsEditableProperty, value); } /// <summary> /// Tell if the item is in edit mode /// </summary> public bool IsInEditMode { get => (bool) this.GetValue(IsInEditModeProperty); set => this.SetValue(IsInEditModeProperty, value); } /// <summary> /// Used if the editable text should be surrounded by more text. /// The TextFormat property uses the String.Format function to format the text, /// which means that the editable text is referenced by {0} inside a string. /// If the TextFormat property is set to either the empty string (""), the string containing only {0} ("{0}"), /// or is not set at all, the control simply shows the string from the Text property. /// </summary> public string TextFormat { get => (string) this.GetValue(TextFormatProperty); set { if (value == string.Empty) { value = "{0}"; } this.SetValue(TextFormatProperty, value); } } /// <summary> /// Format the Text according to TextFormat /// </summary> public string FormattedText => string.Format(this.TextFormat, this.Text); #endregion // Properties. #region Methods /// <summary> /// This delegate is called when the edition mode is changed. /// </summary> /// <param name="pSender">The event sender.</param> /// <param name="pEventArgs">The event arguments.</param> private static void OnEditModeChanged(DependencyObject pObject, DependencyPropertyChangedEventArgs pEventArgs) { var lControl = pObject as EditableInPlaceTextBox; if (lControl != null) { if (lControl.IsEditable) { if (Convert.ToBoolean(pEventArgs.NewValue)) { lControl.mOldText = lControl.Text; } } } } /// <summary> /// This delegate is called when the edition mode is changed. /// </summary> /// <param name="pSender">The event sender.</param> /// <param name="pEventArgs">The event arguments.</param> private static void OnTextChanged(DependencyObject pObject, DependencyPropertyChangedEventArgs pEventArgs) { var lControl = pObject as EditableInPlaceTextBox; if (lControl != null) { lControl.ForceFormatedTextUpdate(); } } /// <summary> /// This delegate is called to coerce the edition mode. /// </summary> /// <param name="pObject">The dependency object.</param> /// <param name="pMode">The edition mode to coerce.</param> /// <returns></returns> private static object CoerceEditMode(DependencyObject pObject, object pMode) { var lNewMode = (bool) pMode; var lControl = pObject as EditableInPlaceTextBox; if (lControl != null) { if (lControl.IsEditable) { return lNewMode; } return false; } return lNewMode; } /// <summary> /// Invoked when we enter edit mode. /// </summary> /// <param name="sender">Sender</param> /// <param name="e">RoutedEventArgs</param> private void OnTextBoxLoaded(object pSender, RoutedEventArgs pEventArgs) { var lTxt = pSender as System.Windows.Controls.TextBox; // Give the TextBox input focus lTxt.Focus(); lTxt.SelectAll(); } /// <summary> /// Invoked when we exit edit mode. /// </summary> /// <param name="sender">sender</param> /// <param name="e">RoutedEventArgs</param> private void OnTextBoxLostFocus(object pSender, RoutedEventArgs pEventArgs) { this.IsInEditMode = false; } /// <summary> /// Invoked when the user edits the annotation. /// </summary> /// <param name="sender">sender</param> /// <param name="e">KeyEventArgs</param> private void OnTextBoxKeyDown(object pSender, KeyEventArgs pEventArgs) { if (pEventArgs.Key == Key.Enter) { this.IsInEditMode = false; pEventArgs.Handled = true; } else if (pEventArgs.Key == Key.Escape) { this.IsInEditMode = false; // it undo the change done to the text this.Text = this.mOldText; pEventArgs.Handled = true; } } /// <summary> /// Invoked when the user clicks twice. /// </summary> /// <param name="sender">sender</param> /// <param name="pEventArgs">The event arguments.</param> private void OnMouseDoubleClick(object pSender, MouseButtonEventArgs pEventArgs) { if (this.IsEditable && this.IsInEditMode == false) { this.IsInEditMode = true; } } /// <summary> /// Force the update of the formated string into the view when the /// control is not in edit mode. /// </summary> /// <remarks> /// This method is mainly used to refresh the text displayed in the control /// when it is not in the edit mode. /// In this state, the FormatedText property is used to display the text. /// The NotifyPropertyChanged could be used to force the refresh, but it doesn't /// work because the data context is not "this" object. /// The only way to force the refresh is then to force the edit mode and then /// go back to the non edit mode. This way, the FormatedText property is called /// when the corresponding DataTemplate is loaded, and the GUI is refreshed. /// </remarks> private void ForceFormatedTextUpdate() { if (this.IsLoaded && !this.IsInEditMode) { var lBackupIsEditable = this.IsEditable; var lBackupIsInEditMode = this.IsInEditMode; this.IsEditable = true; this.IsInEditMode = true; this.IsInEditMode = false; this.IsEditable = false; this.IsEditable = lBackupIsEditable; this.IsInEditMode = lBackupIsInEditMode; } } #endregion // Methods. } }
/* Copyright (c) Microsoft Corporation 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 THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Diagnostics; namespace Microsoft.Research.DryadLinq { /// <summary> /// The Nullable attribute specifies if a field is nullable. The information is used by DryadLINQ /// serialization. DryadLINQ serialization by default treats all fields not nullable. /// </summary> [AttributeUsage(AttributeTargets.Field|AttributeTargets.Property|AttributeTargets.Class|AttributeTargets.Method, AllowMultiple = false)] public sealed class NullableAttribute : Attribute { private bool m_canBeNull; /// <summary> /// Initializes an instance of NullableAttribute. /// </summary> /// <param name="canBeNull">true iff the target of the attribute is nullable</param> public NullableAttribute(bool canBeNull) { this.m_canBeNull = canBeNull; } /// <summary> /// Determines if the target of this attribute is nullable. /// </summary> public bool CanBeNull { get { return this.m_canBeNull; } } } [AttributeUsage(AttributeTargets.Method|AttributeTargets.Constructor, AllowMultiple = true)] internal sealed class FieldMappingAttribute : Attribute { private string m_source; private string m_destination; public FieldMappingAttribute(string src, string dest) { this.m_source = src; this.m_destination = dest; } public string Source { get { return this.m_source; } } public string Destination { get { return this.m_destination; } } } [AttributeUsage(AttributeTargets.Class|AttributeTargets.Interface, AllowMultiple = false)] internal sealed class AutoTypeInferenceAttribute : Attribute { public AutoTypeInferenceAttribute() { } } [AttributeUsage(AttributeTargets.Method|AttributeTargets.Constructor, AllowMultiple = false)] internal sealed class DistinctAttribute : Attribute { private bool m_mustBeDistinct; private string m_comparer; public DistinctAttribute() { this.m_mustBeDistinct = false; this.m_comparer = null; } public DistinctAttribute(string comparer) { this.m_mustBeDistinct = false; this.m_comparer = comparer; } public bool MustBeDistinct { get { return this.m_mustBeDistinct; } set { this.m_mustBeDistinct = value; } } public object Comparer { get { if (this.m_comparer == null) return null; object val = TypeSystem.GetFieldValue(this.m_comparer); if (val == null) { throw new DryadLinqException(DryadLinqErrorCode.DistinctAttributeComparerNotDefined, String.Format(SR.DistinctAttributeComparerNotDefined, this.m_comparer)); } return val; } } } /// <summary> /// The Resource attribute is used to specify the computation cost of a user defined /// function (UDF). IsStateful asserts that the function is stateful; IsExpensive /// asserts that the function is expensive to compute. The information is useful in /// generating better execution plan. For example, expensive associative aggregation /// functions enables the use of multiple aggregation layers. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public sealed class ResourceAttribute : Attribute { private bool m_isStateful; private bool m_isExpensive; /// <summary> /// Initializes an instance of the Resource attribute. The default value of /// IsStateful is true; the default value of IsExpensive is false. /// </summary> public ResourceAttribute() { this.m_isStateful = true; this.m_isExpensive = false; } /// <summary> /// Gets and sets the IsStateful flag. /// </summary> public bool IsStateful { get { return this.m_isStateful; } set { this.m_isStateful = value; } } /// <summary> /// Gets and sets the IsExpensive flag. /// </summary> public bool IsExpensive { get { return this.m_isExpensive; } set { this.m_isExpensive = value; } } } /// <summary> /// Indicates that a method can be decomposed to multiple methods. The argument to the /// constructor must be of type IDecomposable. The computation of the method annotated /// by this attribute can be decomposed to a sequence of calls to the Seed, Accumulate, /// RecursiveAccumulate methods and a FinalReduce. /// </summary> /// <remarks> /// If a method is decomposable, a user can annotate it with this attribute. This enables /// DryadLINQ to perform a generalized "combiner" optimization. /// </remarks> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public sealed class DecomposableAttribute : Attribute { private Type m_decompositionType; /// <summary> /// Initializes an instance of DecomposableAttribute. The argument is a type that implements /// <see cref="IDecomposable{TSource, TAccumulate, TResult}"/>. /// </summary> /// <param name="decompositionType">A type that implements IDecomposable{TSource, TAccumulate, TResult}</param> public DecomposableAttribute(Type decompositionType) { m_decompositionType = decompositionType; } /// <summary> /// A type that implements IDecomposable{TSource, TAccumulate, TResult} where /// TSource is the element type of the input, TAccumulate is the element type /// of an intermediate dataset, and TResult is the output type of the method /// annotated by this attribute. /// </summary> public Type DecompositionType { get { return m_decompositionType; } } } /// <summary> /// Indicates that a method is an associative aggregation method. The argument to the /// constructor must be of type IAssociative. The computation of the method annotated /// by this attribute can be decomposed to a sequence of calls to the Seed and /// RecursiveAccumulate methods. /// </summary> /// <remarks> /// If a method is associative, a user can annotate it with this attribute. This enables /// DryadLINQ to perform the "combiner" optimization. /// </remarks> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public sealed class AssociativeAttribute : Attribute { private Type m_associativeType; /// <summary> /// Initializes an instance of AssociativeAttribute. The argument is a type that implements /// <see cref="IAssociative{T}"/>. /// </summary> /// <remarks> /// During aggregation, the recursiveAccumulator will be used to aggregate items arising /// from the main aggregation. /// </remarks> /// <param name="associativeType">A type that implements IAssociative{T}, where T /// is the output type of the method annotated by this attribute.</param> public AssociativeAttribute(Type associativeType) { this.m_associativeType = associativeType; } /// <summary> /// A type that implements IAssociative{T} where T is the output type of methods /// that are decorated with this attribute. /// </summary> public Type AssociativeType { get { return this.m_associativeType; } } } /// <summary> /// Provides a user-defined serialization method for a .NET type. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited=false)] public sealed class CustomDryadLinqSerializerAttribute : Attribute { /// <summary> /// Initializes an instance of CustomDryadLinqSerializer attribute. /// </summary> /// <param name="serializerType">A type that implements IDryadLinqSerializer{T}, where T /// is the .NET type to be serialized.</param> public CustomDryadLinqSerializerAttribute(Type serializerType) { this.SerializerType = serializerType; // We need to make sure serializerType implements IDryadLinqSerializer<T> // However we will defer that check until DryadCodeGen.FindCustomSerializerType(), because // 1) we don't have access to <T> here but it's available at code gen time, and // 2) because an exception coming from the attribute ctor leads to an obscure failure. } /// <summary> /// Gets and sets the type object for serialization. /// </summary> public Type SerializerType { get; private set; } } internal static class AttributeSystem { private static Dictionary<Expression, Attribute[]> attribMap = new Dictionary<Expression, Attribute[]>(); internal static void Add(LambdaExpression func, Attribute attrib) { Attribute[] attribs; if (attribMap.TryGetValue(func, out attribs)) { Attribute[] oldAttribs = attribs; attribs = new Attribute[oldAttribs.Length+1]; Array.Copy(oldAttribs, attribs, oldAttribs.Length); attribs[oldAttribs.Length] = attrib; attribMap.Remove(func); } else { attribs = new Attribute[] { attrib }; } attribMap[func] = attribs; } private static Attribute[] Get(LambdaExpression func, Type attribType) { Attribute[] attribs; attribMap.TryGetValue(func, out attribs); if (attribs != null) { ArrayList alist = new ArrayList(); foreach (var x in attribs) { if (x.GetType() == attribType) { alist.Add(x); } } attribs = (Attribute[])alist.ToArray(attribType); } return attribs; } internal static Attribute[] GetAttribs(LambdaExpression func, Type attribType) { Attribute[] attribs1 = AttributeSystem.Get(func, attribType); Attribute[] attribs2 = null; if (func.Body is MethodCallExpression) { MethodCallExpression expr = (MethodCallExpression)func.Body; attribs2 = Attribute.GetCustomAttributes(expr.Method, attribType); } else if (func.Body is NewExpression && ((NewExpression)func.Body).Constructor != null) { NewExpression expr = (NewExpression)func.Body; attribs2 = Attribute.GetCustomAttributes(expr.Constructor, attribType); } else if (func.Body is BinaryExpression) { BinaryExpression expr = (BinaryExpression)func.Body; if (expr.Method != null) { attribs2 = Attribute.GetCustomAttributes(expr.Method, attribType); } } else if (func.Body is InvocationExpression) { InvocationExpression expr = (InvocationExpression)func.Body; if (expr.Expression is LambdaExpression) { attribs2 = GetAttribs((LambdaExpression)expr.Expression, attribType); } } if (attribs1 == null) { return attribs2; } if (attribs2 == null) { return attribs1; } ArrayList alist = new ArrayList(); foreach (var x in attribs1) { alist.Add(x); } foreach (var x in attribs2) { alist.Add(x); } Attribute[] attribs = (Attribute[])alist.ToArray(attribType); return attribs; } internal static Attribute GetAttrib(Expression expr, Type attribType) { Attribute[] attribs = null; if (expr is MethodCallExpression) { attribs = Attribute.GetCustomAttributes(((MethodCallExpression)expr).Method, attribType); } else if (expr is NewExpression && ((NewExpression) expr).Constructor != null) { attribs = Attribute.GetCustomAttributes(((NewExpression)expr).Constructor, attribType); } else if (expr is LambdaExpression) { attribs = GetAttribs((LambdaExpression)expr, attribType); } if (attribs == null || attribs.Length == 0) return null; return attribs[0]; } internal static DecomposableAttribute GetDecomposableAttrib(Expression expr) { return (DecomposableAttribute)GetAttrib(expr, typeof(DecomposableAttribute)); } internal static AssociativeAttribute GetAssociativeAttrib(Expression expr) { return (AssociativeAttribute)GetAttrib(expr, typeof(AssociativeAttribute)); } internal static ResourceAttribute GetResourceAttrib(LambdaExpression func) { return (ResourceAttribute)GetAttrib(func, typeof(ResourceAttribute)); } internal static FieldMappingAttribute[] GetFieldMappingAttribs(LambdaExpression func) { Attribute[] a = GetAttribs(func, typeof(FieldMappingAttribute)); if (a == null || a.Length == 0) return null; return (FieldMappingAttribute[])a; } internal static bool DoAutoTypeInference(DryadLinqContext context, Type type) { if (!StaticConfig.AllowAutoTypeInference) return false; object[] a = type.GetCustomAttributes(typeof(AutoTypeInferenceAttribute), true); return (a.Length != 0); } internal static DistinctAttribute GetDistinctAttrib(LambdaExpression func) { return (DistinctAttribute)GetAttrib(func, typeof(DistinctAttribute)); } internal static bool FieldCanBeNull(FieldInfo finfo) { if (finfo == null || finfo.FieldType.IsValueType) return false; object[] attribs = finfo.GetCustomAttributes(typeof(NullableAttribute), true); if (attribs.Length == 0) { return StaticConfig.AllowNullFields; } return ((NullableAttribute)attribs[0]).CanBeNull; } internal static bool RecordCanBeNull(DryadLinqContext context, Type type) { if (type == null || type.IsValueType) return false; object[] attribs = type.GetCustomAttributes(typeof(NullableAttribute), true); if (attribs.Length == 0) { return StaticConfig.AllowNullRecords; } return ((NullableAttribute)attribs[0]).CanBeNull; } } }
using System; using System.Collections; using System.Text; using NDatabase.Api; using NDatabase.Exceptions; namespace NDatabase.Btree { internal abstract class AbstractBTreeNode : IBTreeNode { /// <summary> /// The BTree owner of this node /// </summary> [NonPersistent] protected IBTree Btree; protected int NbChildren; protected int NbKeys; protected object[] Values; protected IComparable[] Keys; protected int MaxNbChildren; private int _degree; private int _maxNbKeys; protected AbstractBTreeNode(IBTree btree) { BasicInit(btree); } #region IBTreeNode Members public abstract void InsertKeyAndValue(IComparable key, object value); public abstract IBTreeNode GetChildAt(int index, bool throwExceptionIfNotExist); public abstract IBTreeNode GetParent(); public abstract object GetParentId(); public abstract void SetParent(IBTreeNode node); public abstract bool HasParent(); protected abstract void MoveChildFromTo(int sourceIndex, int destinationIndex, bool throwExceptionIfDoesNotExist); /// <summary> /// Creates a new node with the right part of this node. /// </summary> /// <remarks> /// Creates a new node with the right part of this node. This should only be called on a full node /// </remarks> public virtual IBTreeNode ExtractRightPart() { if (!IsFull()) throw new BTreeException("extract right part called on non full node"); // Creates an empty new node var rightPartNode = Btree.BuildNode(); var j = 0; for (var i = _degree; i < _maxNbKeys; i++) { rightPartNode.SetKeyAndValueAt(Keys[i], Values[i], j, false, false); Keys[i] = null; Values[i] = null; rightPartNode.SetChildAt(this, i, j, false); // TODO must we load all nodes to set new parent var bTreeNode = rightPartNode.GetChildAt(j, false); if (bTreeNode != null) bTreeNode.SetParent(rightPartNode); SetNullChildAt(i); j++; } rightPartNode.SetChildAt(this, MaxNbChildren - 1, j, false); // correct father id var c1TreeNode = rightPartNode.GetChildAt(j, false); if (c1TreeNode != null) c1TreeNode.SetParent(rightPartNode); SetNullChildAt(MaxNbChildren - 1); // resets last child Keys[_degree - 1] = null; // resets median element Values[_degree - 1] = null; // set numbers NbKeys = _degree - 1; var originalNbChildren = NbChildren; NbChildren = Math.Min(NbChildren, _degree); rightPartNode.SetNbKeys(_degree - 1); rightPartNode.SetNbChildren(originalNbChildren - NbChildren); BTreeValidator.ValidateNode(this); BTreeValidator.ValidateNode(rightPartNode); BTreeValidator.CheckDuplicateChildren(this, rightPartNode); return rightPartNode; } public virtual IKeyAndValue GetKeyAndValueAt(int index) { if (Keys[index] == null && Values[index] == null) return null; return new KeyAndValue(Keys[index], Values[index]); } public virtual IKeyAndValue GetLastKeyAndValue() { return GetKeyAndValueAt(NbKeys - 1); } public virtual IComparable GetKeyAt(int index) { return Keys[index]; } public virtual IKeyAndValue GetMedian() { var medianPosition = _degree - 1; return GetKeyAndValueAt(medianPosition); } /// <summary> /// Returns the position of the key. /// </summary> /// <remarks> /// Returns the position of the key. If the key does not exist in node, returns the position where this key should be,multiplied by -1 <pre>for example for node of degree 3 : [1 89 452 789 - ], /// calling getPositionOfKey(89) returns 2 (starts with 1) /// calling getPositionOfKey(99) returns -2 (starts with 1),because the position should be done, but it does not exist so multiply by -1 /// this is used to know the child we should descend to!in this case the getChild(2).</pre> /// </remarks> /// <param name="key"> </param> /// <returns> The position of the key,as a negative number if key does not exist, warning, the position starts with 1and not 0! </returns> public virtual int GetPositionOfKey(IComparable key) { var i = 0; while (i < NbKeys) { var result = Keys[i].CompareTo(key); if (result == 0) return i + 1; if (result > 0) return -(i + 1); i++; } return -(i + 1); } public virtual void IncrementNbChildren() { NbChildren++; } public virtual void SetKeyAndValueAt(IComparable key, object value, int index) { Keys[index] = key; Values[index] = value; } public virtual void SetKeyAndValueAt(IKeyAndValue keyAndValue, int index) { SetKeyAndValueAt(keyAndValue.GetKey(), keyAndValue.GetValue(), index); } public virtual void SetKeyAndValueAt(IComparable key, object value, int index, bool shiftIfAlreadyExist, bool incrementNbKeys) { if (shiftIfAlreadyExist && index < NbKeys) RightShiftFrom(index, true); Keys[index] = key; Values[index] = value; if (incrementNbKeys) NbKeys++; } public virtual void SetKeyAndValueAt(IKeyAndValue keyAndValue, int index, bool shiftIfAlreadyExist, bool incrementNbKeys) { SetKeyAndValueAt(keyAndValue.GetKey(), keyAndValue.GetValue(), index, shiftIfAlreadyExist, incrementNbKeys); } public virtual bool IsFull() { return NbKeys == _maxNbKeys; } public virtual bool IsLeaf() { return NbChildren == 0; } /// <summary> /// Can only merge node without intersection =&gt; the greater key of this must be smaller than the smallest key of the node /// </summary> public virtual void MergeWith(IBTreeNode node) { BTreeValidator.ValidateNode(this); BTreeValidator.ValidateNode(node); CheckIfCanMergeWith(node); var j = NbKeys; for (var i = 0; i < node.GetNbKeys(); i++) { SetKeyAndValueAt(node.GetKeyAt(i), node.GetValueAsObjectAt(i), j, false, false); SetChildAt(node, i, j, false); j++; } // in this, we have to take the last child if (node.GetNbChildren() > node.GetNbKeys()) SetChildAt(node, node.GetNbChildren() - 1, j, true); NbKeys += node.GetNbKeys(); NbChildren += node.GetNbChildren(); BTreeValidator.ValidateNode(this); } public virtual int GetNbKeys() { return NbKeys; } public virtual void SetNbChildren(int nbChildren) { NbChildren = nbChildren; } public virtual void SetNbKeys(int nbKeys) { NbKeys = nbKeys; } public virtual int GetDegree() { return _degree; } public virtual int GetNbChildren() { return NbChildren; } public virtual object DeleteKeyForLeafNode(IKeyAndValue keyAndValue) { var position = GetPositionOfKey(keyAndValue.GetKey()); if (position < 0) return null; var realPosition = position - 1; var value = Values[realPosition]; LeftShiftFrom(realPosition, false); NbKeys--; BTreeValidator.ValidateNode(this); return value; } public void DeleteKeyAndValueAt(int keyIndex, bool shiftChildren) { LeftShiftFrom(keyIndex, shiftChildren); NbKeys--; // only decrease child number if child are involved in shifting if (shiftChildren && NbChildren > keyIndex) NbChildren--; } public virtual void SetBTree(IBTree btree) { Btree = btree; } public virtual IBTree GetBTree() { return Btree; } public virtual void Clear() { BasicInit(Btree); } public abstract void DeleteChildAt(int arg1); public abstract object GetChildIdAt(int arg1, bool arg2); public abstract object GetId(); public abstract object GetValueAsObjectAt(int arg1); public abstract void SetChildAt(IBTreeNode arg1, int arg2, int arg3, bool arg4); public abstract void SetChildAt(IBTreeNode arg1, int arg2); public abstract void SetId(object arg1); protected abstract void SetNullChildAt(int arg1); #endregion private void BasicInit(IBTree btree) { Btree = btree; _degree = btree.GetDegree(); _maxNbKeys = 2 * _degree - 1; MaxNbChildren = 2 * _degree; Keys = new IComparable[_maxNbKeys]; Values = new object[_maxNbKeys]; NbKeys = 0; NbChildren = 0; Init(); } protected abstract void Init(); protected void RightShiftFrom(int position, bool shiftChildren) { if (IsFull()) throw new BTreeException("Node is full, can't right shift!"); // Shift keys for (var i = NbKeys; i > position; i--) { Keys[i] = Keys[i - 1]; Values[i] = Values[i - 1]; } Keys[position] = null; Values[position] = null; // Shift children if (!shiftChildren) return; for (var i = NbChildren; i > position; i--) MoveChildFromTo(i - 1, i, true); // setChildAt(getChildAt(i-1,true),i); SetNullChildAt(position); } protected void LeftShiftFrom(int position, bool shiftChildren) { for (var i = position; i < NbKeys - 1; i++) { Keys[i] = Keys[i + 1]; Values[i] = Values[i + 1]; if (shiftChildren) MoveChildFromTo(i + 1, i, false); } // setChildAt(getChildAt(i+1,false), i); Keys[NbKeys - 1] = null; Values[NbKeys - 1] = null; if (!shiftChildren) return; MoveChildFromTo(NbKeys, NbKeys - 1, false); // setChildAt(getChildAt(nbKeys,false), nbKeys-1); SetNullChildAt(NbKeys); } private void CheckIfCanMergeWith(IBTreeNode node) { if (NbKeys + node.GetNbKeys() > _maxNbKeys) { var errorMessage = string.Concat("Trying to merge two nodes with too many keys ", NbKeys.ToString(), " + ", node.GetNbKeys().ToString(), " > ", _maxNbKeys.ToString()); throw new BTreeException(errorMessage); } if (NbKeys > 0) { var greatestOfThis = Keys[NbKeys - 1]; var smallestOfOther = node.GetKeyAt(0); if (greatestOfThis.CompareTo(smallestOfOther) >= 0) { var errorMessage = string.Format("Trying to merge two nodes that have intersections : {0} / {1}", ToString(), node); throw new BTreeNodeValidationException(errorMessage); } } if (NbKeys < NbChildren) throw new BTreeNodeValidationException("Trying to merge two nodes where the first one has more children than keys"); } public override string ToString() { var buffer = new StringBuilder(); buffer.Append("id=").Append(GetId()).Append(" {keys(").Append(NbKeys).Append(")=("); for (var i = 0; i < NbKeys; i++) { if (i > 0) buffer.Append(","); var value = BuildValueRepresentation(Values[i]); buffer.Append("[").Append(Keys[i]).Append("/").Append(value).Append("]"); } buffer.Append("), child(").Append(NbChildren).Append(")}"); return buffer.ToString(); } private static string BuildValueRepresentation(object o) { var result = new StringBuilder(); if (o is IList) { foreach (var item in (IList)o) result.AppendFormat("{0},", item); result = result.Remove(result.Length - 1, 1); } else { result.Append(o); } return result.ToString(); } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Data; namespace DotSpatial.Data { /// <summary> /// This represents the column information for one column of a shapefile. /// This specifies precision as well as the typical column information. /// </summary> public class Field : DataColumn { #region Properties /// <summary> /// Initializes a new instance of the <see cref="Field"/> class that is empty. /// This is needed for datatable copy and clone methods. /// </summary> public Field() { } /// <summary> /// Initializes a new instance of the <see cref="Field"/> class. /// Creates a new default field given the specified DataColumn. Numeric types /// default to a size of 255, but will be shortened during the save opperation. /// The default decimal count for double and long is 0, for Currency is 2, for float is /// 3, and for double is 8. These can be changed by changing the DecimalCount property. /// </summary> /// <param name="inColumn">A System.Data.DataColumn to create a Field from.</param> public Field(DataColumn inColumn) : base(inColumn.ColumnName, inColumn.DataType, inColumn.Expression, inColumn.ColumnMapping) { SetupDecimalCount(); if (inColumn.DataType == typeof(string)) { Length = inColumn.MaxLength <= 254 ? (byte)inColumn.MaxLength : (byte)254; } else if (inColumn.DataType == typeof(DateTime)) { Length = 8; } else if (inColumn.DataType == typeof(bool)) { Length = 1; } } /// <summary> /// Initializes a new instance of the <see cref="Field"/> class, as type string, using the specified column name. /// </summary> /// <param name="inColumnName">The string name of the column.</param> public Field(string inColumnName) : base(inColumnName) { // can't setup decimal count without a data type } /// <summary> /// Initializes a new instance of the <see cref="Field"/> class with a specific name for a specified data type. /// </summary> /// <param name="inColumnName">The string name of the column.</param> /// <param name="inDataType">The System.Type describing the datatype of the field.</param> public Field(string inColumnName, Type inDataType) : base(inColumnName, inDataType) { SetupDecimalCount(); } /// <summary> /// Initializes a new instance of the <see cref="Field"/> class with a specific name and using a simplified enumeration of possible types. /// </summary> /// <param name="inColumnName">The string name of the column.</param> /// <param name="type">The type enumeration that clarifies which basic data type to use.</param> public Field(string inColumnName, FieldDataType type) : base(inColumnName) { if (type == FieldDataType.Double) DataType = typeof(double); if (type == FieldDataType.Integer) DataType = typeof(int); if (type == FieldDataType.String) DataType = typeof(string); } /* * Field Types Specified by the dBASE Format Specifications * * http://www.dbase.com/Knowledgebase/INT/db7_file_fmt.htm * * Symbol | Data Type | Description * -------+--------------+------------------------------------------------------------------------------------- * B | Binary | 10 digits representing a .DBT block number. The number is stored as a string, right justified and padded with blanks. * C | Character | All OEM code page characters - padded with blanks to the width of the field. * D | Date | 8 bytes - date stored as a string in the format YYYYMMDD. * N | Numeric | Number stored as a string, right justified, and padded with blanks to the width of the field. * L | Logical | 1 byte - initialized to 0x20 (space) otherwise T or F. * M | Memo | 10 digits (bytes) representing a .DBT block number. The number is stored as a string, right justified and padded with blanks. * @ | Timestamp | 8 bytes - two longs, first for date, second for time. The date is the number of days since 01/01/4713 BC. Time is hours * 3600000L + minutes * 60000L + Seconds * 1000L * I | Long | 4 bytes. Leftmost bit used to indicate sign, 0 negative. * + |Autoincrement | Same as a Long * F | Float | Number stored as a string, right justified, and padded with blanks to the width of the field. * O | Double | 8 bytes - no conversions, stored as a double. * G | OLE | 10 digits (bytes) representing a .DBT block number. The number is stored as a string, right justified and padded with blanks. */ /// <summary> /// Initializes a new instance of the <see cref="Field"/> class. /// </summary> /// <param name="columnName">The string name of the column.</param> /// <param name="typeCode">A code specified by the dBASE Format Specifications that indicates what type should be used.</param> /// <param name="length">The character length of the field.</param> /// <param name="decimalCount">Represents the number of decimals to preserve after a 0.</param> public Field(string columnName, char typeCode, byte length, byte decimalCount) : base(columnName) { Length = length; ColumnName = columnName; DecimalCount = decimalCount; // Date or Timestamp if (typeCode == 'D' || typeCode == '@') { // date DataType = typeof(DateTime); return; } if (typeCode == 'L') { DataType = typeof(bool); return; } // Long or AutoIncrement if (typeCode == 'I' || typeCode == '+') { DataType = typeof(int); return; } if (typeCode == 'O') { DataType = typeof(double); return; } if (typeCode == 'N' || typeCode == 'B' || typeCode == 'M' || typeCode == 'F' || typeCode == 'G') { // The strategy here is to assign the smallest type that we KNOW will be large enough // to hold any value with the length (in digits) and characters. // even though double can hold as high a value as a "Number" can go, it can't // preserve the extraordinary 255 digit precision that a Number has. The strategy // is to assess the length in characters and assign a numeric type where no // value may exist outside the range. (They can always change the datatype later.) // The basic encoding we are using here if (decimalCount == 0) { if (length < 3) { // 0 to 255 DataType = typeof(byte); return; } if (length < 5) { // -32768 to 32767 DataType = typeof(short); // Int16 return; } if (length < 10) { // -2147483648 to 2147483647 DataType = typeof(int); // Int32 return; } if (length < 19) { // -9223372036854775808 to -9223372036854775807 DataType = typeof(long); // Int64 return; } } if (decimalCount > 15) { // we know this has too many significant digits to fit in a double: // a double can hold 15-16 significant digits: https://msdn.microsoft.com/en-us/library/678hzkk9.aspx DataType = typeof(string); MaxLength = length; return; } // Singles -3.402823E+38 to 3.402823E+38 // Doubles -1.79769313486232E+308 to 1.79769313486232E+308 // Decimals -79228162514264337593543950335 to 79228162514264337593543950335 // Doubles have the range to handle any number with the 255 character size, // but won't preserve the precision that is possible. It is still // preferable to have a numeric type in 99% of cases, and double is the easiest. DataType = typeof(double); return; } // Type code is either C or not recognized, in which case we will just end up with a string // representation of whatever the characters are. DataType = typeof(string); MaxLength = length; } /// <summary> /// Gets the single character dBase code. Only some of these are supported with Esri. /// The possible values are defined in FieldTypeCharacters. /// </summary> public char TypeCharacter => FieldTypeCharacterMapperManager.Mapper.Map(DataType); /// <summary> /// Gets or sets the number of places to keep after the 0 in number formats. /// As far as dbf fields are concerned, all numeric datatypes use the same database number format. /// </summary> public byte DecimalCount { get; set; } /// <summary> /// Gets or sets the length of the field in bytes. /// </summary> public byte Length { get; set; } /// <summary> /// Gets or sets the offset of the field on a row in the file. /// </summary> public int DataAddress { get; set; } /// <summary> /// Gets or sets the Number Converter associated with this field. /// </summary> public NumberConverter NumberConverter { get; set; } /// <summary> /// Internal method that decides an appropriate decimal count, given a data column. /// </summary> private void SetupDecimalCount() { // Going this way, we want a large enough decimal count to hold any of the possible numeric values. // We will try to make the length large enough to hold any values, but some doubles simply will be // too large to be stored in this format, so we will throw exceptions if that happens later. // These sizes represent the "maximized" length and decimal counts that will be shrunk in order // to fit the data before saving. if (DataType == typeof(float)) { //// _decimalCount = (byte)40; // Singles -3.402823E+38 to 3.402823E+38 //// _length = (byte)40; Length = 18; DecimalCount = 6; return; } if (DataType == typeof(double)) { //// _decimalCount = (byte)255; // Doubles -1.79769313486232E+308 to 1.79769313486232E+308 //// _length = (byte)255; Length = 18; DecimalCount = 9; return; } if (DataType == typeof(decimal)) { Length = 18; DecimalCount = 9; // Decimals -79228162514264337593543950335 to 79228162514264337593543950335 return; } if (DataType == typeof(byte)) { // 0 to 255 DecimalCount = 0; Length = 3; return; } if (DataType == typeof(short)) { // -32768 to 32767 Length = 6; DecimalCount = 0; return; } if (DataType == typeof(int)) { // -2147483648 to 2147483647 Length = 11; DecimalCount = 0; return; } if (DataType == typeof(long)) { // -9223372036854775808 to -9223372036854775807 Length = 20; DecimalCount = 0; } } #endregion } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.Runtime { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Threading; using Microsoft.Win32; static class Fx { const string defaultEventSource = "System.Runtime"; #if DEBUG const string WinFXRegistryKey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP"; const string WcfRegistryKey = WinFXRegistryKey + @"\CDF\v4.0\Debug"; const string AssertsFailFastName = "AssertsFailFast"; const string BreakOnExceptionTypesName = "BreakOnExceptionTypes"; const string FastDebugName = "FastDebug"; const string StealthDebuggerName = "StealthDebugger"; static bool breakOnExceptionTypesRetrieved; static Type[] breakOnExceptionTypesCache; static bool fastDebugRetrieved; static bool fastDebugCache; static bool stealthDebuggerRetrieved; static bool stealthDebuggerCache; #endif static ExceptionTrace exceptionTrace; static EtwDiagnosticTrace diagnosticTrace; [Fx.Tag.SecurityNote(Critical = "This delegate is called from within a ConstrainedExecutionRegion, must not be settable from PT code")] [SecurityCritical] static ExceptionHandler asynchronousThreadExceptionHandler; public static ExceptionTrace Exception { get { if (exceptionTrace == null) { // don't need a lock here since a true singleton is not required exceptionTrace = new ExceptionTrace(defaultEventSource, Trace); } return exceptionTrace; } } public static EtwDiagnosticTrace Trace { get { if (diagnosticTrace == null) { diagnosticTrace = InitializeTracing(); } return diagnosticTrace; } } [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical field EtwProvider", Safe = "Doesn't leak info\\resources")] [SecuritySafeCritical] [SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.UseNewGuidHelperRule, Justification = "This is a method that creates ETW provider passing Guid Provider ID.")] static EtwDiagnosticTrace InitializeTracing() { EtwDiagnosticTrace trace = new EtwDiagnosticTrace(defaultEventSource, EtwDiagnosticTrace.DefaultEtwProviderId); if (null != trace.EtwProvider) { trace.RefreshState += delegate() { Fx.UpdateLevel(); }; } Fx.UpdateLevel(trace); return trace; } public static ExceptionHandler AsynchronousThreadExceptionHandler { [Fx.Tag.SecurityNote(Critical = "access critical field", Safe = "ok for get-only access")] [SecuritySafeCritical] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] get { return Fx.asynchronousThreadExceptionHandler; } [Fx.Tag.SecurityNote(Critical = "sets a critical field")] [SecurityCritical] set { Fx.asynchronousThreadExceptionHandler = value; } } // Do not call the parameter "message" or else FxCop thinks it should be localized. [Conditional("DEBUG")] public static void Assert(bool condition, string description) { if (!condition) { Assert(description); } } [Conditional("DEBUG")] public static void Assert(string description) { AssertHelper.FireAssert(description); } public static void AssertAndThrow(bool condition, string description) { if (!condition) { AssertAndThrow(description); } } [MethodImpl(MethodImplOptions.NoInlining)] public static Exception AssertAndThrow(string description) { Fx.Assert(description); TraceCore.ShipAssertExceptionMessage(Trace, description); throw new InternalException(description); } public static void AssertAndThrowFatal(bool condition, string description) { if (!condition) { AssertAndThrowFatal(description); } } [MethodImpl(MethodImplOptions.NoInlining)] public static Exception AssertAndThrowFatal(string description) { Fx.Assert(description); TraceCore.ShipAssertExceptionMessage(Trace, description); throw new FatalInternalException(description); } public static void AssertAndFailFast(bool condition, string description) { if (!condition) { AssertAndFailFast(description); } } // This never returns. The Exception return type lets you write 'throw AssertAndFailFast()' which tells the compiler/tools that // execution stops. [Fx.Tag.SecurityNote(Critical = "Calls into critical method Environment.FailFast", Safe = "The side affect of the app crashing is actually intended here")] [SecuritySafeCritical] [MethodImpl(MethodImplOptions.NoInlining)] public static Exception AssertAndFailFast(string description) { Fx.Assert(description); string failFastMessage = InternalSR.FailFastMessage(description); // The catch is here to force the finally to run, as finallys don't run until the stack walk gets to a catch. // The catch makes sure that the finally will run before the stack-walk leaves the frame, but the code inside is impossible to reach. try { try { Fx.Exception.TraceFailFast(failFastMessage); } finally { Environment.FailFast(failFastMessage); } } catch { throw; } return null; // we'll never get here since we've just fail-fasted } public static bool IsFatal(Exception exception) { while (exception != null) { if (exception is FatalException || (exception is OutOfMemoryException && !(exception is InsufficientMemoryException)) || exception is ThreadAbortException || exception is FatalInternalException) { return true; } // These exceptions aren't themselves fatal, but since the CLR uses them to wrap other exceptions, // we want to check to see whether they've been used to wrap a fatal exception. If so, then they // count as fatal. if (exception is TypeInitializationException || exception is TargetInvocationException) { exception = exception.InnerException; } else if (exception is AggregateException) { // AggregateExceptions have a collection of inner exceptions, which may themselves be other // wrapping exceptions (including nested AggregateExceptions). Recursively walk this // hierarchy. The (singular) InnerException is included in the collection. ReadOnlyCollection<Exception> innerExceptions = ((AggregateException)exception).InnerExceptions; foreach (Exception innerException in innerExceptions) { if (IsFatal(innerException)) { return true; } } break; } else { break; } } return false; } // This method should be only used for debug build. internal static bool AssertsFailFast { get { #if DEBUG object value; return TryGetDebugSwitch(Fx.AssertsFailFastName, out value) && typeof(int).IsAssignableFrom(value.GetType()) && ((int)value) != 0; #else return false; #endif } } // This property should be only used for debug build. internal static Type[] BreakOnExceptionTypes { get { #if DEBUG if (!Fx.breakOnExceptionTypesRetrieved) { object value; if (TryGetDebugSwitch(Fx.BreakOnExceptionTypesName, out value)) { string[] typeNames = value as string[]; if (typeNames != null && typeNames.Length > 0) { List<Type> types = new List<Type>(typeNames.Length); for (int i = 0; i < typeNames.Length; i++) { types.Add(Type.GetType(typeNames[i], false)); } if (types.Count != 0) { Fx.breakOnExceptionTypesCache = types.ToArray(); } } } Fx.breakOnExceptionTypesRetrieved = true; } return Fx.breakOnExceptionTypesCache; #else return null; #endif } } // This property should be only used for debug build. internal static bool FastDebug { get { #if DEBUG if (!Fx.fastDebugRetrieved) { object value; if (TryGetDebugSwitch(Fx.FastDebugName, out value)) { Fx.fastDebugCache = typeof(int).IsAssignableFrom(value.GetType()) && ((int)value) != 0; } Fx.fastDebugRetrieved = true; } return Fx.fastDebugCache; #else return false; #endif } } // This property should be only used for debug build. internal static bool StealthDebugger { get { #if DEBUG if (!Fx.stealthDebuggerRetrieved) { object value; if (TryGetDebugSwitch(Fx.StealthDebuggerName, out value)) { Fx.stealthDebuggerCache = typeof(int).IsAssignableFrom(value.GetType()) && ((int)value) != 0; } Fx.stealthDebuggerRetrieved = true; } return Fx.stealthDebuggerCache; #else return false; #endif } } #if DEBUG static bool TryGetDebugSwitch(string name, out object value) { value = null; try { RegistryKey key = Registry.LocalMachine.OpenSubKey(Fx.WcfRegistryKey); if (key != null) { using (key) { value = key.GetValue(name); } } } catch (SecurityException) { // This debug-only code shouldn't trace. } return value != null; } #endif public static Action<T1> ThunkCallback<T1>(Action<T1> callback) { return (new ActionThunk<T1>(callback)).ThunkFrame; } public static AsyncCallback ThunkCallback(AsyncCallback callback) { return (new AsyncThunk(callback)).ThunkFrame; } public static WaitCallback ThunkCallback(WaitCallback callback) { return (new WaitThunk(callback)).ThunkFrame; } public static TimerCallback ThunkCallback(TimerCallback callback) { return (new TimerThunk(callback)).ThunkFrame; } public static WaitOrTimerCallback ThunkCallback(WaitOrTimerCallback callback) { return (new WaitOrTimerThunk(callback)).ThunkFrame; } public static SendOrPostCallback ThunkCallback(SendOrPostCallback callback) { return (new SendOrPostThunk(callback)).ThunkFrame; } [Fx.Tag.SecurityNote(Critical = "Construct the unsafe object IOCompletionThunk")] [SecurityCritical] public static IOCompletionCallback ThunkCallback(IOCompletionCallback callback) { return (new IOCompletionThunk(callback)).ThunkFrame; } [SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.UseNewGuidHelperRule, Justification = "These are the core methods that should be used for all other Guid(string) calls.")] public static Guid CreateGuid(string guidString) { bool success = false; Guid result = Guid.Empty; try { result = new Guid(guidString); success = true; } finally { if (!success) { AssertAndThrow("Creation of the Guid failed."); } } return result; } [SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.UseNewGuidHelperRule, Justification = "These are the core methods that should be used for all other Guid(string) calls.")] public static bool TryCreateGuid(string guidString, out Guid result) { bool success = false; result = Guid.Empty; try { result = new Guid(guidString); success = true; } catch (ArgumentException) { // ---- this } catch (FormatException) { // ---- this } catch (OverflowException) { // ---- this } return success; } public static byte[] AllocateByteArray(int size) { try { // Safe to catch OOM from this as long as the ONLY thing it does is a simple allocation of a primitive type (no method calls). return new byte[size]; } catch (OutOfMemoryException exception) { // Convert OOM into an exception that can be safely handled by higher layers. throw Fx.Exception.AsError( new InsufficientMemoryException(InternalSR.BufferAllocationFailed(size), exception)); } } public static char[] AllocateCharArray(int size) { try { // Safe to catch OOM from this as long as the ONLY thing it does is a simple allocation of a primitive type (no method calls). return new char[size]; } catch (OutOfMemoryException exception) { // Convert OOM into an exception that can be safely handled by higher layers. throw Fx.Exception.AsError( new InsufficientMemoryException(InternalSR.BufferAllocationFailed(size * sizeof(char)), exception)); } } [SuppressMessage(FxCop.Category.Design, FxCop.Rule.DoNotCatchGeneralExceptionTypes, Justification = "Don't want to hide the exception which is about to crash the process.")] [Fx.Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] static void TraceExceptionNoThrow(Exception exception) { try { // This call exits the CER. However, when still inside a catch, normal ThreadAbort is prevented. // Rude ThreadAbort will still be allowed to terminate processing. Fx.Exception.TraceUnhandledException(exception); } catch { // This empty catch is only acceptable because we are a) in a CER and b) processing an exception // which is about to crash the process anyway. } } [SuppressMessage(FxCop.Category.Design, FxCop.Rule.DoNotCatchGeneralExceptionTypes, Justification = "Don't want to hide the exception which is about to crash the process.")] [SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.IsFatalRule, Justification = "Don't want to hide the exception which is about to crash the process.")] [Fx.Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] static bool HandleAtThreadBase(Exception exception) { // This area is too sensitive to do anything but return. if (exception == null) { Fx.Assert("Null exception in HandleAtThreadBase."); return false; } TraceExceptionNoThrow(exception); try { ExceptionHandler handler = Fx.AsynchronousThreadExceptionHandler; return handler == null ? false : handler.HandleException(exception); } catch (Exception secondException) { // Don't let a new exception hide the original exception. TraceExceptionNoThrow(secondException); } return false; } static void UpdateLevel(EtwDiagnosticTrace trace) { if (trace == null) { return; } if (TraceCore.ActionItemCallbackInvokedIsEnabled(trace) || TraceCore.ActionItemScheduledIsEnabled(trace)) { trace.SetEnd2EndActivityTracingEnabled(true); } } static void UpdateLevel() { UpdateLevel(Fx.Trace); } public abstract class ExceptionHandler { [Fx.Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")] public abstract bool HandleException(Exception exception); } public static class Tag { public enum CacheAttrition { None, ElementOnTimer, // A finalizer/WeakReference based cache, where the elements are held by WeakReferences (or hold an // inner object by a WeakReference), and the weakly-referenced object has a finalizer which cleans the // item from the cache. ElementOnGC, // A cache that provides a per-element token, delegate, interface, or other piece of context that can // be used to remove the element (such as IDisposable). ElementOnCallback, FullPurgeOnTimer, FullPurgeOnEachAccess, PartialPurgeOnTimer, PartialPurgeOnEachAccess, } public enum ThrottleAction { Reject, Pause, } public enum ThrottleMetric { Count, Rate, Other, } public enum Location { InProcess, OutOfProcess, LocalSystem, LocalOrRemoteSystem, // as in a file that might live on a share RemoteSystem, } public enum SynchronizationKind { LockStatement, MonitorWait, MonitorExplicit, InterlockedNoSpin, InterlockedWithSpin, // Same as LockStatement if the field type is object. FromFieldType, } [Flags] public enum BlocksUsing { MonitorEnter, MonitorWait, ManualResetEvent, AutoResetEvent, AsyncResult, IAsyncResult, PInvoke, InputQueue, ThreadNeutralSemaphore, PrivatePrimitive, OtherInternalPrimitive, OtherFrameworkPrimitive, OtherInterop, Other, NonBlocking, // For use by non-blocking SynchronizationPrimitives such as IOThreadScheduler } public static class Strings { internal const string ExternallyManaged = "externally managed"; internal const string AppDomain = "AppDomain"; internal const string DeclaringInstance = "instance of declaring class"; internal const string Unbounded = "unbounded"; internal const string Infinite = "infinite"; } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property | AttributeTargets.Class, AllowMultiple = true, Inherited = false)] [Conditional("DEBUG")] public sealed class FriendAccessAllowedAttribute : Attribute { public FriendAccessAllowedAttribute(string assemblyName) : base() { this.AssemblyName = assemblyName; } public string AssemblyName { get; set; } } public static class Throws { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = true, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class TimeoutAttribute : ThrowsAttribute { public TimeoutAttribute() : this("The operation timed out.") { } public TimeoutAttribute(string diagnosis) : base(typeof(TimeoutException), diagnosis) { } } } [AttributeUsage(AttributeTargets.Field)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class CacheAttribute : Attribute { readonly Type elementType; readonly CacheAttrition cacheAttrition; public CacheAttribute(Type elementType, CacheAttrition cacheAttrition) { Scope = Strings.DeclaringInstance; SizeLimit = Strings.Unbounded; Timeout = Strings.Infinite; if (elementType == null) { throw Fx.Exception.ArgumentNull("elementType"); } this.elementType = elementType; this.cacheAttrition = cacheAttrition; } public Type ElementType { get { return this.elementType; } } public CacheAttrition CacheAttrition { get { return this.cacheAttrition; } } public string Scope { get; set; } public string SizeLimit { get; set; } public string Timeout { get; set; } } [AttributeUsage(AttributeTargets.Field)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class QueueAttribute : Attribute { readonly Type elementType; public QueueAttribute(Type elementType) { Scope = Strings.DeclaringInstance; SizeLimit = Strings.Unbounded; if (elementType == null) { throw Fx.Exception.ArgumentNull("elementType"); } this.elementType = elementType; } public Type ElementType { get { return this.elementType; } } public string Scope { get; set; } public string SizeLimit { get; set; } public bool StaleElementsRemovedImmediately { get; set; } public bool EnqueueThrowsIfFull { get; set; } } [AttributeUsage(AttributeTargets.Field)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class ThrottleAttribute : Attribute { readonly ThrottleAction throttleAction; readonly ThrottleMetric throttleMetric; readonly string limit; public ThrottleAttribute(ThrottleAction throttleAction, ThrottleMetric throttleMetric, string limit) { Scope = Strings.AppDomain; if (string.IsNullOrEmpty(limit)) { throw Fx.Exception.ArgumentNullOrEmpty("limit"); } this.throttleAction = throttleAction; this.throttleMetric = throttleMetric; this.limit = limit; } public ThrottleAction ThrottleAction { get { return this.throttleAction; } } public ThrottleMetric ThrottleMetric { get { return this.throttleMetric; } } public string Limit { get { return this.limit; } } public string Scope { get; set; } } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = true, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class ExternalResourceAttribute : Attribute { readonly Location location; readonly string description; public ExternalResourceAttribute(Location location, string description) { this.location = location; this.description = description; } public Location Location { get { return this.location; } } public string Description { get { return this.description; } } } // Set on a class when that class uses lock (this) - acts as though it were on a field // private object this; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Class, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class SynchronizationObjectAttribute : Attribute { public SynchronizationObjectAttribute() { Blocking = true; Scope = Strings.DeclaringInstance; Kind = SynchronizationKind.FromFieldType; } public bool Blocking { get; set; } public string Scope { get; set; } public SynchronizationKind Kind { get; set; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = true)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class SynchronizationPrimitiveAttribute : Attribute { readonly BlocksUsing blocksUsing; public SynchronizationPrimitiveAttribute(BlocksUsing blocksUsing) { this.blocksUsing = blocksUsing; } public BlocksUsing BlocksUsing { get { return this.blocksUsing; } } public bool SupportsAsync { get; set; } public bool Spins { get; set; } public string ReleaseMethod { get; set; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class BlockingAttribute : Attribute { public BlockingAttribute() { } public string CancelMethod { get; set; } public Type CancelDeclaringType { get; set; } public string Conditional { get; set; } } // Sometime a method will call a conditionally-blocking method in such a way that it is guaranteed // not to block (i.e. the condition can be Asserted false). Such a method can be marked as // GuaranteeNonBlocking as an assertion that the method doesn't block despite calling a blocking method. // // Methods that don't call blocking methods and aren't marked as Blocking are assumed not to block, so // they do not require this attribute. [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class GuaranteeNonBlockingAttribute : Attribute { public GuaranteeNonBlockingAttribute() { } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class NonThrowingAttribute : Attribute { public NonThrowingAttribute() { } } [SuppressMessage(FxCop.Category.Performance, "CA1813:AvoidUnsealedAttributes", Justification = "This is intended to be an attribute heirarchy. It does not affect product perf.")] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = true, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public class ThrowsAttribute : Attribute { readonly Type exceptionType; readonly string diagnosis; public ThrowsAttribute(Type exceptionType, string diagnosis) { if (exceptionType == null) { throw Fx.Exception.ArgumentNull("exceptionType"); } if (string.IsNullOrEmpty(diagnosis)) { throw Fx.Exception.ArgumentNullOrEmpty("diagnosis"); } this.exceptionType = exceptionType; this.diagnosis = diagnosis; } public Type ExceptionType { get { return this.exceptionType; } } public string Diagnosis { get { return this.diagnosis; } } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class InheritThrowsAttribute : Attribute { public InheritThrowsAttribute() { } public Type FromDeclaringType { get; set; } public string From { get; set; } } [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class KnownXamlExternalAttribute : Attribute { public KnownXamlExternalAttribute() { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class XamlVisibleAttribute : Attribute { public XamlVisibleAttribute() : this(true) { } public XamlVisibleAttribute(bool visible) { this.Visible = visible; } public bool Visible { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class SecurityNoteAttribute : Attribute { public SecurityNoteAttribute() { } public string Critical { get; set; } public string Safe { get; set; } public string Miscellaneous { get; set; } } } abstract class Thunk<T> where T : class { [Fx.Tag.SecurityNote(Critical = "Make these safe to use in SecurityCritical contexts.")] [SecurityCritical] T callback; [Fx.Tag.SecurityNote(Critical = "Accesses critical field.", Safe = "Data provided by caller.")] [SecuritySafeCritical] protected Thunk(T callback) { this.callback = callback; } internal T Callback { [Fx.Tag.SecurityNote(Critical = "Accesses critical field.", Safe = "Data is not privileged.")] [SecuritySafeCritical] get { return this.callback; } } } sealed class ActionThunk<T1> : Thunk<Action<T1>> { public ActionThunk(Action<T1> callback) : base(callback) { } public Action<T1> ThunkFrame { get { return new Action<T1>(UnhandledExceptionFrame); } } [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Guaranteed not to call into PT user code from the finally.")] [SecuritySafeCritical] void UnhandledExceptionFrame(T1 result) { RuntimeHelpers.PrepareConstrainedRegions(); try { Callback(result); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } sealed class AsyncThunk : Thunk<AsyncCallback> { public AsyncThunk(AsyncCallback callback) : base(callback) { } public AsyncCallback ThunkFrame { get { return new AsyncCallback(UnhandledExceptionFrame); } } [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Guaranteed not to call into PT user code from the finally.")] [SecuritySafeCritical] void UnhandledExceptionFrame(IAsyncResult result) { RuntimeHelpers.PrepareConstrainedRegions(); try { Callback(result); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } sealed class WaitThunk : Thunk<WaitCallback> { public WaitThunk(WaitCallback callback) : base(callback) { } public WaitCallback ThunkFrame { get { return new WaitCallback(UnhandledExceptionFrame); } } [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Guaranteed not to call into PT user code from the finally.")] [SecuritySafeCritical] void UnhandledExceptionFrame(object state) { RuntimeHelpers.PrepareConstrainedRegions(); try { Callback(state); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } sealed class TimerThunk : Thunk<TimerCallback> { public TimerThunk(TimerCallback callback) : base(callback) { } public TimerCallback ThunkFrame { get { return new TimerCallback(UnhandledExceptionFrame); } } [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Guaranteed not to call into PT user code from the finally.")] [SecuritySafeCritical] void UnhandledExceptionFrame(object state) { RuntimeHelpers.PrepareConstrainedRegions(); try { Callback(state); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } sealed class WaitOrTimerThunk : Thunk<WaitOrTimerCallback> { public WaitOrTimerThunk(WaitOrTimerCallback callback) : base(callback) { } public WaitOrTimerCallback ThunkFrame { get { return new WaitOrTimerCallback(UnhandledExceptionFrame); } } [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Guaranteed not to call into PT user code from the finally.")] [SecuritySafeCritical] void UnhandledExceptionFrame(object state, bool timedOut) { RuntimeHelpers.PrepareConstrainedRegions(); try { Callback(state, timedOut); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } sealed class SendOrPostThunk : Thunk<SendOrPostCallback> { public SendOrPostThunk(SendOrPostCallback callback) : base(callback) { } public SendOrPostCallback ThunkFrame { get { return new SendOrPostCallback(UnhandledExceptionFrame); } } [Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Guaranteed not to call into PT user code from the finally.")] [SecuritySafeCritical] void UnhandledExceptionFrame(object state) { RuntimeHelpers.PrepareConstrainedRegions(); try { Callback(state); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } // This can't derive from Thunk since T would be unsafe. [Fx.Tag.SecurityNote(Critical = "unsafe object")] [SecurityCritical] unsafe sealed class IOCompletionThunk { [Fx.Tag.SecurityNote(Critical = "Make these safe to use in SecurityCritical contexts.")] IOCompletionCallback callback; [Fx.Tag.SecurityNote(Critical = "Accesses critical field.", Safe = "Data provided by caller.")] public IOCompletionThunk(IOCompletionCallback callback) { this.callback = callback; } public IOCompletionCallback ThunkFrame { [Fx.Tag.SecurityNote(Safe = "returns a delegate around the safe method UnhandledExceptionFrame")] get { return new IOCompletionCallback(UnhandledExceptionFrame); } } [Fx.Tag.SecurityNote(Critical = "Accesses critical field, calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Delegates can be invoked, guaranteed not to call into PT user code from the finally.")] void UnhandledExceptionFrame(uint error, uint bytesRead, NativeOverlapped* nativeOverlapped) { RuntimeHelpers.PrepareConstrainedRegions(); try { this.callback(error, bytesRead, nativeOverlapped); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } [Serializable] class InternalException : SystemException { public InternalException(string description) : base(InternalSR.ShipAssertExceptionMessage(description)) { } protected InternalException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] class FatalInternalException : InternalException { public FatalInternalException(string description) : base(description) { } protected FatalInternalException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // 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 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Threading; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Interpreter.Default; using Microsoft.PythonTools.Parsing; namespace Microsoft.PythonTools.Interpreter { /// <summary> /// Base class for interpreter factories that have an executable file /// following CPython command-line conventions, a standard library that is /// stored on disk as .py files, and using <see cref="PythonTypeDatabase"/> /// for the completion database. /// </summary> public class PythonInterpreterFactoryWithDatabase : IPythonInterpreterFactoryWithDatabase2, IDisposable { private readonly InterpreterConfiguration _config; private PythonTypeDatabase _typeDb, _typeDbWithoutPackages; private bool _generating, _isValid, _isCheckingDatabase, _disposed; private string[] _missingModules; private string _isCurrentException; private readonly Timer _refreshIsCurrentTrigger; private FileSystemWatcher _libWatcher; private readonly object _libWatcherLock = new object(); private FileSystemWatcher _verWatcher; private FileSystemWatcher _verDirWatcher; private readonly object _verWatcherLock = new object(); // Only one thread can be updating our current state private readonly SemaphoreSlim _isCurrentSemaphore = new SemaphoreSlim(1); // Only four threads can be updating any state. This is to prevent I/O // saturation when multiple threads refresh simultaneously. private static readonly SemaphoreSlim _sharedIsCurrentSemaphore = new SemaphoreSlim(4); [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "breaking change")] public PythonInterpreterFactoryWithDatabase( InterpreterConfiguration config, bool watchLibraryForChanges ) { _config = config; if (_config == null) { throw new ArgumentNullException("config"); } // Avoid creating a interpreter with an unsupported version. // https://github.com/Microsoft/PTVS/issues/706 try { var langVer = _config.Version.ToLanguageVersion(); } catch (InvalidOperationException ex) { throw new ArgumentException(ex.Message, ex); } if (watchLibraryForChanges && Directory.Exists(_config.LibraryPath)) { _refreshIsCurrentTrigger = new Timer(RefreshIsCurrentTimer_Elapsed); _libWatcher = CreateLibraryWatcher(); _isCheckingDatabase = true; _refreshIsCurrentTrigger.Change(1000, Timeout.Infinite); _verWatcher = CreateDatabaseVerWatcher(); _verDirWatcher = CreateDatabaseDirectoryWatcher(); } // Assume the database is valid if the directory exists, then switch // to invalid after we've checked. _isValid = Directory.Exists(DatabasePath); } public InterpreterConfiguration Configuration { get { return _config; } } /// <summary> /// Determines whether instances of this factory should assume that /// libraries are laid out exactly as CPython. If false, the interpreter /// will be queried for its search paths. /// </summary> public virtual bool AssumeSimpleLibraryLayout { get { return true; } } /// <summary> /// Returns a new interpreter created with the specified factory. /// </summary> /// <remarks> /// This is intended for use by derived classes only. To get an /// interpreter instance, use <see cref="CreateInterpreter"/>. /// </remarks> public virtual IPythonInterpreter MakeInterpreter(PythonInterpreterFactoryWithDatabase factory) { return new CPythonInterpreter(factory); } public IPythonInterpreter CreateInterpreter() { return MakeInterpreter(this); } /// <summary> /// Returns the database for this factory. This database may be shared /// between callers and should be cloned before making modifications. /// /// This function never returns null. /// </summary> public PythonTypeDatabase GetCurrentDatabase() { if (_typeDb == null || _typeDb.DatabaseDirectory != DatabasePath) { _typeDb = MakeTypeDatabase(DatabasePath) ?? PythonTypeDatabase.CreateDefaultTypeDatabase(this); } return _typeDb; } /// <summary> /// Returns the database for this factory, optionally excluding package /// analysis. This database may be shared between callers and should be /// cloned before making modifications. /// /// This function never returns null. /// </summary> public PythonTypeDatabase GetCurrentDatabase(bool includeSitePackages) { if (includeSitePackages) { return GetCurrentDatabase(); } if (_typeDbWithoutPackages == null || _typeDbWithoutPackages.DatabaseDirectory != DatabasePath) { _typeDbWithoutPackages = MakeTypeDatabase(DatabasePath, false) ?? PythonTypeDatabase.CreateDefaultTypeDatabase(this); } return _typeDbWithoutPackages; } /// <summary> /// Returns a new database loaded from the specified path. If null is /// returned, <see cref="GetCurrentDatabase"/> will assume the default /// completion DB is intended. /// </summary> /// <remarks> /// This is intended for overriding in derived classes. To get a /// queryable database instance, use <see cref="GetCurrentDatabase"/> or /// <see cref="CreateInterpreter"/>. /// </remarks> public virtual PythonTypeDatabase MakeTypeDatabase(string databasePath, bool includeSitePackages = true) { if (!_generating && PythonTypeDatabase.IsDatabaseVersionCurrent(databasePath)) { var paths = new List<string>(); paths.Add(databasePath); if (includeSitePackages) { paths.AddRange(PathUtils.EnumerateDirectories(databasePath, recurse: false)); } try { return new PythonTypeDatabase(this, paths); } catch (IOException) { } catch (UnauthorizedAccessException) { } } return PythonTypeDatabase.CreateDefaultTypeDatabase(this); } private bool WatchingLibrary { get { if (_libWatcher != null) { lock (_libWatcherLock) { return _libWatcher != null && _libWatcher.EnableRaisingEvents; } } return false; } set { if (_libWatcher != null) { lock (_libWatcherLock) { if (_libWatcher == null || _libWatcher.EnableRaisingEvents == value) { return; } try { _libWatcher.EnableRaisingEvents = value; } catch (IOException) { // May occur if the library has been deleted while the // watcher was disabled. _libWatcher.Dispose(); _libWatcher = null; } catch (ObjectDisposedException) { _libWatcher = null; } } } } } public virtual void GenerateDatabase(GenerateDatabaseOptions options, Action<int> onExit = null) { var req = new PythonTypeDatabaseCreationRequest { Factory = this, OutputPath = DatabasePath, SkipUnchanged = options.HasFlag(GenerateDatabaseOptions.SkipUnchanged), DetectLibraryPath = !AssumeSimpleLibraryLayout }; GenerateDatabase(req, onExit); } protected virtual void GenerateDatabase(PythonTypeDatabaseCreationRequest request, Action<int> onExit = null) { WatchingLibrary = false; _generating = true; PythonTypeDatabase.GenerateAsync(request).ContinueWith(t => { int exitCode; try { exitCode = t.Result; } catch (Exception ex) { Debug.Fail(ex.ToString()); exitCode = PythonTypeDatabase.InvalidOperationExitCode; } if (exitCode != PythonTypeDatabase.AlreadyGeneratingExitCode) { _generating = false; } if (onExit != null) { onExit(exitCode); } }); } /// <summary> /// Called to inform the interpreter that its database cannot be loaded /// and may need to be regenerated. /// </summary> public void NotifyCorruptDatabase() { _isValid = false; OnIsCurrentChanged(); OnNewDatabaseAvailable(); } public bool IsGenerating { get { return _generating; } } private void OnDatabaseVerChanged(object sender, FileSystemEventArgs e) { if ((!e.Name.Equals("database.ver", StringComparison.OrdinalIgnoreCase) && !e.Name.Equals("database.pid", StringComparison.OrdinalIgnoreCase)) || !PathUtils.IsSubpathOf(DatabasePath, e.FullPath)) { return; } RefreshIsCurrent(); if (IsCurrent) { NotifyNewDatabase(); } } private void NotifyNewDatabase() { _generating = false; OnIsCurrentChanged(); WatchingLibrary = true; // This also clears the previous database so that we load the new // one next time someone requests it. OnNewDatabaseAvailable(); } private bool IsValid { get { return _isValid && _missingModules == null && _isCurrentException == null; } } public virtual bool IsCurrent { get { return !IsGenerating && IsValid; } } public virtual bool IsCheckingDatabase { get { return _isCheckingDatabase; } } public virtual string DatabasePath { get { return Path.Combine( PythonTypeDatabase.CompletionDatabasePath, Configuration.Id.Replace('|', '\\').ToString() ); } } public string GetAnalysisLogContent(IFormatProvider culture) { var analysisLog = Path.Combine(DatabasePath, "AnalysisLog.txt"); if (File.Exists(analysisLog)) { try { return File.ReadAllText(analysisLog); } catch (Exception ex) { return string.Format( culture, "Error reading {0}. Please let analysis complete and try again.\r\n{1}", analysisLog, ex ); } } return null; } /// <summary> /// Called to manually trigger a refresh of <see cref="IsCurrent"/>. /// After completion, <see cref="IsCurrentChanged"/> will always be /// raised, regardless of whether the values were changed. /// </summary> public virtual void RefreshIsCurrent() { try { if (!_isCurrentSemaphore.Wait(0)) { // Another thread is working on our state, so we will wait for // them to finish and return, since the value is up to date. _isCurrentSemaphore.Wait(); _isCurrentSemaphore.Release(); return; } } catch (ObjectDisposedException) { // We've been disposed and the call has come in from // externally, probably a timer. return; } try { _isCheckingDatabase = true; OnIsCurrentChanged(); // Wait for a slot that will allow us to scan the disk. This // prevents too many threads from updating at once and causing // I/O saturation. _sharedIsCurrentSemaphore.Wait(); try { _generating = PythonTypeDatabase.IsDatabaseRegenerating(DatabasePath); WatchingLibrary = !_generating; if (_generating) { // Skip the rest of the checks, because we know we're // not current. } else if (!PythonTypeDatabase.IsDatabaseVersionCurrent(DatabasePath)) { _isValid = false; _missingModules = null; _isCurrentException = null; } else { _isValid = true; HashSet<string> existingDatabase = null; string[] missingModules = null; for (int retries = 3; retries > 0; --retries) { try { existingDatabase = GetExistingDatabase(DatabasePath); break; } catch (UnauthorizedAccessException) { } catch (IOException) { } Thread.Sleep(100); } if (existingDatabase == null) { // This will either succeed or throw again. If it throws // then the error is reported to the user. existingDatabase = GetExistingDatabase(DatabasePath); } for (int retries = 3; retries > 0; --retries) { try { missingModules = GetMissingModules(existingDatabase); break; } catch (UnauthorizedAccessException) { } catch (IOException) { } Thread.Sleep(100); } if (missingModules == null) { // This will either succeed or throw again. If it throws // then the error is reported to the user. missingModules = GetMissingModules(existingDatabase); } if (missingModules.Length > 0) { var oldModules = _missingModules; if (oldModules == null || oldModules.Length != missingModules.Length || !oldModules.SequenceEqual(missingModules)) { } _missingModules = missingModules; } else { _missingModules = null; } } _isCurrentException = null; } finally { _sharedIsCurrentSemaphore.Release(); } } catch (Exception ex) { // Report the exception text as the reason. _isCurrentException = ex.ToString(); _missingModules = null; } finally { _isCheckingDatabase = false; try { _isCurrentSemaphore.Release(); } catch (ObjectDisposedException) { // The semaphore is not locked for disposal as it is only // used to prevent reentrance into this function. As a // result, it may have been disposed while we were in here. } } OnIsCurrentChanged(); } private static HashSet<string> GetExistingDatabase(string databasePath) { return new HashSet<string>( PathUtils.EnumerateFiles(databasePath, "*.idb").Select(f => Path.GetFileNameWithoutExtension(f)), StringComparer.InvariantCultureIgnoreCase ); } /// <summary> /// Returns a sequence of module names that are required for a database. /// If any of these are missing, the database will be marked as invalid. /// </summary> private IEnumerable<string> RequiredBuiltinModules { get { if (Configuration.Version.Major == 2) { yield return "__builtin__"; } else if (Configuration.Version.Major == 3) { yield return "builtins"; } } } private string[] GetMissingModules(HashSet<string> existingDatabase) { var searchPaths = PythonTypeDatabase.GetCachedDatabaseSearchPaths(DatabasePath); if (searchPaths == null) { // No cached search paths means our database is out of date. return existingDatabase .Except(RequiredBuiltinModules) .OrderBy(name => name, StringComparer.InvariantCultureIgnoreCase) .ToArray(); } return PythonTypeDatabase.GetDatabaseExpectedModules(_config.Version, searchPaths) .SelectMany() .Select(mp => mp.ModuleName) .Concat(RequiredBuiltinModules) .Where(m => !existingDatabase.Contains(m)) .OrderBy(name => name, StringComparer.InvariantCultureIgnoreCase) .ToArray(); } private void RefreshIsCurrentTimer_Elapsed(object state) { if (_disposed) { return; } if (Directory.Exists(Configuration.LibraryPath)) { RefreshIsCurrent(); } else { if (_libWatcher != null) { lock (_libWatcherLock) { if (_libWatcher != null) { _libWatcher.Dispose(); _libWatcher = null; } } } OnIsCurrentChanged(); } } private void OnRenamed(object sender, RenamedEventArgs e) { _refreshIsCurrentTrigger.Change(1000, Timeout.Infinite); } private void OnChanged(object sender, FileSystemEventArgs e) { _refreshIsCurrentTrigger.Change(1000, Timeout.Infinite); } public event EventHandler IsCurrentChanged; public event EventHandler NewDatabaseAvailable; protected void OnIsCurrentChanged() { var evt = IsCurrentChanged; if (evt != null) { evt(this, EventArgs.Empty); } } /// <summary> /// Clears any cached type databases and raises the /// <see cref="NewDatabaseAvailable"/> event. /// </summary> protected void OnNewDatabaseAvailable() { _typeDb = null; _typeDbWithoutPackages = null; var evt = NewDatabaseAvailable; if (evt != null) { evt(this, EventArgs.Empty); } } static string GetPackageName(string fullName) { int firstDot = fullName.IndexOf('.'); return (firstDot > 0) ? fullName.Remove(firstDot) : fullName; } public virtual string GetFriendlyIsCurrentReason(IFormatProvider culture) { var missingModules = _missingModules; if (_isCurrentException != null) { return "An error occurred. Click Copy to get full details."; } else if (_generating) { return "Currently regenerating"; } else if (_libWatcher == null) { return "Interpreter has no library"; } else if (!Directory.Exists(DatabasePath)) { return "Database has never been generated"; } else if (!_isValid) { return "Database is corrupt or an old version"; } else if (missingModules != null) { if (missingModules.Length < 100) { return string.Format(culture, "The following modules have not been analyzed:{0} {1}", Environment.NewLine, string.Join(Environment.NewLine + " ", missingModules) ); } else { var packages = new List<string>( from m in missingModules group m by GetPackageName(m) into groupedByPackage where groupedByPackage.Count() > 1 orderby groupedByPackage.Key select groupedByPackage.Key ); if (packages.Count > 0 && packages.Count < 100) { return string.Format(culture, "{0} modules have not been analyzed.{2}Packages include:{2} {1}", missingModules.Length, string.Join(Environment.NewLine + " ", packages), Environment.NewLine ); } else { return string.Format(culture, "{0} modules have not been analyzed.", missingModules.Length ); } } } return "Up to date"; } public virtual string GetIsCurrentReason(IFormatProvider culture) { var missingModules = _missingModules; var reason = "Database at " + DatabasePath; if (_isCurrentException != null) { return reason + " raised an exception while refreshing:" + Environment.NewLine + _isCurrentException; } else if (_generating) { return reason + " is regenerating"; } else if (_libWatcher == null) { return "Interpreter has no library"; } else if (!Directory.Exists(DatabasePath)) { return reason + " does not exist"; } else if (!_isValid) { return reason + " is corrupt or an old version"; } else if (missingModules != null) { return reason + " does not contain the following modules:" + Environment.NewLine + string.Join(Environment.NewLine, missingModules); } return reason + " is up to date"; } public IEnumerable<string> GetUpToDateModules() { if (!Directory.Exists(DatabasePath)) { return Enumerable.Empty<string>(); } // Currently we assume that if the file exists, it's up to date. // PyLibAnalyzer will perform timestamp checks if the user manually // refreshes. return PathUtils.EnumerateFiles(DatabasePath, "*.idb") .Select(f => Path.GetFileNameWithoutExtension(f)); } #region IDisposable Members protected virtual void Dispose(bool disposing) { if (!_disposed) { _disposed = true; if (_verWatcher != null || _verDirWatcher != null) { lock (_verWatcherLock) { if (_verWatcher != null) { _verWatcher.EnableRaisingEvents = false; _verWatcher.Dispose(); _verWatcher = null; } if (_verDirWatcher != null) { _verDirWatcher.EnableRaisingEvents = false; _verDirWatcher.Dispose(); _verDirWatcher = null; } } } if (_libWatcher != null) { lock (_libWatcherLock) { if (_libWatcher != null) { _libWatcher.EnableRaisingEvents = false; _libWatcher.Dispose(); _libWatcher = null; } } } if (_refreshIsCurrentTrigger != null) { _refreshIsCurrentTrigger.Dispose(); } _isCurrentSemaphore.Dispose(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion #region Directory watchers private FileSystemWatcher CreateLibraryWatcher() { FileSystemWatcher watcher = null; try { watcher = new FileSystemWatcher { IncludeSubdirectories = true, Path = _config.LibraryPath, NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite }; watcher.Created += OnChanged; watcher.Deleted += OnChanged; watcher.Changed += OnChanged; watcher.Renamed += OnRenamed; watcher.EnableRaisingEvents = true; } catch (IOException) { // Raced with directory deletion. We normally handle the // library being deleted by disposing the watcher, but this // occurs in response to an event from the watcher. Because // we never got to start watching, we will just dispose // immediately. if (watcher != null) { watcher.Dispose(); } } catch (ArgumentException ex) { if (watcher != null) { watcher.Dispose(); } Debug.WriteLine("Error starting FileSystemWatcher:\r\n{0}", ex); } return watcher; } private FileSystemWatcher CreateDatabaseDirectoryWatcher() { FileSystemWatcher watcher = null; lock (_verWatcherLock) { var dirName = PathUtils.GetFileOrDirectoryName(DatabasePath); var dir = Path.GetDirectoryName(DatabasePath); while (PathUtils.IsValidPath(dir) && !Directory.Exists(dir)) { dirName = PathUtils.GetFileOrDirectoryName(dir); dir = Path.GetDirectoryName(dir); } if (Directory.Exists(dir)) { try { watcher = new FileSystemWatcher { IncludeSubdirectories = false, Path = dir, Filter = dirName, NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName }; } catch (ArgumentException ex) { Debug.WriteLine("Error starting database directory FileSystemWatcher:\r\n{0}", ex); return null; } watcher.Created += OnDatabaseFolderChanged; watcher.Renamed += OnDatabaseFolderChanged; watcher.Deleted += OnDatabaseFolderChanged; try { watcher.EnableRaisingEvents = true; return watcher; } catch (IOException) { // Raced with directory deletion watcher.Dispose(); watcher = null; } } return null; } } private FileSystemWatcher CreateDatabaseVerWatcher() { FileSystemWatcher watcher = null; lock (_verWatcherLock) { var dir = DatabasePath; if (Directory.Exists(dir)) { try { watcher = new FileSystemWatcher { IncludeSubdirectories = false, Path = dir, Filter = "database.*", NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite }; } catch (ArgumentException ex) { Debug.WriteLine("Error starting database.ver FileSystemWatcher:\r\n{0}", ex); return null; } watcher.Deleted += OnDatabaseVerChanged; watcher.Created += OnDatabaseVerChanged; watcher.Changed += OnDatabaseVerChanged; try { watcher.EnableRaisingEvents = true; return watcher; } catch (IOException) { // Raced with directory deletion. Fall through and find // a parent directory that exists. watcher.Dispose(); watcher = null; } } return null; } } private void OnDatabaseFolderChanged(object sender, FileSystemEventArgs e) { lock (_verWatcherLock) { if (_verWatcher != null) { _verWatcher.EnableRaisingEvents = false; _verWatcher.Dispose(); } if (_verDirWatcher != null) { _verDirWatcher.EnableRaisingEvents = false; _verDirWatcher.Dispose(); } _verDirWatcher = CreateDatabaseDirectoryWatcher(); _verWatcher = CreateDatabaseVerWatcher(); RefreshIsCurrent(); } } #endregion } }
namespace Nancy.Tests.Unit.ModelBinding { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Xml.Serialization; using FakeItEasy; using Nancy.Configuration; using Nancy.IO; using Nancy.Json; using Nancy.ModelBinding; using Nancy.ModelBinding.DefaultBodyDeserializers; using Nancy.ModelBinding.DefaultConverters; using Nancy.Responses.Negotiation; using Nancy.Tests.Fakes; using Nancy.Tests.Unit.ModelBinding.DefaultBodyDeserializers; using Xunit; using Xunit.Extensions; public class DefaultBinderFixture { private readonly IFieldNameConverter passthroughNameConverter; private readonly BindingDefaults emptyDefaults; private readonly JavaScriptSerializer serializer; private readonly BindingDefaults bindingDefaults; public DefaultBinderFixture() { var environment = new DefaultNancyEnvironment(); environment.AddValue(JsonConfiguration.Default); this.passthroughNameConverter = A.Fake<IFieldNameConverter>(); A.CallTo(() => this.passthroughNameConverter.Convert(null)).WithAnyArguments() .ReturnsLazily(f => (string)f.Arguments[0]); this.serializer = new JavaScriptSerializer(); this.serializer.RegisterConverters(JsonConfiguration.Default.Converters); this.bindingDefaults = new BindingDefaults(environment); this.emptyDefaults = A.Fake<BindingDefaults>(options => options.WithArgumentsForConstructor(new[] { environment })); A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new IBodyDeserializer[] { }); A.CallTo(() => this.emptyDefaults.DefaultTypeConverters).Returns(new ITypeConverter[] { }); } [Fact] public void Should_throw_if_type_converters_is_null() { // Given, When var result = Record.Exception(() => new DefaultBinder(null, new IBodyDeserializer[] { }, A.Fake<IFieldNameConverter>(), this.bindingDefaults)); // Then result.ShouldBeOfType(typeof(ArgumentNullException)); } [Fact] public void Should_throw_if_body_deserializers_is_null() { // Given, When var result = Record.Exception(() => new DefaultBinder(new ITypeConverter[] { }, null, A.Fake<IFieldNameConverter>(), this.bindingDefaults)); // Then result.ShouldBeOfType(typeof(ArgumentNullException)); } [Fact] public void Should_throw_if_body_deserializer_fails_and_IgnoreErrors_is_false() { // Given var deserializer = new ThrowingBodyDeserializer<FormatException>(); var binder = this.GetBinder(bodyDeserializers: new[] { deserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); var config = new BindingConfig { IgnoreErrors = false }; // When var result = Record.Exception(() => binder.Bind(context, this.GetType(), null, config)); // Then result.ShouldBeOfType<ModelBindingException>(); result.InnerException.ShouldBeOfType<FormatException>(); } [Fact] public void Should_not_throw_if_body_deserializer_fails_and_IgnoreErrors_is_true() { // Given var deserializer = new ThrowingBodyDeserializer<FormatException>(); var binder = this.GetBinder(bodyDeserializers: new[] { deserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); var config = new BindingConfig { IgnoreErrors = true }; // When, Then Assert.DoesNotThrow(() => binder.Bind(context, this.GetType(), null, config)); } [Fact] public void Should_throw_if_field_name_converter_is_null() { // Given, When var result = Record.Exception(() => new DefaultBinder(new ITypeConverter[] { }, new IBodyDeserializer[] { }, null, this.bindingDefaults)); // Then result.ShouldBeOfType(typeof(ArgumentNullException)); } [Fact] public void Should_throw_if_defaults_is_null() { // Given, When var result = Record.Exception(() => new DefaultBinder(new ITypeConverter[] { }, new IBodyDeserializer[] { }, A.Fake<IFieldNameConverter>(), null)); // Then result.ShouldBeOfType(typeof(ArgumentNullException)); } [Fact] public void Should_call_body_deserializer_if_one_matches() { // Given var deserializer = A.Fake<IBodyDeserializer>(); A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true); var binder = this.GetBinder(bodyDeserializers: new[] { deserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When binder.Bind(context, this.GetType(), null, BindingConfig.Default); // Then A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments() .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_not_call_body_deserializer_if_doesnt_match() { // Given var deserializer = A.Fake<IBodyDeserializer>(); A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(false); var binder = this.GetBinder(bodyDeserializers: new[] { deserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When binder.Bind(context, this.GetType(), null, BindingConfig.Default); // Then A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments() .MustNotHaveHappened(); } [Fact] public void Should_pass_request_content_type_to_can_deserialize() { // Then var deserializer = A.Fake<IBodyDeserializer>(); var binder = this.GetBinder(bodyDeserializers: new[] { deserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When binder.Bind(context, this.GetType(), null, BindingConfig.Default); // Then A.CallTo(() => deserializer.CanDeserialize(A<MediaRange>.That.Matches(x => x.Matches("application/xml")), A<BindingContext>._)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_pass_binding_context_to_can_deserialize() { // Then var deserializer = A.Fake<IBodyDeserializer>(); var binder = this.GetBinder(bodyDeserializers: new[] { deserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When binder.Bind(context, this.GetType(), null, BindingConfig.Default); // Then A.CallTo(() => deserializer.CanDeserialize(A<MediaRange>.That.Matches(x => x.Matches("application/xml")), A<BindingContext>.That.Not.IsNull())) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_use_object_from_deserializer_if_one_returned() { // Given var modelObject = new TestModel { StringProperty = "Hello!" }; var deserializer = A.Fake<IBodyDeserializer>(); A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true); A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments().Returns(modelObject); var binder = this.GetBinder(bodyDeserializers: new[] { deserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When var result = binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.ShouldBeOfType<TestModel>(); ((TestModel)result).StringProperty.ShouldEqual("Hello!"); } [Fact] public void Should_use_object_from_deserializer_if_one_returned_and_overwrite_when_allowed() { // Given var modelObject = new TestModel { StringPropertyWithDefaultValue = "Hello!" }; var deserializer = A.Fake<IBodyDeserializer>(); A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true); A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments().Returns(modelObject); var binder = this.GetBinder(bodyDeserializers: new[] { deserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When var result = binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.ShouldBeOfType<TestModel>(); ((TestModel)result).StringPropertyWithDefaultValue.ShouldEqual("Hello!"); } [Fact] public void Should_use_object_from_deserializer_if_one_returned_and_not_overwrite_when_not_allowed() { // Given var modelObject = new TestModel() { StringPropertyWithDefaultValue = "Hello!", StringFieldWithDefaultValue = "World!", }; var deserializer = A.Fake<IBodyDeserializer>(); A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true); A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments().Returns(modelObject); var binder = this.GetBinder(bodyDeserializers: new[] { deserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When var result = binder.Bind(context, typeof(TestModel), null, BindingConfig.NoOverwrite); // Then result.ShouldBeOfType<TestModel>(); ((TestModel)result).StringPropertyWithDefaultValue.ShouldEqual("Default Property Value"); ((TestModel)result).StringFieldWithDefaultValue.ShouldEqual("Default Field Value"); } [Fact] public void Should_see_if_a_type_converter_is_available_for_each_property_on_the_model_where_incoming_value_exists() { // Given var typeConverter = A.Fake<ITypeConverter>(); A.CallTo(() => typeConverter.CanConvertTo(null, null)).WithAnyArguments().Returns(false); var binder = this.GetBinder(typeConverters: new[] { typeConverter }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["StringProperty"] = "Test"; context.Request.Form["IntProperty"] = "12"; // When binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then A.CallTo(() => typeConverter.CanConvertTo(null, null)).WithAnyArguments() .MustHaveHappened(Repeated.Exactly.Times(2)); } [Fact] public void Should_call_convert_on_type_converter_if_available() { // Given var typeConverter = A.Fake<ITypeConverter>(); A.CallTo(() => typeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true); A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null); var binder = this.GetBinder(typeConverters: new[] { typeConverter }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["StringProperty"] = "Test"; // When binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments() .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_ignore_properties_that_cannot_be_converted() { // Given var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["StringProperty"] = "Test"; context.Request.Form["IntProperty"] = "12"; context.Request.Form["DateProperty"] = "Broken"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(12); result.DateProperty.ShouldEqual(default(DateTime)); } [Fact] public void Should_throw_ModelBindingException_if_convertion_of_a_property_fails() { // Given var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["IntProperty"] = "badint"; context.Request.Form["AnotherIntProperty"] = "morebad"; // Then Type modelType = typeof(TestModel); Assert.Throws<ModelBindingException>(() => binder.Bind(context, modelType, null, BindingConfig.Default)) .ShouldMatch(exception => exception.BoundType == modelType && exception.PropertyBindingExceptions.Any(pe => pe.PropertyName == "IntProperty" && pe.AttemptedValue == "badint") && exception.PropertyBindingExceptions.Any(pe => pe.PropertyName == "AnotherIntProperty" && pe.AttemptedValue == "morebad") && exception.PropertyBindingExceptions.All(pe => pe.InnerException.Message.Contains(pe.AttemptedValue) && pe.InnerException.Message.Contains(modelType.GetProperty(pe.PropertyName).PropertyType.Name))); } [Fact] public void Should_not_throw_ModelBindingException_if_convertion_of_property_fails_and_ignore_error_is_true() { // Given var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["IntProperty"] = "badint"; context.Request.Form["AnotherIntProperty"] = "morebad"; var config = new BindingConfig {IgnoreErrors = true}; // When // Then Assert.DoesNotThrow(() => binder.Bind(context, typeof(TestModel), null, config)); } [Fact] public void Should_set_remaining_properties_when_one_fails_and_ignore_error_is_enabled() { // Given var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["IntProperty"] = "badint"; context.Request.Form["AnotherIntProperty"] = 10; var config = new BindingConfig { IgnoreErrors = true }; // When var model = binder.Bind(context, typeof(TestModel), null, config) as TestModel; // Then model.AnotherIntProperty.ShouldEqual(10); } [Fact] public void Should_ignore_indexer_properties() { // Given var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); var validProperties = 0; var deserializer = A.Fake<IBodyDeserializer>(); A.CallTo(() => deserializer.CanDeserialize(A<MediaRange>._, A<BindingContext>._)).Returns(true); A.CallTo(() => deserializer.Deserialize(A<MediaRange>._, A<Stream>.Ignored, A<BindingContext>.Ignored)) .Invokes(f => { validProperties = f.Arguments.Get<BindingContext>(2).ValidModelBindingMembers.Count(); }) .Returns(new TestModel()); A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { deserializer }); // When binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then validProperties.ShouldEqual(22); } [Fact] public void Should_pass_binding_context_to_default_deserializer() { // Given var deserializer = A.Fake<IBodyDeserializer>(); var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { deserializer }); // When binder.Bind(context, this.GetType(), null, BindingConfig.Default); // Then A.CallTo(() => deserializer.CanDeserialize(A<MediaRange>.That.Matches(x => x.Matches("application/xml")), A<BindingContext>.That.Not.IsNull())) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_use_field_name_converter_for_each_field() { // Given var binder = this.GetBinder(); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["StringProperty"] = "Test"; context.Request.Form["IntProperty"] = "12"; // When binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then A.CallTo(() => this.passthroughNameConverter.Convert(null)).WithAnyArguments() .MustHaveHappened(Repeated.Exactly.Times(2)); } [Fact] public void Should_not_bind_anything_on_blacklist() { // Given var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["StringProperty"] = "Test"; context.Request.Form["IntProperty"] = "12"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default, "IntProperty"); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(0); } [Fact] public void Should_not_bind_anything_on_blacklist_when_the_blacklist_is_specified_by_expressions() { // Given var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["StringProperty"] = "Test"; context.Request.Form["IntProperty"] = "12"; var fakeModule = A.Fake<INancyModule>(); var fakeModelBinderLocator = A.Fake<IModelBinderLocator>(); A.CallTo(() => fakeModule.Context).Returns(context); A.CallTo(() => fakeModule.ModelBinderLocator).Returns(fakeModelBinderLocator); A.CallTo(() => fakeModelBinderLocator.GetBinderForType(typeof (TestModel), context)).Returns(binder); // When var result = fakeModule.Bind<TestModel>(tm => tm.IntProperty); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(0); } [Fact] public void Should_use_default_body_deserializer_if_one_found() { // Given var deserializer = A.Fake<IBodyDeserializer>(); A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true); A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { deserializer }); var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When binder.Bind(context, this.GetType(), null, BindingConfig.Default); // Then A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments() .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_use_default_type_converter_if_one_found() { // Given var typeConverter = A.Fake<ITypeConverter>(); A.CallTo(() => typeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true); A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null); A.CallTo(() => this.emptyDefaults.DefaultTypeConverters).Returns(new[] { typeConverter }); var binder = this.GetBinder(new ITypeConverter[] { }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["StringProperty"] = "Test"; // When binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments() .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void User_body_serializer_should_take_precedence_over_default_one() { // Given var userDeserializer = A.Fake<IBodyDeserializer>(); A.CallTo(() => userDeserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true); var defaultDeserializer = A.Fake<IBodyDeserializer>(); A.CallTo(() => defaultDeserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true); A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { defaultDeserializer }); var binder = this.GetBinder(bodyDeserializers: new[] { userDeserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When binder.Bind(context, this.GetType(), null, BindingConfig.Default); // Then A.CallTo(() => userDeserializer.Deserialize(null, null, null)).WithAnyArguments() .MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => defaultDeserializer.Deserialize(null, null, null)).WithAnyArguments() .MustNotHaveHappened(); } [Fact] public void User_type_converter_should_take_precedence_over_default_one() { // Given var userTypeConverter = A.Fake<ITypeConverter>(); A.CallTo(() => userTypeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true); A.CallTo(() => userTypeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null); var defaultTypeConverter = A.Fake<ITypeConverter>(); A.CallTo(() => defaultTypeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true); A.CallTo(() => defaultTypeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null); A.CallTo(() => this.emptyDefaults.DefaultTypeConverters).Returns(new[] { defaultTypeConverter }); var binder = this.GetBinder(new[] { userTypeConverter }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["StringProperty"] = "Test"; // When binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then A.CallTo(() => userTypeConverter.Convert(null, null, null)).WithAnyArguments() .MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => defaultTypeConverter.Convert(null, null, null)).WithAnyArguments() .MustNotHaveHappened(); } [Fact] public void Should_bind_model_from_request() { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Query["StringProperty"] = "Test"; context.Request.Query["IntProperty"] = "3"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(3); } [Fact] public void Should_bind_inherited_model_from_request() { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Query["StringProperty"] = "Test"; context.Request.Query["IntProperty"] = "3"; context.Request.Query["AnotherProperty"] = "Hello"; // When var result = (InheritedTestModel)binder.Bind(context, typeof(InheritedTestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(3); result.AnotherProperty.ShouldEqual("Hello"); } [Fact] public void Should_bind_model_from_context_parameters() { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Parameters["StringProperty"] = "Test"; context.Parameters["IntProperty"] = "3"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(3); } [Fact] public void Form_properties_should_take_precendence_over_request_properties() { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Form["StringProperty"] = "Test"; context.Request.Form["IntProperty"] = "3"; context.Request.Query["StringProperty"] = "Test2"; context.Request.Query["IntProperty"] = "1"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(3); } [Fact] public void Should_bind_multiple_Form_properties_to_list() { //Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["StringProperty_0"] = "Test"; context.Request.Form["IntProperty_0"] = "1"; context.Request.Form["StringProperty_1"] = "Test2"; context.Request.Form["IntProperty_1"] = "2"; // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default); // Then result.First().StringProperty.ShouldEqual("Test"); result.First().IntProperty.ShouldEqual(1); result.Last().StringProperty.ShouldEqual("Test2"); result.Last().IntProperty.ShouldEqual(2); } [Fact] public void Should_bind_more_than_10_multiple_Form_properties_to_list() { //Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["IntProperty_0"] = "1"; context.Request.Form["IntProperty_01"] = "2"; context.Request.Form["IntProperty_02"] = "3"; context.Request.Form["IntProperty_03"] = "4"; context.Request.Form["IntProperty_04"] = "5"; context.Request.Form["IntProperty_05"] = "6"; context.Request.Form["IntProperty_06"] = "7"; context.Request.Form["IntProperty_07"] = "8"; context.Request.Form["IntProperty_08"] = "9"; context.Request.Form["IntProperty_09"] = "10"; context.Request.Form["IntProperty_10"] = "11"; context.Request.Form["IntProperty_11"] = "12"; context.Request.Form["IntProperty_12"] = "13"; // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default); // Then result.First().IntProperty.ShouldEqual(1); result.ElementAt(1).IntProperty.ShouldEqual(2); result.Last().IntProperty.ShouldEqual(13); } [Fact] public void Should_bind_more_than_10_multiple_Form_properties_to_list_should_work_with_padded_zeros() { //Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["IntProperty_00"] = "1"; context.Request.Form["IntProperty_01"] = "2"; context.Request.Form["IntProperty_02"] = "3"; context.Request.Form["IntProperty_03"] = "4"; context.Request.Form["IntProperty_04"] = "5"; context.Request.Form["IntProperty_05"] = "6"; context.Request.Form["IntProperty_06"] = "7"; context.Request.Form["IntProperty_07"] = "8"; context.Request.Form["IntProperty_08"] = "9"; context.Request.Form["IntProperty_09"] = "10"; context.Request.Form["IntProperty_10"] = "11"; context.Request.Form["IntProperty_11"] = "12"; context.Request.Form["IntProperty_12"] = "13"; // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default); // Then result.First().IntProperty.ShouldEqual(1); result.Last().IntProperty.ShouldEqual(13); } [Fact] public void Should_bind_more_than_10_multiple_Form_properties_to_list_starting_counting_from_1() { //Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["IntProperty_01"] = "1"; context.Request.Form["IntProperty_02"] = "2"; context.Request.Form["IntProperty_03"] = "3"; context.Request.Form["IntProperty_04"] = "4"; context.Request.Form["IntProperty_05"] = "5"; context.Request.Form["IntProperty_06"] = "6"; context.Request.Form["IntProperty_07"] = "7"; context.Request.Form["IntProperty_08"] = "8"; context.Request.Form["IntProperty_09"] = "9"; context.Request.Form["IntProperty_10"] = "10"; context.Request.Form["IntProperty_11"] = "11"; context.Request.Form["IntProperty_12"] = "12"; // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default); // Then result.First().IntProperty.ShouldEqual(1); result.Last().IntProperty.ShouldEqual(12); } [Fact] public void Should_be_able_to_bind_more_than_once_should_ignore_non_list_properties_when_binding_to_a_list() { // Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["StringProperty"] = "Test"; context.Request.Form["IntProperty"] = "3"; context.Request.Form["NestedIntProperty[0]"] = "1"; context.Request.Form["NestedIntField[0]"] = "2"; context.Request.Form["NestedStringProperty[0]"] = "one"; context.Request.Form["NestedStringField[0]"] = "two"; context.Request.Form["NestedIntProperty[1]"] = "3"; context.Request.Form["NestedIntField[1]"] = "4"; context.Request.Form["NestedStringProperty[1]"] = "three"; context.Request.Form["NestedStringField[1]"] = "four"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); var result2 = (List<AnotherTestModel>)binder.Bind(context, typeof(List<AnotherTestModel>), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(3); result2.ShouldHaveCount(2); result2.First().NestedIntProperty.ShouldEqual(1); result2.First().NestedIntField.ShouldEqual(2); result2.First().NestedStringProperty.ShouldEqual("one"); result2.First().NestedStringField.ShouldEqual("two"); result2.Last().NestedIntProperty.ShouldEqual(3); result2.Last().NestedIntField.ShouldEqual(4); result2.Last().NestedStringProperty.ShouldEqual("three"); result2.Last().NestedStringField.ShouldEqual("four"); } [Fact] public void Should_bind_more_than_10_multiple_Form_properties_to_list_starting_with_jagged_ids() { //Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["IntProperty_01"] = "1"; context.Request.Form["IntProperty_04"] = "2"; context.Request.Form["IntProperty_05"] = "3"; context.Request.Form["IntProperty_06"] = "4"; context.Request.Form["IntProperty_09"] = "5"; context.Request.Form["IntProperty_11"] = "6"; context.Request.Form["IntProperty_57"] = "7"; context.Request.Form["IntProperty_199"] = "8"; context.Request.Form["IntProperty_1599"] = "9"; context.Request.Form["StringProperty_1599"] = "nine"; context.Request.Form["IntProperty_233"] = "10"; context.Request.Form["IntProperty_14"] = "11"; context.Request.Form["IntProperty_12"] = "12"; // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default); // Then result.First().IntProperty.ShouldEqual(1); result.Last().IntProperty.ShouldEqual(9); result.Last().StringProperty.ShouldEqual("nine"); } [Fact] public void Should_bind_to_IEnumerable_from_Form() { //Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["IntValuesProperty"] = "1,2,3,4"; context.Request.Form["IntValuesField"] = "5,6,7,8"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.IntValuesProperty.ShouldHaveCount(4); result.IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 }); result.IntValuesField.ShouldHaveCount(4); result.IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 }); } [Fact] public void Should_bind_to_IEnumerable_from_Form_with_multiple_inputs() { // Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["IntValuesProperty_0"] = "1,2,3,4"; context.Request.Form["IntValuesField_0"] = "5,6,7,8"; context.Request.Form["IntValuesProperty_1"] = "9,10,11,12"; context.Request.Form["IntValuesField_1"] = "13,14,15,16"; // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default); // Then result.ShouldHaveCount(2); result.First().IntValuesProperty.ShouldHaveCount(4); result.First().IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 }); result.First().IntValuesField.ShouldHaveCount(4); result.First().IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 }); result.Last().IntValuesProperty.ShouldHaveCount(4); result.Last().IntValuesProperty.ShouldEqualSequence(new[] { 9, 10, 11, 12 }); result.Last().IntValuesField.ShouldHaveCount(4); result.Last().IntValuesField.ShouldEqualSequence(new[] { 13, 14, 15, 16 }); } [Fact] public void Should_bind_to_IEnumerable_from_Form_with_multiple_inputs_using_brackets_and_specifying_an_instance() { // Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["IntValuesProperty[0]"] = "1,2,3,4"; context.Request.Form["IntValuesField[0]"] = "5,6,7,8"; context.Request.Form["IntValuesProperty[1]"] = "9,10,11,12"; context.Request.Form["IntValuesField[1]"] = "13,14,15,16"; // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), new List<TestModel> { new TestModel {AnotherStringProperty = "Test"} }, new BindingConfig { Overwrite = false}); // Then result.ShouldHaveCount(2); result.First().AnotherStringProperty.ShouldEqual("Test"); result.First().IntValuesProperty.ShouldHaveCount(4); result.First().IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 }); result.First().IntValuesField.ShouldHaveCount(4); result.First().IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 }); result.Last().AnotherStringProperty.ShouldBeNull(); result.Last().IntValuesProperty.ShouldHaveCount(4); result.Last().IntValuesProperty.ShouldEqualSequence(new[] { 9, 10, 11, 12 }); result.Last().IntValuesField.ShouldHaveCount(4); result.Last().IntValuesField.ShouldEqualSequence(new[] { 13, 14, 15, 16 }); } [Fact] public void Should_bind_to_IEnumerable_from_Form_with_multiple_inputs_using_brackets() { // Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["IntValuesProperty[0]"] = "1,2,3,4"; context.Request.Form["IntValuesField[0]"] = "5,6,7,8"; context.Request.Form["IntValuesProperty[1]"] = "9,10,11,12"; context.Request.Form["IntValuesField[1]"] = "13,14,15,16"; // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default); // Then result.ShouldHaveCount(2); result.First().IntValuesProperty.ShouldHaveCount(4); result.First().IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 }); result.First().IntValuesField.ShouldHaveCount(4); result.First().IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 }); result.Last().IntValuesProperty.ShouldHaveCount(4); result.Last().IntValuesProperty.ShouldEqualSequence(new[] { 9, 10, 11, 12 }); result.Last().IntValuesField.ShouldHaveCount(4); result.Last().IntValuesField.ShouldEqualSequence(new[] { 13, 14, 15, 16 }); } [Fact] public void Should_bind_collections_regardless_of_case() { // Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["lowercaseintproperty[0]"] = "1"; context.Request.Form["lowercaseintproperty[1]"] = "2"; context.Request.Form["lowercaseIntproperty[2]"] = "3"; context.Request.Form["lowercaseIntproperty[3]"] = "4"; context.Request.Form["Lowercaseintproperty[4]"] = "5"; context.Request.Form["Lowercaseintproperty[5]"] = "6"; context.Request.Form["LowercaseIntproperty[6]"] = "7"; context.Request.Form["LowercaseIntproperty[7]"] = "8"; context.Request.Form["lowercaseintfield[0]"] = "9"; context.Request.Form["lowercaseintfield[1]"] = "10"; context.Request.Form["lowercaseIntfield[2]"] = "11"; context.Request.Form["lowercaseIntfield[3]"] = "12"; context.Request.Form["Lowercaseintfield[4]"] = "13"; context.Request.Form["Lowercaseintfield[5]"] = "14"; context.Request.Form["LowercaseIntfield[6]"] = "15"; context.Request.Form["LowercaseIntfield[7]"] = "16"; // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default); // Then result.ShouldHaveCount(8); result.First().lowercaseintproperty.ShouldEqual(1); result.Last().lowercaseintproperty.ShouldEqual(8); result.First().lowercaseintfield.ShouldEqual(9); result.Last().lowercaseintfield.ShouldEqual(16); } [Fact] public void Form_properties_should_take_precendence_over_request_properties_and_context_properties() { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Form["StringProperty"] = "Test"; context.Request.Form["IntProperty"] = "3"; context.Request.Query["StringProperty"] = "Test2"; context.Request.Query["IntProperty"] = "1"; context.Parameters["StringProperty"] = "Test3"; context.Parameters["IntProperty"] = "2"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(3); } [Fact] public void Request_properties_should_take_precendence_over_context_properties() { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Query["StringProperty"] = "Test"; context.Request.Query["IntProperty"] = "12"; context.Parameters["StringProperty"] = "Test2"; context.Parameters["IntProperty"] = "13"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(12); } [Fact] public void Should_be_able_to_bind_from_form_and_request_simultaneously() { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Form["StringProperty"] = "Test"; context.Request.Query["IntProperty"] = "12"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(12); } [Theory] [InlineData("de-DE", 4.50)] [InlineData("en-GB", 450)] [InlineData("en-US", 450)] [InlineData("sv-SE", 4.50)] [InlineData("ru-RU", 4.50)] [InlineData("zh-TW", 450)] public void Should_be_able_to_bind_culturally_aware_form_properties_if_numeric(string culture, double expected) { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Culture = new CultureInfo(culture); context.Request.Form["DoubleProperty"] = "4,50"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.DoubleProperty.ShouldEqual(expected); } [Theory] [InlineData("12/25/2012", 12, 25, 2012, "en-US")] [InlineData("12/12/2012", 12, 12, 2012, "en-US")] [InlineData("25/12/2012", 12, 25, 2012, "en-GB")] [InlineData("12/12/2012", 12, 12, 2012, "en-GB")] [InlineData("12/12/2012", 12, 12, 2012, "ru-RU")] [InlineData("25/12/2012", 12, 25, 2012, "ru-RU")] [InlineData("2012-12-25", 12, 25, 2012, "zh-TW")] [InlineData("2012-12-12", 12, 12, 2012, "zh-TW")] public void Should_be_able_to_bind_culturally_aware_form_properties_if_datetime(string date, int month, int day, int year, string culture) { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Culture = new CultureInfo(culture); context.Request.Form["DateProperty"] = date; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.DateProperty.Date.Month.ShouldEqual(month); result.DateProperty.Date.Day.ShouldEqual(day); result.DateProperty.Date.Year.ShouldEqual(year); } [Fact] public void Should_be_able_to_bind_from_request_and_context_simultaneously() { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Query["StringProperty"] = "Test"; context.Parameters["IntProperty"] = "12"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(12); } [Fact] public void Should_not_overwrite_nullable_property_if_already_set_and_overwriting_is_not_allowed() { // Given var binder = this.GetBinder(); var existing = new TestModel { StringProperty = "Existing Value" }; var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Query["StringProperty"] = "Test"; context.Request.Query["IntProperty"] = "12"; context.Parameters["StringProperty"] = "Test2"; context.Parameters["IntProperty"] = "1"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.NoOverwrite); // Then result.StringProperty.ShouldEqual("Existing Value"); result.IntProperty.ShouldEqual(12); } [Fact] public void Should_not_overwrite_non_nullable_property_if_already_set_and_overwriting_is_not_allowed() { // Given var binder = this.GetBinder(); var existing = new TestModel { IntProperty = 27 }; var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Query["StringProperty"] = "Test"; context.Request.Query["IntProperty"] = "12"; context.Parameters["StringProperty"] = "Test2"; context.Parameters["IntProperty"] = "1"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.NoOverwrite); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(27); } [Fact] public void Should_overwrite_nullable_property_if_already_set_and_overwriting_is_allowed() { // Given var binder = this.GetBinder(); var existing = new TestModel { StringProperty = "Existing Value" }; var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Parameters["StringProperty"] = "Test2"; context.Parameters["IntProperty"] = "1"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test2"); result.IntProperty.ShouldEqual(1); } [Fact] public void Should_overwrite_non_nullable_property_if_already_set_and_overwriting_is_allowed() { // Given var binder = this.GetBinder(); var existing = new TestModel { IntProperty = 27 }; var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Parameters["StringProperty"] = "Test2"; context.Parameters["IntProperty"] = "1"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test2"); result.IntProperty.ShouldEqual(1); } [Fact] public void Should_bind_list_model_from_body() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() }); var body = XmlBodyDeserializerFixture.ToXmlString(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } })); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body); // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default); // Then result.First().StringProperty.ShouldEqual("Test"); result.Last().StringProperty.ShouldEqual("AnotherTest"); } [Fact] public void Should_bind_array_model_from_body() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() }); var body = XmlBodyDeserializerFixture.ToXmlString(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } })); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body); // When var result = (TestModel[])binder.Bind(context, typeof(TestModel[]), null, BindingConfig.Default); // Then result.First().StringProperty.ShouldEqual("Test"); result.Last().StringProperty.ShouldEqual("AnotherTest"); } [Fact] public void Should_bind_string_array_model_from_body() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) }); var body = serializer.Serialize(new[] { "Test","AnotherTest"}); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body); // When var result = (string[])binder.Bind(context, typeof(string[]), null, BindingConfig.Default); // Then result.First().ShouldEqual("Test"); result.Last().ShouldEqual("AnotherTest"); } [Fact] public void Should_bind_ienumerable_model_from_body() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) }); var body = serializer.Serialize(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } })); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body); // When var result = (IEnumerable<TestModel>)binder.Bind(context, typeof(IEnumerable<TestModel>), null, BindingConfig.Default); // Then result.First().StringProperty.ShouldEqual("Test"); result.Last().StringProperty.ShouldEqual("AnotherTest"); } [Fact] public void Should_bind_ienumerable_model_with_instance_from_body() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) }); var body = serializer.Serialize(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } })); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body); var then = DateTime.Now; var instance = new List<TestModel> { new TestModel{ DateProperty = then }, new TestModel { IntProperty = 9, AnotherStringProperty = "Bananas" } }; // When var result = (IEnumerable<TestModel>)binder.Bind(context, typeof(IEnumerable<TestModel>), instance, new BindingConfig{Overwrite = false}); // Then result.First().StringProperty.ShouldEqual("Test"); result.First().DateProperty.ShouldEqual(then); result.Last().StringProperty.ShouldEqual("AnotherTest"); result.Last().IntProperty.ShouldEqual(9); result.Last().AnotherStringProperty.ShouldEqual("Bananas"); } [Fact] public void Should_bind_model_with_instance_from_body() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() }); var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { StringProperty = "Test" }); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body); var then = DateTime.Now; var instance = new TestModel { DateProperty = then, IntProperty = 6, AnotherStringProperty = "Beers" }; // Wham var result = (TestModel)binder.Bind(context, typeof(TestModel), instance, new BindingConfig { Overwrite = false }); // Then result.StringProperty.ShouldEqual("Test"); result.DateProperty.ShouldEqual(then); result.IntProperty.ShouldEqual(6); result.AnotherStringProperty.ShouldEqual("Beers"); } [Fact] public void Should_bind_model_from_body_that_contains_an_array() { //Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) }); var body = serializer.Serialize( new TestModel { StringProperty = "Test", SomeStringsProperty = new[] { "E", "A", "D", "G", "B", "E" }, SomeStringsField = new[] { "G", "D", "A", "E" }, }); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body); // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.SomeStringsProperty.ShouldHaveCount(6); result.SomeStringsProperty.ShouldEqualSequence(new[] { "E", "A", "D", "G", "B", "E" }); result.SomeStringsField.ShouldHaveCount(4); result.SomeStringsField.ShouldEqualSequence(new[] { "G", "D", "A", "E" }); } [Fact] public void Should_bind_array_model_from_body_that_contains_an_array() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) }); var body = serializer.Serialize(new[] { new TestModel() { StringProperty = "Test", SomeStringsProperty = new[] {"E", "A", "D", "G", "B", "E"}, SomeStringsField = new[] { "G", "D", "A", "E" }, }, new TestModel() { StringProperty = "AnotherTest", SomeStringsProperty = new[] {"E", "A", "D", "G", "B", "E"}, SomeStringsField = new[] { "G", "D", "A", "E" }, } }); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body); // When var result = (TestModel[])binder.Bind(context, typeof(TestModel[]), null, BindingConfig.Default, "SomeStringsProperty", "SomeStringsField"); // Then result.ShouldHaveCount(2); result.First().SomeStringsProperty.ShouldBeNull(); result.First().SomeStringsField.ShouldBeNull(); result.Last().SomeStringsProperty.ShouldBeNull(); result.Last().SomeStringsField.ShouldBeNull(); } [Fact] public void Form_request_and_context_properties_should_take_precedence_over_body_properties() { // Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var bodyDeserializers = new IBodyDeserializer[] { new XmlBodyDeserializer() }; var binder = this.GetBinder(typeConverters, bodyDeserializers); var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { IntProperty = 0, StringProperty = "From body" }); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body); context.Request.Form["StringProperty"] = "From form"; context.Request.Query["IntProperty"] = "1"; context.Parameters["AnotherStringProperty"] = "From context"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("From form"); result.AnotherStringProperty.ShouldEqual("From context"); result.IntProperty.ShouldEqual(1); } [Fact] public void Form_request_and_context_properties_should_be_ignored_in_body_only_mode_when_there_is_a_body() { // Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var bodyDeserializers = new IBodyDeserializer[] { new XmlBodyDeserializer() }; var binder = GetBinder(typeConverters, bodyDeserializers); var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { IntProperty = 2, StringProperty = "From body" }); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body); context.Request.Form["StringProperty"] = "From form"; context.Request.Query["IntProperty"] = "1"; context.Parameters["AnotherStringProperty"] = "From context"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, new BindingConfig { BodyOnly = true }); // Then result.StringProperty.ShouldEqual("From body"); result.AnotherStringProperty.ShouldBeNull(); // not in body, so default value result.IntProperty.ShouldEqual(2); } [Fact] public void Form_request_and_context_properties_should_NOT_be_used_in_body_only_mode_if_there_is_no_body() { // Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Form["StringProperty"] = "From form"; context.Request.Query["IntProperty"] = "1"; context.Parameters["AnotherStringProperty"] = "From context"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, new BindingConfig { BodyOnly = true }); // Then result.StringProperty.ShouldEqual(null); result.AnotherStringProperty.ShouldEqual(null); result.IntProperty.ShouldEqual(0); } [Fact] public void Should_be_able_to_bind_body_request_form_and_context_properties() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() }); var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { DateProperty = new DateTime(2012, 8, 16) }); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body); context.Request.Form["IntProperty"] = "0"; context.Request.Query["StringProperty"] = "From Query"; context.Parameters["AnotherStringProperty"] = "From Context"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("From Query"); result.IntProperty.ShouldEqual(0); result.DateProperty.ShouldEqual(new DateTime(2012, 8, 16)); result.AnotherStringProperty.ShouldEqual("From Context"); } [Fact] public void Should_ignore_existing_instance_if_type_doesnt_match() { //Given var binder = this.GetBinder(); var existing = new object(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.Default); // Then result.ShouldNotBeSameAs(existing); } [Fact] public void Should_bind_to_valuetype_from_body() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) }); var body = serializer.Serialize(1); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body); // When var result = (int)binder.Bind(context, typeof(int), null, BindingConfig.Default); // Then result.ShouldEqual(1); } [Fact] public void Should_bind_ienumerable_model__of_valuetype_from_body() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) }); var body = serializer.Serialize(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body); // When var result = (IEnumerable<int>)binder.Bind(context, typeof(IEnumerable<int>), null, BindingConfig.Default); // Then result.ShouldEqualSequence(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }); } [Fact] public void Should_bind_to_model_with_non_public_default_constructor() { var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/json" }); context.Request.Form["IntProperty"] = "10"; var result = (TestModelWithHiddenDefaultConstructor)binder.Bind(context, typeof (TestModelWithHiddenDefaultConstructor), null, BindingConfig.Default); result.ShouldNotBeNull(); result.IntProperty.ShouldEqual(10); } private IBinder GetBinder(IEnumerable<ITypeConverter> typeConverters = null, IEnumerable<IBodyDeserializer> bodyDeserializers = null, IFieldNameConverter nameConverter = null, BindingDefaults bindingDefaults = null) { var converters = typeConverters ?? new ITypeConverter[] { new DateTimeConverter(), new NumericConverter(), new FallbackConverter() }; var deserializers = bodyDeserializers ?? new IBodyDeserializer[] { }; var converter = nameConverter ?? this.passthroughNameConverter; var defaults = bindingDefaults ?? this.emptyDefaults; return new DefaultBinder(converters, deserializers, converter, defaults); } private static NancyContext CreateContextWithHeader(string name, IEnumerable<string> values) { var header = new Dictionary<string, IEnumerable<string>> { { name, values } }; return new NancyContext { Request = new FakeRequest("GET", "/", header), Parameters = DynamicDictionary.Empty }; } private static NancyContext CreateContextWithHeaderAndBody(string name, IEnumerable<string> values, string body) { var header = new Dictionary<string, IEnumerable<string>> { { name, values } }; byte[] byteArray = Encoding.UTF8.GetBytes(body); var bodyStream = RequestStream.FromStream(new MemoryStream(byteArray)); return new NancyContext { Request = new FakeRequest("GET", "/", header, bodyStream, "http", string.Empty), Parameters = DynamicDictionary.Empty }; } private static INancyEnvironment GetTestingEnvironment() { var envionment = new DefaultNancyEnvironment(); envionment.AddValue(JsonConfiguration.Default); return envionment; } public class TestModel { public TestModel() { this.StringPropertyWithDefaultValue = "Default Property Value"; this.StringFieldWithDefaultValue = "Default Field Value"; } public string StringProperty { get; set; } public string AnotherStringProperty { get; set; } public string StringField; public string AnotherStringField; public int IntProperty { get; set; } public int AnotherIntProperty { get; set; } public int IntField; public int AnotherIntField; public int lowercaseintproperty { get; set; } public int lowercaseintfield; public DateTime DateProperty { get; set; } public DateTime DateField; public string StringPropertyWithDefaultValue { get; set; } public string StringFieldWithDefaultValue; public double DoubleProperty { get; set; } public double DoubleField; [XmlIgnore] public IEnumerable<int> IntValuesProperty { get; set; } [XmlIgnore] public IEnumerable<int> IntValuesField; public string[] SomeStringsProperty { get; set; } public string[] SomeStringsField; public int this[int index] { get { return 0; } set { } } public List<AnotherTestModel> ModelsProperty { get; set; } public List<AnotherTestModel> ModelsField; } public class InheritedTestModel : TestModel { public string AnotherProperty { get; set; } } public class AnotherTestModel { public string NestedStringProperty { get; set; } public int NestedIntProperty { get; set; } public double NestedDoubleProperty { get; set; } public string NestedStringField; public int NestedIntField; public double NestedDoubleField; } private class ThrowingBodyDeserializer<T> : IBodyDeserializer where T : Exception, new() { public bool CanDeserialize(MediaRange mediaRange, BindingContext context) { return true; } public object Deserialize(MediaRange mediaRange, Stream bodyStream, BindingContext context) { throw new T(); } } public class TestModelWithHiddenDefaultConstructor { public int IntProperty { get; private set; } private TestModelWithHiddenDefaultConstructor() { } } } public class BindingConfigFixture { [Fact] public void Should_allow_overwrite_on_new_instance() { // Given // When var instance = new BindingConfig(); // Then instance.Overwrite.ShouldBeTrue(); } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System; using System.Text; // Missing XML Docs #pragma warning disable 1591 namespace NUnit.Common { public enum TokenKind { Eof, Word, String, Symbol } public class Token { public Token(TokenKind kind) : this(kind, string.Empty) { } public Token(TokenKind kind, char ch) : this(kind, ch.ToString()) { } public Token(TokenKind kind, string text) { Kind = kind; Text = text; } public TokenKind Kind { get; } public string Text { get; } public int Pos { get; set; } #region Equality Overrides public override bool Equals(object obj) { return obj is Token && this == (Token)obj; } public override int GetHashCode() { return Text.GetHashCode(); } public override string ToString() { return Text != null ? Kind.ToString() + ":" + Text : Kind.ToString(); } public static bool operator ==(Token t1, Token t2) { bool t1Null = ReferenceEquals(t1, null); bool t2Null = ReferenceEquals(t2, null); if (t1Null && t2Null) return true; if (t1Null || t2Null) return false; return t1.Kind == t2.Kind && t1.Text == t2.Text; } public static bool operator !=(Token t1, Token t2) { return !(t1 == t2); } #endregion } /// <summary> /// Tokenizer class performs lexical analysis for the TestSelectionParser. /// It recognizes a very limited set of tokens: words, symbols and /// quoted strings. This is sufficient for the simple DSL we use to /// select which tests to run. /// </summary> public class Tokenizer { private readonly string _input; private int _index; private const char EOF_CHAR = '\0'; private const string WORD_BREAK_CHARS = "=!()&|"; private static readonly string[] DOUBLE_CHAR_SYMBOLS = new string[] { "==", "=~", "!=", "!~", "&&", "||" }; private Token _lookahead; public Tokenizer(string input) { if (input == null) throw new ArgumentNullException(nameof(input)); _input = input; _index = 0; } public Token LookAhead { get { if (_lookahead == null) _lookahead = GetNextToken(); return _lookahead; } } public Token NextToken() { Token result = _lookahead ?? GetNextToken(); _lookahead = null; return result; } private Token GetNextToken() { SkipBlanks(); var ch = NextChar; int pos = _index; switch (ch) { case EOF_CHAR: return new Token(TokenKind.Eof) { Pos = pos }; // Single char symbols case '(': case ')': GetChar(); return new Token(TokenKind.Symbol, ch) { Pos = pos }; // Possible double char symbols case '&': case '|': case '=': case '!': GetChar(); foreach(string dbl in DOUBLE_CHAR_SYMBOLS) if (ch == dbl[0] && NextChar == dbl[1]) { GetChar(); return new Token(TokenKind.Symbol, dbl) { Pos = pos }; } return new Token(TokenKind.Symbol, ch); case '"': case '\'': case '/': return GetString(); default: return GetWord(); } } private bool IsWordChar(char c) { if (char.IsWhiteSpace(c) || c == EOF_CHAR) return false; return WORD_BREAK_CHARS.IndexOf(c) < 0; } private Token GetWord() { var sb = new StringBuilder(); int pos = _index; while (IsWordChar(NextChar)) sb.Append(GetChar()); return new Token(TokenKind.Word, sb.ToString()) { Pos = pos }; } private Token GetString() { var sb = new StringBuilder(); int pos = _index; char quote = GetChar(); // Save the initial quote char while (NextChar != EOF_CHAR) { var ch = GetChar(); if (ch == '\\') ch = GetChar(); else if (ch == quote) break; sb.Append(ch); } return new Token(TokenKind.String, sb.ToString()) { Pos = pos }; } /// <summary> /// Get the next character in the input, consuming it. /// </summary> /// <returns>The next char</returns> private char GetChar() { return _index < _input.Length ? _input[_index++] : EOF_CHAR; } /// <summary> /// Peek ahead at the next character in input /// </summary> private char NextChar { get { return _index < _input.Length ? _input[_index] : EOF_CHAR; } } private void SkipBlanks() { while (char.IsWhiteSpace(NextChar)) _index++; } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.ComponentModel; using System.Windows.Forms.VisualStyles; namespace xDockPanel { internal class VS2005DockPaneCaption : DockPaneCaptionBase { private sealed class InertButton : InertButtonBase { private Bitmap m_image, m_imageAutoHide; public InertButton(VS2005DockPaneCaption dockPaneCaption, Bitmap image, Bitmap imageAutoHide) : base() { m_dockPaneCaption = dockPaneCaption; m_image = image; m_imageAutoHide = imageAutoHide; RefreshChanges(); } private VS2005DockPaneCaption m_dockPaneCaption; private VS2005DockPaneCaption DockPaneCaption { get { return m_dockPaneCaption; } } public bool IsAutoHide { get { return DockPaneCaption.DockPane.IsAutoHide; } } public override Bitmap Image { get { return IsAutoHide ? m_imageAutoHide : m_image; } } protected override void OnRefreshChanges() { if (DockPaneCaption.DockPane.DockPanel != null) { if (DockPaneCaption.TextColor != ForeColor) { ForeColor = DockPaneCaption.TextColor; Invalidate(); } } } } #region consts private const int _TextGapTop = 2; private const int _TextGapBottom = 0; private const int _TextGapLeft = 3; private const int _TextGapRight = 3; private const int _ButtonGapTop = 2; private const int _ButtonGapBottom = 1; private const int _ButtonGapBetween = 1; private const int _ButtonGapLeft = 1; private const int _ButtonGapRight = 2; #endregion private static Bitmap _imageButtonClose; private static Bitmap ImageButtonClose { get { if (_imageButtonClose == null) _imageButtonClose = Properties.Resources.DockPane_Close; return _imageButtonClose; } } private InertButton m_buttonClose; private InertButton ButtonClose { get { if (m_buttonClose == null) { m_buttonClose = new InertButton(this, ImageButtonClose, ImageButtonClose); m_toolTip.SetToolTip(m_buttonClose, ToolTipClose); m_buttonClose.Click += new EventHandler(Close_Click); Controls.Add(m_buttonClose); } return m_buttonClose; } } private static Bitmap _imageButtonAutoHide; private static Bitmap ImageButtonAutoHide { get { if (_imageButtonAutoHide == null) _imageButtonAutoHide = Properties.Resources.DockPane_Dock; return _imageButtonAutoHide; } } private static Bitmap _imageButtonDock; private static Bitmap ImageButtonDock { get { if (_imageButtonDock == null) _imageButtonDock = Properties.Resources.DockPane_AutoHide; return _imageButtonDock; } } private InertButton m_buttonAutoHide; private InertButton ButtonAutoHide { get { if (m_buttonAutoHide == null) { m_buttonAutoHide = new InertButton(this, ImageButtonDock, ImageButtonAutoHide); m_toolTip.SetToolTip(m_buttonAutoHide, ToolTipAutoHide); m_buttonAutoHide.Click += new EventHandler(AutoHide_Click); Controls.Add(m_buttonAutoHide); } return m_buttonAutoHide; } } private static Bitmap _imageButtonOptions; private static Bitmap ImageButtonOptions { get { if (_imageButtonOptions == null) _imageButtonOptions = Properties.Resources.DockPane_Option; return _imageButtonOptions; } } private InertButton m_buttonOptions; private InertButton ButtonOptions { get { if (m_buttonOptions == null) { m_buttonOptions = new InertButton(this, ImageButtonOptions, ImageButtonOptions); m_toolTip.SetToolTip(m_buttonOptions, ToolTipOptions); m_buttonOptions.Click += new EventHandler(Options_Click); Controls.Add(m_buttonOptions); } return m_buttonOptions; } } private IContainer m_components; private IContainer Components { get { return m_components; } } private ToolTip m_toolTip; public VS2005DockPaneCaption(DockPane pane) : base(pane) { SuspendLayout(); m_components = new Container(); m_toolTip = new ToolTip(Components); ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) Components.Dispose(); base.Dispose(disposing); } private static int TextGapTop { get { return _TextGapTop; } } public Font TextFont { get { return DockPane.DockPanel.Skin.DockPaneStripSkin.TextFont; } } private static int TextGapBottom { get { return _TextGapBottom; } } private static int TextGapLeft { get { return _TextGapLeft; } } private static int TextGapRight { get { return _TextGapRight; } } private static int ButtonGapTop { get { return _ButtonGapTop; } } private static int ButtonGapBottom { get { return _ButtonGapBottom; } } private static int ButtonGapLeft { get { return _ButtonGapLeft; } } private static int ButtonGapRight { get { return _ButtonGapRight; } } private static int ButtonGapBetween { get { return _ButtonGapBetween; } } private static string _toolTipClose; private static string ToolTipClose { get { if (_toolTipClose == null) _toolTipClose = "Close"; return _toolTipClose; } } private static string _toolTipOptions; private static string ToolTipOptions { get { if (_toolTipOptions == null) _toolTipOptions = "Options"; return _toolTipOptions; } } private static string _toolTipAutoHide; private static string ToolTipAutoHide { get { if (_toolTipAutoHide == null) _toolTipAutoHide = "AutoHide"; return _toolTipAutoHide; } } private static Blend _activeBackColorGradientBlend; private static Blend ActiveBackColorGradientBlend { get { if (_activeBackColorGradientBlend == null) { Blend blend = new Blend(2); blend.Factors = new float[]{0.5F, 1.0F}; blend.Positions = new float[]{0.0F, 1.0F}; _activeBackColorGradientBlend = blend; } return _activeBackColorGradientBlend; } } private Color TextColor { get { if (DockPane.IsActivated) return DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor; else return DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor; } } private static TextFormatFlags _textFormat = TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis | TextFormatFlags.VerticalCenter; private TextFormatFlags TextFormat { get { return _textFormat; } } protected internal override int MeasureHeight() { int height = TextFont.Height + TextGapTop + TextGapBottom; if (height < ButtonClose.Image.Height + ButtonGapTop + ButtonGapBottom) height = ButtonClose.Image.Height + ButtonGapTop + ButtonGapBottom; return height; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint (e); DrawCaption(e.Graphics); } private void DrawCaption(Graphics g) { if (ClientRectangle.Width == 0 || ClientRectangle.Height == 0) return; if (DockPane.IsActivated) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, startColor, endColor, gradientMode)) { brush.Blend = ActiveBackColorGradientBlend; g.FillRectangle(brush, ClientRectangle); } } else { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, startColor, endColor, gradientMode)) { g.FillRectangle(brush, ClientRectangle); } } Rectangle rectCaption = ClientRectangle; Rectangle rectCaptionText = rectCaption; rectCaptionText.X += TextGapLeft; rectCaptionText.Width -= TextGapLeft + TextGapRight; rectCaptionText.Width -= ButtonGapLeft + ButtonClose.Width + ButtonGapRight; if (ShouldShowAutoHideButton) rectCaptionText.Width -= ButtonAutoHide.Width + ButtonGapBetween; if (HasTabPageContextMenu) rectCaptionText.Width -= ButtonOptions.Width + ButtonGapBetween; rectCaptionText.Y += TextGapTop; rectCaptionText.Height -= TextGapTop + TextGapBottom; Color colorText; if (DockPane.IsActivated) colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor; else colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor; TextRenderer.DrawText(g, DockPane.CaptionText, TextFont, rectCaptionText, colorText, TextFormat); } protected override void OnLayout(LayoutEventArgs levent) { SetButtonsPosition(); base.OnLayout (levent); } protected override void OnRefreshChanges() { SetButtons(); Invalidate(); } private bool CloseButtonEnabled { get { return (DockPane.ActiveContent != null)? DockPane.ActiveContent.DockHandler.CloseButton : false; } } /// <summary> /// Determines whether the close button is visible on the content /// </summary> private bool CloseButtonVisible { get { return (DockPane.ActiveContent != null) ? DockPane.ActiveContent.DockHandler.CloseButtonVisible : false; } } private bool ShouldShowAutoHideButton { get { return !DockPane.IsFloat; } } private void SetButtons() { ButtonClose.Enabled = CloseButtonEnabled; ButtonClose.Visible = CloseButtonVisible; ButtonAutoHide.Visible = ShouldShowAutoHideButton; ButtonOptions.Visible = HasTabPageContextMenu; ButtonClose.RefreshChanges(); ButtonAutoHide.RefreshChanges(); ButtonOptions.RefreshChanges(); SetButtonsPosition(); } private void SetButtonsPosition() { // set the size and location for close and auto-hide buttons Rectangle rectCaption = ClientRectangle; int buttonWidth = ButtonClose.Image.Width; int buttonHeight = ButtonClose.Image.Height; int height = rectCaption.Height - ButtonGapTop - ButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * (height / buttonHeight); buttonHeight = height; } Size buttonSize = new Size(buttonWidth, buttonHeight); int x = rectCaption.X + rectCaption.Width - 1 - ButtonGapRight - m_buttonClose.Width; int y = rectCaption.Y + ButtonGapTop; Point point = new Point(x, y); ButtonClose.Bounds = new Rectangle(point, buttonSize); // If the close button is not visible draw the auto hide button overtop. // Otherwise it is drawn to the left of the close button. if (CloseButtonVisible) point.Offset(-(buttonWidth + ButtonGapBetween), 0); ButtonAutoHide.Bounds = new Rectangle(point, buttonSize); if (ShouldShowAutoHideButton) point.Offset(-(buttonWidth + ButtonGapBetween), 0); ButtonOptions.Bounds = new Rectangle(point, buttonSize); } private void Close_Click(object sender, EventArgs e) { DockPane.CloseActiveContent(); } private void AutoHide_Click(object sender, EventArgs e) { DockPane.DockState = DockHelper.ToggleAutoHideState(DockPane.DockState); if (DockHelper.IsDockAutoHide(DockPane.DockState)) { DockPane.DockPanel.ActiveAutoHideContent = null; DockPane.NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(DockPane); } } private void Options_Click(object sender, EventArgs e) { ShowTabPageContextMenu(PointToClient(Control.MousePosition)); } } }
// 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.Dynamic.Utils; namespace System.Linq.Expressions.Interpreter { internal abstract class GreaterThanOrEqualInstruction : Instruction { private readonly object _nullValue; private static Instruction s_SByte, s_Int16, s_Char, s_Int32, s_Int64, s_Byte, s_UInt16, s_UInt32, s_UInt64, s_Single, s_Double; private static Instruction s_liftedToNullSByte, s_liftedToNullInt16, s_liftedToNullChar, s_liftedToNullInt32, s_liftedToNullInt64, s_liftedToNullByte, s_liftedToNullUInt16, s_liftedToNullUInt32, s_liftedToNullUInt64, s_liftedToNullSingle, s_liftedToNullDouble; public override int ConsumedStack => 2; public override int ProducedStack => 1; public override string InstructionName => "GreaterThanOrEqual"; private GreaterThanOrEqualInstruction(object nullValue) { _nullValue = nullValue; } private sealed class GreaterThanOrEqualSByte : GreaterThanOrEqualInstruction { public GreaterThanOrEqualSByte(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((sbyte)left >= (sbyte)right); } return 1; } } private sealed class GreaterThanOrEqualInt16 : GreaterThanOrEqualInstruction { public GreaterThanOrEqualInt16(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((short)left >= (short)right); } return 1; } } private sealed class GreaterThanOrEqualChar : GreaterThanOrEqualInstruction { public GreaterThanOrEqualChar(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((char)left >= (char)right); } return 1; } } private sealed class GreaterThanOrEqualInt32 : GreaterThanOrEqualInstruction { public GreaterThanOrEqualInt32(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((int)left >= (int)right); } return 1; } } private sealed class GreaterThanOrEqualInt64 : GreaterThanOrEqualInstruction { public GreaterThanOrEqualInt64(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((long)left >= (long)right); } return 1; } } private sealed class GreaterThanOrEqualByte : GreaterThanOrEqualInstruction { public GreaterThanOrEqualByte(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((byte)left >= (byte)right); } return 1; } } private sealed class GreaterThanOrEqualUInt16 : GreaterThanOrEqualInstruction { public GreaterThanOrEqualUInt16(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((ushort)left >= (ushort)right); } return 1; } } private sealed class GreaterThanOrEqualUInt32 : GreaterThanOrEqualInstruction { public GreaterThanOrEqualUInt32(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((uint)left >= (uint)right); } return 1; } } private sealed class GreaterThanOrEqualUInt64 : GreaterThanOrEqualInstruction { public GreaterThanOrEqualUInt64(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((ulong)left >= (ulong)right); } return 1; } } private sealed class GreaterThanOrEqualSingle : GreaterThanOrEqualInstruction { public GreaterThanOrEqualSingle(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((float)left >= (float)right); } return 1; } } private sealed class GreaterThanOrEqualDouble : GreaterThanOrEqualInstruction { public GreaterThanOrEqualDouble(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((double)left >= (double)right); } return 1; } } public static Instruction Create(Type type, bool liftedToNull = false) { Debug.Assert(!type.IsEnum); if (liftedToNull) { switch (type.GetNonNullableType().GetTypeCode()) { case TypeCode.SByte: return s_liftedToNullSByte ?? (s_liftedToNullSByte = new GreaterThanOrEqualSByte(null)); case TypeCode.Int16: return s_liftedToNullInt16 ?? (s_liftedToNullInt16 = new GreaterThanOrEqualInt16(null)); case TypeCode.Char: return s_liftedToNullChar ?? (s_liftedToNullChar = new GreaterThanOrEqualChar(null)); case TypeCode.Int32: return s_liftedToNullInt32 ?? (s_liftedToNullInt32 = new GreaterThanOrEqualInt32(null)); case TypeCode.Int64: return s_liftedToNullInt64 ?? (s_liftedToNullInt64 = new GreaterThanOrEqualInt64(null)); case TypeCode.Byte: return s_liftedToNullByte ?? (s_liftedToNullByte = new GreaterThanOrEqualByte(null)); case TypeCode.UInt16: return s_liftedToNullUInt16 ?? (s_liftedToNullUInt16 = new GreaterThanOrEqualUInt16(null)); case TypeCode.UInt32: return s_liftedToNullUInt32 ?? (s_liftedToNullUInt32 = new GreaterThanOrEqualUInt32(null)); case TypeCode.UInt64: return s_liftedToNullUInt64 ?? (s_liftedToNullUInt64 = new GreaterThanOrEqualUInt64(null)); case TypeCode.Single: return s_liftedToNullSingle ?? (s_liftedToNullSingle = new GreaterThanOrEqualSingle(null)); case TypeCode.Double: return s_liftedToNullDouble ?? (s_liftedToNullDouble = new GreaterThanOrEqualDouble(null)); default: throw ContractUtils.Unreachable; } } else { switch (type.GetNonNullableType().GetTypeCode()) { case TypeCode.SByte: return s_SByte ?? (s_SByte = new GreaterThanOrEqualSByte(Utils.BoxedFalse)); case TypeCode.Int16: return s_Int16 ?? (s_Int16 = new GreaterThanOrEqualInt16(Utils.BoxedFalse)); case TypeCode.Char: return s_Char ?? (s_Char = new GreaterThanOrEqualChar(Utils.BoxedFalse)); case TypeCode.Int32: return s_Int32 ?? (s_Int32 = new GreaterThanOrEqualInt32(Utils.BoxedFalse)); case TypeCode.Int64: return s_Int64 ?? (s_Int64 = new GreaterThanOrEqualInt64(Utils.BoxedFalse)); case TypeCode.Byte: return s_Byte ?? (s_Byte = new GreaterThanOrEqualByte(Utils.BoxedFalse)); case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new GreaterThanOrEqualUInt16(Utils.BoxedFalse)); case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new GreaterThanOrEqualUInt32(Utils.BoxedFalse)); case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new GreaterThanOrEqualUInt64(Utils.BoxedFalse)); case TypeCode.Single: return s_Single ?? (s_Single = new GreaterThanOrEqualSingle(Utils.BoxedFalse)); case TypeCode.Double: return s_Double ?? (s_Double = new GreaterThanOrEqualDouble(Utils.BoxedFalse)); default: throw ContractUtils.Unreachable; } } } } }
using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; using Microsoft.Extensions.Logging; using Orleans.Configuration; using Orleans.Messaging; namespace Orleans.Runtime.Messaging { internal sealed class SiloConnection : Connection { private static readonly Response PingResponse = new Response(null); private readonly MessageCenter messageCenter; private readonly ConnectionManager connectionManager; private readonly ConnectionOptions connectionOptions; public SiloConnection( SiloAddress remoteSiloAddress, ConnectionContext connection, ConnectionDelegate middleware, IServiceProvider serviceProvider, INetworkingTrace trace, MessageCenter messageCenter, MessageFactory messageFactory, ILocalSiloDetails localSiloDetails, ConnectionManager connectionManager, ConnectionOptions connectionOptions) : base(connection, middleware, messageFactory, serviceProvider, trace) { this.messageCenter = messageCenter; this.connectionManager = connectionManager; this.connectionOptions = connectionOptions; this.LocalSiloAddress = localSiloDetails.SiloAddress; this.RemoteSiloAddress = remoteSiloAddress; } public SiloAddress RemoteSiloAddress { get; private set; } public SiloAddress LocalSiloAddress { get; } protected override ConnectionDirection ConnectionDirection => ConnectionDirection.SiloToSilo; protected override IMessageCenter MessageCenter => this.messageCenter; public NetworkProtocolVersion RemoteProtocolVersion { get; private set; } protected override void OnReceivedMessage(Message msg) { // See it's a Ping message, and if so, short-circuit it if (msg.IsPing()) { this.HandlePingMessage(msg); return; } // sniff message headers for directory cache management this.messageCenter.SniffIncomingMessage?.Invoke(msg); // Don't process messages that have already timed out if (msg.IsExpired) { msg.DropExpiredMessage(this.Log, MessagingStatisticsGroup.Phase.Receive); return; } // If we've stopped application message processing, then filter those out now // Note that if we identify or add other grains that are required for proper stopping, we will need to treat them as we do the membership table grain here. if (messageCenter.IsBlockingApplicationMessages && (msg.Category == Message.Categories.Application) && !Constants.SystemMembershipTableId.Equals(msg.SendingGrain)) { // We reject new requests, and drop all other messages if (msg.Direction != Message.Directions.Request) return; MessagingStatisticsGroup.OnRejectedMessage(msg); var rejection = this.MessageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable, "Silo stopping"); this.Send(rejection); return; } // Make sure the message is for us. Note that some control messages may have no target // information, so a null target silo is OK. if ((msg.TargetSilo == null) || msg.TargetSilo.Matches(this.LocalSiloAddress)) { // See if it's a message for a client we're proxying. if (messageCenter.IsProxying && messageCenter.TryDeliverToProxy(msg)) return; // Nope, it's for us messageCenter.OnReceivedMessage(msg); return; } if (!msg.TargetSilo.Endpoint.Equals(this.LocalSiloAddress.Endpoint)) { // If the message is for some other silo altogether, then we need to forward it. if (this.Log.IsEnabled(LogLevel.Trace)) this.Log.Trace("Forwarding message {0} from {1} to silo {2}", msg.Id, msg.SendingSilo, msg.TargetSilo); messageCenter.OutboundQueue.SendMessage(msg); return; } // If the message was for this endpoint but an older epoch, then reject the message // (if it was a request), or drop it on the floor if it was a response or one-way. if (msg.Direction == Message.Directions.Request) { MessagingStatisticsGroup.OnRejectedMessage(msg); var rejection = this.MessageFactory.CreateRejectionResponse( msg, Message.RejectionTypes.Transient, $"The target silo is no longer active: target was {msg.TargetSilo.ToLongString()}, but this silo is {this.LocalSiloAddress.ToLongString()}. The rejected message is {msg}."); // Invalidate the remote caller's activation cache entry. if (msg.TargetAddress != null) { rejection.AddToCacheInvalidationHeader(msg.TargetAddress); } this.Send(rejection); if (this.Log.IsEnabled(LogLevel.Debug)) { this.Log.Debug( "Rejecting an obsolete request; target was {0}, but this silo is {1}. The rejected message is {2}.", msg.TargetSilo.ToLongString(), this.LocalSiloAddress.ToLongString(), msg); } } } private void HandlePingMessage(Message msg) { MessagingStatisticsGroup.OnPingReceive(msg.SendingSilo); if (this.Log.IsEnabled(LogLevel.Trace)) { var objectId = RuntimeHelpers.GetHashCode(msg); this.Log.LogTrace("Responding to Ping from {Silo} with object id {ObjectId}. Message {Message}", msg.SendingSilo, objectId, msg); } if (!msg.TargetSilo.Equals(this.LocalSiloAddress)) { // Got ping that is not destined to me. For example, got a ping to my older incarnation. MessagingStatisticsGroup.OnRejectedMessage(msg); Message rejection = this.MessageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable, $"The target silo is no longer active: target was {msg.TargetSilo.ToLongString()}, but this silo is {this.LocalSiloAddress.ToLongString()}. " + $"The rejected ping message is {msg}."); this.Send(rejection); } else { var response = this.MessageFactory.CreateResponseMessage(msg); response.BodyObject = PingResponse; this.Send(response); } } protected override void OnSendMessageFailure(Message message, string error) { if (message?.Headers != null && message.IsPing()) { this.Log.LogWarning("Failed to send ping message {Message}", message); } this.FailMessage(message, error); } protected override async Task RunInternal() { Exception error = default; try { if (this.connectionOptions.ProtocolVersion == NetworkProtocolVersion.Version1) { // This version of the protocol does not support symmetric preamble, so either send or receive preamble depending on // Whether or not this is an inbound or outbound connection. if (this.RemoteSiloAddress is null) { // Inbound connection var protocolVersion = await ReadPreamble(); // To support graceful transition to higher protocol versions, send a preamble if the remote endpoint supports it. if (protocolVersion >= NetworkProtocolVersion.Version2) { await WritePreamble(); } } else { // Outbound connection await WritePreamble(); } } else { // Later versions of the protocol send and receive preamble at both ends of the connection. if (this.RemoteSiloAddress is null) { // Inbound connection var protocolVersion = await ReadPreamble(); // To support graceful transition from lower protocol versions, only send a preamble if the remote endpoint supports it. if (protocolVersion >= NetworkProtocolVersion.Version2) { await WritePreamble(); } } else { // Outbound connection await Task.WhenAll(ReadPreamble().AsTask(), WritePreamble()); } } this.MessageReceivedCounter = MessagingStatisticsGroup.GetMessageReceivedCounter(this.RemoteSiloAddress); this.MessageSentCounter = MessagingStatisticsGroup.GetMessageSendCounter(this.RemoteSiloAddress); await base.RunInternal(); } catch (Exception exception) when ((error = exception) is null) { Debug.Fail("Execution should not be able to reach this point."); } finally { if (!(this.RemoteSiloAddress is null)) { this.connectionManager.OnConnectionTerminated(this.RemoteSiloAddress, this, error); } } async Task WritePreamble() { await ConnectionPreamble.Write( this.Context, Constants.SiloDirectConnectionId, this.connectionOptions.ProtocolVersion, this.LocalSiloAddress); } async ValueTask<NetworkProtocolVersion> ReadPreamble() { var (grainId, protocolVersion, siloAddress) = await ConnectionPreamble.Read(this.Context); if (!grainId.Equals(Constants.SiloDirectConnectionId)) { throw new InvalidOperationException("Unexpected non-proxied connection on silo endpoint."); } if (siloAddress is object) { this.RemoteSiloAddress = siloAddress; this.connectionManager.OnConnected(siloAddress, this); } this.RemoteProtocolVersion = protocolVersion; return protocolVersion; } } protected override bool PrepareMessageForSend(Message msg) { // Don't send messages that have already timed out if (msg.IsExpired) { msg.DropExpiredMessage(this.Log, MessagingStatisticsGroup.Phase.Send); if (msg.IsPing()) { this.Log.LogWarning("Droppping expired ping message {Message}", msg); } return false; } // Fill in the outbound message with our silo address, if it's not already set if (msg.SendingSilo == null) msg.SendingSilo = this.LocalSiloAddress; if (this.Log.IsEnabled(LogLevel.Debug) && msg.IsPing()) { this.Log.LogDebug("Sending ping message {Message}", msg); } if (this.RemoteSiloAddress is object && msg.TargetSilo is object && !this.RemoteSiloAddress.Matches(msg.TargetSilo)) { this.Log.LogWarning( "Attempting to send message addressed to {TargetSilo} to connection with {RemoteSiloAddress}. Message {Message}", msg.TargetSilo, this.RemoteSiloAddress, msg); } return true; } public void FailMessage(Message msg, string reason) { if (msg?.Headers != null && msg.IsPing()) { this.Log.LogWarning("Failed ping message {Message}", msg); } MessagingStatisticsGroup.OnFailedSentMessage(msg); if (msg.Direction == Message.Directions.Request) { if (this.Log.IsEnabled(LogLevel.Debug)) this.Log.Debug(ErrorCode.MessagingSendingRejection, "Silo {SiloAddress} is rejecting message: {Message}. Reason = {Reason}", this.LocalSiloAddress, msg, reason); // Done retrying, send back an error instead this.messageCenter.SendRejection(msg, Message.RejectionTypes.Transient, $"Silo {this.LocalSiloAddress} is rejecting message: {msg}. Reason = {reason}"); } else { this.Log.Info(ErrorCode.Messaging_OutgoingMS_DroppingMessage, "Silo {SiloAddress} is dropping message: {Message}. Reason = {Reason}", this.LocalSiloAddress, msg, reason); MessagingStatisticsGroup.OnDroppedSentMessage(msg); } } public override void Send(Message message) { if (this.RemoteProtocolVersion == NetworkProtocolVersion.Version1 && this.RemoteSiloAddress is null) { // Incoming Version1 connections are half-duplex (read-only) this.messageCenter.SendMessage(message); } else { base.Send(message); } } protected override void RetryMessage(Message msg, Exception ex = null) { if (msg == null) return; if (msg?.Headers != null && msg.IsPing()) { this.Log.LogWarning("Retrying ping message {Message}", msg); } if (msg.RetryCount < MessagingOptions.DEFAULT_MAX_MESSAGE_SEND_RETRIES) { msg.RetryCount = msg.RetryCount + 1; this.messageCenter.SendMessage(msg); } else { var reason = new StringBuilder("Retry count exceeded. "); if (ex != null) { reason.Append("Original exception is: ").Append(ex.ToString()); } reason.Append("Msg is: ").Append(msg); FailMessage(msg, reason.ToString()); } } } }
namespace PokerTell.LiveTracker.Tests.ViewModels { using System; using System.Collections.Generic; using Microsoft.Practices.Composite.Events; using Moq; using NUnit.Framework; using PokerTell.Infrastructure.Events; using PokerTell.Infrastructure.Interfaces; using PokerTell.Infrastructure.Interfaces.Statistics; using PokerTell.LiveTracker.Tests.Utilities; using PokerTell.LiveTracker.ViewModels; using PokerTell.UnitTests.Tools; using Tools.WPF.Interfaces; public class PokerTableStatisticsViewModelTests { Mock<IConstructor<IPlayerStatisticsViewModel>> _playerStatisticsViewModelMakeStub; StubBuilder _stub; PokerTableStatisticsViewModelTester _sut; [SetUp] public void _Init() { _stub = new StubBuilder(); _playerStatisticsViewModelMakeStub = new Mock<IConstructor<IPlayerStatisticsViewModel>>(); _playerStatisticsViewModelMakeStub .SetupGet(make => make.New) .Returns(_stub.Out<IPlayerStatisticsViewModel>); _sut = new PokerTableStatisticsViewModelTester(_playerStatisticsViewModelMakeStub.Object); } [Test] public void ApplyFilterTo_Player1TwoPlayersAtTable_AppliesFilterToPlayer1() { const string player1 = "player1"; const string player2 = "player2"; var player1Mock = AddPlayerMock(player1); AddPlayerMock(player2); var filterStub = _stub.Out<IAnalyzablePokerPlayersFilter>(); _sut.ApplyFilterToInvoke(player1, filterStub); player1Mock.VerifySet(p => p.Filter = filterStub); } [Test] public void ApplyFilterTo_Player1TwoPlayersAtTable_DoesNotApplyFilterToPlayer2() { const string player1 = "player1"; const string player2 = "player2"; AddPlayerMock(player1); var player2Mock = AddPlayerMock(player2); var filterStub = _stub.Out<IAnalyzablePokerPlayersFilter>(); _sut.ApplyFilterToInvoke(player1, filterStub); player2Mock.VerifySet(p => p.Filter = filterStub, Times.Never()); } [Test] public void ApplyFilterToAll_TwoPlayersAtTable_AppliesFilterToBothPlayers() { const string player1 = "player1"; const string player2 = "player2"; var player1Mock = AddPlayerMock(player1); var player2Mock = AddPlayerMock(player2); var filterStub = _stub.Out<IAnalyzablePokerPlayersFilter>(); _sut.ApplyFilterToAllInvoke(filterStub); player1Mock.VerifySet(p => p.Filter = filterStub); player2Mock.VerifySet(p => p.Filter = filterStub); } [Test] public void Constructor_Always_InitializesPlayers() { _sut.Players.ShouldHaveCount(0); } [Test] public void UpdateWith_DifferentPlayerThanIsInPlayers_AddsDifferentPlayer() { const string player1 = "player1"; const string differentPlayer = "differentPlayer"; AddPlayerMock(player1); var differentPlayerStatistics = Utils.PlayerStatisticsStubFor(differentPlayer); var differentPlayerMock = Utils.PlayerStatisticsVM_MockFor(differentPlayer); _playerStatisticsViewModelMakeStub .SetupGet(make => make.New) .Returns(differentPlayerMock.Object); _sut.UpdateWith(new[] { differentPlayerStatistics }); _sut.Players.ShouldContain(differentPlayerMock.Object); } [Test] public void UpdateWith_DifferentPlayerThanIsInPlayers_DoesNotUpdateOriginalPlayer() { const string player1 = "player1"; const string differentPlayer = "differentPlayer"; var player1Mock = AddPlayerMock(player1); var differentPlayerStatistics = Utils.PlayerStatisticsStubFor(differentPlayer); _sut.UpdateWith(new[] { differentPlayerStatistics }); player1Mock.Verify(p => p.UpdateWith(differentPlayerStatistics), Times.Never()); } [Test] public void UpdateWith_DifferentPlayerThanIsInPlayers_RemovesOriginalPlayer() { const string player1 = "player1"; const string differentPlayer = "differentPlayer"; var player1Mock = AddPlayerMock(player1); var differentPlayerStatistics = Utils.PlayerStatisticsStubFor(differentPlayer); _sut.UpdateWith(new[] { differentPlayerStatistics }); _sut.Players.ShouldNotContain(player1Mock.Object); } [Test] public void UpdateWith_DifferentPlayerThanIsInPlayers_UpdatesDifferentPlayer() { const string player1 = "player1"; const string differentPlayer = "differentPlayer"; AddPlayerMock(player1); var differentPlayerStatistics = Utils.PlayerStatisticsStubFor(differentPlayer); var differentPlayerMock = Utils.PlayerStatisticsVM_MockFor(differentPlayer); _playerStatisticsViewModelMakeStub .SetupGet(make => make.New) .Returns(differentPlayerMock.Object); _sut.UpdateWith(new[] { differentPlayerStatistics }); differentPlayerMock.Verify(p => p.UpdateWith(differentPlayerStatistics)); } [Test] public void UpdateWith_EmptyList_ThrowsArgumentException() { Assert.Throws<ArgumentException>(() => _sut.UpdateWith(new List<IPlayerStatistics>())); } [Test] public void UpdateWith_SamePlayerAsIsInPlayers_UpdatesThatPlayer() { const string player1 = "player1"; var player1Mock = AddPlayerMock(player1); var player1Statistics = Utils.PlayerStatisticsStubFor(player1); _sut.UpdateWith(new[] { player1Statistics }); player1Mock.Verify(p => p.UpdateWith(player1Statistics)); } [Test] public void UpdateWith_SelectedPlayerNotInStatistics_SelectedPlayerIsSetToFirstPlayer() { const string player1 = "player1"; const string player2 = "player2"; var player1Mock = AddPlayerMock(player1); var player2Mock = AddPlayerMock(player2); _sut.SelectedPlayer = player2Mock.Object; _sut.UpdateWith(new[] { Utils.PlayerStatisticsStubFor(player1) }); _sut.SelectedPlayer.ShouldBeEqualTo(player1Mock.Object); } Mock<IPlayerStatisticsViewModel> AddPlayerMock(string name) { var playerViewModelMock = Utils.PlayerStatisticsVM_MockFor(name); _sut.Players.Add(playerViewModelMock.Object); return playerViewModelMock; } class PokerTableStatisticsViewModelTester : PokerTableStatisticsViewModel { public PokerTableStatisticsViewModelTester(IConstructor<IPlayerStatisticsViewModel> playerStatisticsViewModelMake) : base( new Mock<ISettings>().Object, new Mock<IDimensionsViewModel>().Object, playerStatisticsViewModelMake, new StubBuilder().Out<IDetailedStatisticsAnalyzerViewModel>(), new StubBuilder().Out<IActiveAnalyzablePlayersSelector>(), new StubBuilder().Out<IFilterPopupViewModel>()) { } public void ApplyFilterToAllInvoke(IAnalyzablePokerPlayersFilter filter) { ApplyFilterToAll(filter); } public void ApplyFilterToInvoke(string playerName, IAnalyzablePokerPlayersFilter filter) { ApplyFilterTo(playerName, filter); } } } }
// Copyright 2016 Esri // // 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 ArcGIS.Core.Geometry; using ArcGIS.Desktop.Framework.Threading.Tasks; using ArcGIS.Desktop.Mapping; using CoordinateConversionLibrary; using CoordinateConversionLibrary.Helpers; using CoordinateConversionLibrary.Models; using Jitbit.Utils; using ProAppCoordConversionModule.Models; using ProAppCoordConversionModule.Views; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace ProAppCoordConversionModule.ViewModels { public class ProCollectTabViewModel : ProTabBaseViewModel { public ProCollectTabViewModel() { ListBoxItemAddInPoint = null; CoordinateAddInPoints = new ObservableCollection<AddInPoint>(); DeletePointCommand = new RelayCommand(OnDeletePointCommand); DeleteAllPointsCommand = new RelayCommand(OnDeleteAllPointsCommand); ClearGraphicsCommand = new RelayCommand(OnClearGraphicsCommand); EnterKeyCommand = new RelayCommand(OnEnterKeyCommand); SaveAsCommand = new RelayCommand(OnSaveAsCommand); CopyCoordinateCommand = new RelayCommand(OnCopyCommand); CopyAllCoordinatesCommand = new RelayCommand(OnCopyAllCommand); PasteCoordinatesCommand = new RelayCommand(OnPasteCommand); // Listen to collection changed event and notify colleagues CoordinateAddInPoints.CollectionChanged += CoordinateAddInPoints_CollectionChanged; Mediator.Register(CoordinateConversionLibrary.Constants.SetListBoxItemAddInPoint, OnSetListBoxItemAddInPoint); Mediator.Register(CoordinateConversionLibrary.Constants.IMPORT_COORDINATES, OnImportCoordinates); } /// <summary> /// Notify if collection list has any items /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CoordinateAddInPoints_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { Mediator.NotifyColleagues(CoordinateConversionLibrary.Constants.CollectListHasItems, CoordinateAddInPoints.Any()); } private void OnImportCoordinates(object obj) { var progressDialog = new ProgressDialog("Processing.. Please wait"); progressDialog.Show(); try { IsToolActive = false; if (obj == null) return; var input = obj as List<Dictionary<string, Tuple<object, bool>>>; if (input != null) foreach (var item in input) { var coordinate = item.Where(x => x.Key == OutputFieldName).Select(x => Convert.ToString(x.Value.Item1)).FirstOrDefault(); if (coordinate == "" || item.Where(x => x.Key == PointFieldName).Any()) continue; this.ProcessInputValue(coordinate); InputCoordinate = coordinate; if (!HasInputError) { if (item.ContainsKey(PointFieldName)) continue; item.Add(PointFieldName, Tuple.Create((object)proCoordGetter.Point, false)); OnNewMapPoint(item); } } else { List<string> coordinates = obj as List<string>; if (coordinates == null) return; this.ClearListBoxSelection(); foreach (var coordinate in coordinates) { ProcessInputValue(coordinate); InputCoordinate = coordinate; if (!HasInputError) OnNewMapPoint(proCoordGetter.Point); } InputCoordinate = ""; } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Failed in OnImportCoordinates: " + ex.Message); } progressDialog.Hide(); } private void ClearListBoxSelection() { UpdateHighlightedGraphics(true); Mediator.NotifyColleagues(CoordinateConversionLibrary.Constants.CollectListHasItems, CoordinateAddInPoints.Any()); } public bool HasListBoxRightClickSelectedItem { get { return ListBoxItemAddInPoint != null; } } public bool HasAnySelectedItems { get { return CoordinateAddInPoints.Any(p => p.IsSelected == true); } } public AddInPoint ListBoxItemAddInPoint { get; set; } private object _ListBoxSelectedItem = null; public object ListBoxSelectedItem { get { return _ListBoxSelectedItem; } set { // we are using this to know when the selection changes // setting null will allow this setter to be called in multiple selection mode _ListBoxSelectedItem = null; RaisePropertyChanged(() => ListBoxSelectedItem); // update selections UpdateHighlightedGraphics(false); var addinPoint = CoordinateAddInPoints.Where(x => x.IsSelected).FirstOrDefault(); proCoordGetter.Point = addinPoint.Point; Mediator.NotifyColleagues(CoordinateConversionLibrary.Constants.RequestOutputUpdate, null); } } private int _ListBoxSelectedIndex = -1; public int ListBoxSelectedIndex { get { return _ListBoxSelectedIndex; } set { // this works with the ListBoxSelectedItem // without this the un-selecting of 1 will not trigger an update _ListBoxSelectedIndex = value; RaisePropertyChanged(() => ListBoxSelectedIndex); } } public RelayCommand DeletePointCommand { get; set; } public RelayCommand DeleteAllPointsCommand { get; set; } public RelayCommand ClearGraphicsCommand { get; set; } public RelayCommand EnterKeyCommand { get; set; } public RelayCommand SaveAsCommand { get; set; } public RelayCommand CopyCoordinateCommand { get; set; } public RelayCommand CopyAllCoordinatesCommand { get; set; } public RelayCommand PasteCoordinatesCommand { get; set; } private void OnDeletePointCommand(object obj) { var items = obj as IList; if (items == null) return; var objects = items.Cast<AddInPoint>().ToList(); DeletePoints(objects); } private void OnDeleteAllPointsCommand(object obj) { DeletePoints(CoordinateAddInPoints.ToList()); } private void OnClearGraphicsCommand(object obj) { DeletePoints(CoordinateAddInPoints.ToList()); } private void OnEnterKeyCommand(object obj) { if (!HasInputError && InputCoordinate.Length > 0) { AddCollectionPoint(proCoordGetter.Point); } } // Call CopyAllCoordinateOutputs event private void OnCopyAllCommand(object obj) { OnCopyAllCoordinateOutputs(CoordinateAddInPoints.ToList()); } // copy parameter to clipboard public override void OnCopyCommand(object obj) { var items = obj as IList; if (items == null) return; var objects = items.Cast<AddInPoint>().ToList(); if (!objects.Any()) return; var sb = new StringBuilder(); foreach (var point in objects) { sb.AppendLine(point.Text); } if (sb.Length > 0) { // copy to clipboard System.Windows.Clipboard.SetText(sb.ToString()); } } private async void OnSaveAsCommand(object obj) { var saveAsDialog = new ProSaveAsFormatView(); var vm = new ProSaveAsFormatViewModel(); saveAsDialog.DataContext = vm; if (saveAsDialog.ShowDialog() == true) { IsToolActive = false; var fcUtils = new FeatureClassUtils(); string path = fcUtils.PromptUserWithSaveDialog(vm.FeatureIsChecked, vm.ShapeIsChecked, vm.KmlIsChecked, vm.CSVIsChecked); if (path != null) { var displayAmb = CoordinateConversionLibraryConfig.AddInConfig.DisplayAmbiguousCoordsDlg; CoordinateConversionLibraryConfig.AddInConfig.DisplayAmbiguousCoordsDlg = false; try { string folderName = System.IO.Path.GetDirectoryName(path); var mapPointList = CoordinateAddInPoints.Select(i => i.Point).ToList(); if (vm.FeatureIsChecked) { var ccMapPointList = GetMapPointExportFormat(CoordinateAddInPoints); await fcUtils.CreateFCOutput(path, SaveAsType.FileGDB, ccMapPointList, MapView.Active.Map.SpatialReference, MapView.Active, CoordinateConversionLibrary.GeomType.Point); } else if (vm.ShapeIsChecked || vm.KmlIsChecked) { var ccMapPointList = GetMapPointExportFormat(CoordinateAddInPoints); await fcUtils.CreateFCOutput(path, SaveAsType.Shapefile, ccMapPointList, MapView.Active.Map.SpatialReference, MapView.Active, CoordinateConversionLibrary.GeomType.Point, vm.KmlIsChecked); } else if (vm.CSVIsChecked) { var aiPoints = CoordinateAddInPoints.ToList(); if (!aiPoints.Any()) return; var csvExport = new CsvExport(); foreach (var point in aiPoints) { var results = GetOutputFormats(point); csvExport.AddRow(); foreach (var item in results) csvExport[item.Key] = item.Value; if (point.FieldsDictionary != null) { foreach (KeyValuePair<string, Tuple<object, bool>> item in point.FieldsDictionary) if (item.Key != PointFieldName && item.Key != OutputFieldName) csvExport[item.Key] = item.Value.Item1; } } csvExport.ExportToFile(path); System.Windows.Forms.MessageBox.Show(CoordinateConversionLibrary.Properties.Resources.CSVExportSuccessfulMessage + path, CoordinateConversionLibrary.Properties.Resources.CSVExportSuccessfulCaption); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } CoordinateConversionLibraryConfig.AddInConfig.DisplayAmbiguousCoordsDlg = displayAmb; } } } private List<CCProGraphic> GetMapPointExportFormat(ObservableCollection<AddInPoint> mapPointList) { List<CCProGraphic> results = new List<CCProGraphic>(); var columnCollection = new List<string>(); var dictionary = new Dictionary<string, object>(); foreach (var point in mapPointList) { var attributes = GetOutputFormats(point); if (point.FieldsDictionary != null) { foreach (KeyValuePair<string, Tuple<object, bool>> item in point.FieldsDictionary) if (item.Key != PointFieldName && item.Key != OutputFieldName) { attributes[item.Key] = Convert.ToString(item.Value.Item1); if (!columnCollection.Contains(item.Key)) columnCollection.Add(item.Key); } } CCProGraphic ccMapPoint = new CCProGraphic() { Attributes = attributes, MapPoint = point.Point }; results.Add(ccMapPoint); } foreach (var item in results) { foreach (var column in columnCollection) { if (!item.Attributes.ContainsKey(column)) { item.Attributes.Add(column, null); } } } return results; } /// <summary> /// Copies all coordinates to the clipboard /// </summary> /// <param name="obj"></param> private void OnCopyAllCoordinateOutputs(List<AddInPoint> aiPoints) { var sb = new StringBuilder(); if (aiPoints == null || !aiPoints.Any()) return; foreach (var point in aiPoints) { sb.AppendLine(point.Text); } if (sb.Length > 0) { // copy to clipboard System.Windows.Clipboard.SetText(sb.ToString()); } } private async void AddCollectionPoint(MapPoint point, Dictionary<string, Tuple<object, bool>> fieldsDictionary = null) { var guid = await AddGraphicToMap(point, ColorFactory.Instance.RedRGB, true, 7); var addInPoint = new AddInPoint() { Point = point, GUID = guid, FieldsDictionary = fieldsDictionary }; //Add point to the top of the list CoordinateAddInPoints.Add(addInPoint); } private void RemoveGraphics(List<string> guidList) { var list = ProGraphicsList.Where(g => guidList.Contains(g.GUID)).ToList(); foreach (var graphic in list) { if (graphic.Disposable != null) graphic.Disposable.Dispose(); ProGraphicsList.Remove(graphic); } //TODO do we still use HasMapGraphics? //RaisePropertyChanged(() => HasMapGraphics); } private void DeletePoints(List<AddInPoint> aiPoints) { if (aiPoints == null || !aiPoints.Any()) return; // remove graphics from map var guidList = aiPoints.Select(x => x.GUID).ToList(); RemoveGraphics(guidList); foreach (var point in aiPoints) { CoordinateAddInPoints.Remove(point); } } private void OnSetListBoxItemAddInPoint(object obj) { ListBoxItemAddInPoint = obj as AddInPoint; RaisePropertyChanged(() => HasListBoxRightClickSelectedItem); } public override void OnPasteCommand(object obj) { var input = Clipboard.GetText().Trim(); string[] lines = input.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); var coordinates = new List<string>(); foreach (var item in lines) { if (item.Trim() == "") continue; var sb = new StringBuilder(); sb.Append(item.Trim()); coordinates.Add(sb.ToString()); } Mediator.NotifyColleagues(CoordinateConversionLibrary.Constants.IMPORT_COORDINATES, coordinates); } #region overrides internal override void OnFlashPointCommandAsync(object obj) { if (MapView.Active == null) { System.Windows.Forms.MessageBox.Show(CoordinateConversionLibrary.Properties.Resources.LoadMapMsg); return; } if (ListBoxItemAddInPoint != null) { var geometry = ListBoxItemAddInPoint.Point; ListBoxItemAddInPoint = null; base.OnFlashPointCommandAsync(geometry); } } public override bool OnNewMapPoint(object obj) { if (!base.OnNewMapPoint(obj)) return false; var input = obj as Dictionary<string, Tuple<object, bool>>; if (input != null) { var point = input.Where(x => x.Key == PointFieldName).Select(x => x.Value.Item1).FirstOrDefault(); AddCollectionPoint(point as MapPoint, input); } else { var point = obj as MapPoint; AddCollectionPoint(point, input); } return true; } public override void OnDisplayCoordinateTypeChanged(CoordinateConversionLibrary.Models.CoordinateConversionLibraryConfig obj) { base.OnDisplayCoordinateTypeChanged(obj); // update list box coordinates var list = CoordinateAddInPoints.ToList(); CoordinateAddInPoints.Clear(); foreach (var item in list) CoordinateAddInPoints.Add(item); } public override async void OnMapPointSelection(object obj) { var mp = obj as MapPoint; var dblSrchDis = MapView.Active.Extent.Width / 200; var poly = GeometryEngine.Instance.Buffer(mp, dblSrchDis); AddInPoint closestPoint = null; Double distance = 0; foreach (var item in ProCollectTabViewModel.CoordinateAddInPoints) { if (item.Point.SpatialReference != MapView.Active.Map.SpatialReference) item.Point = GeometryEngine.Instance.Project(item.Point, MapView.Active.Map.SpatialReference) as MapPoint; var isWithinExtent = await IsPointWithinExtent(item.Point, poly.Extent); if (isWithinExtent) { double resultDistance = GeometryEngine.Instance.Distance(item.Point, mp); distance = (distance < resultDistance && distance > 0) ? distance : resultDistance; if (resultDistance == distance) { closestPoint = item; distance = resultDistance; } } } if (closestPoint != null) { closestPoint.IsSelected = true; ListBoxSelectedItem = closestPoint; } RaisePropertyChanged(() => ListBoxSelectedItem); } #endregion overrides internal async Task<bool> IsPointWithinExtent(MapPoint point, Envelope env) { var result = await QueuedTask.Run(() => { Geometry projectedPoint = GeometryEngine.Instance.Project(point, env.SpatialReference); return GeometryEngine.Instance.Contains(env, projectedPoint); }); return result; } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft 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 AutoMapper; using Microsoft.Azure.Commands.Network.Models; using Microsoft.Azure.Commands.ResourceManager.Common.Tags; using Microsoft.Azure.Management.Network; using System; using System.Collections; using System.Collections.Generic; using System.Management.Automation; using MNM = Microsoft.Azure.Management.Network.Models; namespace Microsoft.Azure.Commands.Network { [Cmdlet(VerbsCommon.New, "AzureRmVirtualNetworkGateway", SupportsShouldProcess = true), OutputType(typeof(PSVirtualNetworkGateway))] public class NewAzureVirtualNetworkGatewayCommand : VirtualNetworkGatewayBaseCmdlet { [Alias("ResourceName")] [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource name.")] [ValidateNotNullOrEmpty] public virtual string Name { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")] [ValidateNotNullOrEmpty] public virtual string ResourceGroupName { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "location.")] [ValidateNotNullOrEmpty] public string Location { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The IpConfigurations for Virtual network gateway.")] [ValidateNotNullOrEmpty] public List<PSVirtualNetworkGatewayIpConfiguration> IpConfigurations { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The type of this virtual network gateway: Vpn, ExoressRoute")] [ValidateSet( MNM.VirtualNetworkGatewayType.Vpn, MNM.VirtualNetworkGatewayType.ExpressRoute, IgnoreCase = true)] public string GatewayType { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The type of the Vpn:PolicyBased/RouteBased")] [ValidateSet( MNM.VpnType.PolicyBased, MNM.VpnType.RouteBased, IgnoreCase = true)] public string VpnType { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "EnableBgp Flag")] public bool EnableBgp { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The type of the Vpn:PolicyBased/RouteBased")] [ValidateSet( MNM.VirtualNetworkGatewaySkuTier.Basic, MNM.VirtualNetworkGatewaySkuTier.Standard, MNM.VirtualNetworkGatewaySkuTier.HighPerformance, IgnoreCase = true)] public string GatewaySku { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = "SetByResource", HelpMessage = "GatewayDefaultSite")] public PSLocalNetworkGateway GatewayDefaultSite { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "P2S VpnClient AddressPool")] [ValidateNotNullOrEmpty] public List<string> VpnClientAddressPool { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of VpnClientRootCertificates to be added.")] public List<PSVpnClientRootCertificate> VpnClientRootCertificates { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of VpnClientCertificates to be revoked.")] public List<PSVpnClientRevokedCertificate> VpnClientRevokedCertificates { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The virtual network gateway's ASN for BGP over VPN")] public uint Asn { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The weight added to routes learned over BGP from this virtual network gateway")] public int PeerWeight { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "An array of hashtables which represents resource tags.")] public Hashtable[] Tag { get; set; } [Parameter( Mandatory = false, HelpMessage = "Do not ask for confirmation if you want to overrite a resource")] public SwitchParameter Force { get; set; } public override void Execute() { base.Execute(); WriteWarning("The output object type of this cmdlet will be modified in a future release."); var present = this.IsVirtualNetworkGatewayPresent(this.ResourceGroupName, this.Name); ConfirmAction( Force.IsPresent, string.Format(Properties.Resources.OverwritingResource, Name), Properties.Resources.CreatingResourceMessage, Name, () => { var virtualNetworkGateway = CreateVirtualNetworkGateway(); WriteObject(virtualNetworkGateway); }, () => present); } private PSVirtualNetworkGateway CreateVirtualNetworkGateway() { var vnetGateway = new PSVirtualNetworkGateway(); vnetGateway.Name = this.Name; vnetGateway.ResourceGroupName = this.ResourceGroupName; vnetGateway.Location = this.Location; if (this.IpConfigurations != null) { vnetGateway.IpConfigurations = this.IpConfigurations; } vnetGateway.GatewayType = this.GatewayType; vnetGateway.VpnType = this.VpnType; vnetGateway.EnableBgp = this.EnableBgp; if (this.GatewayDefaultSite != null) { vnetGateway.GatewayDefaultSite = new PSResourceId(); vnetGateway.GatewayDefaultSite.Id = this.GatewayDefaultSite.Id; } else { vnetGateway.GatewayDefaultSite = null; } if (this.GatewaySku != null) { vnetGateway.Sku = new PSVirtualNetworkGatewaySku(); vnetGateway.Sku.Tier = this.GatewaySku; vnetGateway.Sku.Name = this.GatewaySku; } else { vnetGateway.Sku = null; } if (this.VpnClientAddressPool != null || this.VpnClientRootCertificates != null || this.VpnClientRevokedCertificates != null) { vnetGateway.VpnClientConfiguration = new PSVpnClientConfiguration(); if (this.VpnClientAddressPool != null) { // Make sure passed Virtual Network gateway type is RouteBased if P2S VpnClientAddressPool is specified. if (this.VpnType == null || !this.VpnType.Equals(MNM.VpnType.RouteBased)) { throw new ArgumentException("Virtual Network Gateway VpnType should be :{0} when P2S VpnClientAddressPool is specified."); } vnetGateway.VpnClientConfiguration.VpnClientAddressPool = new PSAddressSpace(); vnetGateway.VpnClientConfiguration.VpnClientAddressPool.AddressPrefixes = this.VpnClientAddressPool; } if (this.VpnClientRootCertificates != null) { vnetGateway.VpnClientConfiguration.VpnClientRootCertificates = this.VpnClientRootCertificates; } if (this.VpnClientRevokedCertificates != null) { vnetGateway.VpnClientConfiguration.VpnClientRevokedCertificates = this.VpnClientRevokedCertificates; } } else { vnetGateway.VpnClientConfiguration = null; } if (this.Asn > 0 || this.PeerWeight > 0) { vnetGateway.BgpSettings = new PSBgpSettings(); vnetGateway.BgpSettings.BgpPeeringAddress = null; // We block modifying the gateway's BgpPeeringAddress (CA) if (this.Asn > 0) { vnetGateway.BgpSettings.Asn = this.Asn; } if (this.PeerWeight > 0) { vnetGateway.BgpSettings.PeerWeight = this.PeerWeight; } else if (this.PeerWeight < 0) { throw new ArgumentException("PeerWeight must be a positive integer"); } } // Map to the sdk object var vnetGatewayModel = Mapper.Map<MNM.VirtualNetworkGateway>(vnetGateway); vnetGatewayModel.Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true); // Execute the Create VirtualNetwork call this.VirtualNetworkGatewayClient.CreateOrUpdate(this.ResourceGroupName, this.Name, vnetGatewayModel); var getVirtualNetworkGateway = this.GetVirtualNetworkGateway(this.ResourceGroupName, this.Name); return getVirtualNetworkGateway; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // 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. // File System.Windows.Controls.ScrollViewer.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Controls { public partial class ScrollViewer : ContentControl { #region Methods and constructors public static bool GetCanContentScroll(System.Windows.DependencyObject element) { return default(bool); } public static ScrollBarVisibility GetHorizontalScrollBarVisibility(System.Windows.DependencyObject element) { return default(ScrollBarVisibility); } public static bool GetIsDeferredScrollingEnabled(System.Windows.DependencyObject element) { return default(bool); } public static double GetPanningDeceleration(System.Windows.DependencyObject element) { return default(double); } public static PanningMode GetPanningMode(System.Windows.DependencyObject element) { return default(PanningMode); } public static double GetPanningRatio(System.Windows.DependencyObject element) { return default(double); } public static ScrollBarVisibility GetVerticalScrollBarVisibility(System.Windows.DependencyObject element) { return default(ScrollBarVisibility); } protected override System.Windows.Media.HitTestResult HitTestCore(System.Windows.Media.PointHitTestParameters hitTestParameters) { return default(System.Windows.Media.HitTestResult); } public void InvalidateScrollInfo() { } public void LineDown() { } public void LineLeft() { } public void LineRight() { } public void LineUp() { } protected override System.Windows.Size MeasureOverride(System.Windows.Size constraint) { return default(System.Windows.Size); } public override void OnApplyTemplate() { } protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer() { return default(System.Windows.Automation.Peers.AutomationPeer); } protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e) { } protected override void OnManipulationCompleted(System.Windows.Input.ManipulationCompletedEventArgs e) { } protected override void OnManipulationDelta(System.Windows.Input.ManipulationDeltaEventArgs e) { } protected override void OnManipulationInertiaStarting(System.Windows.Input.ManipulationInertiaStartingEventArgs e) { } protected override void OnManipulationStarting(System.Windows.Input.ManipulationStartingEventArgs e) { } protected override void OnMouseLeftButtonDown(System.Windows.Input.MouseButtonEventArgs e) { } protected override void OnMouseWheel(System.Windows.Input.MouseWheelEventArgs e) { } protected virtual new void OnScrollChanged(ScrollChangedEventArgs e) { } public void PageDown() { } public void PageLeft() { } public void PageRight() { } public void PageUp() { } public void ScrollToBottom() { } public void ScrollToEnd() { } public void ScrollToHome() { } public void ScrollToHorizontalOffset(double offset) { } public void ScrollToLeftEnd() { } public void ScrollToRightEnd() { } public void ScrollToTop() { } public void ScrollToVerticalOffset(double offset) { } public ScrollViewer() { } public static void SetCanContentScroll(System.Windows.DependencyObject element, bool canContentScroll) { } public static void SetHorizontalScrollBarVisibility(System.Windows.DependencyObject element, ScrollBarVisibility horizontalScrollBarVisibility) { } public static void SetIsDeferredScrollingEnabled(System.Windows.DependencyObject element, bool value) { } public static void SetPanningDeceleration(System.Windows.DependencyObject element, double value) { } public static void SetPanningMode(System.Windows.DependencyObject element, PanningMode panningMode) { } public static void SetPanningRatio(System.Windows.DependencyObject element, double value) { } public static void SetVerticalScrollBarVisibility(System.Windows.DependencyObject element, ScrollBarVisibility verticalScrollBarVisibility) { } #endregion #region Properties and indexers public bool CanContentScroll { get { return default(bool); } set { } } public System.Windows.Visibility ComputedHorizontalScrollBarVisibility { get { return default(System.Windows.Visibility); } } public System.Windows.Visibility ComputedVerticalScrollBarVisibility { get { return default(System.Windows.Visibility); } } public double ContentHorizontalOffset { get { return default(double); } private set { } } public double ContentVerticalOffset { get { return default(double); } private set { } } public double ExtentHeight { get { return default(double); } } public double ExtentWidth { get { return default(double); } } internal protected override bool HandlesScrolling { get { return default(bool); } } public double HorizontalOffset { get { return default(double); } private set { } } public ScrollBarVisibility HorizontalScrollBarVisibility { get { return default(ScrollBarVisibility); } set { } } public bool IsDeferredScrollingEnabled { get { return default(bool); } set { } } public double PanningDeceleration { get { return default(double); } set { } } public PanningMode PanningMode { get { return default(PanningMode); } set { } } public double PanningRatio { get { return default(double); } set { } } public double ScrollableHeight { get { return default(double); } } public double ScrollableWidth { get { return default(double); } } internal protected System.Windows.Controls.Primitives.IScrollInfo ScrollInfo { get { return default(System.Windows.Controls.Primitives.IScrollInfo); } set { } } public double VerticalOffset { get { return default(double); } private set { } } public ScrollBarVisibility VerticalScrollBarVisibility { get { return default(ScrollBarVisibility); } set { } } public double ViewportHeight { get { return default(double); } } public double ViewportWidth { get { return default(double); } } #endregion #region Events public event ScrollChangedEventHandler ScrollChanged { add { } remove { } } #endregion #region Fields public readonly static System.Windows.DependencyProperty CanContentScrollProperty; public readonly static System.Windows.DependencyProperty ComputedHorizontalScrollBarVisibilityProperty; public readonly static System.Windows.DependencyProperty ComputedVerticalScrollBarVisibilityProperty; public readonly static System.Windows.DependencyProperty ContentHorizontalOffsetProperty; public readonly static System.Windows.DependencyProperty ContentVerticalOffsetProperty; public readonly static System.Windows.DependencyProperty ExtentHeightProperty; public readonly static System.Windows.DependencyProperty ExtentWidthProperty; public readonly static System.Windows.DependencyProperty HorizontalOffsetProperty; public readonly static System.Windows.DependencyProperty HorizontalScrollBarVisibilityProperty; public readonly static System.Windows.DependencyProperty IsDeferredScrollingEnabledProperty; public readonly static System.Windows.DependencyProperty PanningDecelerationProperty; public readonly static System.Windows.DependencyProperty PanningModeProperty; public readonly static System.Windows.DependencyProperty PanningRatioProperty; public readonly static System.Windows.DependencyProperty ScrollableHeightProperty; public readonly static System.Windows.DependencyProperty ScrollableWidthProperty; public readonly static System.Windows.RoutedEvent ScrollChangedEvent; public readonly static System.Windows.DependencyProperty VerticalOffsetProperty; public readonly static System.Windows.DependencyProperty VerticalScrollBarVisibilityProperty; public readonly static System.Windows.DependencyProperty ViewportHeightProperty; public readonly static System.Windows.DependencyProperty ViewportWidthProperty; #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Orleans.GrainDirectory; namespace Orleans.Runtime { internal interface IGrainTypeResolver { bool TryGetGrainClassData(Type grainInterfaceType, out GrainClassData implementation, string grainClassNamePrefix); bool TryGetGrainClassData(int grainInterfaceId, out GrainClassData implementation, string grainClassNamePrefix); bool TryGetGrainClassData(string grainImplementationClassName, out GrainClassData implementation); bool IsUnordered(int grainTypeCode); string GetLoadedGrainAssemblies(); } /// <summary> /// Internal data structure that holds a grain interfaces to grain classes map. /// </summary> [Serializable] internal class GrainInterfaceMap : IGrainTypeResolver { /// <summary> /// Metadata for a grain interface /// </summary> [Serializable] internal class GrainInterfaceData { [NonSerialized] private readonly Type iface; private readonly HashSet<GrainClassData> implementations; internal Type Interface { get { return iface; } } internal int InterfaceId { get; private set; } internal string GrainInterface { get; private set; } internal GrainClassData[] Implementations { get { return implementations.ToArray(); } } internal GrainClassData PrimaryImplementation { get; private set; } internal GrainInterfaceData(int interfaceId, Type iface, string grainInterface) { InterfaceId = interfaceId; this.iface = iface; GrainInterface = grainInterface; implementations = new HashSet<GrainClassData>(); } internal void AddImplementation(GrainClassData implementation, bool primaryImplemenation = false) { lock (this) { if (!implementations.Contains(implementation)) implementations.Add(implementation); if (primaryImplemenation) PrimaryImplementation = implementation; } } public override string ToString() { return String.Format("{0}:{1}", GrainInterface, InterfaceId); } } private readonly Dictionary<string, GrainInterfaceData> typeToInterfaceData; private readonly Dictionary<int, GrainInterfaceData> table; private readonly HashSet<int> unordered; private readonly Dictionary<int, GrainClassData> implementationIndex; [NonSerialized] // Client shouldn't need this private readonly Dictionary<string, string> primaryImplementations; private readonly bool localTestMode; private readonly HashSet<string> loadedGrainAsemblies; private readonly PlacementStrategy defaultPlacementStrategy; internal IList<int> SupportedGrainTypes { get { return implementationIndex.Keys.ToList(); } } public GrainInterfaceMap(bool localTestMode, PlacementStrategy defaultPlacementStrategy) { table = new Dictionary<int, GrainInterfaceData>(); typeToInterfaceData = new Dictionary<string, GrainInterfaceData>(); primaryImplementations = new Dictionary<string, string>(); implementationIndex = new Dictionary<int, GrainClassData>(); unordered = new HashSet<int>(); this.localTestMode = localTestMode; this.defaultPlacementStrategy = defaultPlacementStrategy; if(localTestMode) // if we are running in test mode, we'll build a list of loaded grain assemblies to help with troubleshooting deployment issue loadedGrainAsemblies = new HashSet<string>(); } internal void AddMap(GrainInterfaceMap map) { foreach (var kvp in map.typeToInterfaceData) { if (!typeToInterfaceData.ContainsKey(kvp.Key)) { typeToInterfaceData.Add(kvp.Key, kvp.Value); } } foreach (var kvp in map.table) { if (!table.ContainsKey(kvp.Key)) { table.Add(kvp.Key, kvp.Value); } } foreach (var grainClassTypeCode in map.unordered) { unordered.Add(grainClassTypeCode); } foreach (var kvp in map.implementationIndex) { if (!implementationIndex.ContainsKey(kvp.Key)) { implementationIndex.Add(kvp.Key, kvp.Value); } } } internal void AddEntry(int interfaceId, Type iface, int grainTypeCode, string grainInterface, string grainClass, string assembly, bool isGenericGrainClass, PlacementStrategy placement, MultiClusterRegistrationStrategy registrationStrategy, bool primaryImplementation = false) { lock (this) { GrainInterfaceData grainInterfaceData; if (table.ContainsKey(interfaceId)) { grainInterfaceData = table[interfaceId]; } else { grainInterfaceData = new GrainInterfaceData(interfaceId, iface, grainInterface); table[interfaceId] = grainInterfaceData; var interfaceTypeKey = GetTypeKey(iface, isGenericGrainClass); typeToInterfaceData[interfaceTypeKey] = grainInterfaceData; } var implementation = new GrainClassData(grainTypeCode, grainClass, isGenericGrainClass, grainInterfaceData, placement, registrationStrategy); if (!implementationIndex.ContainsKey(grainTypeCode)) implementationIndex.Add(grainTypeCode, implementation); grainInterfaceData.AddImplementation(implementation, primaryImplementation); if (primaryImplementation) { primaryImplementations[grainInterface] = grainClass; } else { if (!primaryImplementations.ContainsKey(grainInterface)) primaryImplementations.Add(grainInterface, grainClass); } if (localTestMode) { if (!loadedGrainAsemblies.Contains(assembly)) loadedGrainAsemblies.Add(assembly); } } } internal Dictionary<string, string> GetPrimaryImplementations() { lock (this) { return new Dictionary<string, string>(primaryImplementations); } } internal bool TryGetPrimaryImplementation(string grainInterface, out string grainClass) { lock (this) { return primaryImplementations.TryGetValue(grainInterface, out grainClass); } } internal bool TryGetServiceInterface(int interfaceId, out Type iface) { lock (this) { iface = null; if (!table.ContainsKey(interfaceId)) return false; var interfaceData = table[interfaceId]; iface = interfaceData.Interface; return true; } } internal bool ContainsGrainInterface(int interfaceId) { lock (this) { return table.ContainsKey(interfaceId); } } internal bool ContainsGrainImplementation(int typeCode) { lock (this) { return implementationIndex.ContainsKey(typeCode); } } internal bool TryGetTypeInfo(int typeCode, out string grainClass, out PlacementStrategy placement, out MultiClusterRegistrationStrategy registrationStrategy, string genericArguments = null) { lock (this) { grainClass = null; placement = this.defaultPlacementStrategy; registrationStrategy = null; if (!implementationIndex.ContainsKey(typeCode)) return false; var implementation = implementationIndex[typeCode]; grainClass = implementation.GetClassName(genericArguments); placement = implementation.PlacementStrategy ?? this.defaultPlacementStrategy; registrationStrategy = implementation.RegistrationStrategy; return true; } } internal bool TryGetGrainClass(int grainTypeCode, out string grainClass, string genericArguments) { grainClass = null; GrainClassData implementation; if (!implementationIndex.TryGetValue(grainTypeCode, out implementation)) { return false; } grainClass = implementation.GetClassName(genericArguments); return true; } public bool TryGetGrainClassData(Type interfaceType, out GrainClassData implementation, string grainClassNamePrefix) { implementation = null; GrainInterfaceData interfaceData; var typeInfo = interfaceType.GetTypeInfo(); // First, try to find a non-generic grain implementation: if (this.typeToInterfaceData.TryGetValue(GetTypeKey(interfaceType, false), out interfaceData) && TryGetGrainClassData(interfaceData, out implementation, grainClassNamePrefix)) { return true; } // If a concrete implementation was not found and the interface is generic, // try to find a generic grain implementation: if (typeInfo.IsGenericType && this.typeToInterfaceData.TryGetValue(GetTypeKey(interfaceType, true), out interfaceData) && TryGetGrainClassData(interfaceData, out implementation, grainClassNamePrefix)) { return true; } return false; } public bool TryGetGrainClassData(int grainInterfaceId, out GrainClassData implementation, string grainClassNamePrefix = null) { implementation = null; GrainInterfaceData interfaceData; if (!table.TryGetValue(grainInterfaceId, out interfaceData)) { return false; } return TryGetGrainClassData(interfaceData, out implementation, grainClassNamePrefix); } private string GetTypeKey(Type interfaceType, bool isGenericGrainClass) { var typeInfo = interfaceType.GetTypeInfo(); if (isGenericGrainClass && typeInfo.IsGenericType) { return typeInfo.GetGenericTypeDefinition().AssemblyQualifiedName; } else { return TypeUtils.GetTemplatedName( TypeUtils.GetFullName(interfaceType), interfaceType, interfaceType.GetGenericArguments(), t => false); } } private static bool TryGetGrainClassData(GrainInterfaceData interfaceData, out GrainClassData implementation, string grainClassNamePrefix) { implementation = null; var implementations = interfaceData.Implementations; if (implementations.Length == 0) return false; if (String.IsNullOrEmpty(grainClassNamePrefix)) { if (implementations.Length == 1) { implementation = implementations[0]; return true; } if (interfaceData.PrimaryImplementation != null) { implementation = interfaceData.PrimaryImplementation; return true; } throw new OrleansException(String.Format("Cannot resolve grain interface ID={0} to a grain class because of multiple implementations of it: {1}", interfaceData.InterfaceId, Utils.EnumerableToString(implementations, d => d.GrainClass, ",", false))); } if (implementations.Length == 1) { if (implementations[0].GrainClass.StartsWith(grainClassNamePrefix, StringComparison.Ordinal)) { implementation = implementations[0]; return true; } return false; } var matches = implementations.Where(impl => impl.GrainClass.Equals(grainClassNamePrefix)).ToArray(); //exact match? if (matches.Length == 0) matches = implementations.Where( impl => impl.GrainClass.StartsWith(grainClassNamePrefix, StringComparison.Ordinal)).ToArray(); //prefix matches if (matches.Length == 0) return false; if (matches.Length == 1) { implementation = matches[0]; return true; } throw new OrleansException(String.Format("Cannot resolve grain interface ID={0}, grainClassNamePrefix={1} to a grain class because of multiple implementations of it: {2}", interfaceData.InterfaceId, grainClassNamePrefix, Utils.EnumerableToString(matches, d => d.GrainClass, ",", false))); } public bool TryGetGrainClassData(string grainImplementationClassName, out GrainClassData implementation) { implementation = null; // have to iterate since _primaryImplementations is not serialized. foreach (var interfaceData in table.Values) { foreach(var implClass in interfaceData.Implementations) if (implClass.GrainClass.Equals(grainImplementationClassName)) { implementation = implClass; return true; } } return false; } public string GetLoadedGrainAssemblies() { return loadedGrainAsemblies != null ? loadedGrainAsemblies.ToStrings() : String.Empty; } public void AddToUnorderedList(int grainClassTypeCode) { if (!unordered.Contains(grainClassTypeCode)) unordered.Add(grainClassTypeCode); } public bool IsUnordered(int grainTypeCode) { return unordered.Contains(grainTypeCode); } } /// <summary> /// Metadata for a grain class /// </summary> [Serializable] internal sealed class GrainClassData { [NonSerialized] private readonly GrainInterfaceMap.GrainInterfaceData interfaceData; [NonSerialized] private readonly Dictionary<string, string> genericClassNames; private readonly PlacementStrategy placementStrategy; private readonly MultiClusterRegistrationStrategy registrationStrategy; private readonly bool isGeneric; internal int GrainTypeCode { get; private set; } internal string GrainClass { get; private set; } internal PlacementStrategy PlacementStrategy { get { return placementStrategy; } } internal GrainInterfaceMap.GrainInterfaceData InterfaceData { get { return interfaceData; } } internal bool IsGeneric { get { return isGeneric; } } public MultiClusterRegistrationStrategy RegistrationStrategy { get { return registrationStrategy; } } internal GrainClassData(int grainTypeCode, string grainClass, bool isGeneric, GrainInterfaceMap.GrainInterfaceData interfaceData, PlacementStrategy placement, MultiClusterRegistrationStrategy registrationStrategy) { GrainTypeCode = grainTypeCode; GrainClass = grainClass; this.isGeneric = isGeneric; this.interfaceData = interfaceData; genericClassNames = new Dictionary<string, string>(); // TODO: initialize only for generic classes placementStrategy = placement; this.registrationStrategy = registrationStrategy ?? MultiClusterRegistrationStrategy.GetDefault(); } internal string GetClassName(string typeArguments) { // Knowing whether the grain implementation is generic allows for non-generic grain classes // to implement one or more generic grain interfaces. // For generic grain classes, the assumption that they take the same generic arguments // as the implemented generic interface(s) still holds. if (!isGeneric || String.IsNullOrWhiteSpace(typeArguments)) { return GrainClass; } else { lock (this) { if (genericClassNames.ContainsKey(typeArguments)) return genericClassNames[typeArguments]; var className = String.Format("{0}[{1}]", GrainClass, typeArguments); genericClassNames.Add(typeArguments, className); return className; } } } internal long GetTypeCode(Type interfaceType) { var typeInfo = interfaceType.GetTypeInfo(); if (typeInfo.IsGenericType && this.IsGeneric) { string args = TypeUtils.GetGenericTypeArgs(typeInfo.GetGenericArguments(), t => true); int hash = Utils.CalculateIdHash(args); return (((long)(hash & 0x00FFFFFF)) << 32) + GrainTypeCode; } else { return GrainTypeCode; } } public override string ToString() { return String.Format("{0}:{1}", GrainClass, GrainTypeCode); } public override int GetHashCode() { return GrainTypeCode; } public override bool Equals(object obj) { if(!(obj is GrainClassData)) return false; return GrainTypeCode == ((GrainClassData) obj).GrainTypeCode; } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoad.Business.ERCLevel { /// <summary> /// D05Level111ReChild (editable child object).<br/> /// This is a generated base class of <see cref="D05Level111ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="D04Level11"/> collection. /// </remarks> [Serializable] public partial class D05Level111ReChild : BusinessBase<D05Level111ReChild> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_Child_Name, "Level_1_1_1 Child Name"); /// <summary> /// Gets or sets the Level_1_1_1 Child Name. /// </summary> /// <value>The Level_1_1_1 Child Name.</value> public string Level_1_1_1_Child_Name { get { return GetProperty(Level_1_1_1_Child_NameProperty); } set { SetProperty(Level_1_1_1_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="D05Level111ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="D05Level111ReChild"/> object.</returns> internal static D05Level111ReChild NewD05Level111ReChild() { return DataPortal.CreateChild<D05Level111ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="D05Level111ReChild"/> object, based on given parameters. /// </summary> /// <param name="cMarentID2">The CMarentID2 parameter of the D05Level111ReChild to fetch.</param> /// <returns>A reference to the fetched <see cref="D05Level111ReChild"/> object.</returns> internal static D05Level111ReChild GetD05Level111ReChild(int cMarentID2) { return DataPortal.FetchChild<D05Level111ReChild>(cMarentID2); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="D05Level111ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private D05Level111ReChild() { // Prevent direct creation // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="D05Level111ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="D05Level111ReChild"/> object from the database, based on given criteria. /// </summary> /// <param name="cMarentID2">The CMarent ID2.</param> protected void Child_Fetch(int cMarentID2) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetD05Level111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@CMarentID2", cMarentID2).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, cMarentID2); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } BusinessRules.CheckRules(); } } /// <summary> /// Loads a <see cref="D05Level111ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="D05Level111ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(D04Level11 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddD05Level111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_Child_Name", ReadProperty(Level_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="D05Level111ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(D04Level11 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateD05Level111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_Child_Name", ReadProperty(Level_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="D05Level111ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(D04Level11 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteD05Level111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region Pseudo Events /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System; using System.Runtime.InteropServices; using System.Security; namespace BulletSharp { public abstract class OverlapCallback : IDisposable { internal IntPtr _native; public bool ProcessOverlap(BroadphasePair pair) { return btOverlapCallback_processOverlap(_native, pair._native); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { btOverlapCallback_delete(_native); _native = IntPtr.Zero; } } ~OverlapCallback() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btOverlapCallback_processOverlap(IntPtr obj, IntPtr pair); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btOverlapCallback_delete(IntPtr obj); } public class OverlapFilterCallback : IDisposable // abstract { internal IntPtr _native; internal OverlapFilterCallback(IntPtr native) { _native = native; } public bool NeedBroadphaseCollision(BroadphaseProxy proxy0, BroadphaseProxy proxy1) { return btOverlapFilterCallback_needBroadphaseCollision(_native, proxy0._native, proxy1._native); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { btOverlapFilterCallback_delete(_native); _native = IntPtr.Zero; } } ~OverlapFilterCallback() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btOverlapFilterCallback_needBroadphaseCollision(IntPtr obj, IntPtr proxy0, IntPtr proxy1); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btOverlapFilterCallback_delete(IntPtr obj); } public abstract class OverlappingPairCache : OverlappingPairCallback { OverlappingPairCallback _ghostPairCallback; AlignedBroadphasePairArray _overlappingPairArray; internal OverlappingPairCache(IntPtr native, bool preventDelete) : base(native, preventDelete) { } public void CleanOverlappingPair(BroadphasePair pair, Dispatcher dispatcher) { btOverlappingPairCache_cleanOverlappingPair(_native, pair._native, dispatcher._native); } public void CleanProxyFromPairs(BroadphaseProxy proxy, Dispatcher dispatcher) { btOverlappingPairCache_cleanProxyFromPairs(_native, proxy._native, dispatcher._native); } public BroadphasePair FindPair(BroadphaseProxy proxy0, BroadphaseProxy proxy1) { return new BroadphasePair(btOverlappingPairCache_findPair(_native, proxy0._native, proxy1._native)); } /* public void ProcessAllOverlappingPairs(OverlapCallback __unnamed0, Dispatcher dispatcher) { btOverlappingPairCache_processAllOverlappingPairs(_native, __unnamed0._native, dispatcher._native); } */ public void SetInternalGhostPairCallback(OverlappingPairCallback ghostPairCallback) { _ghostPairCallback = ghostPairCallback; btOverlappingPairCache_setInternalGhostPairCallback(_native, ghostPairCallback._native); } public void SetOverlapFilterCallback(OverlapFilterCallback callback) { btOverlappingPairCache_setOverlapFilterCallback(_native, callback._native); } public void SortOverlappingPairs(Dispatcher dispatcher) { btOverlappingPairCache_sortOverlappingPairs(_native, dispatcher._native); } public bool HasDeferredRemoval { get { return btOverlappingPairCache_hasDeferredRemoval(_native); } } public int NumOverlappingPairs { get { return btOverlappingPairCache_getNumOverlappingPairs(_native); } } public AlignedBroadphasePairArray OverlappingPairArray { get { IntPtr pairArrayPtr = btOverlappingPairCache_getOverlappingPairArray(_native); if (_overlappingPairArray == null || _overlappingPairArray._native != pairArrayPtr) { _overlappingPairArray = new AlignedBroadphasePairArray(pairArrayPtr); } return _overlappingPairArray; } } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btOverlappingPairCache_cleanOverlappingPair(IntPtr obj, IntPtr pair, IntPtr dispatcher); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btOverlappingPairCache_cleanProxyFromPairs(IntPtr obj, IntPtr proxy, IntPtr dispatcher); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btOverlappingPairCache_findPair(IntPtr obj, IntPtr proxy0, IntPtr proxy1); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btOverlappingPairCache_getNumOverlappingPairs(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btOverlappingPairCache_getOverlappingPairArray(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btOverlappingPairCache_getOverlappingPairArrayPtr(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btOverlappingPairCache_hasDeferredRemoval(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btOverlappingPairCache_processAllOverlappingPairs(IntPtr obj, IntPtr __unnamed0, IntPtr dispatcher); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btOverlappingPairCache_setInternalGhostPairCallback(IntPtr obj, IntPtr ghostPairCallback); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btOverlappingPairCache_setOverlapFilterCallback(IntPtr obj, IntPtr callback); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btOverlappingPairCache_sortOverlappingPairs(IntPtr obj, IntPtr dispatcher); } public class HashedOverlappingPairCache : OverlappingPairCache { internal HashedOverlappingPairCache(IntPtr native, bool preventDelete) : base(native, preventDelete) { } public HashedOverlappingPairCache() : base(btHashedOverlappingPairCache_new(), false) { } public override BroadphasePair AddOverlappingPair(BroadphaseProxy proxy0, BroadphaseProxy proxy1) { return new BroadphasePair(btOverlappingPairCallback_addOverlappingPair(_native, proxy0._native, proxy1._native)); } public bool NeedsBroadphaseCollision(BroadphaseProxy proxy0, BroadphaseProxy proxy1) { return btHashedOverlappingPairCache_needsBroadphaseCollision(_native, proxy0._native, proxy1._native); } public override IntPtr RemoveOverlappingPair(BroadphaseProxy proxy0, BroadphaseProxy proxy1, Dispatcher dispatcher) { return btOverlappingPairCallback_removeOverlappingPair(_native, proxy0._native, proxy1._native, dispatcher._native); } public override void RemoveOverlappingPairsContainingProxy(BroadphaseProxy proxy0, Dispatcher dispatcher) { btOverlappingPairCallback_removeOverlappingPairsContainingProxy(_native, proxy0._native, dispatcher._native); } public int Count { get { return btHashedOverlappingPairCache_GetCount(_native); } } public OverlapFilterCallback OverlapFilterCallback { get { return new OverlapFilterCallback(btHashedOverlappingPairCache_getOverlapFilterCallback(_native)); } } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btHashedOverlappingPairCache_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btHashedOverlappingPairCache_GetCount(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btHashedOverlappingPairCache_getOverlapFilterCallback(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btHashedOverlappingPairCache_needsBroadphaseCollision(IntPtr obj, IntPtr proxy0, IntPtr proxy1); } public class SortedOverlappingPairCache : OverlappingPairCache { public SortedOverlappingPairCache() : base(btSortedOverlappingPairCache_new(), false) { } public override BroadphasePair AddOverlappingPair(BroadphaseProxy proxy0, BroadphaseProxy proxy1) { return new BroadphasePair(btOverlappingPairCallback_addOverlappingPair(_native, proxy0._native, proxy1._native)); } public bool NeedsBroadphaseCollision(BroadphaseProxy proxy0, BroadphaseProxy proxy1) { return btSortedOverlappingPairCache_needsBroadphaseCollision(_native, proxy0._native, proxy1._native); } public override IntPtr RemoveOverlappingPair(BroadphaseProxy proxy0, BroadphaseProxy proxy1, Dispatcher dispatcher) { return btOverlappingPairCallback_removeOverlappingPair(_native, proxy0._native, proxy1._native, dispatcher._native); } public override void RemoveOverlappingPairsContainingProxy(BroadphaseProxy proxy0, Dispatcher dispatcher) { btOverlappingPairCallback_removeOverlappingPairsContainingProxy(_native, proxy0._native, dispatcher._native); } public OverlapFilterCallback OverlapFilterCallback { get { return new OverlapFilterCallback(btSortedOverlappingPairCache_getOverlapFilterCallback(_native)); } } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btSortedOverlappingPairCache_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btSortedOverlappingPairCache_getOverlapFilterCallback(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btSortedOverlappingPairCache_needsBroadphaseCollision(IntPtr obj, IntPtr proxy0, IntPtr proxy1); } public class NullPairCache : OverlappingPairCache { public NullPairCache() : base(btNullPairCache_new(), false) { } public override BroadphasePair AddOverlappingPair(BroadphaseProxy proxy0, BroadphaseProxy proxy1) { return new BroadphasePair(btOverlappingPairCallback_addOverlappingPair(_native, proxy0._native, proxy1._native)); } public override IntPtr RemoveOverlappingPair(BroadphaseProxy proxy0, BroadphaseProxy proxy1, Dispatcher dispatcher) { return btOverlappingPairCallback_removeOverlappingPair(_native, proxy0._native, proxy1._native, dispatcher._native); } public override void RemoveOverlappingPairsContainingProxy(BroadphaseProxy proxy0, Dispatcher dispatcher) { btOverlappingPairCallback_removeOverlappingPairsContainingProxy(_native, proxy0._native, dispatcher._native); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btNullPairCache_new(); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Xml.Linq; namespace NuGetPe { public static class XElementExtensions { [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "We don't care about base types")] public static string GetOptionalAttributeValue(this XElement element, string localName, string namespaceName = null) { XAttribute attr; if (String.IsNullOrEmpty(namespaceName)) { attr = element.Attribute(localName); } else { attr = element.Attribute(XName.Get(localName, namespaceName)); } return attr != null ? attr.Value : null; } [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "We don't care about base types")] public static string GetOptionalElementValue(this XElement element, string localName, string namespaceName = null) { XElement child; if (String.IsNullOrEmpty(namespaceName)) { child = element.Element(localName); } else { child = element.Element(XName.Get(localName, namespaceName)); } return child != null ? child.Value : null; } public static IEnumerable<XElement> ElementsNoNamespace(this XContainer container, string localName) { return container.Elements().Where(e => e.Name.LocalName == localName); } public static IEnumerable<XElement> ElementsNoNamespace(this IEnumerable<XContainer> source, string localName) { return source.Elements().Where(e => e.Name.LocalName == localName); } // REVIEW: We can use a stack if the perf is bad for Except and MergeWith public static XElement Except(this XElement source, XElement target) { if (target == null) { return source; } IEnumerable<XAttribute> attributesToRemove = from e in source.Attributes() where AttributeEquals(e, target.Attribute(e.Name)) select e; // Remove the attributes foreach (XAttribute a in attributesToRemove.ToList()) { a.Remove(); } foreach (XElement sourceChild in source.Elements().ToList()) { XElement targetChild = FindElement(target, sourceChild); if (targetChild != null && !HasConflict(sourceChild, targetChild)) { Except(sourceChild, targetChild); bool hasContent = sourceChild.HasAttributes || sourceChild.HasElements; if (!hasContent) { // Remove the element if there is no content sourceChild.Remove(); targetChild.Remove(); } } } return source; } public static XElement MergeWith(this XElement source, XElement target) { return MergeWith(source, target, null); } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "No reason to create a new type")] public static XElement MergeWith(this XElement source, XElement target, IDictionary<XName, Action<XElement, XElement>> nodeActions) { if (target == null) { return source; } // Merge the attributes foreach (XAttribute targetAttribute in target.Attributes()) { XAttribute sourceAttribute = source.Attribute(targetAttribute.Name); if (sourceAttribute == null) { source.Add(targetAttribute); } } // Go through the elements to be merged foreach (XElement targetChild in target.Elements()) { XElement sourceChild = FindElement(source, targetChild); if (sourceChild != null && !HasConflict(sourceChild, targetChild)) { // Other wise merge recursively sourceChild.MergeWith(targetChild, nodeActions); } else { Action<XElement, XElement> nodeAction; if (nodeActions != null && nodeActions.TryGetValue(targetChild.Name, out nodeAction)) { nodeAction(source, targetChild); } else { // If that element is null then add that node source.Add(targetChild); } } } return source; } private static XElement FindElement(XElement source, XElement targetChild) { // Get all of the elements in the source that match this name List<XElement> sourceElements = source.Elements(targetChild.Name).ToList(); // Try to find the best matching element based on attribute names and values sourceElements.Sort((a, b) => Compare(targetChild, a, b)); return sourceElements.FirstOrDefault(); } private static int Compare(XElement target, XElement left, XElement right) { Debug.Assert(left.Name == right.Name); // First check how much attribute names and values match int leftExactMathes = CountMatches(left, target, AttributeEquals); int rightExactMathes = CountMatches(right, target, AttributeEquals); if (leftExactMathes == rightExactMathes) { // Then check which names match int leftNameMatches = CountMatches(left, target, (a, b) => a.Name == b.Name); int rightNameMatches = CountMatches(right, target, (a, b) => a.Name == b.Name); return rightNameMatches.CompareTo(leftNameMatches); } return rightExactMathes.CompareTo(leftExactMathes); } private static int CountMatches(XElement left, XElement right, Func<XAttribute, XAttribute, bool> matcher) { return (from la in left.Attributes() from ta in right.Attributes() where matcher(la, ta) select la).Count(); } private static bool HasConflict(XElement source, XElement target) { // Get all attributes as name value pairs Dictionary<XName, string> sourceAttr = source.Attributes().ToDictionary(a => a.Name, a => a.Value); // Loop over all the other attributes and see if there are foreach (XAttribute targetAttr in target.Attributes()) { string sourceValue; // if any of the attributes are in the source (names match) but the value doesn't match then we've found a conflict if (sourceAttr.TryGetValue(targetAttr.Name, out sourceValue) && sourceValue != targetAttr.Value) { return true; } } return false; } public static void RemoveAttributes(this XElement element, Func<XAttribute, bool> condition) { element.Attributes() .Where(condition) .ToList() .Remove(); element.Descendants() .ToList() .ForEach(e => RemoveAttributes(e, condition)); } private static bool AttributeEquals(XAttribute source, XAttribute target) { if (source == null && target == null) { return true; } if (source == null || target == null) { return false; } return source.Name == target.Name && source.Value == target.Value; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace Northwind{ /// <summary> /// Strongly-typed collection for the ProductSalesFor1997 class. /// </summary> [Serializable] public partial class ProductSalesFor1997Collection : ReadOnlyList<ProductSalesFor1997, ProductSalesFor1997Collection> { public ProductSalesFor1997Collection() {} } /// <summary> /// This is Read-only wrapper class for the Product Sales for 1997 view. /// </summary> [Serializable] public partial class ProductSalesFor1997 : ReadOnlyRecord<ProductSalesFor1997>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor public static TableSchema.Table Schema { get { if (BaseSchema == null) { SetSQLProps(); } return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Product Sales for 1997", TableType.View, DataService.GetInstance("Northwind")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarCategoryName = new TableSchema.TableColumn(schema); colvarCategoryName.ColumnName = "CategoryName"; colvarCategoryName.DataType = DbType.String; colvarCategoryName.MaxLength = 15; colvarCategoryName.AutoIncrement = false; colvarCategoryName.IsNullable = false; colvarCategoryName.IsPrimaryKey = false; colvarCategoryName.IsForeignKey = false; colvarCategoryName.IsReadOnly = false; schema.Columns.Add(colvarCategoryName); TableSchema.TableColumn colvarProductName = new TableSchema.TableColumn(schema); colvarProductName.ColumnName = "ProductName"; colvarProductName.DataType = DbType.String; colvarProductName.MaxLength = 40; colvarProductName.AutoIncrement = false; colvarProductName.IsNullable = false; colvarProductName.IsPrimaryKey = false; colvarProductName.IsForeignKey = false; colvarProductName.IsReadOnly = false; schema.Columns.Add(colvarProductName); TableSchema.TableColumn colvarProductSales = new TableSchema.TableColumn(schema); colvarProductSales.ColumnName = "ProductSales"; colvarProductSales.DataType = DbType.Currency; colvarProductSales.MaxLength = 0; colvarProductSales.AutoIncrement = false; colvarProductSales.IsNullable = true; colvarProductSales.IsPrimaryKey = false; colvarProductSales.IsForeignKey = false; colvarProductSales.IsReadOnly = false; schema.Columns.Add(colvarProductSales); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["Northwind"].AddSchema("Product Sales for 1997",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public ProductSalesFor1997() { SetSQLProps(); SetDefaults(); MarkNew(); } public ProductSalesFor1997(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public ProductSalesFor1997(object keyID) { SetSQLProps(); LoadByKey(keyID); } public ProductSalesFor1997(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("CategoryName")] [Bindable(true)] public string CategoryName { get { return GetColumnValue<string>("CategoryName"); } set { SetColumnValue("CategoryName", value); } } [XmlAttribute("ProductName")] [Bindable(true)] public string ProductName { get { return GetColumnValue<string>("ProductName"); } set { SetColumnValue("ProductName", value); } } [XmlAttribute("ProductSales")] [Bindable(true)] public decimal? ProductSales { get { return GetColumnValue<decimal?>("ProductSales"); } set { SetColumnValue("ProductSales", value); } } #endregion #region Columns Struct public struct Columns { public static string CategoryName = @"CategoryName"; public static string ProductName = @"ProductName"; public static string ProductSales = @"ProductSales"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace EduHub.Data.Entities { /// <summary> /// CASES Past Students /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class OSCS : EduHubEntity { #region Navigation Property Cache private KGT Cache_ADULT_A_COUNTRY_KGT; private KGT Cache_ADULT_B_COUNTRY_KGT; private KGG Cache_ZEROMTH_CAT_KGG; private KGD Cache_ZEROMTH_CAT_DEST_KGD; private KGT Cache_BIRTH_COUNTRY_KGT; private KGL Cache_HOME_LANG_KGL; private KGG Cache_SIXMTH_CAT_KGG; private KGD Cache_SIXMTH_CAT_DEST_KGD; #endregion /// <inheritdoc /> public override DateTime? EntityLastModified { get { return LW_DATE; } } #region Field Properties /// <summary> /// Sequence no /// </summary> public int OSCSKEY { get; internal set; } /// <summary> /// Surname /// [Uppercase Alphanumeric (30)] /// </summary> public string SURNAME { get; internal set; } /// <summary> /// First given name /// [Alphanumeric (20)] /// </summary> public string FIRST_NAME { get; internal set; } /// <summary> /// Second given name /// [Alphanumeric (20)] /// </summary> public string SECOND_NAME { get; internal set; } /// <summary> /// Street address /// [Alphanumeric (50)] /// </summary> public string ADDRESS { get; internal set; } /// <summary> /// Suburb /// [Alphanumeric (20)] /// </summary> public string SUBURB { get; internal set; } /// <summary> /// Full name of state of address /// [Titlecase (17)] /// </summary> public string STATE { get; internal set; } /// <summary> /// Postcode /// [Alphanumeric (4)] /// </summary> public string POSTCODE { get; internal set; } /// <summary> /// Home telephone number of student including area code /// [Uppercase Alphanumeric (20)] /// </summary> public string TELEPHONE { get; internal set; } /// <summary> /// Date of birth /// </summary> public DateTime? BIRTHDATE { get; internal set; } /// <summary> /// Student gender /// [Uppercase Alphanumeric (1)] /// </summary> public string GENDER { get; internal set; } /// <summary> /// Date of entry to school /// </summary> public DateTime? ENTRY { get; internal set; } /// <summary> /// Student's current home group /// [Uppercase Alphanumeric (3)] /// </summary> public string CURR_HOME_GROUP { get; internal set; } /// <summary> /// Student's previous home group /// [Uppercase Alphanumeric (3)] /// </summary> public string PREV_HOME_GROUP { get; internal set; } /// <summary> /// Total of all absences for this student as at February census /// </summary> public double? ABS_ALL_FEB { get; internal set; } /// <summary> /// Total unapproved absences for this student as at February census /// </summary> public double? ABS_UNAP_FEB { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public double? ELIG_DAYS_FEB { get; internal set; } /// <summary> /// Total of all absences for this student as at August census /// </summary> public double? ABS_ALL_AUG { get; internal set; } /// <summary> /// Total unapproved absences for this student as at August census /// </summary> public double? ABS_UNAP_AUG { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public double? ELIG_DAYS_AUG { get; internal set; } /// <summary> /// Fees owed to the school in respect of this student /// </summary> public decimal? FEES_OWED { get; internal set; } /// <summary> /// Fees paid to the school in respect of this student /// </summary> public decimal? FEES_PAID { get; internal set; } /// <summary> /// Entity number of the school from which the student came to this school /// </summary> public short? ENT_NUMFEEDER { get; internal set; } /// <summary> /// School number of the school from which the student came to this school /// </summary> public short? NUM_FEEDER { get; internal set; } /// <summary> /// Full School number of the school from which the student came to this school /// [Uppercase Alphanumeric (8)] /// </summary> public string FEEDER_SCHOOL { get; internal set; } /// <summary> /// School number of the student's current(?) school /// </summary> public short? NUM_CURRENT { get; internal set; } /// <summary> /// Full School number of the student's current(?) school /// [Uppercase Alphanumeric (8)] /// </summary> public string CURRENT_SCHOOL { get; internal set; } /// <summary> /// Campus number of the campus at which the student was /// </summary> public int? CAMPUS { get; internal set; } /// <summary> /// Entity number of the student's next school /// </summary> public short? ENT_NUMNEXTSCHL { get; internal set; } /// <summary> /// School number of the student's next school /// </summary> public short? NUM_NEXTSCHL { get; internal set; } /// <summary> /// Full School number of the school from which the student's next school /// [Uppercase Alphanumeric (8)] /// </summary> public string NEXT_SCHOOL { get; internal set; } /// <summary> /// Street address of this student's new address /// [Alphanumeric (50)] /// </summary> public string NEW_ADDRESS { get; internal set; } /// <summary> /// Suburb of this student's new address /// [Alphanumeric (20)] /// </summary> public string NEW_SUBURB { get; internal set; } /// <summary> /// Full name of state of this student's new address /// [Titlecase (17)] /// </summary> public string NEW_STATE { get; internal set; } /// <summary> /// Post code of this student's new address /// [Alphanumeric (4)] /// </summary> public string NEW_POSTCODE { get; internal set; } /// <summary> /// New home telephone number of student including area code /// [Uppercase Alphanumeric (20)] /// </summary> public string NEW_TELEPHONE { get; internal set; } /// <summary> /// Date on which the student transferred from this school /// </summary> public DateTime? TRAN_DATE { get; internal set; } /// <summary> /// Title (Ms, Mr, etc.) of first parent/guardian of this student /// [Titlecase (4)] /// </summary> public string ADULT_A_TITLE { get; internal set; } /// <summary> /// Name of first parent/guardian of this student /// [Uppercase Alphanumeric (30)] /// </summary> public string ADULT_A_NAME { get; internal set; } /// <summary> /// (Was M_COUNTRY) Country of birth of first parent/guardian of this student /// [Uppercase Alphanumeric (6)] /// </summary> public string ADULT_A_COUNTRY { get; internal set; } /// <summary> /// (Was M_RELATION) Relationship of first parent/guardian to this student /// [Alphanumeric (20)] /// </summary> public string ADULT_A_RELATION { get; internal set; } /// <summary> /// Title (Ms, Mr, etc.) of second parent/guardian of this student /// [Titlecase (4)] /// </summary> public string ADULT_B_TITLE { get; internal set; } /// <summary> /// Name of second parent/guardian of this student /// [Uppercase Alphanumeric (30)] /// </summary> public string ADULT_B_NAME { get; internal set; } /// <summary> /// Country of birth of second parent/guardian of this student /// [Uppercase Alphanumeric (6)] /// </summary> public string ADULT_B_COUNTRY { get; internal set; } /// <summary> /// Relationship of second parent/guardian to this student /// [Alphanumeric (20)] /// </summary> public string ADULT_B_RELATION { get; internal set; } /// <summary> /// Transfer reason /// [Alphanumeric (50)] /// </summary> public string REASON_TRAN1N { get; internal set; } /// <summary> /// Alternative/additional transfer reason /// [Alphanumeric (50)] /// </summary> public string REASON_TRAN2N { get; internal set; } /// <summary> /// Current year level /// [Uppercase Alphanumeric (4)] /// </summary> public string CURR_YEAR_LEVEL { get; internal set; } /// <summary> /// Previous year level /// [Uppercase Alphanumeric (4)] /// </summary> public string PREV_YEAR_LEVEL { get; internal set; } /// <summary> /// External exam code (BoS no): possibly not required /// </summary> public int? VCE_NUM { get; internal set; } /// <summary> /// Was this student included in the census? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string INCLUDE_CENSUS { get; internal set; } /// <summary> /// Status indicator /// [Uppercase Alphanumeric (1)] /// </summary> public string HMS_DATA_IN { get; internal set; } /// <summary> /// Family occupation status group (1-5) /// [Uppercase Alphanumeric (2)] /// </summary> public string FAM_OCCUPATION { get; internal set; } /// <summary> /// MIPS Destination Category on exit /// [Uppercase Alphanumeric (2)] /// </summary> public string ZEROMTH_CAT { get; internal set; } /// <summary> /// MIPS Destination on exit /// [Uppercase Alphanumeric (4)] /// </summary> public string ZEROMTH_DEST { get; internal set; } /// <summary> /// MIPS Category &amp; Destination on exit /// [Uppercase Alphanumeric (6)] /// </summary> public string ZEROMTH_CAT_DEST { get; internal set; } /// <summary> /// Date MIPS Destination &amp; Category Updated /// </summary> public DateTime? ZEROMTH_DATE { get; internal set; } /// <summary> /// Visa expiry date /// </summary> public DateTime? VISA_EXPIRY { get; internal set; } /// <summary> /// Fraction of time this student spent at this school /// </summary> public double? TIME_FRACTION { get; internal set; } /// <summary> /// Was this student enrolled at this school? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string ENROLLED { get; internal set; } /// <summary> /// School number of a school attended part-time by this student /// </summary> public short? A_SCHL_NUM { get; internal set; } /// <summary> /// Full School number of a school attended part-time by this student /// [Uppercase Alphanumeric (8)] /// </summary> public string A_SCHOOL_NUM { get; internal set; } /// <summary> /// Fraction of time this student spent at that school /// </summary> public double? A_TIME_FRACTION { get; internal set; } /// <summary> /// Was this student enrolled at that school? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string A_ENROLLED { get; internal set; } /// <summary> /// School number of a school attended part-time by this student /// </summary> public short? B_SCHL_NUM { get; internal set; } /// <summary> /// Full School number of a school attended part-time by this student /// [Uppercase Alphanumeric (8)] /// </summary> public string B_SCHOOL_NUM { get; internal set; } /// <summary> /// Fraction of time this student spent at that school /// </summary> public double? B_TIME_FRACTION { get; internal set; } /// <summary> /// Was this student enrolled at that school? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string B_ENROLLED { get; internal set; } /// <summary> /// School number of a school attended part-time by this student /// </summary> public short? C_SCHL_NUM { get; internal set; } /// <summary> /// Full School number of a school attended part-time by this student /// [Uppercase Alphanumeric (8)] /// </summary> public string C_SCHOOL_NUM { get; internal set; } /// <summary> /// Fraction of time this student spent at that school /// </summary> public double? C_TIME_FRACTION { get; internal set; } /// <summary> /// Was this student enrolled at that school? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string C_ENROLLED { get; internal set; } /// <summary> /// School number of a school attended part-time by this student /// </summary> public short? D_SCHL_NUM { get; internal set; } /// <summary> /// Full School number of a school attended part-time by this student /// [Uppercase Alphanumeric (8)] /// </summary> public string D_SCHOOL_NUM { get; internal set; } /// <summary> /// Fraction of time this student spent at that school /// </summary> public double? D_TIME_FRACTION { get; internal set; } /// <summary> /// Was this student enrolled at that school? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string D_ENROLLED { get; internal set; } /// <summary> /// Status code /// [Uppercase Alphanumeric (1)] /// </summary> public string STUD_TYPE { get; internal set; } /// <summary> /// Country of birth /// [Uppercase Alphanumeric (6)] /// </summary> public string BIRTH_COUNTRY { get; internal set; } /// <summary> /// Date of arrival in Australia /// </summary> public DateTime? ARRIVAL { get; internal set; } /// <summary> /// Date of first enrolment in an Australian school /// </summary> public DateTime? AUSSIE_SCHOOL { get; internal set; } /// <summary> /// Student speaks English? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string ENG_SPEAK { get; internal set; } /// <summary> /// The language spoken at home /// [Uppercase Alphanumeric (7)] /// </summary> public string HOME_LANG { get; internal set; } /// <summary> /// Was this student an applicant for, or in receipt of, CSEF? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string ED_ALLOW { get; internal set; } /// <summary> /// Youth allowance (&lt;25) /// [Uppercase Alphanumeric (1)] /// </summary> public string YOUTH_ALLOW { get; internal set; } /// <summary> /// Did this student take religious instruction? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string REL_INSTR { get; internal set; } /// <summary> /// Indigenous origin (Aboriginal/Torres Strait Islander/Both/Neither/Unknown) /// [Uppercase Alphanumeric (1)] /// </summary> public string KOORIE { get; internal set; } /// <summary> /// Aide required to assist integration into school? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string INTEGRATION { get; internal set; } /// <summary> /// Did student repeat a year level? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string REPEAT { get; internal set; } /// <summary> /// Religious denomination of this student /// [Uppercase Alphanumeric (15)] /// </summary> public string RELIG_DENOM { get; internal set; } /// <summary> /// Disability ID of this student /// [Uppercase Alphanumeric (6)] /// </summary> public string DISABILITY_ID { get; internal set; } /// <summary> /// Did this student have a disability? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string DISABILITY { get; internal set; } /// <summary> /// Did this student have a hearing impairment? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string HEARING_IMPAIR { get; internal set; } /// <summary> /// Did this student have a vision impairment? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string VISUAL_IMPAIR { get; internal set; } /// <summary> /// Did this student have a speech impairment? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string SPEECH_IMPAIR { get; internal set; } /// <summary> /// Did this student have a physical impairment? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string PHYSICAL_IMPAIR { get; internal set; } /// <summary> /// Overall Immunisation status of this student /// [Uppercase Alphanumeric (1)] /// </summary> public string IMMUNIZE { get; internal set; } /// <summary> /// Diphtheria immunisation status of this student /// [Uppercase Alphanumeric (1)] /// </summary> public string DIPTHERIA_S { get; internal set; } /// <summary> /// Tetanus immunisation status of this student /// [Uppercase Alphanumeric (1)] /// </summary> public string TETANUS_S { get; internal set; } /// <summary> /// Polio immunisation status of this student /// [Uppercase Alphanumeric (1)] /// </summary> public string POLIO_S { get; internal set; } /// <summary> /// Measles immunisation status of this student /// [Uppercase Alphanumeric (1)] /// </summary> public string MEASLES_S { get; internal set; } /// <summary> /// Mumps immunisation status of this student /// [Uppercase Alphanumeric (1)] /// </summary> public string MUMPS_S { get; internal set; } /// <summary> /// Measles, Mumps and Rubella immunisation status /// [Uppercase Alphanumeric (1)] /// </summary> public string MMR_S { get; internal set; } /// <summary> /// HIB immunisation status /// [Uppercase Alphanumeric (1)] /// </summary> public string HIB_S { get; internal set; } /// <summary> /// Pertussis immunisation status /// [Uppercase Alphanumeric (1)] /// </summary> public string PERTUSSIS_S { get; internal set; } /// <summary> /// Australian residence status: (Permanent/Temporary) /// [Uppercase Alphanumeric (1)] /// </summary> public string RESIDENT_STATUS { get; internal set; } /// <summary> /// Visa Sub-class /// [Uppercase Alphanumeric (3)] /// </summary> public string VISA_CLASS { get; internal set; } /// <summary> /// (Was VISA_SUBCLASS) Visa statistical code /// [Uppercase Alphanumeric (4)] /// </summary> public string VISA_STAT_CODE { get; internal set; } /// <summary> /// Student entitled to Student Resource Package (SRP) funding /// [Uppercase Alphanumeric (1)] /// </summary> public string ORDINARY_STUDENT { get; internal set; } /// <summary> /// Student's living arrangement(At home with TWO parents/guardians,Home with ONE parent/guardian,Arranged by State - Out-of-home-care,Homeless,Independent) /// </summary> public short? FAM_STRUC_TYPE { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string CENSUSDAY_FEB { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string CENSUSDAY_AUG { get; internal set; } /// <summary> /// MIPS Destination Category after 6 months /// [Uppercase Alphanumeric (2)] /// </summary> public string SIXMTH_CAT { get; internal set; } /// <summary> /// MIPS Destination after 6 months /// [Uppercase Alphanumeric (4)] /// </summary> public string SIXMTH_DEST { get; internal set; } /// <summary> /// MIPS Category &amp; Destination after six month /// [Uppercase Alphanumeric (6)] /// </summary> public string SIXMTH_CAT_DEST { get; internal set; } /// <summary> /// Date 6 months MIPS Destination &amp; Category Updated /// </summary> public DateTime? SIXMTH_DATE { get; internal set; } /// <summary> /// International Student Id. /// [Uppercase Alphanumeric (7)] /// </summary> public string ISU_STD_NO { get; internal set; } /// <summary> /// Was Student present on Census Day (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string CENSUSDAY { get; internal set; } /// <summary> /// Last Absence Day /// </summary> public DateTime? LAST_ABSENCE { get; internal set; } /// <summary> /// Total YTD absences for Student /// </summary> public double? YTD_ABSENCE { get; internal set; } /// <summary> /// Total YTD Approved absences for student /// </summary> public double? YTD_APPROVED { get; internal set; } /// <summary> /// Mobile number /// [Uppercase Alphanumeric (20)] /// </summary> public string MOBILE { get; internal set; } /// <summary> /// Last write date /// </summary> public DateTime? LW_DATE { get; internal set; } /// <summary> /// Last write time /// </summary> public short? LW_TIME { get; internal set; } /// <summary> /// Last write operator /// [Uppercase Alphanumeric (128)] /// </summary> public string LW_USER { get; internal set; } #endregion #region Navigation Properties /// <summary> /// KGT (Countries) related entity by [OSCS.ADULT_A_COUNTRY]-&gt;[KGT.COUNTRY] /// (Was M_COUNTRY) Country of birth of first parent/guardian of this student /// </summary> public KGT ADULT_A_COUNTRY_KGT { get { if (ADULT_A_COUNTRY == null) { return null; } if (Cache_ADULT_A_COUNTRY_KGT == null) { Cache_ADULT_A_COUNTRY_KGT = Context.KGT.FindByCOUNTRY(ADULT_A_COUNTRY); } return Cache_ADULT_A_COUNTRY_KGT; } } /// <summary> /// KGT (Countries) related entity by [OSCS.ADULT_B_COUNTRY]-&gt;[KGT.COUNTRY] /// Country of birth of second parent/guardian of this student /// </summary> public KGT ADULT_B_COUNTRY_KGT { get { if (ADULT_B_COUNTRY == null) { return null; } if (Cache_ADULT_B_COUNTRY_KGT == null) { Cache_ADULT_B_COUNTRY_KGT = Context.KGT.FindByCOUNTRY(ADULT_B_COUNTRY); } return Cache_ADULT_B_COUNTRY_KGT; } } /// <summary> /// KGG (Year 9-12 Exit Categories) related entity by [OSCS.ZEROMTH_CAT]-&gt;[KGG.KGGKEY] /// MIPS Destination Category on exit /// </summary> public KGG ZEROMTH_CAT_KGG { get { if (ZEROMTH_CAT == null) { return null; } if (Cache_ZEROMTH_CAT_KGG == null) { Cache_ZEROMTH_CAT_KGG = Context.KGG.FindByKGGKEY(ZEROMTH_CAT); } return Cache_ZEROMTH_CAT_KGG; } } /// <summary> /// KGD (Year 9-12 Exit Destinations) related entity by [OSCS.ZEROMTH_CAT_DEST]-&gt;[KGD.KGDKEY] /// MIPS Category &amp; Destination on exit /// </summary> public KGD ZEROMTH_CAT_DEST_KGD { get { if (ZEROMTH_CAT_DEST == null) { return null; } if (Cache_ZEROMTH_CAT_DEST_KGD == null) { Cache_ZEROMTH_CAT_DEST_KGD = Context.KGD.FindByKGDKEY(ZEROMTH_CAT_DEST); } return Cache_ZEROMTH_CAT_DEST_KGD; } } /// <summary> /// KGT (Countries) related entity by [OSCS.BIRTH_COUNTRY]-&gt;[KGT.COUNTRY] /// Country of birth /// </summary> public KGT BIRTH_COUNTRY_KGT { get { if (BIRTH_COUNTRY == null) { return null; } if (Cache_BIRTH_COUNTRY_KGT == null) { Cache_BIRTH_COUNTRY_KGT = Context.KGT.FindByCOUNTRY(BIRTH_COUNTRY); } return Cache_BIRTH_COUNTRY_KGT; } } /// <summary> /// KGL (Languages) related entity by [OSCS.HOME_LANG]-&gt;[KGL.KGLKEY] /// The language spoken at home /// </summary> public KGL HOME_LANG_KGL { get { if (HOME_LANG == null) { return null; } if (Cache_HOME_LANG_KGL == null) { Cache_HOME_LANG_KGL = Context.KGL.FindByKGLKEY(HOME_LANG); } return Cache_HOME_LANG_KGL; } } /// <summary> /// KGG (Year 9-12 Exit Categories) related entity by [OSCS.SIXMTH_CAT]-&gt;[KGG.KGGKEY] /// MIPS Destination Category after 6 months /// </summary> public KGG SIXMTH_CAT_KGG { get { if (SIXMTH_CAT == null) { return null; } if (Cache_SIXMTH_CAT_KGG == null) { Cache_SIXMTH_CAT_KGG = Context.KGG.FindByKGGKEY(SIXMTH_CAT); } return Cache_SIXMTH_CAT_KGG; } } /// <summary> /// KGD (Year 9-12 Exit Destinations) related entity by [OSCS.SIXMTH_CAT_DEST]-&gt;[KGD.KGDKEY] /// MIPS Category &amp; Destination after six month /// </summary> public KGD SIXMTH_CAT_DEST_KGD { get { if (SIXMTH_CAT_DEST == null) { return null; } if (Cache_SIXMTH_CAT_DEST_KGD == null) { Cache_SIXMTH_CAT_DEST_KGD = Context.KGD.FindByKGDKEY(SIXMTH_CAT_DEST); } return Cache_SIXMTH_CAT_DEST_KGD; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. #if FEATURE_SERIALIZATION using System.Runtime.Serialization.Formatters.Binary; #endif #if !FEATURE_REMOTING using MarshalByRefObject = System.Object; #endif #if FEATURE_COM using ComTypeLibInfo = Microsoft.Scripting.ComInterop.ComTypeLibInfo; using ComTypeLibDesc = Microsoft.Scripting.ComInterop.ComTypeLibDesc; #endif using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython; using IronPython.Runtime; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; [assembly: PythonModule("clr", typeof(IronPython.Runtime.ClrModule))] namespace IronPython.Runtime { /// <summary> /// this class contains objecs and static methods used for /// .NET/CLS interop with Python. /// </summary> public static class ClrModule { #if NETCOREAPP public static readonly bool IsNetCoreApp = true; #elif NETFRAMEWORK public static readonly bool IsNetCoreApp = false; #else public static readonly bool IsNetCoreApp = FrameworkDescription.StartsWith(".NET", StringComparison.Ordinal) && !FrameworkDescription.StartsWith(".NET Framework", StringComparison.Ordinal); #endif public static string TargetFramework => typeof(ClrModule).Assembly.GetCustomAttribute<TargetFrameworkAttribute>()?.FrameworkName; internal static string FileVersion => typeof(ClrModule).Assembly.GetCustomAttribute<AssemblyFileVersionAttribute>()?.Version; #if DEBUG public static readonly bool IsDebug = true; #else public static readonly bool IsDebug = false; #endif public static string FrameworkDescription { get { #if FEATURE_RUNTIMEINFORMATION var frameworkDescription = RuntimeInformation.FrameworkDescription; if (frameworkDescription.StartsWith(".NET Core 4.6.", StringComparison.OrdinalIgnoreCase)) { return $".NET Core 2.x ({frameworkDescription.Substring(10)})"; } return frameworkDescription; #else // try reflection since we're probably running on a newer runtime anyway if (typeof(void).Assembly.GetType("System.Runtime.InteropServices.RuntimeInformation")?.GetProperty("FrameworkDescription")?.GetValue(null) is string frameworkDescription) { return frameworkDescription; } return (IsMono ? "Mono " : ".NET Framework ") + Environment.Version.ToString(); #endif } } private static int _isMono = -1; public static bool IsMono { get { if(_isMono == -1) { _isMono = Type.GetType ("Mono.Runtime") != null ? 1 : 0; } return _isMono == 1; } } private static int _isMacOS = -1; public static bool IsMacOS { get { if(_isMacOS == -1) { _isMacOS = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? 1 : 0; } return _isMacOS == 1; } } [SpecialName] public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { if (!dict.ContainsKey("References")) { dict["References"] = context.ReferencedAssemblies; } } #region Public methods /// <summary> /// Gets the current ScriptDomainManager that IronPython is loaded into. The /// ScriptDomainManager can then be used to work with the language portion of the /// DLR hosting APIs. /// </summary> public static ScriptDomainManager/*!*/ GetCurrentRuntime(CodeContext/*!*/ context) { return context.LanguageContext.DomainManager; } [Documentation(@"Adds a reference to a .NET assembly. Parameters can be an already loaded Assembly object, a full assembly name, or a partial assembly name. After the load the assemblies namespaces and top-level types will be available via import Namespace.")] public static void AddReference(CodeContext/*!*/ context, params object[] references) { if (references == null) throw new TypeErrorException("Expected string or Assembly, got NoneType"); if (references.Length == 0) throw new ValueErrorException("Expected at least one name, got none"); ContractUtils.RequiresNotNull(context, "context"); foreach (object reference in references) { AddReference(context, reference); } } [Documentation(@"Adds a reference to a .NET assembly. One or more assembly names can be provided. The assembly is searched for in the directories specified in sys.path and dependencies will be loaded from sys.path as well. The assembly name should be the filename on disk without a directory specifier and optionally including the .EXE or .DLL extension. After the load the assemblies namespaces and top-level types will be available via import Namespace.")] public static void AddReferenceToFile(CodeContext/*!*/ context, params string[] files) { if (files == null) throw new TypeErrorException("Expected string, got NoneType"); if (files.Length == 0) throw new ValueErrorException("Expected at least one name, got none"); ContractUtils.RequiresNotNull(context, "context"); foreach (string file in files) { AddReferenceToFile(context, file); } } [Documentation(@"Adds a reference to a .NET assembly. Parameters are an assembly name. After the load the assemblies namespaces and top-level types will be available via import Namespace.")] public static void AddReferenceByName(CodeContext/*!*/ context, params string[] names) { if (names == null) throw new TypeErrorException("Expected string, got NoneType"); if (names.Length == 0) throw new ValueErrorException("Expected at least one name, got none"); ContractUtils.RequiresNotNull(context, "context"); foreach (string name in names) { AddReferenceByName(context, name); } } #if FEATURE_LOADWITHPARTIALNAME [Documentation(@"Adds a reference to a .NET assembly. Parameters are a partial assembly name. After the load the assemblies namespaces and top-level types will be available via import Namespace.")] public static void AddReferenceByPartialName(CodeContext/*!*/ context, params string[] names) { if (names == null) throw new TypeErrorException("Expected string, got NoneType"); if (names.Length == 0) throw new ValueErrorException("Expected at least one name, got none"); ContractUtils.RequiresNotNull(context, "context"); foreach (string name in names) { AddReferenceByPartialName(context, name); } } #endif #if FEATURE_FILESYSTEM [Documentation(@"Adds a reference to a .NET assembly. Parameters are a full path to an. assembly on disk. After the load the assemblies namespaces and top-level types will be available via import Namespace.")] public static Assembly/*!*/ LoadAssemblyFromFileWithPath(CodeContext/*!*/ context, string/*!*/ file) { if (file == null) throw new TypeErrorException("LoadAssemblyFromFileWithPath: arg 1 must be a string."); Assembly res; if (!context.LanguageContext.TryLoadAssemblyFromFileWithPath(file, out res)) { if (!Path.IsPathRooted(file)) { throw new ValueErrorException("LoadAssemblyFromFileWithPath: path must be rooted"); } else if (!File.Exists(file)) { throw new ValueErrorException("LoadAssemblyFromFileWithPath: file not found"); } else { throw new ValueErrorException("LoadAssemblyFromFileWithPath: error loading assembly"); } } return res; } [Documentation(@"Loads an assembly from the specified filename and returns the assembly object. Namespaces or types in the assembly can be accessed directly from the assembly object.")] public static Assembly/*!*/ LoadAssemblyFromFile(CodeContext/*!*/ context, string/*!*/ file) { if (file == null) throw new TypeErrorException("Expected string, got NoneType"); if (file.Length == 0) throw new ValueErrorException("assembly name must not be empty string"); ContractUtils.RequiresNotNull(context, "context"); if (file.IndexOf(System.IO.Path.DirectorySeparatorChar) != -1) { throw new ValueErrorException("filenames must not contain full paths, first add the path to sys.path"); } return context.LanguageContext.LoadAssemblyFromFile(file); } #endif #if FEATURE_LOADWITHPARTIALNAME [Documentation(@"Loads an assembly from the specified partial assembly name and returns the assembly object. Namespaces or types in the assembly can be accessed directly from the assembly object.")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadWithPartialName")] public static Assembly/*!*/ LoadAssemblyByPartialName(string/*!*/ name) { if (name == null) { throw new TypeErrorException("LoadAssemblyByPartialName: arg 1 must be a string"); } #pragma warning disable 618, 612 // csc return Assembly.LoadWithPartialName(name); #pragma warning restore 618, 612 } #endif [Documentation(@"Loads an assembly from the specified assembly name and returns the assembly object. Namespaces or types in the assembly can be accessed directly from the assembly object.")] public static Assembly/*!*/ LoadAssemblyByName(CodeContext/*!*/ context, string/*!*/ name) { if (name == null) { throw new TypeErrorException("LoadAssemblyByName: arg 1 must be a string"); } return context.LanguageContext.DomainManager.Platform.LoadAssembly(name); } /// <summary> /// Use(name) -> module /// /// Attempts to load the specified module searching all languages in the loaded ScriptRuntime. /// </summary> public static object Use(CodeContext/*!*/ context, string/*!*/ name) { ContractUtils.RequiresNotNull(context, "context"); if (name == null) { throw new TypeErrorException("Use: arg 1 must be a string"); } var scope = Importer.TryImportSourceFile(context.LanguageContext, name); if (scope == null) { throw new ValueErrorException(String.Format("couldn't find module {0} to use", name)); } return scope; } [Documentation("Converts an array of bytes to a string.")] public static string GetString(byte[] bytes) { return GetString(bytes, bytes.Length); } [Documentation("Converts maxCount of an array of bytes to a string")] public static string GetString(byte[] bytes, int maxCount) { int bytesToCopy = Math.Min(bytes.Length, maxCount); return Encoding.GetEncoding("iso-8859-1").GetString(bytes, 0, bytesToCopy); } [Documentation("Converts a string to an array of bytes")] public static byte[] GetBytes(string s) { return GetBytes(s, s.Length); } [Documentation("Converts maxCount of a string to an array of bytes")] public static byte[] GetBytes(string s, int maxCount) { int charsToCopy = Math.Min(s.Length, maxCount); byte[] ret = new byte[charsToCopy]; Encoding.GetEncoding("iso-8859-1").GetBytes(s, 0, charsToCopy, ret, 0); return ret; } /// <summary> /// Use(path, language) -> module /// /// Attempts to load the specified module belonging to a specific language loaded into the /// current ScriptRuntime. /// </summary> public static object/*!*/ Use(CodeContext/*!*/ context, string/*!*/ path, string/*!*/ language) { ContractUtils.RequiresNotNull(context, "context"); if (path == null) { throw new TypeErrorException("Use: arg 1 must be a string"); } if (language == null) { throw new TypeErrorException("Use: arg 2 must be a string"); } var manager = context.LanguageContext.DomainManager; if (!manager.Platform.FileExists(path)) { throw new ValueErrorException(String.Format("couldn't load module at path '{0}' in language '{1}'", path, language)); } var sourceUnit = manager.GetLanguageByName(language).CreateFileUnit(path); return Importer.ExecuteSourceUnit(context.LanguageContext, sourceUnit); } /// <summary> /// SetCommandDispatcher(commandDispatcher) /// /// Sets the current command dispatcher for the Python command line. /// /// The command dispatcher will be called with a delegate to be executed. The command dispatcher /// should invoke the target delegate in the desired context. /// /// A common use for this is to enable running all REPL commands on the UI thread while the REPL /// continues to run on a non-UI thread. /// </summary> public static Action<Action> SetCommandDispatcher(CodeContext/*!*/ context, Action<Action> dispatcher) { ContractUtils.RequiresNotNull(context, "context"); return ((PythonContext)context.LanguageContext).GetSetCommandDispatcher(dispatcher); } public static void ImportExtensions(CodeContext/*!*/ context, PythonType type) { if (type == null) { throw PythonOps.TypeError("type must not be None"); } else if (!type.IsSystemType) { throw PythonOps.ValueError("type must be .NET type"); } lock (context.ModuleContext) { context.ModuleContext.ExtensionMethods = ExtensionMethodSet.AddType(context.LanguageContext, context.ModuleContext.ExtensionMethods, type); } } public static void ImportExtensions(CodeContext/*!*/ context, [NotNull]NamespaceTracker @namespace) { lock (context.ModuleContext) { context.ModuleContext.ExtensionMethods = ExtensionMethodSet.AddNamespace(context.LanguageContext, context.ModuleContext.ExtensionMethods, @namespace); } } #if FEATURE_COM /// <summary> /// LoadTypeLibrary(rcw) -> type lib desc /// /// Gets an ITypeLib object from OLE Automation compatible RCW , /// reads definitions of CoClass'es and Enum's from this library /// and creates an object that allows to instantiate coclasses /// and get actual values for the enums. /// </summary> public static ComTypeLibInfo LoadTypeLibrary(CodeContext/*!*/ context, object rcw) { return ComTypeLibDesc.CreateFromObject(rcw); } /// <summary> /// LoadTypeLibrary(guid) -> type lib desc /// /// Reads the latest registered type library for the corresponding GUID, /// reads definitions of CoClass'es and Enum's from this library /// and creates a IDynamicMetaObjectProvider that allows to instantiate coclasses /// and get actual values for the enums. /// </summary> public static ComTypeLibInfo LoadTypeLibrary(CodeContext/*!*/ context, Guid typeLibGuid) { return ComTypeLibDesc.CreateFromGuid(typeLibGuid); } /// <summary> /// AddReferenceToTypeLibrary(rcw) -> None /// /// Makes the type lib desc available for importing. See also LoadTypeLibrary. /// </summary> public static void AddReferenceToTypeLibrary(CodeContext/*!*/ context, object rcw) { ComTypeLibInfo typeLibInfo; typeLibInfo = ComTypeLibDesc.CreateFromObject(rcw); PublishTypeLibDesc(context, typeLibInfo.TypeLibDesc); } /// <summary> /// AddReferenceToTypeLibrary(guid) -> None /// /// Makes the type lib desc available for importing. See also LoadTypeLibrary. /// </summary> public static void AddReferenceToTypeLibrary(CodeContext/*!*/ context, Guid typeLibGuid) { ComTypeLibInfo typeLibInfo; typeLibInfo = ComTypeLibDesc.CreateFromGuid(typeLibGuid); PublishTypeLibDesc(context, typeLibInfo.TypeLibDesc); } private static void PublishTypeLibDesc(CodeContext context, ComTypeLibDesc typeLibDesc) { PythonOps.ScopeSetMember(context, context.LanguageContext.DomainManager.Globals, typeLibDesc.Name, typeLibDesc); } #endif #endregion #region Private implementation methods private static void AddReference(CodeContext/*!*/ context, object reference) { Assembly asmRef = reference as Assembly; if (asmRef != null) { AddReference(context, asmRef); return; } if (reference is string strRef) { AddReference(context, strRef); return; } throw new TypeErrorException(String.Format("Invalid assembly type. Expected string or Assembly, got {0}.", reference)); } private static void AddReference(CodeContext/*!*/ context, Assembly assembly) { context.LanguageContext.DomainManager.LoadAssembly(assembly); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] // TODO: fix private static void AddReference(CodeContext/*!*/ context, string name) { if (name == null) throw new TypeErrorException("Expected string, got NoneType"); Assembly asm = null; try { asm = LoadAssemblyByName(context, name); } catch { } // note we don't explicit call to get the file version // here because the assembly resolve event will do it for us. #if FEATURE_LOADWITHPARTIALNAME if (asm == null) { asm = LoadAssemblyByPartialName(name); } #endif if (asm == null) { throw new IOException(String.Format("Could not add reference to assembly {0}", name)); } AddReference(context, asm); } private static void AddReferenceToFile(CodeContext/*!*/ context, string file) { if (file == null) throw new TypeErrorException("Expected string, got NoneType"); #if FEATURE_FILESYSTEM Assembly asm = LoadAssemblyFromFile(context, file); #else Assembly asm = context.LanguageContext.DomainManager.Platform.LoadAssemblyFromPath(file); #endif if (asm == null) { throw new IOException(String.Format("Could not add reference to assembly {0}", file)); } AddReference(context, asm); } #if FEATURE_LOADWITHPARTIALNAME private static void AddReferenceByPartialName(CodeContext/*!*/ context, string name) { if (name == null) throw new TypeErrorException("Expected string, got NoneType"); ContractUtils.RequiresNotNull(context, "context"); Assembly asm = LoadAssemblyByPartialName(name); if (asm == null) { throw new IOException(String.Format("Could not add reference to assembly {0}", name)); } AddReference(context, asm); } #endif private static void AddReferenceByName(CodeContext/*!*/ context, string name) { if (name == null) throw new TypeErrorException("Expected string, got NoneType"); Assembly asm = LoadAssemblyByName(context, name); if (asm == null) { throw new IOException(String.Format("Could not add reference to assembly {0}", name)); } AddReference(context, asm); } #endregion [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] // TODO: fix public sealed class ReferencesList : List<Assembly>, ICodeFormattable { public new void Add(Assembly other) { base.Add(other); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists"), SpecialName] public ClrModule.ReferencesList Add(object other) { IEnumerator ie = PythonOps.GetEnumerator(other); while (ie.MoveNext()) { Assembly cur = ie.Current as Assembly; if (cur == null) throw PythonOps.TypeError("non-assembly added to references list"); base.Add(cur); } return this; } public string/*!*/ __repr__(CodeContext/*!*/ context) { StringBuilder res = new StringBuilder("("); string comma = ""; foreach (Assembly asm in this) { res.Append(comma); res.Append('<'); res.Append(asm.FullName); res.Append('>'); comma = "," + Environment.NewLine; } res.AppendLine(")"); return res.ToString(); } } private static PythonType _strongBoxType; #region Runtime Type Checking support #if FEATURE_FILESYSTEM [Documentation(@"Adds a reference to a .NET assembly. One or more assembly names can be provided which are fully qualified names to the file on disk. The directory is added to sys.path and AddReferenceToFile is then called. After the load the assemblies namespaces and top-level types will be available via import Namespace.")] public static void AddReferenceToFileAndPath(CodeContext/*!*/ context, params string[] files) { if (files == null) throw new TypeErrorException("Expected string, got NoneType"); ContractUtils.RequiresNotNull(context, "context"); foreach (string file in files) { AddReferenceToFileAndPath(context, file); } } private static void AddReferenceToFileAndPath(CodeContext/*!*/ context, string file) { if (file == null) throw PythonOps.TypeError("Expected string, got NoneType"); // update our path w/ the path of this file... string path = System.IO.Path.GetDirectoryName(Path.GetFullPath(file)); List list; PythonContext pc = context.LanguageContext; if (!pc.TryGetSystemPath(out list)) { throw PythonOps.TypeError("cannot update path, it is not a list"); } list.append(path); Assembly asm = pc.LoadAssemblyFromFile(file); if (asm == null) throw PythonOps.IOError("file does not exist: {0}", file); AddReference(context, asm); } #endif /// <summary> /// Gets the CLR Type object from a given Python type object. /// </summary> public static Type GetClrType(Type type) { return type; } /// <summary> /// Gets the Python type object from a given CLR Type object. /// </summary> public static PythonType GetPythonType(Type t) { return DynamicHelpers.GetPythonTypeFromType(t); } /// <summary> /// OBSOLETE: Gets the Python type object from a given CLR Type object. /// /// Use clr.GetPythonType instead. /// </summary> [Obsolete("Call clr.GetPythonType instead")] public static PythonType GetDynamicType(Type t) { return DynamicHelpers.GetPythonTypeFromType(t); } public static PythonType Reference { get { return StrongBox; } } public static PythonType StrongBox { get { if (_strongBoxType == null) { _strongBoxType = DynamicHelpers.GetPythonTypeFromType(typeof(StrongBox<>)); } return _strongBoxType; } } /// <summary> /// accepts(*types) -> ArgChecker /// /// Decorator that returns a new callable object which will validate the arguments are of the specified types. /// </summary> /// <param name="types"></param> /// <returns></returns> public static object accepts(params object[] types) { return new ArgChecker(types); } /// <summary> /// returns(type) -> ReturnChecker /// /// Returns a new callable object which will validate the return type is of the specified type. /// </summary> public static object returns(object type) { return new ReturnChecker(type); } public static object Self() { return null; } #endregion /// <summary> /// Decorator for verifying the arguments to a function are of a specified type. /// </summary> public class ArgChecker { private object[] expected; public ArgChecker(object[] prms) { expected = prms; } #region ICallableWithCodeContext Members [SpecialName] public object Call(CodeContext context, object func) { // expect only to receive the function we'll call here. return new RuntimeArgChecker(func, expected); } #endregion } /// <summary> /// Returned value when using clr.accepts/ArgChecker. Validates the argument types and /// then calls the original function. /// </summary> public class RuntimeArgChecker : PythonTypeSlot { private object[] _expected; private object _func; private object _inst; public RuntimeArgChecker(object function, object[] expectedArgs) { _expected = expectedArgs; _func = function; } public RuntimeArgChecker(object instance, object function, object[] expectedArgs) : this(function, expectedArgs) { _inst = instance; } private void ValidateArgs(object[] args) { int start = 0; if (_inst != null) { start = 1; } // no need to validate self... the method should handle it. for (int i = start; i < args.Length + start; i++) { PythonType dt = DynamicHelpers.GetPythonType(args[i - start]); if (!(_expected[i] is PythonType expct)) expct = ((OldClass)_expected[i]).TypeObject; if (dt != _expected[i] && !dt.IsSubclassOf(expct)) { throw PythonOps.AssertionError("argument {0} has bad value (got {1}, expected {2})", i, dt, _expected[i]); } } } #region ICallableWithCodeContext Members [SpecialName] public object Call(CodeContext context, params object[] args) { ValidateArgs(args); if (_inst != null) { return PythonOps.CallWithContext(context, _func, ArrayUtils.Insert(_inst, args)); } else { return PythonOps.CallWithContext(context, _func, args); } } #endregion internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { value = new RuntimeArgChecker(instance, _func, _expected); return true; } internal override bool GetAlwaysSucceeds { get { return true; } } #region IFancyCallable Members [SpecialName] public object Call(CodeContext context, [ParamDictionary]IDictionary<object, object> dict, params object[] args) { ValidateArgs(args); if (_inst != null) { return PythonCalls.CallWithKeywordArgs(context, _func, ArrayUtils.Insert(_inst, args), dict); } else { return PythonCalls.CallWithKeywordArgs(context, _func, args, dict); } } #endregion } /// <summary> /// Decorator for verifying the return type of functions. /// </summary> public class ReturnChecker { public object retType; public ReturnChecker(object returnType) { retType = returnType; } #region ICallableWithCodeContext Members [SpecialName] public object Call(CodeContext context, object func) { // expect only to receive the function we'll call here. return new RuntimeReturnChecker(func, retType); } #endregion } /// <summary> /// Returned value when using clr.returns/ReturnChecker. Calls the original function and /// validates the return type is of a specified type. /// </summary> public class RuntimeReturnChecker : PythonTypeSlot { private object _retType; private object _func; private object _inst; public RuntimeReturnChecker(object function, object expectedReturn) { _retType = expectedReturn; _func = function; } public RuntimeReturnChecker(object instance, object function, object expectedReturn) : this(function, expectedReturn) { _inst = instance; } private void ValidateReturn(object ret) { // we return void... if (ret == null && _retType == null) return; PythonType dt = DynamicHelpers.GetPythonType(ret); if (dt != _retType) { if (!(_retType is PythonType expct)) expct = ((OldClass)_retType).TypeObject; if (!dt.IsSubclassOf(expct)) throw PythonOps.AssertionError("bad return value returned (expected {0}, got {1})", _retType, dt); } } #region ICallableWithCodeContext Members [SpecialName] public object Call(CodeContext context, params object[] args) { object ret; if (_inst != null) { ret = PythonOps.CallWithContext(context, _func, ArrayUtils.Insert(_inst, args)); } else { ret = PythonOps.CallWithContext(context, _func, args); } ValidateReturn(ret); return ret; } #endregion #region IDescriptor Members public object GetAttribute(object instance, object owner) { return new RuntimeReturnChecker(instance, _func, _retType); } #endregion internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { value = GetAttribute(instance, owner); return true; } internal override bool GetAlwaysSucceeds { get { return true; } } #region IFancyCallable Members [SpecialName] public object Call(CodeContext context, [ParamDictionary]IDictionary<object, object> dict, params object[] args) { object ret; if (_inst != null) { ret = PythonCalls.CallWithKeywordArgs(context, _func, ArrayUtils.Insert(_inst, args), dict); } else { return PythonCalls.CallWithKeywordArgs(context, _func, args, dict); } ValidateReturn(ret); return ret; } #endregion } /// <summary> /// returns the result of dir(o) as-if "import clr" has not been performed. /// </summary> public static List Dir(object o) { IList<object> ret = PythonOps.GetAttrNames(DefaultContext.Default, o); List lret = new List(ret); lret.sort(DefaultContext.Default); return lret; } /// <summary> /// Returns the result of dir(o) as-if "import clr" has been performed. /// </summary> public static List DirClr(object o) { IList<object> ret = PythonOps.GetAttrNames(DefaultContext.DefaultCLS, o); List lret = new List(ret); lret.sort(DefaultContext.DefaultCLS); return lret; } /// <summary> /// Attempts to convert the provided object to the specified type. Conversions that /// will be attempted include standard Python conversions as well as .NET implicit /// and explicit conversions. /// /// If the conversion cannot be performed a TypeError will be raised. /// </summary> public static object Convert(CodeContext/*!*/ context, object o, Type toType) { return Converter.Convert(o, toType); } #if FEATURE_FILESYSTEM && FEATURE_REFEMIT /// <summary> /// Provides a helper for compiling a group of modules into a single assembly. The assembly can later be /// reloaded using the clr.AddReference API. /// </summary> public static void CompileModules(CodeContext/*!*/ context, string/*!*/ assemblyName, [ParamDictionary]IDictionary<string, object> kwArgs, params string/*!*/[]/*!*/ filenames) { ContractUtils.RequiresNotNull(assemblyName, "assemblyName"); ContractUtils.RequiresNotNullItems(filenames, "filenames"); PythonContext pc = context.LanguageContext; for (int i = 0; i < filenames.Length; i++) { filenames[i] = Path.GetFullPath(filenames[i]); } Dictionary<string, string> packageMap = BuildPackageMap(filenames); List<SavableScriptCode> code = new List<SavableScriptCode>(); foreach (string filename in filenames) { if (!pc.DomainManager.Platform.FileExists(filename)) { throw PythonOps.IOError($"Couldn't find file for compilation: {filename}"); } ScriptCode sc; string modName; string dname = Path.GetDirectoryName(filename); string outFilename = ""; if (Path.GetFileName(filename) == "__init__.py") { // remove __init__.py to get package name dname = Path.GetDirectoryName(dname); if (String.IsNullOrEmpty(dname)) { modName = Path.GetDirectoryName(filename); } else { modName = Path.GetFileNameWithoutExtension(Path.GetDirectoryName(filename)); } outFilename = Path.DirectorySeparatorChar + "__init__.py"; } else { modName = Path.GetFileNameWithoutExtension(filename); } // see if we have a parent package, if so incorporate it into // our name if (packageMap.TryGetValue(dname, out string parentPackage)) { modName = parentPackage + "." + modName; } outFilename = modName.Replace('.', Path.DirectorySeparatorChar) + outFilename; SourceUnit su = pc.CreateSourceUnit( new FileStreamContentProvider( context.LanguageContext.DomainManager.Platform, filename ), outFilename, pc.DefaultEncoding, SourceCodeKind.File ); sc = context.LanguageContext.GetScriptCode(su, modName, ModuleOptions.Initialize, Compiler.CompilationMode.ToDisk); code.Add((SavableScriptCode)sc); } if (kwArgs != null && kwArgs.TryGetValue("mainModule", out object mainModule)) { if (mainModule is string strModule) { if (!pc.DomainManager.Platform.FileExists(strModule)) { throw PythonOps.IOError("Couldn't find main file for compilation: {0}", strModule); } SourceUnit su = pc.CreateFileUnit(strModule, pc.DefaultEncoding, SourceCodeKind.File); code.Add((SavableScriptCode)context.LanguageContext.GetScriptCode(su, "__main__", ModuleOptions.Initialize, Compiler.CompilationMode.ToDisk)); } } SavableScriptCode.SaveToAssembly(assemblyName, kwArgs, code.ToArray()); } #endif #if FEATURE_REFEMIT /// <summary> /// clr.CompileSubclassTypes(assemblyName, *typeDescription) /// /// Provides a helper for creating an assembly which contains pre-generated .NET /// base types for new-style types. /// /// This assembly can then be AddReferenced or put sys.prefix\DLLs and the cached /// types will be used instead of generating the types at runtime. /// /// This function takes the name of the assembly to save to and then an arbitrary /// number of parameters describing the types to be created. Each of those /// parameter can either be a plain type or a sequence of base types. /// /// clr.CompileSubclassTypes(object) -> create a base type for object /// clr.CompileSubclassTypes(object, str, System.Collections.ArrayList) -> create /// base types for both object and ArrayList. /// /// clr.CompileSubclassTypes(object, (object, IComparable)) -> create base types for /// object and an object which implements IComparable. /// /// </summary> public static void CompileSubclassTypes(string/*!*/ assemblyName, params object[] newTypes) { if (assemblyName == null) { throw PythonOps.TypeError("CompileTypes expected str for assemblyName, got NoneType"); } var typesToCreate = new List<PythonTuple>(); foreach (object o in newTypes) { if (o is PythonType) { typesToCreate.Add(PythonTuple.MakeTuple(o)); } else { typesToCreate.Add(PythonTuple.Make(o)); } } NewTypeMaker.SaveNewTypes(assemblyName, typesToCreate); } #endif /// <summary> /// clr.GetSubclassedTypes() -> tuple /// /// Returns a tuple of information about the types which have been subclassed. /// /// This tuple can be passed to clr.CompileSubclassTypes to cache these /// types on disk such as: /// /// clr.CompileSubclassTypes('assembly', *clr.GetSubclassedTypes()) /// </summary> public static PythonTuple GetSubclassedTypes() { List<object> res = new List<object>(); foreach (NewTypeInfo info in NewTypeMaker._newTypes.Keys) { Type clrBaseType = info.BaseType; Type tempType = clrBaseType; while (tempType != null) { if (tempType.IsGenericType && tempType.GetGenericTypeDefinition() == typeof(Extensible<>)) { clrBaseType = tempType.GetGenericArguments()[0]; break; } tempType = tempType.BaseType; } PythonType baseType = DynamicHelpers.GetPythonTypeFromType(clrBaseType); if (info.InterfaceTypes.Count == 0) { res.Add(baseType); } else if (info.InterfaceTypes.Count > 0) { PythonType[] types = new PythonType[info.InterfaceTypes.Count + 1]; types[0] = baseType; for (int i = 0; i < info.InterfaceTypes.Count; i++) { types[i + 1] = DynamicHelpers.GetPythonTypeFromType(info.InterfaceTypes[i]); } res.Add(PythonTuple.MakeTuple(types)); } } return PythonTuple.MakeTuple(res.ToArray()); } /// <summary> /// Provides a StreamContentProvider for a stream of content backed by a file on disk. /// </summary> [Serializable] internal sealed class FileStreamContentProvider : StreamContentProvider { private readonly string _path; private readonly PALHolder _pal; internal string Path { get { return _path; } } #region Construction internal FileStreamContentProvider(PlatformAdaptationLayer manager, string path) { ContractUtils.RequiresNotNull(path, "path"); _path = path; _pal = new PALHolder(manager); } #endregion public override Stream GetStream() { return _pal.GetStream(Path); } [Serializable] private class PALHolder : MarshalByRefObject { [NonSerialized] private readonly PlatformAdaptationLayer _pal; internal PALHolder(PlatformAdaptationLayer pal) { _pal = pal; } internal Stream GetStream(string path) { return _pal.OpenInputFileStream(path); } } } /// <summary> /// Goes through the list of files identifying the relationship between packages /// and subpackages. Returns a dictionary with all of the package filenames (minus __init__.py) /// mapping to their full name. For example given a structure: /// /// C:\ /// someDir\ /// package\ /// __init__.py /// a.py /// b\ /// __init.py /// c.py /// /// Returns: /// {r'C:\somedir\package' : 'package', r'C:\somedir\package\b', 'package.b'} /// /// This can then be used for calculating the full module name of individual files /// and packages. For example a's full name is "package.a" and c's full name is /// "package.b.c". /// </summary> private static Dictionary<string/*!*/, string/*!*/>/*!*/ BuildPackageMap(string/*!*/[]/*!*/ filenames) { // modules which are the children of packages should have the __name__ // package.subpackage.modulename, not just modulename. So first // we need to get a list of all the modules... List<string> modules = new List<string>(); foreach (string filename in filenames) { if (filename.EndsWith("__init__.py")) { // this is a package modules.Add(filename); } } // next we need to understand the relationship between the packages so // if we have package.subpackage1 and package.subpackage2 we know // both of these are children of the package. So sort the module names, // shortest name first... SortModules(modules); // finally build up the package names for the dirs... Dictionary<string, string> packageMap = new Dictionary<string, string>(); foreach (string packageName in modules) { string dirName = Path.GetDirectoryName(packageName); // remove __init__.py string pkgName = String.Empty; string fullName = Path.GetFileName(Path.GetDirectoryName(packageName)); if (packageMap.TryGetValue(Path.GetDirectoryName(dirName), out pkgName)) { // remove directory name fullName = pkgName + "." + fullName; } packageMap[Path.GetDirectoryName(packageName)] = fullName; } return packageMap; } private static void SortModules(List<string> modules) { modules.Sort((string x, string y) => x.Length - y.Length); } /// <summary> /// Returns a list of profile data. The values are tuples of Profiler.Data objects /// /// All times are expressed in the same unit of measure as DateTime.Ticks /// </summary> public static PythonTuple GetProfilerData(CodeContext/*!*/ context, [DefaultParameterValue(false)]bool includeUnused) { return new PythonTuple(Profiler.GetProfiler(context.LanguageContext).GetProfile(includeUnused)); } /// <summary> /// Resets all profiler counters back to zero /// </summary> public static void ClearProfilerData(CodeContext/*!*/ context) { Profiler.GetProfiler(context.LanguageContext).Reset(); } /// <summary> /// Enable or disable profiling for the current ScriptEngine. This will only affect code /// that is compiled after the setting is changed; previously-compiled code will retain /// whatever setting was active when the code was originally compiled. /// /// The easiest way to recompile a module is to reload() it. /// </summary> public static void EnableProfiler(CodeContext/*!*/ context, bool enable) { var pc = context.LanguageContext; var po = pc.Options as PythonOptions; po.EnableProfiler = enable; } #if FEATURE_SERIALIZATION /// <summary> /// Serializes data using the .NET serialization formatter for complex /// types. Returns a tuple identifying the serialization format and the serialized /// data which can be fed back into clr.Deserialize. /// /// Current serialization formats include custom formats for primitive .NET /// types which aren't already recognized as tuples. None is used to indicate /// that the Binary .NET formatter is used. /// </summary> public static PythonTuple/*!*/ Serialize(object self) { if (self == null) { return PythonTuple.MakeTuple(null, String.Empty); } string data, format; switch (CompilerHelpers.GetType(self).GetTypeCode()) { // for the primitive non-python types just do a simple // serialization case TypeCode.Byte: case TypeCode.Char: case TypeCode.DBNull: case TypeCode.Decimal: case TypeCode.Int16: case TypeCode.Int64: case TypeCode.SByte: case TypeCode.Single: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: data = self.ToString(); format = CompilerHelpers.GetType(self).FullName; break; default: // something more complex, let the binary formatter handle it BinaryFormatter bf = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); bf.Serialize(stream, self); data = stream.ToArray().MakeString(); format = null; break; } return PythonTuple.MakeTuple(format, data); } /// <summary> /// Deserializes the result of a Serialize call. This can be used to perform serialization /// for .NET types which are serializable. This method is the callable object provided /// from __reduce_ex__ for .serializable .NET types. /// /// The first parameter indicates the serialization format and is the first tuple element /// returned from the Serialize call. /// /// The second parameter is the serialized data. /// </summary> public static object Deserialize(string serializationFormat, [NotNull]string/*!*/ data) { if (serializationFormat != null) { switch (serializationFormat) { case "System.Byte": return Byte.Parse(data); case "System.Char": return Char.Parse(data); case "System.DBNull": return DBNull.Value; case "System.Decimal": return Decimal.Parse(data); case "System.Int16": return Int16.Parse(data); case "System.Int64": return Int64.Parse(data); case "System.SByte": return SByte.Parse(data); case "System.Single": return Single.Parse(data); case "System.UInt16": return UInt16.Parse(data); case "System.UInt32": return UInt32.Parse(data); case "System.UInt64": return UInt64.Parse(data); default: throw PythonOps.ValueError("unknown serialization format: {0}", serializationFormat); } } else if (String.IsNullOrEmpty(data)) { return null; } MemoryStream stream = new MemoryStream(data.MakeByteArray()); BinaryFormatter bf = new BinaryFormatter(); return bf.Deserialize(stream); } #endif } }
//Uncomment the next line to enable debugging (also uncomment it in AstarPath.cs) //#define ProfileAstar //@SHOWINEDITOR //#define ASTAR_UNITY_PRO_PROFILER //@SHOWINEDITOR Requires ProfileAstar, profiles section of astar code which will show up in the Unity Pro Profiler. using System.Collections.Generic; using System; using UnityEngine; #if UNITY_5_5_OR_NEWER using UnityEngine.Profiling; #endif namespace Pathfinding { public class AstarProfiler { public class ProfilePoint { //public DateTime lastRecorded; //public TimeSpan totalTime; public System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); public int totalCalls; public long tmpBytes; public long totalBytes; } static readonly Dictionary<string, ProfilePoint> profiles = new Dictionary<string, ProfilePoint>(); static DateTime startTime = DateTime.UtcNow; public static ProfilePoint[] fastProfiles; public static string[] fastProfileNames; private AstarProfiler() { } [System.Diagnostics.Conditional("ProfileAstar")] public static void InitializeFastProfile (string[] profileNames) { fastProfileNames = new string[profileNames.Length+2]; Array.Copy(profileNames, fastProfileNames, profileNames.Length); fastProfileNames[fastProfileNames.Length-2] = "__Control1__"; fastProfileNames[fastProfileNames.Length-1] = "__Control2__"; fastProfiles = new ProfilePoint[fastProfileNames.Length]; for (int i = 0; i < fastProfiles.Length; i++) fastProfiles[i] = new ProfilePoint(); } [System.Diagnostics.Conditional("ProfileAstar")] public static void StartFastProfile (int tag) { //profiles.TryGetValue(tag, out point); fastProfiles[tag].watch.Start();//lastRecorded = DateTime.UtcNow; } [System.Diagnostics.Conditional("ProfileAstar")] public static void EndFastProfile (int tag) { /*if (!profiles.ContainsKey(tag)) * { * Debug.LogError("Can only end profiling for a tag which has already been started (tag was " + tag + ")"); * return; * }*/ ProfilePoint point = fastProfiles[tag]; point.totalCalls++; point.watch.Stop(); //DateTime now = DateTime.UtcNow; //point.totalTime += now - point.lastRecorded; //fastProfiles[tag] = point; } [System.Diagnostics.Conditional("ASTAR_UNITY_PRO_PROFILER")] public static void EndProfile () { Profiler.EndSample(); } [System.Diagnostics.Conditional("ProfileAstar")] public static void StartProfile (string tag) { //Console.WriteLine ("Profile Start - " + tag); ProfilePoint point; profiles.TryGetValue(tag, out point); if (point == null) { point = new ProfilePoint(); profiles[tag] = point; } point.tmpBytes = GC.GetTotalMemory(false); point.watch.Start(); //point.lastRecorded = DateTime.UtcNow; //Debug.Log ("Starting " + tag); } [System.Diagnostics.Conditional("ProfileAstar")] public static void EndProfile (string tag) { if (!profiles.ContainsKey(tag)) { Debug.LogError("Can only end profiling for a tag which has already been started (tag was " + tag + ")"); return; } //Console.WriteLine ("Profile End - " + tag); //DateTime now = DateTime.UtcNow; ProfilePoint point = profiles[tag]; //point.totalTime += now - point.lastRecorded; ++point.totalCalls; point.watch.Stop(); point.totalBytes += GC.GetTotalMemory(false) - point.tmpBytes; //profiles[tag] = point; //Debug.Log ("Ending " + tag); } [System.Diagnostics.Conditional("ProfileAstar")] public static void Reset () { profiles.Clear(); startTime = DateTime.UtcNow; if (fastProfiles != null) { for (int i = 0; i < fastProfiles.Length; i++) { fastProfiles[i] = new ProfilePoint(); } } } [System.Diagnostics.Conditional("ProfileAstar")] public static void PrintFastResults () { if (fastProfiles == null) return; StartFastProfile(fastProfiles.Length-2); for (int i = 0; i < 1000; i++) { StartFastProfile(fastProfiles.Length-1); EndFastProfile(fastProfiles.Length-1); } EndFastProfile(fastProfiles.Length-2); double avgOverhead = fastProfiles[fastProfiles.Length-2].watch.Elapsed.TotalMilliseconds / 1000.0; TimeSpan endTime = DateTime.UtcNow - startTime; var output = new System.Text.StringBuilder(); output.Append("============================\n\t\t\t\tProfile results:\n============================\n"); output.Append("Name | Total Time | Total Calls | Avg/Call | Bytes"); //foreach(KeyValuePair<string, ProfilePoint> pair in profiles) for (int i = 0; i < fastProfiles.Length; i++) { string name = fastProfileNames[i]; ProfilePoint value = fastProfiles[i]; int totalCalls = value.totalCalls; double totalTime = value.watch.Elapsed.TotalMilliseconds - avgOverhead*totalCalls; if (totalCalls < 1) continue; output.Append("\n").Append(name.PadLeft(10)).Append("| "); output.Append(totalTime.ToString("0.0 ").PadLeft(10)).Append(value.watch.Elapsed.TotalMilliseconds.ToString("(0.0)").PadLeft(10)).Append("| "); output.Append(totalCalls.ToString().PadLeft(10)).Append("| "); output.Append((totalTime / totalCalls).ToString("0.000").PadLeft(10)); /* output.Append("\nProfile"); * output.Append(name); * output.Append(" took \t"); * output.Append(totalTime.ToString("0.0")); * output.Append(" ms to complete over "); * output.Append(totalCalls); * output.Append(" iteration"); * if (totalCalls != 1) output.Append("s"); * output.Append(", averaging \t"); * output.Append((totalTime / totalCalls).ToString("0.000")); * output.Append(" ms per call"); */ } output.Append("\n\n============================\n\t\tTotal runtime: "); output.Append(endTime.TotalSeconds.ToString("F3")); output.Append(" seconds\n============================"); Debug.Log(output.ToString()); } [System.Diagnostics.Conditional("ProfileAstar")] public static void PrintResults () { TimeSpan endTime = DateTime.UtcNow - startTime; var output = new System.Text.StringBuilder(); output.Append("============================\n\t\t\t\tProfile results:\n============================\n"); int maxLength = 5; foreach (KeyValuePair<string, ProfilePoint> pair in profiles) { maxLength = Math.Max(pair.Key.Length, maxLength); } output.Append(" Name ".PadRight(maxLength)). Append("|").Append(" Total Time ".PadRight(20)). Append("|").Append(" Total Calls ".PadRight(20)). Append("|").Append(" Avg/Call ".PadRight(20)); foreach (var pair in profiles) { double totalTime = pair.Value.watch.Elapsed.TotalMilliseconds; int totalCalls = pair.Value.totalCalls; if (totalCalls < 1) continue; string name = pair.Key; output.Append("\n").Append(name.PadRight(maxLength)).Append("| "); output.Append(totalTime.ToString("0.0").PadRight(20)).Append("| "); output.Append(totalCalls.ToString().PadRight(20)).Append("| "); output.Append((totalTime / totalCalls).ToString("0.000").PadRight(20)); output.Append(AstarMath.FormatBytesBinary((int)pair.Value.totalBytes).PadLeft(10)); /*output.Append("\nProfile "); * output.Append(pair.Key); * output.Append(" took "); * output.Append(totalTime.ToString("0")); * output.Append(" ms to complete over "); * output.Append(totalCalls); * output.Append(" iteration"); * if (totalCalls != 1) output.Append("s"); * output.Append(", averaging "); * output.Append((totalTime / totalCalls).ToString("0.0")); * output.Append(" ms per call");*/ } output.Append("\n\n============================\n\t\tTotal runtime: "); output.Append(endTime.TotalSeconds.ToString("F3")); output.Append(" seconds\n============================"); Debug.Log(output.ToString()); } } }
// // MRMoveActivity.cs // // Author: // Steve Jakab <> // // Copyright (c) 2014 Steve Jakab // // 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 UnityEngine; using System.Collections; using System.Collections.Generic; using AssemblyCSharp; namespace PortableRealm { public class MRMoveActivity : MRActivity { #region Properties public MRClearing Clearing { get{ return mClearing; } set{ mClearing = value; } } #endregion #region Methods public MRMoveActivity() : base(MRGame.eActivity.Move) { } protected override void InternalUpdate() { if (mClearing == null) { Debug.LogError("Executing move with no destination"); Executed = true; return; } // make sure the clearings connect bool validForMoveType = false; MRILocation currentLocation = Owner.Location; switch (Owner.MoveType) { case MRGame.eMoveType.Walk: { MRRoad road = currentLocation.RoadTo(Clearing); if (road != null) { // if we're walking along a hidden road, make sure we've discovered it if (road.type == MRRoad.eRoadType.HiddenPath || road.type == MRRoad.eRoadType.SecretPassage) { if (Owner.DiscoveredRoads.IndexOf(road) >= 0) validForMoveType = true; else Debug.LogWarning("Secret path not discovered"); } else validForMoveType = true; } else Debug.LogWarning("No road"); break; } case MRGame.eMoveType.WalkThroughWoods: if (currentLocation.RoadTo(Clearing) != null || currentLocation.MyTileSide == Clearing.MyTileSide) { validForMoveType = true; } break; case MRGame.eMoveType.Fly: break; } if (validForMoveType) { switch (mClearing.type) { case MRClearing.eType.Woods: case MRClearing.eType.Cave: TestForDroppedItems(); Owner.Location = Clearing; break; case MRClearing.eType.Mountain: { // only move if the previous activity was a move to the same clearing int myIndex = Parent.Activities.IndexOf(this); if (myIndex > 0) { MRActivity prevActivity = Parent.Activities[myIndex - 1]; if (prevActivity is MRMoveActivity && ((MRMoveActivity)prevActivity).Clearing == Clearing) { TestForDroppedItems(); Owner.Location = Clearing; // temp - test fatigue /* if (Owner is MRCharacter) { MRCharacter character = (MRCharacter)Owner; if (character.CanFatigueChit(1)) { character.SetFatigueBalance(1); } } */ } } break; } } } Executed = true; } private void TestForDroppedItems() { if (Owner is MRCharacter) { MRCharacter character = (MRCharacter)Owner; IList<MRItem> toDrop = new List<MRItem>(); foreach (MRItem item in character.ActiveItems) { if (!character.CanMoveWithItem(item)) toDrop.Add(item); } foreach (MRItem item in character.InactiveItems) { if (!character.CanMoveWithItem(item)) toDrop.Add(item); } if (toDrop.Count > 0) { foreach (MRItem item in toDrop) { if (item is MRTreasure) ((MRTreasure)item).Hidden = true; character.RemoveItem(item); character.Location.AbandonedItems.AddPieceToBottom(item); } MRGame.TheGame.ShowInformationDialog("Abandoned some items that were too heavy"); } } } public override bool Load(JSONObject root) { bool result = base.Load(root); if (result) { JSONValue clearingTest = root["clearing"]; if (clearingTest != null) { string clearingName = ((JSONString)clearingTest).Value; mClearing = MRGame.TheGame.GetClearing(clearingName); if (mClearing == null) { Debug.LogError("Move activity null clearing for " + clearingName); } } } return result; } public override void Save(JSONObject root) { base.Save(root); if (mClearing != null) { root["clearing"] = new JSONString(mClearing.Name); } } #endregion #region Members private MRClearing mClearing; #endregion } }
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 MVCApiTest.Areas.HelpPage.ModelDescriptions; using MVCApiTest.Areas.HelpPage.Models; namespace MVCApiTest.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); } } } }
#region File Description //----------------------------------------------------------------------------- // BloomComponent.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; #endregion namespace Infiniminer { public class BloomComponent { #region Fields SpriteBatch spriteBatch; Effect bloomExtractEffect; Effect bloomCombineEffect; Effect gaussianBlurEffect; ResolveTexture2D resolveTarget; RenderTarget2D renderTarget1; RenderTarget2D renderTarget2; GraphicsDevice GraphicsDevice = null; // Choose what display settings the bloom should use. public BloomSettings Settings { get { return settings; } set { settings = value; } } BloomSettings settings = BloomSettings.PresetSettings[0]; // Optionally displays one of the intermediate buffers used // by the bloom postprocess, so you can see exactly what is // being drawn into each rendertarget. public enum IntermediateBuffer { PreBloom, BlurredHorizontally, BlurredBothWays, FinalResult, } public IntermediateBuffer ShowBuffer { get { return showBuffer; } set { showBuffer = value; } } IntermediateBuffer showBuffer = IntermediateBuffer.FinalResult; #endregion #region Initialization /// <summary> /// Load your graphics content. /// </summary> public void Load(GraphicsDevice device, ContentManager content) { GraphicsDevice = device; spriteBatch = new SpriteBatch(GraphicsDevice); bloomExtractEffect = content.Load<Effect>("BloomExtract"); bloomCombineEffect = content.Load<Effect>("BloomCombine"); gaussianBlurEffect = content.Load<Effect>("GaussianBlur"); // Look up the resolution and format of our main backbuffer. PresentationParameters pp = GraphicsDevice.PresentationParameters; int width = pp.BackBufferWidth; int height = pp.BackBufferHeight; SurfaceFormat format = pp.BackBufferFormat; // Create a texture for reading back the backbuffer contents. resolveTarget = new ResolveTexture2D(GraphicsDevice, width, height, 1, format); // Create two rendertargets for the bloom processing. These are half the // size of the backbuffer, in order to minimize fillrate costs. Reducing // the resolution in this way doesn't hurt quality, because we are going // to be blurring the bloom images in any case. width /= 4; height /= 4; renderTarget1 = new RenderTarget2D(GraphicsDevice, width, height, 1, format); renderTarget2 = new RenderTarget2D(GraphicsDevice, width, height, 1, format); } /// <summary> /// Unload your graphics content. /// </summary> protected void Dispose() { resolveTarget.Dispose(); renderTarget1.Dispose(); renderTarget2.Dispose(); } #endregion #region Draw /// <summary> /// This is where it all happens. Grabs a scene that has already been rendered, /// and uses postprocess magic to add a glowing bloom effect over the top of it. /// </summary> public void Draw(GraphicsDevice device) { // Resolve the scene into a texture, so we can // use it as input data for the bloom processing. GraphicsDevice.ResolveBackBuffer(resolveTarget); // Pass 1: draw the scene into rendertarget 1, using a // shader that extracts only the brightest parts of the image. bloomExtractEffect.Parameters["BloomThreshold"].SetValue(Settings.BloomThreshold); DrawFullscreenQuad(resolveTarget, renderTarget1, bloomExtractEffect, IntermediateBuffer.PreBloom); // Pass 2: draw from rendertarget 1 into rendertarget 2, // using a shader to apply a horizontal gaussian blur filter. SetBlurEffectParameters(1.0f / (float)renderTarget1.Width, 0); DrawFullscreenQuad(renderTarget1.GetTexture(), renderTarget2, gaussianBlurEffect, IntermediateBuffer.BlurredHorizontally); // Pass 3: draw from rendertarget 2 back into rendertarget 1, // using a shader to apply a vertical gaussian blur filter. SetBlurEffectParameters(0, 1.0f / (float)renderTarget1.Height); DrawFullscreenQuad(renderTarget2.GetTexture(), renderTarget1, gaussianBlurEffect, IntermediateBuffer.BlurredBothWays); // Pass 4: draw both rendertarget 1 and the original scene // image back into the main backbuffer, using a shader that // combines them to produce the final bloomed result. GraphicsDevice.SetRenderTarget(0, null); EffectParameterCollection parameters = bloomCombineEffect.Parameters; parameters["BloomIntensity"].SetValue(Settings.BloomIntensity); parameters["BaseIntensity"].SetValue(Settings.BaseIntensity); parameters["BloomSaturation"].SetValue(Settings.BloomSaturation); parameters["BaseSaturation"].SetValue(Settings.BaseSaturation); GraphicsDevice.Textures[1] = resolveTarget; Viewport viewport = GraphicsDevice.Viewport; DrawFullscreenQuad(renderTarget1.GetTexture(), viewport.Width, viewport.Height, bloomCombineEffect, IntermediateBuffer.FinalResult); } /// <summary> /// Helper for drawing a texture into a rendertarget, using /// a custom shader to apply postprocessing effects. /// </summary> void DrawFullscreenQuad(Texture2D texture, RenderTarget2D renderTarget, Effect effect, IntermediateBuffer currentBuffer) { GraphicsDevice.SetRenderTarget(0, renderTarget); DrawFullscreenQuad(texture, renderTarget.Width, renderTarget.Height, effect, currentBuffer); GraphicsDevice.SetRenderTarget(0, null); } /// <summary> /// Helper for drawing a texture into the current rendertarget, /// using a custom shader to apply postprocessing effects. /// </summary> void DrawFullscreenQuad(Texture2D texture, int width, int height, Effect effect, IntermediateBuffer currentBuffer) { spriteBatch.Begin(SpriteBlendMode.None, SpriteSortMode.Immediate, SaveStateMode.SaveState); // Begin the custom effect, if it is currently enabled. If the user // has selected one of the show intermediate buffer options, we still // draw the quad to make sure the image will end up on the screen, // but might need to skip applying the custom pixel shader. if (showBuffer >= currentBuffer) { effect.Begin(); effect.CurrentTechnique.Passes[0].Begin(); } // Draw the quad. spriteBatch.Draw(texture, new Rectangle(0, 0, width, height), Color.White); spriteBatch.End(); // End the custom effect. if (showBuffer >= currentBuffer) { effect.CurrentTechnique.Passes[0].End(); effect.End(); } } /// <summary> /// Computes sample weightings and texture coordinate offsets /// for one pass of a separable gaussian blur filter. /// </summary> void SetBlurEffectParameters(float dx, float dy) { // Look up the sample weight and offset effect parameters. EffectParameter weightsParameter, offsetsParameter; weightsParameter = gaussianBlurEffect.Parameters["SampleWeights"]; offsetsParameter = gaussianBlurEffect.Parameters["SampleOffsets"]; // Look up how many samples our gaussian blur effect supports. int sampleCount = weightsParameter.Elements.Count; // Create temporary arrays for computing our filter settings. float[] sampleWeights = new float[sampleCount]; Vector2[] sampleOffsets = new Vector2[sampleCount]; // The first sample always has a zero offset. sampleWeights[0] = ComputeGaussian(0); sampleOffsets[0] = new Vector2(0); // Maintain a sum of all the weighting values. float totalWeights = sampleWeights[0]; // Add pairs of additional sample taps, positioned // along a line in both directions from the center. for (int i = 0; i < sampleCount / 2; i++) { // Store weights for the positive and negative taps. float weight = ComputeGaussian(i + 1); sampleWeights[i * 2 + 1] = weight; sampleWeights[i * 2 + 2] = weight; totalWeights += weight * 2; // To get the maximum amount of blurring from a limited number of // pixel shader samples, we take advantage of the bilinear filtering // hardware inside the texture fetch unit. If we position our texture // coordinates exactly halfway between two texels, the filtering unit // will average them for us, giving two samples for the price of one. // This allows us to step in units of two texels per sample, rather // than just one at a time. The 1.5 offset kicks things off by // positioning us nicely in between two texels. float sampleOffset = i * 2 + 1.5f; Vector2 delta = new Vector2(dx, dy) * sampleOffset; // Store texture coordinate offsets for the positive and negative taps. sampleOffsets[i * 2 + 1] = delta; sampleOffsets[i * 2 + 2] = -delta; } // Normalize the list of sample weightings, so they will always sum to one. for (int i = 0; i < sampleWeights.Length; i++) { sampleWeights[i] /= totalWeights; } // Tell the effect about our new filter settings. weightsParameter.SetValue(sampleWeights); offsetsParameter.SetValue(sampleOffsets); } /// <summary> /// Evaluates a single point on the gaussian falloff curve. /// Used for setting up the blur filter weightings. /// </summary> float ComputeGaussian(float n) { float theta = Settings.BlurAmount; return (float)((1.0 / Math.Sqrt(2 * Math.PI * theta)) * Math.Exp(-(n * n) / (2 * theta * theta))); } #endregion } }
// 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 System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Commands; using Microsoft.CodeAnalysis.Editor.CSharp.RenameTracking; using Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Editor.VisualBasic.RenameTracking; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.CodeAnalysis.UnitTests.Diagnostics; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking { internal sealed class RenameTrackingTestState : IDisposable { private readonly ITagger<RenameTrackingTag> _tagger; public readonly TestWorkspace Workspace; private readonly IWpfTextView _view; private readonly ITextUndoHistoryRegistry _historyRegistry; private string _notificationMessage = null; private readonly TestHostDocument _hostDocument; public TestHostDocument HostDocument { get { return _hostDocument; } } private readonly IEditorOperations _editorOperations; public IEditorOperations EditorOperations { get { return _editorOperations; } } private readonly MockRefactorNotifyService _mockRefactorNotifyService; public MockRefactorNotifyService RefactorNotifyService { get { return _mockRefactorNotifyService; } } private readonly CodeFixProvider _codeFixProvider; private readonly RenameTrackingCancellationCommandHandler _commandHandler = new RenameTrackingCancellationCommandHandler(); public static async Task<RenameTrackingTestState> CreateAsync( string markup, string languageName, bool onBeforeGlobalSymbolRenamedReturnValue = true, bool onAfterGlobalSymbolRenamedReturnValue = true) { var workspace = await CreateTestWorkspaceAsync(markup, languageName, TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic()); return new RenameTrackingTestState(workspace, languageName, onBeforeGlobalSymbolRenamedReturnValue, onAfterGlobalSymbolRenamedReturnValue); } public RenameTrackingTestState( TestWorkspace workspace, string languageName, bool onBeforeGlobalSymbolRenamedReturnValue = true, bool onAfterGlobalSymbolRenamedReturnValue = true) { this.Workspace = workspace; _hostDocument = Workspace.Documents.First(); _view = _hostDocument.GetTextView(); _view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, _hostDocument.CursorPosition.Value)); _editorOperations = Workspace.GetService<IEditorOperationsFactoryService>().GetEditorOperations(_view); _historyRegistry = Workspace.ExportProvider.GetExport<ITextUndoHistoryRegistry>().Value; _mockRefactorNotifyService = new MockRefactorNotifyService { OnBeforeSymbolRenamedReturnValue = onBeforeGlobalSymbolRenamedReturnValue, OnAfterSymbolRenamedReturnValue = onAfterGlobalSymbolRenamedReturnValue }; // Mock the action taken by the workspace INotificationService var notificationService = Workspace.Services.GetService<INotificationService>() as INotificationServiceCallback; var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => _notificationMessage = message); notificationService.NotificationCallback = callback; var tracker = new RenameTrackingTaggerProvider( _historyRegistry, Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value, Workspace.ExportProvider.GetExport<IInlineRenameService>().Value, Workspace.ExportProvider.GetExport<IDiagnosticAnalyzerService>().Value, SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService), Workspace.ExportProvider.GetExports<IAsynchronousOperationListener, FeatureMetadata>()); _tagger = tracker.CreateTagger<RenameTrackingTag>(_hostDocument.GetTextBuffer()); if (languageName == LanguageNames.CSharp) { _codeFixProvider = new CSharpRenameTrackingCodeFixProvider( Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value, _historyRegistry, SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService)); } else if (languageName == LanguageNames.VisualBasic) { _codeFixProvider = new VisualBasicRenameTrackingCodeFixProvider( Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value, _historyRegistry, SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService)); } else { throw new ArgumentException("Invalid language name: " + languageName, nameof(languageName)); } } private static Task<TestWorkspace> CreateTestWorkspaceAsync(string code, string languageName, ExportProvider exportProvider = null) { var xml = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document>{1}</Document> </Project> </Workspace>", languageName, code); return TestWorkspace.CreateAsync(xml, exportProvider: exportProvider); } public void SendEscape() { _commandHandler.ExecuteCommand(new EscapeKeyCommandArgs(_view, _view.TextBuffer), () => { }); } public void MoveCaret(int delta) { var position = _view.Caret.Position.BufferPosition.Position; _view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, position + delta)); } public void Undo(int count = 1) { var history = _historyRegistry.GetHistory(_view.TextBuffer); history.Undo(count); } public void Redo(int count = 1) { var history = _historyRegistry.GetHistory(_view.TextBuffer); history.Redo(count); } public async Task AssertNoTag() { await WaitForAsyncOperationsAsync(); var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection()); Assert.Equal(0, tags.Count()); } public async Task<IList<Diagnostic>> GetDocumentDiagnosticsAsync(Document document = null) { document = document ?? this.Workspace.CurrentSolution.GetDocument(_hostDocument.Id); var analyzer = new RenameTrackingDiagnosticAnalyzer(); return (await DiagnosticProviderTestUtilities.GetDocumentDiagnosticsAsync(analyzer, document, (await document.GetSyntaxRootAsync()).FullSpan)).ToList(); } public async Task AssertTag(string expectedFromName, string expectedToName, bool invokeAction = false) { await WaitForAsyncOperationsAsync(); var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection()); // There should only ever be one tag Assert.Equal(1, tags.Count()); var tag = tags.Single(); var document = this.Workspace.CurrentSolution.GetDocument(_hostDocument.Id); var diagnostics = await GetDocumentDiagnosticsAsync(document); // There should be a single rename tracking diagnostic Assert.Equal(1, diagnostics.Count); Assert.Equal(RenameTrackingDiagnosticAnalyzer.DiagnosticId, diagnostics[0].Id); var actions = new List<CodeAction>(); var context = new CodeFixContext(document, diagnostics[0], (a, d) => actions.Add(a), CancellationToken.None); await _codeFixProvider.RegisterCodeFixesAsync(context); // There should only be one code action Assert.Equal(1, actions.Count); Assert.Equal(string.Format(EditorFeaturesResources.Rename_0_to_1, expectedFromName, expectedToName), actions[0].Title); if (invokeAction) { var operations = (await actions[0].GetOperationsAsync(CancellationToken.None)).ToArray(); Assert.Equal(1, operations.Length); operations[0].Apply(this.Workspace, new ProgressTracker(), CancellationToken.None); } } public void AssertNoNotificationMessage() { Assert.Null(_notificationMessage); } public void AssertNotificationMessage() { Assert.NotNull(_notificationMessage); } private async Task WaitForAsyncOperationsAsync() { var waiters = Workspace.ExportProvider.GetExportedValues<IAsynchronousOperationWaiter>(); await waiters.WaitAllAsync(); } public void Dispose() { Workspace.Dispose(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans; using Orleans.Hosting; using Orleans.Runtime.Configuration; using Orleans.TestingHost; using Tester; using TestExtensions; using Xunit; using Xunit.Abstractions; using Orleans.MultiCluster; using Orleans.Configuration; using Microsoft.Extensions.Options; using Microsoft.Extensions.DependencyInjection; namespace Tests.GeoClusterTests { /// <summary> /// A utility class for tests that include multiple clusters. /// </summary> public class TestingClusterHost : IDisposable { public readonly Dictionary<string, ClusterInfo> Clusters = new Dictionary<string, ClusterInfo>(); protected ITestOutputHelper output; private TimeSpan gossipStabilizationTime = TimeSpan.FromSeconds(10); public TestingClusterHost(ITestOutputHelper output = null) { this.output = output; TestUtils.CheckForAzureStorage(); } public struct ClusterInfo { public TestCluster Cluster; public int SequenceNumber; // we number created clusters in order of creation public IEnumerable<SiloHandle> Silos => Cluster.GetActiveSilos(); } public void WriteLog(string format, params object[] args) { if (output != null) output.WriteLine("{0} {1}", DateTime.UtcNow, string.Format(format, args)); } public async Task RunWithTimeout(string name, int msec, Func<Task> test) { WriteLog("--- Starting {0}", name); var stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); var testtask = test(); await Task.WhenAny(testtask, Task.Delay(System.Diagnostics.Debugger.IsAttached ? 3600000 : msec)); stopwatch.Stop(); if (!testtask.IsCompleted) { WriteLog("--- {0} Timed out after {1})", name, stopwatch.Elapsed); Assert.True(false, string.Format("{0} took too long, timed out", name)); } try // see if there was an exception and print it for logging { await testtask; WriteLog("--- {0} Done (elapsed = {1})", name, stopwatch.Elapsed); } catch (Exception e) { WriteLog("--- Exception observed in {0}: {1})", name, e); throw; } } public void AssertEqual<T>(T expected, T actual, string comment) { try { Assert.Equal(expected, actual); } catch (Exception) { WriteLog("Equality assertion failed; expected={0}, actual={1} comment={2}", expected, actual, comment); throw; } } /// <summary> /// Wait for the multicluster-gossip sub-system to stabilize. /// </summary> public async Task WaitForMultiClusterGossipToStabilizeAsync(bool account_for_lost_messages) { TimeSpan stabilizationTime = account_for_lost_messages ? gossipStabilizationTime : TimeSpan.FromSeconds(1); WriteLog("WaitForMultiClusterGossipToStabilizeAsync is about to sleep for {0}", stabilizationTime); await Task.Delay(stabilizationTime); WriteLog("WaitForMultiClusterGossipToStabilizeAsync is done sleeping"); } public Task WaitForLivenessToStabilizeAsync() { return this.Clusters.Any() ? this.Clusters.First().Value.Cluster.WaitForLivenessToStabilizeAsync() : Task.Delay(gossipStabilizationTime); } public void StopAllSilos() { foreach (var cluster in Clusters.Values) { cluster.Cluster.StopAllSilos(); } } public ParallelOptions paralleloptions = new ParallelOptions() { MaxDegreeOfParallelism = 4 }; private static int GetPortBase(int clusternumber) { return 21000 + (clusternumber + 1) * 100; } private static int GetProxyBase(int clusternumber) { return 22000 + (clusternumber + 2) * 100; } public void NewGeoCluster(Guid globalServiceId, string clusterId, short numSilos) { NewGeoCluster<NoOpSiloBuilderConfigurator>(globalServiceId, clusterId, numSilos); } public void NewGeoCluster<TSiloBuilderConfigurator>( Guid globalServiceId, string clusterId, short numSilos, Action<TestClusterBuilder> configureTestCluster = null) where TSiloBuilderConfigurator : ISiloBuilderConfigurator, new() { NewCluster( globalServiceId.ToString(), clusterId, numSilos, builder => { builder.AddSiloBuilderConfigurator<TSiloBuilderConfigurator>(); builder.AddSiloBuilderConfigurator<StandardGeoClusterConfigurator>(); configureTestCluster?.Invoke(builder); }); } private class StandardGeoClusterConfigurator : ISiloBuilderConfigurator { public void Configure(ISiloHostBuilder hostBuilder) { hostBuilder.Configure<MultiClusterOptions>( options => { options.HasMultiClusterNetwork = true; options.MaxMultiClusterGateways = 2; options.DefaultMultiCluster = null; options.GossipChannels = new Dictionary<string, string> { [MultiClusterOptions.BuiltIn.AzureTable] = TestDefaultConfiguration.DataConnectionString }; }); } } private class NoOpSiloBuilderConfigurator : ISiloBuilderConfigurator { public void Configure(ISiloHostBuilder hostBuilder) { } } private class TestSiloBuilderConfigurator : ISiloBuilderConfigurator { public void Configure(ISiloHostBuilder hostBuilder) { hostBuilder.ConfigureLogging(builder => { builder.AddFilter("Orleans.Runtime.Catalog", LogLevel.Debug); builder.AddFilter("Orleans.Runtime.Dispatcher", LogLevel.Trace); builder.AddFilter("Orleans.Runtime.GrainDirectory.LocalGrainDirectory", LogLevel.Trace); builder.AddFilter("Orleans.Runtime.GrainDirectory.GlobalSingleInstanceRegistrar", LogLevel.Trace); builder.AddFilter("Orleans.Runtime.LogConsistency.ProtocolServices", LogLevel.Trace); builder.AddFilter("Orleans.Storage.MemoryStorageGrain", LogLevel.Debug); }); hostBuilder.AddAzureTableGrainStorage("AzureStore", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) => { options.ConnectionString = TestDefaultConfiguration.DataConnectionString; })); hostBuilder.AddAzureBlobGrainStorage("PubSubStore", (AzureBlobStorageOptions options) => { options.ConnectionString = TestDefaultConfiguration.DataConnectionString; }); } } public void NewCluster(Guid serviceId, string clusterId, short numSilos) { NewCluster<NoOpSiloBuilderConfigurator>(serviceId, clusterId, numSilos); } public void NewCluster<TSiloBuilderConfigurator>(Guid serviceId, string clusterId, short numSilos) where TSiloBuilderConfigurator : ISiloBuilderConfigurator, new() { NewCluster( serviceId.ToString(), clusterId, numSilos, builder => builder.AddSiloBuilderConfigurator<TSiloBuilderConfigurator>()); } public void NewCluster(string serviceId, string clusterId, short numSilos, Action<TestClusterBuilder> configureTestCluster) { TestCluster testCluster; lock (Clusters) { var myCount = Clusters.Count; WriteLog("Starting Cluster {0} ({1})...", myCount, clusterId); var builder = new TestClusterBuilder(initialSilosCount: numSilos) { Options = { ServiceId = serviceId, ClusterId = clusterId, BaseSiloPort = GetPortBase(myCount), BaseGatewayPort = GetProxyBase(myCount) }, CreateSiloAsync = AppDomainSiloHandle.Create }; builder.AddSiloBuilderConfigurator<TestSiloBuilderConfigurator>(); builder.AddSiloBuilderConfigurator<SiloHostConfigurator>(); configureTestCluster?.Invoke(builder); testCluster = builder.Build(); testCluster.Deploy(); Clusters[clusterId] = new ClusterInfo { Cluster = testCluster, SequenceNumber = myCount }; WriteLog("Cluster {0} started. [{1}]", clusterId, string.Join(" ", testCluster.GetActiveSilos().Select(s => s.ToString()))); } } public class SiloHostConfigurator : ISiloBuilderConfigurator { public void Configure(ISiloHostBuilder hostBuilder) { hostBuilder.AddMemoryGrainStorage("MemoryStore") .AddMemoryGrainStorageAsDefault(); } } public virtual void Dispose() { StopAllClientsAndClusters(); } public void StopAllClientsAndClusters() { WriteLog("Stopping all Clients and Clusters..."); var stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); try { var disposetask = Task.Run(() => { StopAllClients(); WriteLog("All Clients are Stopped."); StopAllClusters(); WriteLog("All Clusters are Stopped."); }); disposetask.WaitWithThrow(TimeSpan.FromMinutes(System.Diagnostics.Debugger.IsAttached ? 60 : 2)); } catch (Exception e) { WriteLog("Exception caught in test cleanup function: {0}", e); throw; } stopwatch.Stop(); WriteLog("Dispose completed (elapsed = {0}).", stopwatch.Elapsed); } public void StopAllClusters() { lock (Clusters) { Parallel.ForEach(Clusters.Keys, paralleloptions, key => { var info = Clusters[key]; info.Cluster.StopAllSilos(); }); Clusters.Clear(); } } private readonly List<ClientWrapperBase> activeClients = new List<ClientWrapperBase>(); // The following is a base class to use for creating client wrappers. // This allows us to create multiple clients that are connected to different silos. public class ClientWrapperBase : IDisposable { public string Name { get; private set; } internal IInternalClusterClient InternalClient { get; } public IClusterClient Client => this.InternalClient; public ClientWrapperBase(string name, int gatewayport, string clusterId, Action<IClientBuilder> clientConfigurator) { this.Name = name; Console.WriteLine($"Initializing client {name}"); var internalClientBuilder = new ClientBuilder() .UseLocalhostClustering(gatewayport, clusterId, clusterId); clientConfigurator?.Invoke(internalClientBuilder); this.InternalClient = (IInternalClusterClient) internalClientBuilder.Build(); this.InternalClient.Connect().Wait(); var loggerFactory = this.InternalClient.ServiceProvider.GetRequiredService<ILoggerFactory>(); this.Logger = loggerFactory.CreateLogger($"Client-{name}"); } public IGrainFactory GrainFactory => this.Client; public ILogger Logger { get; } public void Dispose() { this.InternalClient?.Dispose(); } } // Create a new client. public T NewClient<T>( string clusterId, int clientNumber, Func<string, int, string, Action<IClientBuilder>, T> factory, Action<IClientBuilder> clientConfigurator = null) where T : ClientWrapperBase { var ci = this.Clusters[clusterId]; var name = string.Format("Client-{0}-{1}", clusterId, clientNumber); // clients are assigned to silos round-robin var gatewayport = ci.Silos.ElementAt(clientNumber).GatewayAddress.Endpoint.Port; WriteLog("Starting {0} connected to {1}", name, gatewayport); var client = factory(name, gatewayport, clusterId, clientConfigurator); lock (activeClients) { activeClients.Add(client); } WriteLog("Started {0} connected", name); return client; } public void StopAllClients() { List<ClientWrapperBase> clients; lock (activeClients) { clients = activeClients.ToList(); activeClients.Clear(); } Parallel.For(0, clients.Count, paralleloptions, (i) => { try { this.WriteLog("Stopping client {0}", i); clients[i]?.Client.Close().Wait(); } catch (Exception e) { this.WriteLog("Exception caught While stopping client {0}: {1}", i, e); } finally { clients[i]?.Dispose(); } }); } public void BlockAllClusterCommunication(string from, string to) { foreach (var silo in Clusters[from].Silos) { var hooks = ((AppDomainSiloHandle) silo).AppDomainTestHook; foreach (var dest in Clusters[to].Silos) { WriteLog("Blocking {0}->{1}", silo, dest); hooks.BlockSiloCommunication(dest.SiloAddress.Endpoint, 100); } } } public void UnblockAllClusterCommunication(string from) { foreach (var silo in Clusters[from].Silos) { WriteLog("Unblocking {0}", silo); var hooks = ((AppDomainSiloHandle)silo).AppDomainTestHook; hooks.UnblockSiloCommunication(); } } public void SetProtocolMessageFilterForTesting(string originCluster, Func<ILogConsistencyProtocolMessage, bool> filter) { var silos = Clusters[originCluster].Silos; foreach (var silo in silos) { var hooks = ((AppDomainSiloHandle) silo).AppDomainTestHook; hooks.ProtocolMessageFilterForTesting = filter; } } } }
// Copyright (c) Microsoft. 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.Linq; using System.Xml.Linq; using CoreXml.Test.XLinq; using Microsoft.Test.ModuleCore; namespace XLinqTests { public class AddNodeBefore : AddNodeBeforeAfterBase { // to test: // - order // - parent, document property // - query // - value // - assigning/cloning nodes (connected, not connected) // ---- // add valid: // - elem (just root), PI, Comment, XDecl/XDocType (order!) //[Variation(Priority = 1, Desc = "Adding multiple (4) objects into XElement - not connected", Params = new object[] { false, 4 })] //[Variation(Priority = 1, Desc = "Adding multiple (4) objects into XElement - connected", Params = new object[] { true, 4 })] //[Variation(Priority = 1, Desc = "Adding single object into XElement - not connected", Params = new object[] { false, 1 })] //[Variation(Priority = 1, Desc = "Adding single object into XElement - connected", Params = new object[] { true, 1 })] #region Public Methods and Operators public override void AddChildren() { AddChild(new TestVariation(AddingMultipleNodesIntoElement) { Attribute = new VariationAttribute("Adding single object into XElement - connected") { Params = new object[] { true, 1 }, Priority = 1 } }); AddChild(new TestVariation(AddingMultipleNodesIntoElement) { Attribute = new VariationAttribute("Adding multiple (4) objects into XElement - connected") { Params = new object[] { true, 4 }, Priority = 1 } }); AddChild(new TestVariation(AddingMultipleNodesIntoElement) { Attribute = new VariationAttribute("Adding multiple (4) objects into XElement - not connected") { Params = new object[] { false, 4 }, Priority = 1 } }); AddChild(new TestVariation(AddingMultipleNodesIntoElement) { Attribute = new VariationAttribute("Adding single object into XElement - not connected") { Params = new object[] { false, 1 }, Priority = 1 } }); AddChild(new TestVariation(InvalidNodeTypes) { Attribute = new VariationAttribute("Invalid node types - single object") { Priority = 2 } }); AddChild(new TestVariation(ValidAddIntoXDocument) { Attribute = new VariationAttribute("XDocument valid add - connected (single)") { Params = new object[] { true, 1 }, Priority = 0 } }); AddChild(new TestVariation(ValidAddIntoXDocument) { Attribute = new VariationAttribute("XDocument valid add - connected (multiple)") { Params = new object[] { true, 3 }, Priority = 1 } }); AddChild(new TestVariation(ValidAddIntoXDocument) { Attribute = new VariationAttribute("XDocument valid add - not connected (single)") { Params = new object[] { false, 1 }, Priority = 0 } }); AddChild(new TestVariation(ValidAddIntoXDocument) { Attribute = new VariationAttribute("XDocument valid add - not connected (multiple)") { Params = new object[] { false, 3 }, Priority = 1 } }); AddChild(new TestVariation(InvalidAddIntoXDocument) { Attribute = new VariationAttribute("XDocument Invalid Add") { Priority = 0 } }); AddChild(new TestVariation(InvalidAddIntoXDocument1) { Attribute = new VariationAttribute("XDocument invalid add - double DTD") { Priority = 1 } }); AddChild(new TestVariation(InvalidAddIntoXDocument2) { Attribute = new VariationAttribute("XDocument invalid add - DTD after element") { Priority = 1 } }); AddChild(new TestVariation(InvalidAddIntoXDocument3) { Attribute = new VariationAttribute("XDocument invalid add - multiple root elements") { Priority = 1 } }); AddChild(new TestVariation(InvalidAddIntoXDocument5) { Attribute = new VariationAttribute("XDocument invalid add - CData, attribute, text (no whitespace)") { Priority = 1 } }); AddChild(new TestVariation(WorkOnTextNodes1) { Attribute = new VariationAttribute("Working on the text nodes 1.") { Priority = 1 } }); AddChild(new TestVariation(WorkOnTextNodes2) { Attribute = new VariationAttribute("Working on the text nodes 2.") { Priority = 1 } }); } public void AddingMultipleNodesIntoElement() { AddingMultipleNodesIntoElement(delegate(XNode n, object[] content) { n.AddBeforeSelf(content); }, CalculateExpectedValuesAddBefore); } public IEnumerable<ExpectedValue> CalculateExpectedValuesAddBefore(XContainer orig, int startPos, IEnumerable<object> newNodes) { int counter = 0; for (XNode node = orig.FirstNode; node != null; node = node.NextNode, counter++) { if (counter == startPos) { foreach (object o in newNodes) { yield return new ExpectedValue(o is XNode && (o as XNode).Parent == null && (o as XNode).Document == null, o); } } yield return new ExpectedValue(true, node); // Don't build on the text node identity } } //[Variation(Priority = 2, Desc = "Invalid node types - single object")] //[Variation(Priority = 0, Desc = "XDocument Invalid Add")] public void InvalidAddIntoXDocument() { runWithEvents = (bool)Params[0]; object[] nodes = { new XDocument(), new XAttribute("id", "a1") }; XNode[] origNodes = { new XComment("original"), new XProcessingInstruction("OO", "oo") }; foreach (object o in nodes) { var doc1 = new XDocument(origNodes); var doc2 = new XDocument(origNodes); try { if (runWithEvents) { eHelper = new EventsHelper(doc1); } doc1.FirstNode.AddBeforeSelf(o); if (runWithEvents) { eHelper.Verify(XObjectChange.Add, o); } TestLog.Compare(false, "Exception has been expected here"); } catch (ArgumentException) { } } } //[Variation(Priority = 1, Desc = "XDocument invalid add - double DTD")] public void InvalidAddIntoXDocument1() { runWithEvents = (bool)Params[0]; try { var doc = new XDocument(new XDocumentType("root", null, null, null), new XElement("A")); var o = new XDocumentType("D", null, null, null); if (runWithEvents) { eHelper = new EventsHelper(doc); } doc.FirstNode.AddBeforeSelf(o); if (runWithEvents) { eHelper.Verify(XObjectChange.Add, o); } TestLog.Compare(false, "Exception expected"); } catch (InvalidOperationException) { } } //[Variation(Priority = 1, Desc = "XDocument invalid add - DTD after element")] public void InvalidAddIntoXDocument2() { runWithEvents = (bool)Params[0]; try { var doc = new XDocument(new XElement("A"), new XComment("comm")); var o = new XDocumentType("D", null, null, null); if (runWithEvents) { eHelper = new EventsHelper(doc); } doc.LastNode.AddBeforeSelf(o); if (runWithEvents) { eHelper.Verify(XObjectChange.Add, o); } TestLog.Compare(false, "Exception expected"); } catch (InvalidOperationException) { } } //[Variation(Priority = 1, Desc = "XDocument invalid add - multiple root elements")] public void InvalidAddIntoXDocument3() { runWithEvents = (bool)Params[0]; try { var doc = new XDocument(new XProcessingInstruction("pi", "halala"), new XElement("A")); var o = new XElement("C"); if (runWithEvents) { eHelper = new EventsHelper(doc); } doc.LastNode.AddBeforeSelf(o); if (runWithEvents) { eHelper.Verify(XObjectChange.Add, o); } TestLog.Compare(false, "Exception expected"); } catch (InvalidOperationException) { } } //[Variation(Priority = 1, Desc = "XDocument invalid add - CData, attribute, text (no whitespace)")] public void InvalidAddIntoXDocument5() { runWithEvents = (bool)Params[0]; foreach (object o in new object[] { new XCData("CD"), new XAttribute("a1", "avalue"), "text1", new XText("text2"), new XDocument() }) { try { var doc = new XDocument(new XElement("A")); if (runWithEvents) { eHelper = new EventsHelper(doc); } doc.LastNode.AddBeforeSelf(o); if (runWithEvents) { eHelper.Verify(XObjectChange.Add, o); } TestLog.Compare(false, "Exception expected"); } catch (ArgumentException) { } } } public void InvalidNodeTypes() { runWithEvents = (bool)Params[0]; var root = new XElement("root", new XAttribute("a", "b"), new XElement("here"), "tests"); var rootCopy = new XElement(root); XElement elem = root.Element("here"); object[] nodes = { new XAttribute("xx", "yy"), new XDocument(), new XDocumentType("root", null, null, null) }; if (runWithEvents) { eHelper = new EventsHelper(elem); } foreach (object o in nodes) { try { elem.AddBeforeSelf(o); if (runWithEvents) { eHelper.Verify(XObjectChange.Add, o); } TestLog.Compare(false, "Should fail!"); } catch (ArgumentException) { TestLog.Compare(XNode.DeepEquals(root, rootCopy), "root.DeepEquals(rootCopy)"); } } } //[Variation(Priority = 0, Desc = "XDocument valid add - connected (single)", Params = new object[] { true, 1 })] //[Variation(Priority = 0, Desc = "XDocument valid add - not connected (single)", Params = new object[] { false, 1 })] //[Variation(Priority = 1, Desc = "XDocument valid add - connected (multiple)", Params = new object[] { true, 3 })] //[Variation(Priority = 1, Desc = "XDocument valid add - not connected (multiple)", Params = new object[] { false, 3 })] public void ValidAddIntoXDocument() { ValidAddIntoXDocument(delegate(XNode n, object[] content) { n.AddBeforeSelf(content); }, CalculateExpectedValuesAddBefore); } //[Variation(Priority = 1, Desc = "Working on the text nodes 1.")] public void WorkOnTextNodes1() { runWithEvents = (bool)Params[0]; var elem = new XElement("A", new XElement("B"), "text2", new XElement("C")); XNode n = elem.FirstNode.NextNode; if (runWithEvents) { eHelper = new EventsHelper(elem); } n.AddBeforeSelf("text0"); n.AddBeforeSelf("text1"); if (runWithEvents) { eHelper.Verify(new[] { XObjectChange.Add, XObjectChange.Value }); } TestLog.Compare(elem.Nodes().Count(), 4, "elem.Nodes().Count(), 4"); TestLog.Compare((n as XText).Value, "text2", "(n as XText).Value, text2"); TestLog.Compare((n.PreviousNode as XText).Value, "text0text1", "(n as XText).Value, text0text1"); } //[Variation(Priority = 1, Desc = "Working on the text nodes 2.")] public void WorkOnTextNodes2() { runWithEvents = (bool)Params[0]; var elem = new XElement("A", new XElement("B"), "text2", new XElement("C")); XNode n = elem.FirstNode.NextNode; if (runWithEvents) { eHelper = new EventsHelper(elem); } n.AddBeforeSelf("text0", "text1"); if (runWithEvents) { eHelper.Verify(XObjectChange.Add); } TestLog.Compare(elem.Nodes().Count(), 4, "elem.Nodes().Count(), 4"); TestLog.Compare((n as XText).Value, "text2", "(n as XText).Value, text2"); TestLog.Compare((n.PreviousNode as XText).Value, "text0text1", "(n as XText).Value, text0text1"); } #endregion // Type is CoreXml.Test.XLinq.FunctionalTests+TreeManipulationTests+AddNodeBefore // Test Case } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Orleans; using Orleans.Runtime; using Orleans.Streams; using UnitTests.GrainInterfaces; using UnitTests.Grains; using UnitTests.TestHelper; namespace UnitTests.StreamingTests { public class Streaming_ConsumerClientObject : IAsyncObserver<StreamItem>, IStreaming_ConsumerGrain { private readonly IClusterClient client; private readonly ConsumerObserver _consumer; private string _providerToUse; private Streaming_ConsumerClientObject(ILogger logger, IClusterClient client) { this.client = client; _consumer = ConsumerObserver.NewObserver(logger); } public static Streaming_ConsumerClientObject NewObserver(ILogger logger, IClusterClient client) { return new Streaming_ConsumerClientObject(logger, client); } public Task OnNextAsync(StreamItem item, StreamSequenceToken token = null) { return _consumer.OnNextAsync(item, token); } public Task OnCompletedAsync() { return _consumer.OnCompletedAsync(); } public Task OnErrorAsync(Exception ex) { return _consumer.OnErrorAsync(ex); } public Task BecomeConsumer(Guid streamId, string providerToUse) { _providerToUse = providerToUse; return _consumer.BecomeConsumer(streamId, this.client.GetStreamProvider(providerToUse), null); } public Task BecomeConsumer(Guid streamId, string providerToUse, string streamNamespace) { _providerToUse = providerToUse; return _consumer.BecomeConsumer(streamId, this.client.GetStreamProvider(providerToUse), streamNamespace); } public Task StopBeingConsumer() { return _consumer.StopBeingConsumer(this.client.GetStreamProvider(_providerToUse)); } public Task<int> GetConsumerCount() { return _consumer.ConsumerCount; } public Task<int> GetItemsConsumed() { return _consumer.ItemsConsumed; } public Task DeactivateConsumerOnIdle() { return Task.CompletedTask; } } public class Streaming_ProducerClientObject : IStreaming_ProducerGrain { private readonly ProducerObserver producer; private readonly IClusterClient client; private Streaming_ProducerClientObject(ILogger logger, IClusterClient client) { this.client = client; this.producer = ProducerObserver.NewObserver(logger, client); } public static Streaming_ProducerClientObject NewObserver(ILogger logger, IClusterClient client) { if (null == logger) throw new ArgumentNullException("logger"); return new Streaming_ProducerClientObject(logger, client); } public Task BecomeProducer(Guid streamId, string providerToUse, string streamNamespace) { this.producer.BecomeProducer(streamId, this.client.GetStreamProvider(providerToUse), streamNamespace); return Task.CompletedTask; } public Task ProduceSequentialSeries(int count) { return this.producer.ProduceSequentialSeries(count); } public Task ProduceParallelSeries(int count) { return this.producer.ProduceParallelSeries(count); } public Task<int> GetItemsProduced() { return this.producer.ItemsProduced; } public Task ProducePeriodicSeries(int count) { return this.producer.ProducePeriodicSeries(timerCallback => { return new AsyncTaskSafeTimer(NullLogger.Instance, timerCallback, null, TimeSpan.Zero, TimeSpan.FromMilliseconds(10)); }, count); } public Task<Guid> GetStreamId() { return this.producer.StreamId; } public Task<string> GetProviderName() { return Task.FromResult(this.producer.ProviderName); } public Task AddNewConsumerGrain(Guid consumerGrainId) { return this.producer.AddNewConsumerGrain(consumerGrainId); } public Task<int> GetExpectedItemsProduced() { return this.producer.ExpectedItemsProduced; } public Task<int> GetProducerCount() { return this.producer.ProducerCount; } public Task StopBeingProducer() { return this.producer.StopBeingProducer(); } public Task VerifyFinished() { return this.producer.VerifyFinished(); } public Task DeactivateProducerOnIdle() { return Task.CompletedTask; } } internal class ConsumerProxy { private readonly IStreaming_ConsumerGrain[] _targets; private readonly ILogger _logger; private readonly IInternalGrainFactory grainFactory; private ConsumerProxy(IStreaming_ConsumerGrain[] targets, ILogger logger, IInternalGrainFactory grainFactory) { _targets = targets; _logger = logger; this.grainFactory = grainFactory; } private static async Task<ConsumerProxy> NewConsumerProxy(Guid streamId, string streamProvider, IStreaming_ConsumerGrain[] targets, ILogger logger, IInternalGrainFactory grainFactory) { if (targets == null) throw new ArgumentNullException("targets"); if (targets.Length == 0) throw new ArgumentException("caller must specify at least one target"); if (String.IsNullOrWhiteSpace(streamProvider)) throw new ArgumentException("Stream provider name is either null or whitespace", "streamProvider"); if (logger == null) throw new ArgumentNullException("logger"); ConsumerProxy newObj = new ConsumerProxy(targets, logger, grainFactory); await newObj.BecomeConsumer(streamId, streamProvider); return newObj; } public static Task<ConsumerProxy> NewConsumerGrainsAsync(Guid streamId, string streamProvider, ILogger logger, IInternalGrainFactory grainFactory, Guid[] grainIds = null, int grainCount = 1) { grainCount = grainIds != null ? grainIds.Length : grainCount; if (grainCount < 1) throw new ArgumentOutOfRangeException("grainCount", "The grain count must be at least one"); logger.Info("ConsumerProxy.NewConsumerGrainsAsync: multiplexing {0} consumer grains for stream {1}.", grainCount, streamId); var grains = new IStreaming_ConsumerGrain[grainCount]; var dedup = new Dictionary<Guid, IStreaming_ConsumerGrain>(); var grainFullName = typeof(Streaming_ConsumerGrain).FullName; for (var i = 0; i < grainCount; ++i) { if (grainIds != null) { // we deduplicate the grain references to ensure that IEnumerable.Distinct() works as intended. if (dedup.ContainsKey(grainIds[i])) grains[i] = dedup[grainIds[i]]; else { var gref = grainFactory.GetGrain<IStreaming_ConsumerGrain>(grainIds[i], grainFullName); grains[i] = gref; dedup[grainIds[i]] = gref; } } else { grains[i] = grainFactory.GetGrain<IStreaming_ConsumerGrain>(Guid.NewGuid(), grainFullName); } } return NewConsumerProxy(streamId, streamProvider, grains, logger, grainFactory); } public static Task<ConsumerProxy> NewProducerConsumerGrainsAsync(Guid streamId, string streamProvider, ILogger logger, int[] grainIds, bool useReentrantGrain, IInternalGrainFactory grainFactory) { int grainCount = grainIds.Length; if (grainCount < 1) throw new ArgumentOutOfRangeException("grainIds", "The grain count must be at least one"); logger.Info("ConsumerProxy.NewProducerConsumerGrainsAsync: multiplexing {0} consumer grains for stream {1}.", grainCount, streamId); var grains = new IStreaming_ConsumerGrain[grainCount]; var dedup = new Dictionary<int, IStreaming_ConsumerGrain>(); for (var i = 0; i < grainCount; ++i) { // we deduplicate the grain references to ensure that IEnumerable.Distinct() works as intended. if (dedup.ContainsKey(grainIds[i])) grains[i] = dedup[grainIds[i]]; else { if (useReentrantGrain) { grains[i] = grainFactory.GetGrain<IStreaming_Reentrant_ProducerConsumerGrain>(grainIds[i]); } else { var grainFullName = typeof(Streaming_ProducerConsumerGrain).FullName; grains[i] = grainFactory.GetGrain<IStreaming_ProducerConsumerGrain>(grainIds[i], grainFullName); } dedup[grainIds[i]] = grains[i]; } } return NewConsumerProxy(streamId, streamProvider, grains, logger, grainFactory); } public static Task<ConsumerProxy> NewConsumerClientObjectsAsync(Guid streamId, string streamProvider, ILogger logger, IInternalClusterClient client, int consumerCount = 1) { if (consumerCount < 1) throw new ArgumentOutOfRangeException("consumerCount", "argument must be 1 or greater"); logger.Info("ConsumerProxy.NewConsumerClientObjectsAsync: multiplexing {0} consumer client objects for stream {1}.", consumerCount, streamId); var objs = new IStreaming_ConsumerGrain[consumerCount]; for (var i = 0; i < consumerCount; ++i) objs[i] = Streaming_ConsumerClientObject.NewObserver(logger, client); return NewConsumerProxy(streamId, streamProvider, objs, logger, client); } public static ConsumerProxy NewConsumerGrainAsync_WithoutBecomeConsumer(Guid consumerGrainId, ILogger logger, IInternalGrainFactory grainFactory, string grainClassName = "") { if (logger == null) throw new ArgumentNullException("logger"); if (string.IsNullOrEmpty(grainClassName)) { grainClassName = typeof(Streaming_ConsumerGrain).FullName; } var grains = new IStreaming_ConsumerGrain[1]; grains[0] = grainFactory.GetGrain<IStreaming_ConsumerGrain>(consumerGrainId, grainClassName); ConsumerProxy newObj = new ConsumerProxy(grains, logger, grainFactory); return newObj; } private async Task BecomeConsumer(Guid streamId, string providerToUse) { List<Task> tasks = new List<Task>(); foreach (var target in _targets) { Task t = target.BecomeConsumer(streamId, providerToUse, null); // Consider: remove this await, let the calls go in parallel. // Have to do it for now to prevent multithreaded scheduler bug from happening. // await t; tasks.Add(t); } await Task.WhenAll(tasks); } private async Task<int> GetItemsConsumed() { var tasks = _targets.Distinct().Select(t => t.GetItemsConsumed()).ToArray(); await Task.WhenAll(tasks); return tasks.Sum(t => t.Result); } public Task<int> ItemsConsumed { get { return GetItemsConsumed(); } } private async Task<int> GetConsumerCount() { var tasks = _targets.Distinct().Select(p => p.GetConsumerCount()).ToArray(); await Task.WhenAll(tasks); return tasks.Sum(t => t.Result); } public Task<int> ConsumerCount { get { return GetConsumerCount(); } } public Task StopBeingConsumer() { var tasks = _targets.Distinct().Select(c => c.StopBeingConsumer()).ToArray(); return Task.WhenAll(tasks); } public async Task DeactivateOnIdle() { var tasks = _targets.Distinct().Select(t => t.DeactivateConsumerOnIdle()).ToArray(); await Task.WhenAll(tasks); } public Task<int> GetNumActivations(IInternalGrainFactory grainFactory) { return GetNumActivations(_targets.Distinct(), grainFactory); } public static async Task<int> GetNumActivations(IEnumerable<IGrain> targets, IInternalGrainFactory grainFactory) { var grainIds = targets.Distinct().Where(t => t is GrainReference).Select(t => ((GrainReference)t).GrainId).ToArray(); IManagementGrain systemManagement = grainFactory.GetGrain<IManagementGrain>(0); var tasks = grainIds.Select(g => systemManagement.GetGrainActivationCount((GrainReference)grainFactory.GetGrain(g))).ToArray(); await Task.WhenAll(tasks); return tasks.Sum(t => t.Result); } } internal class ProducerProxy { private readonly IStreaming_ProducerGrain[] _targets; private readonly ILogger _logger; private readonly Guid _streamId; private readonly string _providerName; private readonly InterlockedFlag _cleanedUpFlag; public Task<int> ExpectedItemsProduced { get { return GetExpectedItemsProduced(); } } public string ProviderName { get { return _providerName; } } public Guid StreamId { get { return _streamId; } } private ProducerProxy(IStreaming_ProducerGrain[] targets, Guid streamId, string providerName, ILogger logger) { _targets = targets; _logger = logger; _streamId = streamId; _providerName = providerName; _cleanedUpFlag = new InterlockedFlag(); } private static async Task<ProducerProxy> NewProducerProxy(IStreaming_ProducerGrain[] targets, Guid streamId, string streamProvider, string streamNamespace, ILogger logger) { if (targets == null) throw new ArgumentNullException("targets"); if (String.IsNullOrWhiteSpace(streamProvider)) throw new ArgumentException("Stream provider name is either null or whitespace", "streamProvider"); if (logger == null) throw new ArgumentNullException("logger"); ProducerProxy newObj = new ProducerProxy(targets, streamId, streamProvider, logger); await newObj.BecomeProducer(streamId, streamProvider, streamNamespace); return newObj; } public static Task<ProducerProxy> NewProducerGrainsAsync(Guid streamId, string streamProvider, string streamNamespace, ILogger logger, IInternalGrainFactory grainFactory, Guid[] grainIds = null, int grainCount = 1) { grainCount = grainIds != null ? grainIds.Length : grainCount; if (grainCount < 1) throw new ArgumentOutOfRangeException("grainCount", "The grain count must be at least one"); logger.Info("ProducerProxy.NewProducerGrainsAsync: multiplexing {0} producer grains for stream {1}.", grainCount, streamId); var grains = new IStreaming_ProducerGrain[grainCount]; var dedup = new Dictionary<Guid, IStreaming_ProducerGrain>(); var producerGrainFullName = typeof(Streaming_ProducerGrain).FullName; for (var i = 0; i < grainCount; ++i) { if (grainIds != null) { // we deduplicate the grain references to ensure that IEnumerable.Distinct() works as intended. if (dedup.ContainsKey(grainIds[i])) grains[i] = dedup[grainIds[i]]; else { var gref = grainFactory.GetGrain<IStreaming_ProducerGrain>(grainIds[i], producerGrainFullName); grains[i] = gref; dedup[grainIds[i]] = gref; } } else { grains[i] = grainFactory.GetGrain<IStreaming_ProducerGrain>(Guid.NewGuid(), producerGrainFullName); } } return NewProducerProxy(grains, streamId, streamProvider, streamNamespace, logger); } public static Task<ProducerProxy> NewProducerConsumerGrainsAsync(Guid streamId, string streamProvider, ILogger logger, int[] grainIds, bool useReentrantGrain, IInternalGrainFactory grainFactory) { int grainCount = grainIds.Length; if (grainCount < 1) throw new ArgumentOutOfRangeException("grainIds", "The grain count must be at least one"); logger.Info("ConsumerProxy.NewProducerConsumerGrainsAsync: multiplexing {0} producer grains for stream {1}.", grainCount, streamId); var grains = new IStreaming_ProducerGrain[grainCount]; var dedup = new Dictionary<int, IStreaming_ProducerGrain>(); for (var i = 0; i < grainCount; ++i) { // we deduplicate the grain references to ensure that IEnumerable.Distinct() works as intended. if (dedup.ContainsKey(grainIds[i])) grains[i] = dedup[grainIds[i]]; else { if (useReentrantGrain) { grains[i] = grainFactory.GetGrain<IStreaming_Reentrant_ProducerConsumerGrain>(grainIds[i]); } else { var grainFullName = typeof(Streaming_ProducerConsumerGrain).FullName; grains[i] = grainFactory.GetGrain<IStreaming_ProducerConsumerGrain>(grainIds[i], grainFullName); } dedup[grainIds[i]] = grains[i]; } } return NewProducerProxy(grains, streamId, streamProvider, null, logger); } public static Task<ProducerProxy> NewProducerClientObjectsAsync(Guid streamId, string streamProvider, string streamNamespace, ILogger logger, IClusterClient client, int producersCount = 1) { if (producersCount < 1) throw new ArgumentOutOfRangeException("producersCount", "The producer count must be at least one"); var producers = new IStreaming_ProducerGrain[producersCount]; for (var i = 0; i < producersCount; ++i) producers[i] = Streaming_ProducerClientObject.NewObserver(logger, client); logger.Info("ProducerProxy.NewProducerClientObjectsAsync: multiplexing {0} producer client objects for stream {1}.", producersCount, streamId); return NewProducerProxy(producers, streamId, streamProvider, streamNamespace, logger); } private Task BecomeProducer(Guid streamId, string providerToUse, string streamNamespace) { _cleanedUpFlag.ThrowNotInitializedIfSet(); return Task.WhenAll(_targets.Select( target => target.BecomeProducer(streamId, providerToUse, streamNamespace)).ToArray()); } public async Task ProduceSequentialSeries(int count) { _cleanedUpFlag.ThrowNotInitializedIfSet(); foreach (var t in _targets.Distinct()) await t.ProduceSequentialSeries(count); } public Task ProduceParallelSeries(int count) { _cleanedUpFlag.ThrowNotInitializedIfSet(); return Task.WhenAll(_targets.Distinct().Select(t => t.ProduceParallelSeries(count)).ToArray()); } public Task ProducePeriodicSeries(int count) { _cleanedUpFlag.ThrowNotInitializedIfSet(); return Task.WhenAll(_targets.Distinct().Select(t => t.ProducePeriodicSeries(count)).ToArray()); } public async Task<Guid> AddNewConsumerGrain() { _cleanedUpFlag.ThrowNotInitializedIfSet(); if (_targets.Length != 1) throw new InvalidOperationException("This method is only supported for singular producer cases"); // disabled temporarily. // return _targets[0].AddNewConsumerGrain(); Guid consumerGrainId = Guid.NewGuid(); await _targets[0].AddNewConsumerGrain(consumerGrainId); return consumerGrainId; } private async Task<int> GetExpectedItemsProduced() { _cleanedUpFlag.ThrowNotInitializedIfSet(); var tasks = _targets.Distinct().Select(t => t.GetExpectedItemsProduced()).ToArray(); await Task.WhenAll(tasks); return tasks.Sum(t => t.Result); } private async Task<int> GetProducerCount() { var tasks = _targets.Distinct().Select(p => p.GetProducerCount()).ToArray(); await Task.WhenAll(tasks); return tasks.Sum(t => t.Result); } public Task<int> ProducerCount { get { // This method is used by the test code to verify that the object has in fact been disposed properly, // so we choose not to throw if the object has already been disposed. return GetProducerCount(); } } public async Task StopBeingProducer() { if (!_cleanedUpFlag.TrySet()) return; var tasks = new List<Task>(); foreach (var i in _targets.Distinct()) { tasks.Add(i.StopBeingProducer()); } await Task.WhenAll(tasks); tasks = new List<Task>(); foreach (var i in _targets.Distinct()) { tasks.Add(i.VerifyFinished()); } await Task.WhenAll(tasks); } public Task DeactivateOnIdle() { var tasks = _targets.Distinct().Select(t => t.DeactivateProducerOnIdle()).ToArray(); return Task.WhenAll(tasks); } public Task<int> GetNumActivations(IInternalGrainFactory grainFactory) { return ConsumerProxy.GetNumActivations(_targets.Distinct(), grainFactory); } } }
/* * 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 QuantConnect.Data; using QuantConnect.Data.Auxiliary; using QuantConnect.Data.Market; using QuantConnect.Securities; using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Lean.Engine.DataFeeds.Enumerators; using QuantConnect.Logging; namespace QuantConnect.ToolBox.RandomDataGenerator { /// <summary> /// Generates random data according to the specified parameters /// </summary> public class RandomDataGenerator { private RandomDataGeneratorSettings _settings; private SecurityManager _securityManager; /// <summary> /// Initializes <see cref="RandomDataGenerator"/> instance fields /// </summary> /// <param name="settings">random data generation settings</param> /// <param name="securityManager">security management</param> public void Init(RandomDataGeneratorSettings settings, SecurityManager securityManager) { _settings = settings; _securityManager = securityManager; } /// <summary> /// Starts data generation /// </summary> public void Run() { var tickTypesPerSecurityType = SubscriptionManager.DefaultDataTypes(); // can specify a seed value in this ctor if determinism is desired var random = new Random(); var randomValueGenerator = new RandomValueGenerator(); if (_settings.RandomSeedSet) { random = new Random(_settings.RandomSeed); randomValueGenerator = new RandomValueGenerator(_settings.RandomSeed); } var symbolGenerator = BaseSymbolGenerator.Create(_settings, randomValueGenerator); var maxSymbolCount = symbolGenerator.GetAvailableSymbolCount(); if (_settings.SymbolCount > maxSymbolCount) { Log.Error($"RandomDataGenerator.Run(): Limiting Symbol count to {maxSymbolCount}, we don't have more {_settings.SecurityType} tickers for {_settings.Market}"); _settings.SymbolCount = maxSymbolCount; } Log.Trace($"RandomDataGenerator.Run(): Begin data generation of {_settings.SymbolCount} randomly generated {_settings.SecurityType} assets..."); // iterate over our randomly generated symbols var count = 0; var progress = 0d; var previousMonth = -1; foreach (var (symbolRef, currentSymbolGroup) in symbolGenerator.GenerateRandomSymbols() .GroupBy(s => s.HasUnderlying ? s.Underlying : s) .Select(g => (g.Key, g.OrderBy(s => s.HasUnderlying).ToList()))) { Log.Trace($"RandomDataGenerator.Run(): Symbol[{++count}]: {symbolRef} Progress: {progress:0.0}% - Generating data..."); var tickGenerators = new List<IEnumerator<Tick>>(); var tickHistories = new Dictionary<Symbol, List<Tick>>(); Security underlyingSecurity = null; foreach (var currentSymbol in currentSymbolGroup) { if (!_securityManager.TryGetValue(currentSymbol, out var security)) { security = _securityManager.CreateSecurity( currentSymbol, new List<SubscriptionDataConfig>(), underlying: underlyingSecurity); _securityManager.Add(security); } underlyingSecurity ??= security; tickGenerators.Add( new TickGenerator(_settings, tickTypesPerSecurityType[currentSymbol.SecurityType].ToArray(), security, randomValueGenerator) .GenerateTicks() .GetEnumerator()); tickHistories.Add( currentSymbol, new List<Tick>()); } using var sync = new SynchronizingEnumerator(tickGenerators); while (sync.MoveNext()) { var dataPoint = sync.Current; if (!_securityManager.TryGetValue(dataPoint.Symbol, out var security)) { Log.Error($"RandomDataGenerator.Run(): Could not find security for symbol {sync.Current.Symbol}"); continue; } tickHistories[security.Symbol].Add(dataPoint as Tick); security.Update(new List<BaseData> { dataPoint }, dataPoint.GetType(), false); } foreach (var (currentSymbol, tickHistory) in tickHistories) { var symbol = currentSymbol; // This is done so that we can update the Symbol in the case of a rename event var delistDate = GetDelistingDate(_settings.Start, _settings.End, randomValueGenerator); var willBeDelisted = randomValueGenerator.NextBool(1.0); // Companies rarely IPO then disappear within 6 months if (willBeDelisted && tickHistory.Select(tick => tick.Time.Month).Distinct().Count() <= 6) { willBeDelisted = false; } var dividendsSplitsMaps = new DividendSplitMapGenerator( symbol, _settings, randomValueGenerator, symbolGenerator, random, delistDate, willBeDelisted); // Keep track of renamed symbols and the time they were renamed. var renamedSymbols = new Dictionary<Symbol, DateTime>(); if (_settings.SecurityType == SecurityType.Equity) { dividendsSplitsMaps.GenerateSplitsDividends(tickHistory); if (!willBeDelisted) { dividendsSplitsMaps.DividendsSplits.Add(new CorporateFactorRow(new DateTime(2050, 12, 31), 1m, 1m)); if (dividendsSplitsMaps.MapRows.Count > 1) { // Remove the last element if we're going to have a 20501231 entry dividendsSplitsMaps.MapRows.RemoveAt(dividendsSplitsMaps.MapRows.Count - 1); } dividendsSplitsMaps.MapRows.Add(new MapFileRow(new DateTime(2050, 12, 31), dividendsSplitsMaps.CurrentSymbol.Value)); } // If the Symbol value has changed, update the current Symbol if (symbol != dividendsSplitsMaps.CurrentSymbol) { // Add all Symbol rename events to dictionary // We skip the first row as it contains the listing event instead of a rename event foreach (var renameEvent in dividendsSplitsMaps.MapRows.Skip(1)) { // Symbol.UpdateMappedSymbol does not update the underlying security ID Symbol, which // is used to create the hash code. Create a new equity Symbol from scratch instead. symbol = Symbol.Create(renameEvent.MappedSymbol, SecurityType.Equity, _settings.Market); renamedSymbols.Add(symbol, renameEvent.Date); Log.Trace($"RandomDataGenerator.Run(): Symbol[{count}]: {symbol} will be renamed on {renameEvent.Date}"); } } else { // This ensures that ticks will be written for the current Symbol up until 9999-12-31 renamedSymbols.Add(symbol, new DateTime(9999, 12, 31)); } symbol = dividendsSplitsMaps.CurrentSymbol; // Write Splits and Dividend events to directory factor_files var factorFile = new CorporateFactorProvider(symbol.Value, dividendsSplitsMaps.DividendsSplits, _settings.Start); var mapFile = new MapFile(symbol.Value, dividendsSplitsMaps.MapRows); factorFile.WriteToFile(symbol); mapFile.WriteToCsv(_settings.Market, symbol.SecurityType); Log.Trace($"RandomDataGenerator.Run(): Symbol[{count}]: {symbol} Dividends, splits, and map files have been written to disk."); } else { // This ensures that ticks will be written for the current Symbol up until 9999-12-31 renamedSymbols.Add(symbol, new DateTime(9999, 12, 31)); } // define aggregators via settings var aggregators = CreateAggregators(_settings, tickTypesPerSecurityType[currentSymbol.SecurityType].ToArray()).ToList(); Symbol previousSymbol = null; var currentCount = 0; var monthsTrading = 0; foreach (var renamed in renamedSymbols) { var previousRenameDate = previousSymbol == null ? new DateTime(1, 1, 1) : renamedSymbols[previousSymbol]; var previousRenameDateDay = new DateTime(previousRenameDate.Year, previousRenameDate.Month, previousRenameDate.Day); var renameDate = renamed.Value; var renameDateDay = new DateTime(renameDate.Year, renameDate.Month, renameDate.Day); foreach (var tick in tickHistory.Where(tick => tick.Time >= previousRenameDate && previousRenameDateDay != TickDay(tick))) { // Prevents the aggregator from being updated with ticks after the rename event if (TickDay(tick) > renameDateDay) { break; } if (tick.Time.Month != previousMonth) { Log.Trace($"RandomDataGenerator.Run(): Symbol[{count}]: Month: {tick.Time:MMMM}"); previousMonth = tick.Time.Month; monthsTrading++; } foreach (var item in aggregators) { tick.Value = tick.Value / dividendsSplitsMaps.FinalSplitFactor; item.Consolidator.Update(tick); } if (monthsTrading >= 6 && willBeDelisted && tick.Time > delistDate) { Log.Trace($"RandomDataGenerator.Run(): Symbol[{count}]: {renamed.Key} delisted at {tick.Time:MMMM yyyy}"); break; } } // count each stage as a point, so total points is 2*Symbol-count // and the current progress is twice the current, but less one because we haven't finished writing data yet progress = 100 * (2 * count - 1) / (2.0 * _settings.SymbolCount); Log.Trace($"RandomDataGenerator.Run(): Symbol[{count}]: {renamed.Key} Progress: {progress:0.0}% - Saving data in LEAN format"); // persist consolidated data to disk foreach (var item in aggregators) { var writer = new LeanDataWriter(item.Resolution, renamed.Key, Globals.DataFolder, item.TickType); // send the flushed data into the writer. pulling the flushed list is very important, // lest we likely wouldn't get the last piece of data stuck in the consolidator // Filter out the data we're going to write here because filtering them in the consolidator update phase // makes it write all dates for some unknown reason writer.Write(item.Flush().Where(data => data.Time > previousRenameDate && previousRenameDateDay != DataDay(data))); } // update progress progress = 100 * (2 * count) / (2.0 * _settings.SymbolCount); Log.Trace($"RandomDataGenerator.Run(): Symbol[{count}]: {symbol} Progress: {progress:0.0}% - Symbol data generation and output completed"); previousSymbol = renamed.Key; currentCount++; } } } Log.Trace("RandomDataGenerator.Run(): Random data generation has completed."); DateTime TickDay(Tick tick) => new(tick.Time.Year, tick.Time.Month, tick.Time.Day); DateTime DataDay(BaseData data) => new(data.Time.Year, data.Time.Month, data.Time.Day); } public static DateTime GetDateMidpoint(DateTime start, DateTime end) { TimeSpan span = end.Subtract(start); int span_time = (int)span.TotalMinutes; double diff_span = -(span_time / 2.0); DateTime start_time = end.AddMinutes(Math.Round(diff_span, 2, MidpointRounding.ToEven)); //Returns a DateTime object that is halfway between start and end return start_time; } public static DateTime GetDelistingDate(DateTime start, DateTime end, RandomValueGenerator randomValueGenerator) { var mid_point = GetDateMidpoint(start, end); var delist_Date = randomValueGenerator.NextDate(mid_point, end, null); //Returns a DateTime object that is a random value between the mid_point and end return delist_Date; } public static IEnumerable<TickAggregator> CreateAggregators(RandomDataGeneratorSettings settings, TickType[] tickTypes) { // create default aggregators for tick type/resolution foreach (var tickAggregator in TickAggregator.ForTickTypes(settings.Resolution, tickTypes)) { yield return tickAggregator; } // ensure we have a daily consolidator when coarse is enabled if (settings.IncludeCoarse && settings.Resolution != Resolution.Daily) { // prefer trades for coarse - in practice equity only does trades, but leaving this as configurable if (tickTypes.Contains(TickType.Trade)) { yield return TickAggregator.ForTickTypes(Resolution.Daily, TickType.Trade).Single(); } else { yield return TickAggregator.ForTickTypes(Resolution.Daily, TickType.Quote).Single(); } } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace NoCode.FBDCore { [Serializable] public class FBD { private int _ID; private int _code; private List<FBDPara> _inputParaList = new List<FBDPara>(); private List<FBDPara> _outputParaList = new List<FBDPara>(); private FBDPara _headPara; private string _name; private TreeGroupItem _group; private string _illustration; private Size _size; private Point _location; private bool _selected; private bool inCompile; private Color _FBDColor; private int _order; public int ID { get { return this._ID; } set { this._ID = value; } } public int Code { get { return this._code; } set { this._code = value; } } public List<FBDPara> InputParaList { get { return this._inputParaList; } set { this._inputParaList = value; } } public List<FBDPara> OutputParaList { get { return this._outputParaList; } set { this._outputParaList = value; } } public FBDPara HeadPara { get { return this._headPara; } set { this._headPara = value; } } public string Name { get { return this._name; } set { this._name = value; } } public TreeGroupItem Group { get { return this._group; } set { this._group = value; } } public string Illustration { get { return this._illustration; } set { this._illustration = value; } } public Size Size { get { return this._size; } set { this._size = value; } } public Point Location { get { return this._location; } set { this._location = value; } } public bool Selected { get { return this._selected; } set { this._selected = value; } } public Color FBDColor { get { return this._FBDColor; } set { this._FBDColor = value; } } public int Order { get { return this._order; } set { this._order = value; } } public FBD Clone() { FBD result; using (MemoryStream memoryStream = new MemoryStream()) { BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(memoryStream, this); using (MemoryStream memoryStream2 = new MemoryStream(memoryStream.ToArray())) { FBD fBD = (FBD)binaryFormatter.Deserialize(memoryStream2); result = fBD; } } return result; } public Image DrawMe() { Bitmap bitmap = new Bitmap(100 * this._size.Width + 1, 20 * this._size.Height + 1); Graphics graphics = Graphics.FromImage(bitmap); Rectangle rect = new Rectangle(100 * ((this.InputParaList.Count == 0) ? 0 : 1), 20 * ((this.HeadPara == null) ? 0 : 1), (this._size.Width - ((this.InputParaList.Count == 0) ? 0 : 1) - ((this.OutputParaList.Count == 0) ? 0 : 1)) * 100, (this._size.Height - ((this.HeadPara == null) ? 0 : 1)) * 20); LinearGradientBrush brush = new LinearGradientBrush(rect, Color.White, this._FBDColor, 75f); graphics.FillRectangle(brush, rect); Pen pen; if (this._selected) { pen = new Pen(Color.Red, 2f); } else { pen = new Pen(Color.Black, 0f); } graphics.DrawRectangle(pen, rect); SizeF sizeF = graphics.MeasureString(this._name + ":" + this._order.ToString(), SystemFonts.DefaultFont); graphics.DrawString(this._name + ":" + this._order.ToString(), SystemFonts.DefaultFont, Brushes.Black, (float)(rect.X + rect.Width / 2) - sizeF.Width / 2f, (float)(rect.Y + 10) - sizeF.Height / 2f); if (this._headPara != null) { Image image = this._headPara.DrawMe(); graphics.DrawImage(image, rect.X + rect.Width / 2 - image.Width / 2, rect.Y - 10 - image.Height / 2); } foreach (FBDPara current in this.InputParaList) { graphics.DrawImage(current.DrawMe(), 0, 20 * current.Index); } foreach (FBDPara current2 in this.OutputParaList) { graphics.DrawImage(current2.DrawMe(), rect.X + rect.Width - 100, 20 * current2.Index); } return bitmap; } public FBDHitTestResultEnum HitTest(Point p) { Rectangle rect = new Rectangle(100 * ((this.InputParaList.Count == 0) ? 0 : 1), 20 * ((this.HeadPara == null) ? 0 : 1), (this._size.Width - ((this.InputParaList.Count == 0) ? 0 : 1) - ((this.OutputParaList.Count == 0) ? 0 : 1)) * 100, (this._size.Height - ((this.HeadPara == null) ? 0 : 1)) * 20); Region region = new Region(rect); if (region.IsVisible(p)) { return FBDHitTestResultEnum.FBD; } return FBDHitTestResultEnum.None; } public void SortOrder(List<FBD> sortedFBDList) { if (this.inCompile || sortedFBDList.Contains(this)) { return; } this.inCompile = true; foreach (FBDPara current in this.InputParaList) { if (current.LineFromPara != null) { current.LineFromPara.Owner.SortOrder(sortedFBDList); } } sortedFBDList.Add(this); this.inCompile = false; } public bool Check() { bool result = true; foreach (FBDPara current in this.InputParaList) { if (!current.Check()) { result = false; } } foreach (FBDPara current2 in this.OutputParaList) { if (!current2.Check()) { result = false; } } if (this._headPara != null && !this._headPara.Check()) { result = false; } return result; } public void Compile() { } } }
using System; using System.Collections; using System.Text; using System.Collections.Generic; /* Based on the JSON parser from * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html * * I simplified it so that it doesn't throw exceptions * and can be used in Unity iPhone with maximum code stripping. */ /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable. /// All numbers are parsed to doubles. /// </summary> public class MiniJSON { private const int TOKEN_NONE = 0; private const int TOKEN_CURLY_OPEN = 1; private const int TOKEN_CURLY_CLOSE = 2; private const int TOKEN_SQUARED_OPEN = 3; private const int TOKEN_SQUARED_CLOSE = 4; private const int TOKEN_COLON = 5; private const int TOKEN_COMMA = 6; private const int TOKEN_STRING = 7; private const int TOKEN_NUMBER = 8; private const int TOKEN_TRUE = 9; private const int TOKEN_FALSE = 10; private const int TOKEN_NULL = 11; private const int BUILDER_CAPACITY = 2000; /// <summary> /// On decoding, this value holds the position at which the parse failed (-1 = no error). /// </summary> protected static int lastErrorIndex = -1; protected static string lastDecode = ""; public static bool isReadable = true; protected static int depth = 0; /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns> public static object jsonDecode( string json ) { // save the string for debug information MiniJSON.lastDecode = json; MiniJSON.depth = 0; if( json != null ) { char[] charArray = json.ToCharArray(); int index = 0; bool success = true; object value = MiniJSON.parseValue( charArray, ref index, ref success ); if( success ) MiniJSON.lastErrorIndex = -1; else MiniJSON.lastErrorIndex = index; return value; } else { return null; } } /// <summary> /// Converts a Hashtable / ArrayList / Dictionary(string,string) object into a JSON string /// </summary> /// <param name="json">A Hashtable / ArrayList</param> /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns> public static string jsonEncode( object json ) { var builder = new StringBuilder( BUILDER_CAPACITY ); var success = MiniJSON.serializeValue( json, builder ); return ( success ? builder.ToString() : null ); } /// <summary> /// On decoding, this function returns the position at which the parse failed (-1 = no error). /// </summary> /// <returns></returns> public static bool lastDecodeSuccessful() { return ( MiniJSON.lastErrorIndex == -1 ); } /// <summary> /// On decoding, this function returns the position at which the parse failed (-1 = no error). /// </summary> /// <returns></returns> public static int getLastErrorIndex() { return MiniJSON.lastErrorIndex; } /// <summary> /// If a decoding error occurred, this function returns a piece of the JSON string /// at which the error took place. To ease debugging. /// </summary> /// <returns></returns> public static string getLastErrorSnippet() { if( MiniJSON.lastErrorIndex == -1 ) { return ""; } else { int startIndex = MiniJSON.lastErrorIndex - 5; int endIndex = MiniJSON.lastErrorIndex + 15; if( startIndex < 0 ) startIndex = 0; if( endIndex >= MiniJSON.lastDecode.Length ) endIndex = MiniJSON.lastDecode.Length - 1; return MiniJSON.lastDecode.Substring( startIndex, endIndex - startIndex + 1 ); } } #region Parsing protected static Hashtable parseObject( char[] json, ref int index ) { Hashtable table = new Hashtable(); int token; // { nextToken( json, ref index ); bool done = false; while( !done ) { token = lookAhead( json, index ); if( token == MiniJSON.TOKEN_NONE ) { return null; } else if( token == MiniJSON.TOKEN_COMMA ) { nextToken( json, ref index ); } else if( token == MiniJSON.TOKEN_CURLY_CLOSE ) { nextToken( json, ref index ); return table; } else { // name string name = parseString( json, ref index ); if( name == null ) { return null; } // : token = nextToken( json, ref index ); if( token != MiniJSON.TOKEN_COLON ) return null; // value bool success = true; object value = parseValue( json, ref index, ref success ); if( !success ) return null; table[name] = value; } } return table; } protected static ArrayList parseArray( char[] json, ref int index ) { ArrayList array = new ArrayList(); // [ nextToken( json, ref index ); bool done = false; while( !done ) { int token = lookAhead( json, index ); if( token == MiniJSON.TOKEN_NONE ) { return null; } else if( token == MiniJSON.TOKEN_COMMA ) { nextToken( json, ref index ); } else if( token == MiniJSON.TOKEN_SQUARED_CLOSE ) { nextToken( json, ref index ); break; } else { bool success = true; object value = parseValue( json, ref index, ref success ); if( !success ) return null; array.Add( value ); } } return array; } protected static object parseValue( char[] json, ref int index, ref bool success ) { switch( lookAhead( json, index ) ) { case MiniJSON.TOKEN_STRING: return parseString( json, ref index ); case MiniJSON.TOKEN_NUMBER: return parseNumber( json, ref index ); case MiniJSON.TOKEN_CURLY_OPEN: return parseObject( json, ref index ); case MiniJSON.TOKEN_SQUARED_OPEN: return parseArray( json, ref index ); case MiniJSON.TOKEN_TRUE: nextToken( json, ref index ); return Boolean.Parse( "TRUE" ); case MiniJSON.TOKEN_FALSE: nextToken( json, ref index ); return Boolean.Parse( "FALSE" ); case MiniJSON.TOKEN_NULL: nextToken( json, ref index ); return null; case MiniJSON.TOKEN_NONE: break; } success = false; return null; } protected static string parseString( char[] json, ref int index ) { string s = ""; char c; eatWhitespace( json, ref index ); // " c = json[index++]; bool complete = false; while( !complete ) { if( index == json.Length ) break; c = json[index++]; if( c == '"' ) { complete = true; break; } else if( c == '\\' ) { if( index == json.Length ) break; c = json[index++]; if( c == '"' ) { s += '"'; } else if( c == '\\' ) { s += '\\'; } else if( c == '/' ) { s += '/'; } else if( c == 'b' ) { s += '\b'; } else if( c == 'f' ) { s += '\f'; } else if( c == 'n' ) { s += '\n'; } else if( c == 'r' ) { s += '\r'; } else if( c == 't' ) { s += '\t'; } else if( c == 'u' ) { int remainingLength = json.Length - index; if( remainingLength >= 4 ) { char[] unicodeCharArray = new char[4]; Array.Copy( json, index, unicodeCharArray, 0, 4 ); // Drop in the HTML markup for the unicode character s += "\\u" + new string( unicodeCharArray ) /*+ ";"*/; //uint codePoint = UInt32.Parse(new string(unicodeCharArray), NumberStyles.HexNumber); //// convert the integer codepoint to a unicode char and add to string //s += Char.ConvertFromUtf32((int)codePoint); // skip 4 chars index += 4; } else { break; } } } else { s += c; } } if( !complete ) return null; return s; } protected static double parseNumber( char[] json, ref int index ) { eatWhitespace( json, ref index ); int lastIndex = getLastIndexOfNumber( json, index ); int charLength = ( lastIndex - index ) + 1; char[] numberCharArray = new char[charLength]; Array.Copy( json, index, numberCharArray, 0, charLength ); index = lastIndex + 1; return Double.Parse( new string( numberCharArray ) ); // , CultureInfo.InvariantCulture); } protected static int getLastIndexOfNumber( char[] json, int index ) { int lastIndex; for( lastIndex = index; lastIndex < json.Length; lastIndex++ ) if( "0123456789+-.eE".IndexOf( json[lastIndex] ) == -1 ) { break; } return lastIndex - 1; } protected static void eatWhitespace( char[] json, ref int index ) { for( ; index < json.Length; index++ ) if( " \t\n\r".IndexOf( json[index] ) == -1 ) { break; } } protected static int lookAhead( char[] json, int index ) { int saveIndex = index; return nextToken( json, ref saveIndex ); } protected static int nextToken( char[] json, ref int index ) { eatWhitespace( json, ref index ); if( index == json.Length ) { return MiniJSON.TOKEN_NONE; } char c = json[index]; index++; switch( c ) { case '{': return MiniJSON.TOKEN_CURLY_OPEN; case '}': return MiniJSON.TOKEN_CURLY_CLOSE; case '[': return MiniJSON.TOKEN_SQUARED_OPEN; case ']': return MiniJSON.TOKEN_SQUARED_CLOSE; case ',': return MiniJSON.TOKEN_COMMA; case '"': return MiniJSON.TOKEN_STRING; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return MiniJSON.TOKEN_NUMBER; case ':': return MiniJSON.TOKEN_COLON; } index--; int remainingLength = json.Length - index; // false if( remainingLength >= 5 ) { if( json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e' ) { index += 5; return MiniJSON.TOKEN_FALSE; } } // true if( remainingLength >= 4 ) { if( json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e' ) { index += 4; return MiniJSON.TOKEN_TRUE; } } // null if( remainingLength >= 4 ) { if( json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l' ) { index += 4; return MiniJSON.TOKEN_NULL; } } return MiniJSON.TOKEN_NONE; } #endregion #region Serialization protected static bool serializeObjectOrArray( object objectOrArray, StringBuilder builder ) { if( objectOrArray is Hashtable ) { return serializeObject( (Hashtable)objectOrArray, builder ); } else if( objectOrArray is ArrayList ) { return serializeArray( (ArrayList)objectOrArray, builder ); } else { return false; } } protected static bool serializeObject( Hashtable anObject, StringBuilder builder ) { if (MiniJSON.isReadable) { builder.Append( "{\n" ); MiniJSON.depth++; } else { builder.Append( "{" ); } IDictionaryEnumerator e = anObject.GetEnumerator(); bool first = true; while( e.MoveNext() ) { string key = e.Key.ToString(); object value = e.Value; if( !first ) { if (MiniJSON.isReadable) { builder.Append( ",\n" ); } else { builder.Append( ", " ); } } if (MiniJSON.isReadable) { for (int d=0; d<MiniJSON.depth; d++) { builder.Append( "\t" ); } } serializeString( key, builder ); builder.Append( ":" ); if( !serializeValue( value, builder ) ) { return false; } first = false; } if (MiniJSON.isReadable) { builder.Append( "\n" ); MiniJSON.depth--; for (int d=0; d<MiniJSON.depth; d++) { builder.Append( "\t" ); } } builder.Append( "}" ); return true; } protected static bool serializeDictionary( Dictionary<string,string> dict, StringBuilder builder ) { if (MiniJSON.isReadable) { builder.Append( "{\n" ); MiniJSON.depth++; } else { builder.Append( "{" ); } bool first = true; foreach( var kv in dict ) { if( !first ) { if (MiniJSON.isReadable) { builder.Append( ",\n" ); } else { builder.Append( ", " ); } } if (MiniJSON.isReadable) { for (int d=0; d<MiniJSON.depth; d++) { builder.Append( "\t" ); } } serializeString( kv.Key, builder ); builder.Append( ":" ); serializeString( kv.Value, builder ); first = false; } if (MiniJSON.isReadable) { builder.Append( "\n" ); MiniJSON.depth--; for (int d=0; d<MiniJSON.depth; d++) { builder.Append( "\t" ); } } builder.Append( "}" ); return true; } protected static bool serializeArray( ArrayList anArray, StringBuilder builder ) { builder.Append( "[" ); bool first = true; for( int i = 0; i < anArray.Count; i++ ) { object value = anArray[i]; if( !first ) { if (MiniJSON.isReadable) { builder.Append( ",\n" ); } else { builder.Append( ", " ); } } if( !serializeValue( value, builder ) ) { return false; } first = false; } builder.Append( "]" ); return true; } protected static bool serializeValue( object value, StringBuilder builder ) { // Type t = value.GetType(); // Debug.Log("type: " + t.ToString() + " isArray: " + t.IsArray); if( value == null ) { builder.Append( "null" ); } else if( value.GetType().IsArray ) { serializeArray( new ArrayList( (ICollection)value ), builder ); } else if( value is string ) { serializeString( (string)value, builder ); } else if( value is Char ) { serializeString( Convert.ToString( (char)value ), builder ); } else if( value is Hashtable ) { serializeObject( (Hashtable)value, builder ); } else if( value is Dictionary<string,string> ) { serializeDictionary( (Dictionary<string,string>)value, builder ); } else if( value is ArrayList ) { serializeArray( (ArrayList)value, builder ); } else if( ( value is Boolean ) && ( (Boolean)value == true ) ) { builder.Append( "true" ); } else if( ( value is Boolean ) && ( (Boolean)value == false ) ) { builder.Append( "false" ); } else if( value.GetType().IsPrimitive ) { serializeNumber( Convert.ToDouble( value ), builder ); } else { return false; } return true; } protected static void serializeString( string aString, StringBuilder builder ) { builder.Append( "\"" ); char[] charArray = aString.ToCharArray(); for( int i = 0; i < charArray.Length; i++ ) { char c = charArray[i]; if( c == '"' ) { builder.Append( "\\\"" ); } else if( c == '\\' ) { builder.Append( "\\\\" ); } else if( c == '\b' ) { builder.Append( "\\b" ); } else if( c == '\f' ) { builder.Append( "\\f" ); } else if( c == '\n' ) { builder.Append( "\\n" ); } else if( c == '\r' ) { builder.Append( "\\r" ); } else if( c == '\t' ) { builder.Append( "\\t" ); } else { //int codepoint = Convert.ToInt32( c ); //if( ( codepoint >= 32 ) && ( codepoint <= 126 ) ) //{ // builder.Append( c ); //} //else //{ // builder.Append( "\\u" + Convert.ToString( codepoint, 16 ).PadLeft( 4, '0' ) ); //} builder.Append( c ); ///* //int codepoint = Convert.ToInt32( c ); //if( ( codepoint >= 32 ) && ( codepoint <= 126 ) ) //{ // builder.Append( c ); //} //else //{ // builder.Append( "\\u" + Convert.ToString( codepoint, 16 ).PadLeft( 4, '0' ) ); //} //*/ } } builder.Append( "\"" ); } protected static void serializeNumber( double number, StringBuilder builder ) { builder.Append( Convert.ToString( number ) ); // , CultureInfo.InvariantCulture)); } #endregion } #region Extension methods public static class MiniJsonExtensions { public static string toJson( this Hashtable obj ) { return MiniJSON.jsonEncode( obj ); } public static string toJson( this Dictionary<string,string> obj ) { return MiniJSON.jsonEncode( obj ); } public static ArrayList arrayListFromJson( this string json ) { return MiniJSON.jsonDecode( json ) as ArrayList; } public static Hashtable hashtableFromJson( this string json ) { return MiniJSON.jsonDecode( json ) as Hashtable; } } #endregion
// // Copyright (c) .NET Foundation and Contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // using CorDebugInterop; using Microsoft.VisualStudio.Debugger.Interop; using Microsoft.VisualStudio.OLE.Interop; using nanoFramework.Tools.Debugger; using System; using System.Collections; using System.Runtime.InteropServices; namespace nanoFramework.Tools.VisualStudio.Extension { public class DebugPort : IDebugPort2, IDebugPortEx2, IDebugPortNotify2, IConnectionPointContainer { private Guid _guid; private ArrayList _alProcesses; private string _name; private ConnectionPoint _cpDebugPortEvents2; //This can't be shared with other debugPorts, for remote attaching to multiple processes....??? protected uint _pidNext; public NanoDeviceBase Device { get; protected set; } public DebugPort(NanoDeviceBase device, DebugPortSupplier portSupplier) { _name = device.Description; DebugPortSupplier = portSupplier; Device = device; _cpDebugPortEvents2 = new ConnectionPoint(this, typeof(IDebugPortEvents2).GUID); _alProcesses = ArrayList.Synchronized(new ArrayList(1)); _pidNext = 1; _guid = Guid.NewGuid(); } public bool ContainsProcess(CorDebugProcess process) { return _alProcesses.Contains(process); } public void RefreshProcesses() { ArrayList processes = new ArrayList(_alProcesses.Count + NanoFrameworkPackage.NanoDeviceCommService.DebugClient.NanoFrameworkDevices.Count); foreach (NanoDeviceBase device in NanoFrameworkPackage.NanoDeviceCommService.DebugClient.NanoFrameworkDevices) { CorDebugProcess process = EnsureProcess(device); processes.Add(process); } for (int i = _alProcesses.Count - 1; i >= 0; i--) { CorDebugProcess process = (CorDebugProcess)_alProcesses[i]; if (!processes.Contains(process)) { RemoveProcess(process); } } } public DebugPortSupplier DebugPortSupplier { [System.Diagnostics.DebuggerHidden]get; protected set; } public void AddProcess(CorDebugProcess process) { if(!_alProcesses.Contains( process )) { _alProcesses.Add( process ); } } public CorDebugProcess EnsureProcess(NanoDeviceBase device) { CorDebugProcess process = ProcessFromPortDefinition(device); if (process == null) { process = new CorDebugProcess(this, device); uint pid = _pidNext++; process.SetPid(pid); AddProcess(process); } return process; } private void RemoveProcess(CorDebugProcess process) { ((ICorDebugProcess)process).Terminate(0); _alProcesses.Remove(process); } public void RemoveProcess(NanoDeviceBase device) { CorDebugProcess process = ProcessFromPortDefinition(device); if (process != null) { RemoveProcess(process); } } public bool AreProcessIdEqual(AD_PROCESS_ID pid1, AD_PROCESS_ID pid2) { if (pid1.ProcessIdType != pid2.ProcessIdType) return false; switch ((AD_PROCESS_ID_TYPE) pid1.ProcessIdType) { case AD_PROCESS_ID_TYPE.AD_PROCESS_ID_SYSTEM: return pid1.dwProcessId == pid2.dwProcessId; case AD_PROCESS_ID_TYPE.AD_PROCESS_ID_GUID: return Guid.Equals(pid1.guidProcessId, pid2.guidProcessId); default: return false; } } public Guid PortId { get { return _guid; } } public string Name { [System.Diagnostics.DebuggerHidden] get { return _name; } } public CorDebugProcess GetDeviceProcess(string deviceName, int eachSecondRetryMaxCount) { if (string.IsNullOrEmpty(deviceName)) throw new Exception("DebugPort.GetDeviceProcess() called with no argument"); MessageCentre.StartProgressMessage(String.Format(Resources.ResourceStrings.StartDeviceSearch, deviceName, eachSecondRetryMaxCount)); CorDebugProcess process = InternalGetDeviceProcess(deviceName); if (process != null) return process; if (eachSecondRetryMaxCount < 0) eachSecondRetryMaxCount = 0; for (int i = 0; i < eachSecondRetryMaxCount && process == null; i++) { System.Threading.Thread.Sleep(1000); process = InternalGetDeviceProcess(deviceName); } MessageCentre.StopProgressMessage(String.Format((process == null) ? Resources.ResourceStrings.DeviceFound : Resources.ResourceStrings.DeviceNotFound, deviceName)); return process; } public CorDebugProcess GetDeviceProcess(string deviceName) { if (string.IsNullOrEmpty(deviceName)) throw new Exception("DebugPort.GetDeviceProcess() called with no argument"); return InternalGetDeviceProcess(deviceName); } private CorDebugProcess InternalGetDeviceProcess(string deviceName) { CorDebugProcess process = null; RefreshProcesses(); for(int i = 0; i < _alProcesses.Count; i++) { CorDebugProcess processT = (CorDebugProcess)_alProcesses[i]; NanoDeviceBase device = processT.Device; if (String.Compare(GetDeviceName(device), deviceName, true) == 0) { process = processT; break; } } // TODO //if(m_portFilter == PortFilter.TcpIp && process == null) //{ // process = EnsureProcess(PortDefinition.CreateInstanceForTcp(deviceName)); //} return process; } public string GetDeviceName(NanoDeviceBase device) { return device.Description; } private bool ArePortEntriesEqual(NanoDeviceBase device1, NanoDeviceBase device2) { if (device1.Description != device2.Description) return false; if (device1.GetType() != device2.GetType()) return false; return true; } private CorDebugProcess ProcessFromPortDefinition(NanoDeviceBase device) { foreach (CorDebugProcess process in _alProcesses) { if (ArePortEntriesEqual(device, process.Device)) return process; } return null; } private CorDebugProcess GetProcess( AD_PROCESS_ID ProcessId ) { AD_PROCESS_ID pid; foreach (CorDebugProcess process in _alProcesses) { pid = process.PhysicalProcessId; if (AreProcessIdEqual(ProcessId, pid)) { return process; } } return null; } private CorDebugProcess GetProcess( IDebugProgramNode2 programNode ) { AD_PROCESS_ID[] pids = new AD_PROCESS_ID[1]; programNode.GetHostPid( pids ); return GetProcess( pids[0] ); } private CorDebugAppDomain GetAppDomain( IDebugProgramNode2 programNode ) { uint appDomainId; CorDebugProcess process = GetProcess( programNode ); IDebugCOMPlusProgramNode2 node = (IDebugCOMPlusProgramNode2)programNode; node.GetAppDomainId( out appDomainId ); CorDebugAppDomain appDomain = process.GetAppDomainFromId( appDomainId ); return appDomain; } private void SendProgramEvent(IDebugProgramNode2 programNode, enum_EVENTATTRIBUTES attributes, Guid iidEvent) { CorDebugProcess process = GetProcess( programNode ); CorDebugAppDomain appDomain = GetAppDomain( programNode ); IDebugEvent2 evt = new DebugEvent((uint) attributes); foreach (IDebugPortEvents2 dpe in _cpDebugPortEvents2.Sinks) { dpe.Event(DebugPortSupplier.CoreServer, this, (IDebugProcess2)process, (IDebugProgram2) appDomain, evt, ref iidEvent); } } #region IDebugPort2 Members int Microsoft.VisualStudio.Debugger.Interop.IDebugPort2.GetPortId(out Guid pguidPort) { pguidPort = PortId; return COM_HResults.S_OK; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPort2.GetProcess(AD_PROCESS_ID ProcessId, out IDebugProcess2 ppProcess) { ppProcess = ((DebugPort)this).GetProcess( ProcessId ); return COM_HResults.BOOL_TO_HRESULT_FAIL( ppProcess != null ); } int Microsoft.VisualStudio.Debugger.Interop.IDebugPort2.GetPortSupplier(out IDebugPortSupplier2 ppSupplier) { ppSupplier = DebugPortSupplier; return COM_HResults.S_OK; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPort2.GetPortRequest(out IDebugPortRequest2 ppRequest) { ppRequest = null; return COM_HResults.E_NOTIMPL; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPort2.EnumProcesses(out IEnumDebugProcesses2 ppEnum) { RefreshProcesses(); ppEnum = new CorDebugEnum(_alProcesses, typeof(IDebugProcess2), typeof(IEnumDebugProcesses2)); return COM_HResults.S_OK; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPort2.GetPortName(out string pbstrName) { pbstrName = _name; return COM_HResults.S_OK; } #endregion #region IDebugPortEx2 Members int Microsoft.VisualStudio.Debugger.Interop.IDebugPortEx2.GetProgram(IDebugProgramNode2 pProgramNode, out IDebugProgram2 ppProgram) { CorDebugAppDomain appDomain = GetAppDomain( pProgramNode ); ppProgram = appDomain; return COM_HResults.S_OK; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPortEx2.LaunchSuspended(string pszExe, string pszArgs, string pszDir, string bstrEnv, uint hStdInput, uint hStdOutput, uint hStdError, out IDebugProcess2 ppPortProcess) { System.Windows.Forms.MessageBox.Show("Hello from LaunchSuspended!"); ppPortProcess = null; return COM_HResults.S_OK; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPortEx2.TerminateProcess(IDebugProcess2 pPortProcess) { return COM_HResults.S_OK; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPortEx2.ResumeProcess(IDebugProcess2 pPortProcess) { return COM_HResults.S_OK; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPortEx2.CanTerminateProcess(IDebugProcess2 pPortProcess) { return COM_HResults.S_OK; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPortEx2.GetPortProcessId(out uint pdwProcessId) { pdwProcessId = 0; return COM_HResults.S_OK; } #endregion #region IDebugPortNotify2 Members int Microsoft.VisualStudio.Debugger.Interop.IDebugPortNotify2.AddProgramNode(IDebugProgramNode2 pProgramNode) { SendProgramEvent(pProgramNode, enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS, typeof(IDebugProgramCreateEvent2).GUID); return COM_HResults.S_OK; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPortNotify2.RemoveProgramNode(IDebugProgramNode2 pProgramNode) { SendProgramEvent(pProgramNode, enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS, typeof(IDebugProgramDestroyEvent2).GUID); return COM_HResults.S_OK; } #endregion #region IConnectionPointContainer Members void Microsoft.VisualStudio.OLE.Interop.IConnectionPointContainer.FindConnectionPoint(ref Guid riid, out IConnectionPoint ppCP) { if (riid.Equals(typeof(IDebugPortEvents2).GUID)) { ppCP = _cpDebugPortEvents2; } else { ppCP = null; Marshal.ThrowExceptionForHR(COM_HResults.CONNECT_E_NOCONNECTION); } } void Microsoft.VisualStudio.OLE.Interop.IConnectionPointContainer.EnumConnectionPoints(out IEnumConnectionPoints ppEnum) { throw new NotImplementedException(); } #endregion } }
/* * Copyright 2007 ZXing authors * * 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. */ namespace com.google.zxing.datamatrix.decoder { using FormatException = com.google.zxing.FormatException; using BitMatrix = com.google.zxing.common.BitMatrix; /// <summary> /// @author bbrown@google.com (Brian Brown) /// </summary> internal sealed class BitMatrixParser { private readonly BitMatrix mappingBitMatrix; private readonly BitMatrix readMappingMatrix; private readonly Version version; /// <param name="bitMatrix"> <seealso cref="BitMatrix"/> to parse </param> /// <exception cref="FormatException"> if dimension is < 8 or > 144 or not 0 mod 2 </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: BitMatrixParser(com.google.zxing.common.BitMatrix bitMatrix) throws com.google.zxing.FormatException internal BitMatrixParser(BitMatrix bitMatrix) { int dimension = bitMatrix.Height; if (dimension < 8 || dimension > 144 || (dimension & 0x01) != 0) { throw FormatException.FormatInstance; } version = readVersion(bitMatrix); this.mappingBitMatrix = extractDataRegion(bitMatrix); this.readMappingMatrix = new BitMatrix(this.mappingBitMatrix.Width, this.mappingBitMatrix.Height); } internal Version Version { get { return version; } } /// <summary> /// <p>Creates the version object based on the dimension of the original bit matrix from /// the datamatrix code.</p> /// /// <p>See ISO 16022:2006 Table 7 - ECC 200 symbol attributes</p> /// </summary> /// <param name="bitMatrix"> Original <seealso cref="BitMatrix"/> including alignment patterns </param> /// <returns> <seealso cref="Version"/> encapsulating the Data Matrix Code's "version" </returns> /// <exception cref="FormatException"> if the dimensions of the mapping matrix are not valid /// Data Matrix dimensions. </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private static Version readVersion(com.google.zxing.common.BitMatrix bitMatrix) throws com.google.zxing.FormatException private static Version readVersion(BitMatrix bitMatrix) { int numRows = bitMatrix.Height; int numColumns = bitMatrix.Width; return Version.getVersionForDimensions(numRows, numColumns); } /// <summary> /// <p>Reads the bits in the <seealso cref="BitMatrix"/> representing the mapping matrix (No alignment patterns) /// in the correct order in order to reconstitute the codewords bytes contained within the /// Data Matrix Code.</p> /// </summary> /// <returns> bytes encoded within the Data Matrix Code </returns> /// <exception cref="FormatException"> if the exact number of bytes expected is not read </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: byte[] readCodewords() throws com.google.zxing.FormatException internal sbyte[] readCodewords() { sbyte[] result = new sbyte[version.TotalCodewords]; int resultOffset = 0; int row = 4; int column = 0; int numRows = mappingBitMatrix.Height; int numColumns = mappingBitMatrix.Width; bool corner1Read = false; bool corner2Read = false; bool corner3Read = false; bool corner4Read = false; // Read all of the codewords do { // Check the four corner cases if ((row == numRows) && (column == 0) && !corner1Read) { result[resultOffset++] = (sbyte) readCorner1(numRows, numColumns); row -= 2; column += 2; corner1Read = true; } else if ((row == numRows - 2) && (column == 0) && ((numColumns & 0x03) != 0) && !corner2Read) { result[resultOffset++] = (sbyte) readCorner2(numRows, numColumns); row -= 2; column += 2; corner2Read = true; } else if ((row == numRows + 4) && (column == 2) && ((numColumns & 0x07) == 0) && !corner3Read) { result[resultOffset++] = (sbyte) readCorner3(numRows, numColumns); row -= 2; column += 2; corner3Read = true; } else if ((row == numRows - 2) && (column == 0) && ((numColumns & 0x07) == 4) && !corner4Read) { result[resultOffset++] = (sbyte) readCorner4(numRows, numColumns); row -= 2; column += 2; corner4Read = true; } else { // Sweep upward diagonally to the right do { if ((row < numRows) && (column >= 0) && !readMappingMatrix.get(column, row)) { result[resultOffset++] = (sbyte) readUtah(row, column, numRows, numColumns); } row -= 2; column += 2; } while ((row >= 0) && (column < numColumns)); row += 1; column += 3; // Sweep downward diagonally to the left do { if ((row >= 0) && (column < numColumns) && !readMappingMatrix.get(column, row)) { result[resultOffset++] = (sbyte) readUtah(row, column, numRows, numColumns); } row += 2; column -= 2; } while ((row < numRows) && (column >= 0)); row += 3; column += 1; } } while ((row < numRows) || (column < numColumns)); if (resultOffset != version.TotalCodewords) { throw FormatException.FormatInstance; } return result; } /// <summary> /// <p>Reads a bit of the mapping matrix accounting for boundary wrapping.</p> /// </summary> /// <param name="row"> Row to read in the mapping matrix </param> /// <param name="column"> Column to read in the mapping matrix </param> /// <param name="numRows"> Number of rows in the mapping matrix </param> /// <param name="numColumns"> Number of columns in the mapping matrix </param> /// <returns> value of the given bit in the mapping matrix </returns> internal bool readModule(int row, int column, int numRows, int numColumns) { // Adjust the row and column indices based on boundary wrapping if (row < 0) { row += numRows; column += 4 - ((numRows + 4) & 0x07); } if (column < 0) { column += numColumns; row += 4 - ((numColumns + 4) & 0x07); } readMappingMatrix.set(column, row); return mappingBitMatrix.get(column, row); } /// <summary> /// <p>Reads the 8 bits of the standard Utah-shaped pattern.</p> /// /// <p>See ISO 16022:2006, 5.8.1 Figure 6</p> /// </summary> /// <param name="row"> Current row in the mapping matrix, anchored at the 8th bit (LSB) of the pattern </param> /// <param name="column"> Current column in the mapping matrix, anchored at the 8th bit (LSB) of the pattern </param> /// <param name="numRows"> Number of rows in the mapping matrix </param> /// <param name="numColumns"> Number of columns in the mapping matrix </param> /// <returns> byte from the utah shape </returns> internal int readUtah(int row, int column, int numRows, int numColumns) { int currentByte = 0; if (readModule(row - 2, column - 2, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(row - 2, column - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(row - 1, column - 2, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(row - 1, column - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(row - 1, column, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(row, column - 2, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(row, column - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(row, column, numRows, numColumns)) { currentByte |= 1; } return currentByte; } /// <summary> /// <p>Reads the 8 bits of the special corner condition 1.</p> /// /// <p>See ISO 16022:2006, Figure F.3</p> /// </summary> /// <param name="numRows"> Number of rows in the mapping matrix </param> /// <param name="numColumns"> Number of columns in the mapping matrix </param> /// <returns> byte from the Corner condition 1 </returns> internal int readCorner1(int numRows, int numColumns) { int currentByte = 0; if (readModule(numRows - 1, 0, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(numRows - 1, 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(numRows - 1, 2, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 2, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(1, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(2, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(3, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } return currentByte; } /// <summary> /// <p>Reads the 8 bits of the special corner condition 2.</p> /// /// <p>See ISO 16022:2006, Figure F.4</p> /// </summary> /// <param name="numRows"> Number of rows in the mapping matrix </param> /// <param name="numColumns"> Number of columns in the mapping matrix </param> /// <returns> byte from the Corner condition 2 </returns> internal int readCorner2(int numRows, int numColumns) { int currentByte = 0; if (readModule(numRows - 3, 0, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(numRows - 2, 0, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(numRows - 1, 0, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 4, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 3, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 2, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(1, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } return currentByte; } /// <summary> /// <p>Reads the 8 bits of the special corner condition 3.</p> /// /// <p>See ISO 16022:2006, Figure F.5</p> /// </summary> /// <param name="numRows"> Number of rows in the mapping matrix </param> /// <param name="numColumns"> Number of columns in the mapping matrix </param> /// <returns> byte from the Corner condition 3 </returns> internal int readCorner3(int numRows, int numColumns) { int currentByte = 0; if (readModule(numRows - 1, 0, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(numRows - 1, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 3, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 2, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(1, numColumns - 3, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(1, numColumns - 2, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(1, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } return currentByte; } /// <summary> /// <p>Reads the 8 bits of the special corner condition 4.</p> /// /// <p>See ISO 16022:2006, Figure F.6</p> /// </summary> /// <param name="numRows"> Number of rows in the mapping matrix </param> /// <param name="numColumns"> Number of columns in the mapping matrix </param> /// <returns> byte from the Corner condition 4 </returns> internal int readCorner4(int numRows, int numColumns) { int currentByte = 0; if (readModule(numRows - 3, 0, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(numRows - 2, 0, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(numRows - 1, 0, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 2, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(1, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(2, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(3, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } return currentByte; } /// <summary> /// <p>Extracts the data region from a <seealso cref="BitMatrix"/> that contains /// alignment patterns.</p> /// </summary> /// <param name="bitMatrix"> Original <seealso cref="BitMatrix"/> with alignment patterns </param> /// <returns> BitMatrix that has the alignment patterns removed </returns> internal BitMatrix extractDataRegion(BitMatrix bitMatrix) { int symbolSizeRows = version.SymbolSizeRows; int symbolSizeColumns = version.SymbolSizeColumns; if (bitMatrix.Height != symbolSizeRows) { throw new System.ArgumentException("Dimension of bitMarix must match the version size"); } int dataRegionSizeRows = version.DataRegionSizeRows; int dataRegionSizeColumns = version.DataRegionSizeColumns; int numDataRegionsRow = symbolSizeRows / dataRegionSizeRows; int numDataRegionsColumn = symbolSizeColumns / dataRegionSizeColumns; int sizeDataRegionRow = numDataRegionsRow * dataRegionSizeRows; int sizeDataRegionColumn = numDataRegionsColumn * dataRegionSizeColumns; BitMatrix bitMatrixWithoutAlignment = new BitMatrix(sizeDataRegionColumn, sizeDataRegionRow); for (int dataRegionRow = 0; dataRegionRow < numDataRegionsRow; ++dataRegionRow) { int dataRegionRowOffset = dataRegionRow * dataRegionSizeRows; for (int dataRegionColumn = 0; dataRegionColumn < numDataRegionsColumn; ++dataRegionColumn) { int dataRegionColumnOffset = dataRegionColumn * dataRegionSizeColumns; for (int i = 0; i < dataRegionSizeRows; ++i) { int readRowOffset = dataRegionRow * (dataRegionSizeRows + 2) + 1 + i; int writeRowOffset = dataRegionRowOffset + i; for (int j = 0; j < dataRegionSizeColumns; ++j) { int readColumnOffset = dataRegionColumn * (dataRegionSizeColumns + 2) + 1 + j; if (bitMatrix.get(readColumnOffset, readRowOffset)) { int writeColumnOffset = dataRegionColumnOffset + j; bitMatrixWithoutAlignment.set(writeColumnOffset, writeRowOffset); } } } } } return bitMatrixWithoutAlignment; } } }
#region License /* * Copyright 2002-2010 the original author or authors. * * 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; using System.IO; using System.Reflection; using System.Threading; using log4net; using NUnit.Framework; using Spring.Threading; namespace Spring.Services.WindowsService.Common.Deploy { [TestFixture] public class ApplicationWatcherManagerTest { ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IApplication application; private string appName; private ApplicationWatcherManager manager; private ISync reconfigured; private int nReconfigured; [SetUp] public void SetUp () { nReconfigured = 0; appName = Guid.NewGuid().ToString(); application = new Application(appName); Directory.CreateDirectory(application.FullPath); manager = new ApplicationWatcherManager(application, 10); manager.Reconfigured += new EventHandler(manager_Reconfigured); reconfigured = new Semaphore(0); } [TearDown] public void TearDown () { manager.Dispose (); Directory.Delete(application.FullPath, true); } [Test] public void RecreatesTheWatcherWhenItsDefinitonChanges() { Assert.IsTrue(manager.Watcher is NullApplicationWatcher); File.Copy("Data/Xml/watcher-0.xml", application.WatcherXmlFullPath, true); reconfigured.Acquire(); Assert.IsTrue(manager.Watcher is NullApplicationWatcher); TestUtils.SafeCopyFile("Data/Xml/watcher-1.xml", application.WatcherXmlFullPath, true); reconfigured.Acquire(); Assert.IsTrue(manager.Watcher is FileSystemApplicationWatcher); TestUtils.SafeDeleteFile(application.WatcherXmlFullPath); reconfigured.Acquire(); Assert.IsTrue(manager.Watcher is NullApplicationWatcher); Assert.AreEqual(3, nReconfigured); } class Watcher : IApplicationWatcher { IApplication application; public bool started, stopped, disposed, filters; public IApplication Application { get { return application; } set { application = value; } } public void StartWatching (IDeployEventDispatcher dispatcher) { started = true; } public void StopWatching () { stopped = true; } public void SetFilters (IList allows, IList disallows) { filters = true; } public void Dispose () { disposed = true; } } class Factory : IApplicationWatcherFactory { public Watcher lastWatcher; public int called = 0; public IApplicationWatcher CreateApplicationWatcher (IApplication application) { called++; lastWatcher = new Watcher(); lastWatcher.Application = application; return lastWatcher; } public ApplicationWatcherManager CreateApplicationWatcherMonitor (IApplication application) { throw new NotImplementedException (); } } [Test] public void StopsAndDisposeTheOldWatcherAndStartTheNewWatcherWhenItChanges () { TestUtils.ConfigureLog4Net(); IApplication application = new Application(appName); Factory factory = new Factory(); ApplicationWatcherManager m = new ApplicationWatcherManager(factory, application, 100); m.StartWatching(new ForwardingDeployEventDispatcher()); manager.Reconfigured -= new EventHandler(manager_Reconfigured); m.Reconfigured += new EventHandler(manager_Reconfigured); File.Copy("Data/Xml/watcher-0.xml", application.WatcherXmlFullPath, true); reconfigured.Acquire(); log.Debug("first empty definition copied"); Assert.IsTrue(manager.Watcher is NullApplicationWatcher); Watcher watcher1 = factory.lastWatcher; Assert.IsTrue(watcher1.started); bool ok = true; do { try { File.Copy("Data/Xml/watcher-1.xml", application.WatcherXmlFullPath, true); } catch (Exception e) { ok = false; Thread.Sleep(100); log.Error("error copying file", e); } } while (ok == false); reconfigured.Acquire(); log.Debug("good definition copied"); while (!(manager.Watcher is FileSystemApplicationWatcher)) Thread.Sleep(10); Watcher watcher2 = factory.lastWatcher; Assert.IsTrue(watcher2.started); Assert.IsTrue(watcher1.stopped); Assert.IsTrue(watcher1.disposed); Assert.IsTrue(manager.Watcher is FileSystemApplicationWatcher); do { try { File.Delete(application.WatcherXmlFullPath); } catch (Exception e) { log.Error("error cancelling file", e); } } while (File.Exists(application.WatcherXmlFullPath)); reconfigured.Acquire(); log.Debug("good definition deleted"); while (!(manager.Watcher is NullApplicationWatcher)) Thread.Sleep(10); Watcher watcher3 = factory.lastWatcher; Assert.IsTrue(watcher3.started); Assert.IsTrue(watcher2.stopped); Assert.IsTrue(watcher2.disposed); Assert.IsTrue(manager.Watcher is NullApplicationWatcher); Assert.AreEqual(3, nReconfigured); Assert.AreEqual(3 + 1, factory.called); // +1 in ApplicationWatcherManager ctor } private void manager_Reconfigured(object sender, EventArgs e) { ++nReconfigured; log.Debug("releasing reconfigured sync. n. of reconfigs: " + nReconfigured); reconfigured.Release(); } } }
/* This file is part of SevenZipSharp. SevenZipSharp is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SevenZipSharp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with SevenZipSharp. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Runtime.InteropServices; #if MONO using SevenZip.Mono.COM; #endif namespace SevenZip { #if UNMANAGED /// <summary> /// A class that has DisposeStream property. /// </summary> internal class DisposeVariableWrapper { public bool DisposeStream { protected get; set; } protected DisposeVariableWrapper(bool disposeStream) { DisposeStream = disposeStream; } } /// <summary> /// Stream wrapper used in InStreamWrapper /// </summary> internal class StreamWrapper : DisposeVariableWrapper, IDisposable { /// <summary> /// File name associated with the stream (for date fix) /// </summary> private readonly string _fileName; private readonly DateTime _fileTime; /// <summary> /// Worker stream for reading, writing and seeking. /// </summary> private Stream _baseStream; /// <summary> /// Initializes a new instance of the StreamWrapper class /// </summary> /// <param name="baseStream">Worker stream for reading, writing and seeking</param> /// <param name="fileName">File name associated with the stream (for attributes fix)</param> /// <param name="time">File last write time (for attributes fix)</param> /// <param name="disposeStream">Indicates whether to dispose the baseStream</param> protected StreamWrapper(Stream baseStream, string fileName, DateTime time, bool disposeStream) : base(disposeStream) { _baseStream = baseStream; _fileName = fileName; _fileTime = time; } /// <summary> /// Initializes a new instance of the StreamWrapper class /// </summary> /// <param name="baseStream">Worker stream for reading, writing and seeking</param> /// <param name="disposeStream">Indicates whether to dispose the baseStream</param> protected StreamWrapper(Stream baseStream, bool disposeStream) : base(disposeStream) { _baseStream = baseStream; } /// <summary> /// Gets the worker stream for reading, writing and seeking. /// </summary> protected Stream BaseStream { get { return _baseStream; } } #region IDisposable Members /// <summary> /// Cleans up any resources used and fixes file attributes. /// </summary> public void Dispose() { if (_baseStream != null && DisposeStream) { try { _baseStream.Dispose(); } catch (ObjectDisposedException) { } _baseStream = null; } if (!String.IsNullOrEmpty(_fileName) && File.Exists(_fileName)) { try { #if !WINCE File.SetLastWriteTime(_fileName, _fileTime); File.SetLastAccessTime(_fileName, _fileTime); File.SetCreationTime(_fileName, _fileTime); #elif WINCE OpenNETCF.IO.FileHelper.SetLastWriteTime(_fileName, _fileTime); OpenNETCF.IO.FileHelper.SetLastAccessTime(_fileName, _fileTime); OpenNETCF.IO.FileHelper.SetCreationTime(_fileName, _fileTime); #endif //TODO: time support for Windows Phone } catch (ArgumentOutOfRangeException) {} } GC.SuppressFinalize(this); } #endregion public virtual void Seek(long offset, SeekOrigin seekOrigin, IntPtr newPosition) { if (BaseStream != null) { long position = BaseStream.Seek(offset, seekOrigin); if (newPosition != IntPtr.Zero) { Marshal.WriteInt64(newPosition, position); } } } } /// <summary> /// IInStream wrapper used in stream read operations. /// </summary> internal sealed class InStreamWrapper : StreamWrapper, ISequentialInStream, IInStream { /// <summary> /// Initializes a new instance of the InStreamWrapper class. /// </summary> /// <param name="baseStream">Stream for writing data</param> /// <param name="disposeStream">Indicates whether to dispose the baseStream</param> public InStreamWrapper(Stream baseStream, bool disposeStream) : base(baseStream, disposeStream) { } #region ISequentialInStream Members /// <summary> /// Reads data from the stream. /// </summary> /// <param name="data">A data array.</param> /// <param name="size">The array size.</param> /// <returns>The read bytes count.</returns> public int Read(byte[] data, uint size) { int readCount = 0; if (BaseStream != null) { readCount = BaseStream.Read(data, 0, (int) size); if (readCount > 0) { OnBytesRead(new IntEventArgs(readCount)); } } return readCount; } #endregion /// <summary> /// Occurs when IntEventArgs.Value bytes were read from the source. /// </summary> public event EventHandler<IntEventArgs> BytesRead; private void OnBytesRead(IntEventArgs e) { if (BytesRead != null) { BytesRead(this, e); } } } /// <summary> /// IOutStream wrapper used in stream write operations. /// </summary> internal sealed class OutStreamWrapper : StreamWrapper, ISequentialOutStream, IOutStream { /// <summary> /// Initializes a new instance of the OutStreamWrapper class /// </summary> /// <param name="baseStream">Stream for writing data</param> /// <param name="fileName">File name (for attributes fix)</param> /// <param name="time">Time of the file creation (for attributes fix)</param> /// <param name="disposeStream">Indicates whether to dispose the baseStream</param> public OutStreamWrapper(Stream baseStream, string fileName, DateTime time, bool disposeStream) : base(baseStream, fileName, time, disposeStream) {} /// <summary> /// Initializes a new instance of the OutStreamWrapper class /// </summary> /// <param name="baseStream">Stream for writing data</param> /// <param name="disposeStream">Indicates whether to dispose the baseStream</param> public OutStreamWrapper(Stream baseStream, bool disposeStream) : base(baseStream, disposeStream) {} #region IOutStream Members public int SetSize(long newSize) { BaseStream.SetLength(newSize); return 0; } #endregion #region ISequentialOutStream Members /// <summary> /// Writes data to the stream /// </summary> /// <param name="data">Data array</param> /// <param name="size">Array size</param> /// <param name="processedSize">Count of written bytes</param> /// <returns>Zero if Ok</returns> public int Write(byte[] data, uint size, IntPtr processedSize) { BaseStream.Write(data, 0, (int) size); if (processedSize != IntPtr.Zero) { Marshal.WriteInt32(processedSize, (int) size); } OnBytesWritten(new IntEventArgs((int) size)); return 0; } #endregion /// <summary> /// Occurs when IntEventArgs.Value bytes were written. /// </summary> public event EventHandler<IntEventArgs> BytesWritten; private void OnBytesWritten(IntEventArgs e) { if (BytesWritten != null) { BytesWritten(this, e); } } } /// <summary> /// Base multi volume stream wrapper class. /// </summary> internal class MultiStreamWrapper : DisposeVariableWrapper, IDisposable { protected readonly Dictionary<int, KeyValuePair<long, long>> StreamOffsets = new Dictionary<int, KeyValuePair<long, long>>(); protected readonly List<Stream> Streams = new List<Stream>(); protected int CurrentStream; protected long Position; protected long StreamLength; /// <summary> /// Initializes a new instance of the MultiStreamWrapper class. /// </summary> /// <param name="dispose">Perform Dispose() if requested to.</param> protected MultiStreamWrapper(bool dispose) : base(dispose) {} /// <summary> /// Gets the total length of input data. /// </summary> public long Length { get { return StreamLength; } } #region IDisposable Members /// <summary> /// Cleans up any resources used and fixes file attributes. /// </summary> public virtual void Dispose() { if (DisposeStream) { foreach (Stream stream in Streams) { try { stream.Dispose(); } catch (ObjectDisposedException) {} } Streams.Clear(); } GC.SuppressFinalize(this); } #endregion protected static string VolumeNumber(int num) { if (num < 10) { return ".00" + num.ToString(CultureInfo.InvariantCulture); } if (num > 9 && num < 100) { return ".0" + num.ToString(CultureInfo.InvariantCulture); } if (num > 99 && num < 1000) { return "." + num.ToString(CultureInfo.InvariantCulture); } return ""; } private int StreamNumberByOffset(long offset) { foreach (int number in StreamOffsets.Keys) { if (StreamOffsets[number].Key <= offset && StreamOffsets[number].Value >= offset) { return number; } } return -1; } public void Seek(long offset, SeekOrigin seekOrigin, IntPtr newPosition) { long absolutePosition = (seekOrigin == SeekOrigin.Current) ? Position + offset : offset; CurrentStream = StreamNumberByOffset(absolutePosition); long delta = Streams[CurrentStream].Seek( absolutePosition - StreamOffsets[CurrentStream].Key, SeekOrigin.Begin); Position = StreamOffsets[CurrentStream].Key + delta; if (newPosition != IntPtr.Zero) { Marshal.WriteInt64(newPosition, Position); } } } /// <summary> /// IInStream wrapper used in stream multi volume read operations. /// </summary> internal sealed class InMultiStreamWrapper : MultiStreamWrapper, ISequentialInStream, IInStream { /// <summary> /// Initializes a new instance of the InMultiStreamWrapper class. /// </summary> /// <param name="fileName">The archive file name.</param> /// <param name="dispose">Perform Dispose() if requested to.</param> public InMultiStreamWrapper(string fileName, bool dispose) : base(dispose) { string baseName = fileName.Substring(0, fileName.Length - 4); int i = 0; while (File.Exists(fileName)) { Streams.Add(new FileStream(fileName, FileMode.Open)); long length = Streams[i].Length; StreamOffsets.Add(i++, new KeyValuePair<long, long>(StreamLength, StreamLength + length)); StreamLength += length; fileName = baseName + VolumeNumber(i + 1); } } #region ISequentialInStream Members /// <summary> /// Reads data from the stream. /// </summary> /// <param name="data">A data array.</param> /// <param name="size">The array size.</param> /// <returns>The read bytes count.</returns> public int Read(byte[] data, uint size) { var readSize = (int) size; int readCount = Streams[CurrentStream].Read(data, 0, readSize); readSize -= readCount; Position += readCount; while (readCount < (int) size) { if (CurrentStream == Streams.Count - 1) { return readCount; } CurrentStream++; Streams[CurrentStream].Seek(0, SeekOrigin.Begin); int count = Streams[CurrentStream].Read(data, readCount, readSize); readCount += count; readSize -= count; Position += count; } return readCount; } #endregion } #if COMPRESS /// <summary> /// IOutStream wrapper used in multi volume stream write operations. /// </summary> internal sealed class OutMultiStreamWrapper : MultiStreamWrapper, ISequentialOutStream, IOutStream { private readonly string _archiveName; private readonly int _volumeSize; private long _overallLength; /// <summary> /// Initializes a new instance of the OutMultiStreamWrapper class. /// </summary> /// <param name="archiveName">The archive name.</param> /// <param name="volumeSize">The volume size.</param> public OutMultiStreamWrapper(string archiveName, int volumeSize) : base(true) { _archiveName = archiveName; _volumeSize = volumeSize; CurrentStream = -1; NewVolumeStream(); } #region IOutStream Members public int SetSize(long newSize) { return 0; } #endregion #region ISequentialOutStream Members public int Write(byte[] data, uint size, IntPtr processedSize) { int offset = 0; var originalSize = (int) size; Position += size; _overallLength = Math.Max(Position + 1, _overallLength); while (size > _volumeSize - Streams[CurrentStream].Position) { var count = (int) (_volumeSize - Streams[CurrentStream].Position); Streams[CurrentStream].Write(data, offset, count); size -= (uint) count; offset += count; NewVolumeStream(); } Streams[CurrentStream].Write(data, offset, (int) size); if (processedSize != IntPtr.Zero) { Marshal.WriteInt32(processedSize, originalSize); } return 0; } #endregion public override void Dispose() { int lastIndex = Streams.Count - 1; Streams[lastIndex].SetLength(lastIndex > 0? Streams[lastIndex].Position : _overallLength); base.Dispose(); } private void NewVolumeStream() { CurrentStream++; Streams.Add(File.Create(_archiveName + VolumeNumber(CurrentStream + 1))); Streams[CurrentStream].SetLength(_volumeSize); StreamOffsets.Add(CurrentStream, new KeyValuePair<long, long>(0, _volumeSize - 1)); } } #endif internal sealed class FakeOutStreamWrapper : ISequentialOutStream, IDisposable { #region IDisposable Members public void Dispose() { GC.SuppressFinalize(this); } #endregion #region ISequentialOutStream Members /// <summary> /// Does nothing except calling the BytesWritten event /// </summary> /// <param name="data">Data array</param> /// <param name="size">Array size</param> /// <param name="processedSize">Count of written bytes</param> /// <returns>Zero if Ok</returns> public int Write(byte[] data, uint size, IntPtr processedSize) { OnBytesWritten(new IntEventArgs((int) size)); if (processedSize != IntPtr.Zero) { Marshal.WriteInt32(processedSize, (int) size); } return 0; } #endregion /// <summary> /// Occurs when IntEventArgs.Value bytes were written /// </summary> public event EventHandler<IntEventArgs> BytesWritten; private void OnBytesWritten(IntEventArgs e) { if (BytesWritten != null) { BytesWritten(this, e); } } } #endif }
/* * 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 log4net; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections.Generic; using System.Reflection; using System.Text.RegularExpressions; namespace OpenSim.Region.OptionalModules.Avatar.Chat { // An instance of this class exists for every active region internal class RegionState { internal string alertMessage = String.Empty; internal List<IClientAPI> clients = new List<IClientAPI>(); internal IConfig config = null; internal ChannelState cs = null; internal IDialogModule dialogModule = null; // configuration file reference internal bool enabled = true; internal string Host = String.Empty; internal string IDK = String.Empty; internal string LocX = String.Empty; internal string LocY = String.Empty; internal string Region = String.Empty; // associated IRC configuration internal Scene scene = null; // associated scene //AgentAlert internal bool showAlert = false; private const int DEBUG_CHANNEL = 2147483647; // This computation is not the real region center if the region is larger than 256. // This computation isn't fixed because there is not a handle back to the region. private static readonly OpenMetaverse.Vector3 CenterOfRegion = new OpenMetaverse.Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 20); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static int _idk_ = 0; // Runtime variables; these values are assigned when the // IrcState is created and remain constant thereafter. // System values - used only be the IRC classes themselves // This list is used to keep track of who is here, and by // implication, who is not. // Setup runtime variable values public RegionState(Scene p_scene, IConfig p_config) { scene = p_scene; config = p_config; Region = scene.RegionInfo.RegionName; Host = scene.RegionInfo.ExternalHostName; LocX = Convert.ToString(scene.RegionInfo.RegionLocX); LocY = Convert.ToString(scene.RegionInfo.RegionLocY); IDK = Convert.ToString(_idk_++); showAlert = config.GetBoolean("alert_show", false); string alertServerInfo = String.Empty; if (showAlert) { bool showAlertServerInfo = config.GetBoolean("alert_show_serverinfo", true); if (showAlertServerInfo) alertServerInfo = String.Format("\nServer: {0}\nPort: {1}\nChannel: {2}\n\n", config.GetString("server", ""), config.GetString("port", ""), config.GetString("channel", "")); string alertPreMessage = config.GetString("alert_msg_pre", "This region is linked to Irc."); string alertPostMessage = config.GetString("alert_msg_post", "Everything you say in public chat can be listened."); alertMessage = String.Format("{0}\n{1}{2}", alertPreMessage, alertServerInfo, alertPostMessage); dialogModule = scene.RequestModuleInterface<IDialogModule>(); } // OpenChannel conditionally establishes a connection to the // IRC server. The request will either succeed, or it will // throw an exception. ChannelState.OpenChannel(this, config); // Connect channel to world events scene.EventManager.OnChatFromWorld += OnSimChat; scene.EventManager.OnChatFromClient += OnSimChat; scene.EventManager.OnMakeRootAgent += OnMakeRootAgent; scene.EventManager.OnMakeChildAgent += OnMakeChildAgent; m_log.InfoFormat("[IRC-Region {0}] Initialization complete", Region); } // Auto cleanup when abandoned ~RegionState() { if (cs != null) cs.RemoveRegion(this); } // Called by PostInitialize after all regions have been created public void Close() { enabled = false; cs.Close(this); } // This handler detects chat events int he virtual world. public void OnSimChat(Object sender, OSChatMessage msg) { // early return if this comes from the IRC forwarder if (cs.irc.Equals(sender)) return; // early return if nothing to forward if (msg.Message.Length == 0) return; // check for commands coming from avatars or in-world // object (if commands are enabled) if (cs.CommandsEnabled && msg.Channel == cs.CommandChannel) { m_log.DebugFormat("[IRC-Region {0}] command on channel {1}: {2}", Region, msg.Channel, msg.Message); string[] messages = msg.Message.Split(' '); string command = messages[0].ToLower(); try { switch (command) { // These commands potentially require a change in the // underlying ChannelState. case "server": cs.Close(this); cs = cs.UpdateServer(this, messages[1]); cs.Open(this); break; case "port": cs.Close(this); cs = cs.UpdatePort(this, messages[1]); cs.Open(this); break; case "channel": cs.Close(this); cs = cs.UpdateChannel(this, messages[1]); cs.Open(this); break; case "nick": cs.Close(this); cs = cs.UpdateNickname(this, messages[1]); cs.Open(this); break; // These may also (but are less likely) to require a // change in ChannelState. case "client-reporting": cs = cs.UpdateClientReporting(this, messages[1]); break; case "in-channel": cs = cs.UpdateRelayIn(this, messages[1]); break; case "out-channel": cs = cs.UpdateRelayOut(this, messages[1]); break; // These are all taken to be temporary changes in state // so the underlying connector remains intact. But note // that with regions sharing a connector, there could // be interference. case "close": enabled = false; cs.Close(this); break; case "connect": enabled = true; cs.Open(this); break; case "reconnect": enabled = true; cs.Close(this); cs.Open(this); break; // This one is harmless as far as we can judge from here. // If it is not, then the complaints will eventually make // that evident. default: m_log.DebugFormat("[IRC-Region {0}] Forwarding unrecognized command to IRC : {1}", Region, msg.Message); cs.irc.Send(msg.Message); break; } } catch (Exception ex) { m_log.WarnFormat("[IRC-Region {0}] error processing in-world command channel input: {1}", Region, ex.Message); m_log.Debug(ex); } return; } // The command channel remains enabled, even if we have otherwise disabled the IRC // interface. if (!enabled) return; // drop messages unless they are on a valid in-world // channel as configured in the ChannelState if (!cs.ValidInWorldChannels.Contains(msg.Channel)) { m_log.DebugFormat("[IRC-Region {0}] dropping message {1} on channel {2}", Region, msg, msg.Channel); return; } ScenePresence avatar = null; string fromName = msg.From; if (msg.Sender != null) { avatar = scene.GetScenePresence(msg.Sender.AgentId); if (avatar != null) fromName = avatar.Name; } if (!cs.irc.Connected) { m_log.WarnFormat("[IRC-Region {0}] IRCConnector not connected: dropping message from {1}", Region, fromName); return; } m_log.DebugFormat("[IRC-Region {0}] heard on channel {1} : {2}", Region, msg.Channel, msg.Message); if (null != avatar && cs.RelayChat && (msg.Channel == 0 || msg.Channel == DEBUG_CHANNEL)) { string txt = msg.Message; if (txt.StartsWith("/me ")) txt = String.Format("{0} {1}", fromName, msg.Message.Substring(4)); cs.irc.PrivMsg(cs.PrivateMessageFormat, fromName, Region, txt); return; } if (null == avatar && cs.RelayPrivateChannels && null != cs.AccessPassword && msg.Channel == cs.RelayChannelOut) { Match m = cs.AccessPasswordRegex.Match(msg.Message); if (null != m) { m_log.DebugFormat("[IRC] relaying message from {0}: {1}", m.Groups["avatar"].ToString(), m.Groups["message"].ToString()); cs.irc.PrivMsg(cs.PrivateMessageFormat, m.Groups["avatar"].ToString(), scene.RegionInfo.RegionName, m.Groups["message"].ToString()); } } } public void Open() { cs.Open(this); enabled = true; } // Called by IRCBridgeModule.Close immediately prior to unload // of the module for this region. This happens when the region // is being removed or the server is terminating. The IRC // BridgeModule will remove the region from the region list // when control returns. // The agent has disconnected, cleanup associated resources internal void LocalChat(string msg) { if (enabled) { OSChatMessage osm = new OSChatMessage(); osm.From = "IRC Agent"; osm.Message = msg; osm.Type = ChatTypeEnum.Region; osm.Position = CenterOfRegion; osm.Sender = null; osm.SenderUUID = OpenMetaverse.UUID.Zero; // Hmph! Still? osm.Channel = 0; OSChat(this, osm); } } internal void OSChat(Object irc, OSChatMessage msg) { if (enabled) { // m_log.DebugFormat("[IRC-OSCHAT] Region {0} being sent message", region.Region); msg.Scene = scene; scene.EventManager.TriggerOnChatBroadcast(irc, msg); } } private void OnClientLoggedOut(IClientAPI client) { try { if (clients.Contains(client)) { if (enabled && (cs.irc.Enabled) && (cs.irc.Connected) && (cs.ClientReporting)) { m_log.InfoFormat("[IRC-Region {0}]: {1} has left", Region, client.Name); //Check if this person is excluded from IRC if (!cs.ExcludeList.Contains(client.Name.ToLower())) { cs.irc.PrivMsg(cs.NoticeMessageFormat, cs.irc.Nick, Region, String.Format("{0} has left", client.Name)); } } client.OnLogout -= OnClientLoggedOut; client.OnConnectionClosed -= OnClientLoggedOut; clients.Remove(client); } } catch (Exception ex) { m_log.ErrorFormat("[IRC-Region {0}]: ClientLoggedOut exception: {1}", Region, ex.Message); m_log.Debug(ex); } } // This event indicates that the agent has left the building. We should treat that the same // as if the agent has logged out (we don't want cross-region noise - or do we?) private void OnMakeChildAgent(ScenePresence presence) { IClientAPI client = presence.ControllingClient; try { if (clients.Contains(client)) { if (enabled && (cs.irc.Enabled) && (cs.irc.Connected) && (cs.ClientReporting)) { string clientName = String.Format("{0} {1}", presence.Firstname, presence.Lastname); m_log.DebugFormat("[IRC-Region {0}] {1} has left", Region, clientName); cs.irc.PrivMsg(cs.NoticeMessageFormat, cs.irc.Nick, Region, String.Format("{0} has left", clientName)); } client.OnLogout -= OnClientLoggedOut; client.OnConnectionClosed -= OnClientLoggedOut; clients.Remove(client); } } catch (Exception ex) { m_log.ErrorFormat("[IRC-Region {0}]: MakeChildAgent exception: {1}", Region, ex.Message); m_log.Debug(ex); } } // An agent has entered the region (from another region). Add the client to the locally // known clients list private void OnMakeRootAgent(ScenePresence presence) { IClientAPI client = presence.ControllingClient; try { if (!clients.Contains(client)) { client.OnLogout += OnClientLoggedOut; client.OnConnectionClosed += OnClientLoggedOut; clients.Add(client); if (enabled && (cs.irc.Enabled) && (cs.irc.Connected) && (cs.ClientReporting)) { string clientName = String.Format("{0} {1}", presence.Firstname, presence.Lastname); m_log.DebugFormat("[IRC-Region {0}] {1} has arrived", Region, clientName); //Check if this person is excluded from IRC if (!cs.ExcludeList.Contains(clientName.ToLower())) { cs.irc.PrivMsg(cs.NoticeMessageFormat, cs.irc.Nick, Region, String.Format("{0} has arrived", clientName)); } } } if (dialogModule != null && showAlert) dialogModule.SendAlertToUser(client, alertMessage, true); } catch (Exception ex) { m_log.ErrorFormat("[IRC-Region {0}]: MakeRootAgent exception: {1}", Region, ex.Message); m_log.Debug(ex); } } // This method gives the region an opportunity to interfere with // message delivery. For now we just enforce the enable/disable // flag. // This supports any local message traffic that might be needed in // support of command processing. At present there is none. } }
using System; using System.Collections.Generic; using System.Linq; using NetGore.Graphics; using NetGore.World; using SFML.Graphics; namespace NetGore.Features.Quests { /// <summary> /// Extends the drawing of the map to provide visual indicators for quests. /// </summary> /// <typeparam name="TCharacter">The type of character.</typeparam> public class QuestMapDrawingExtension<TCharacter> : MapDrawingExtension where TCharacter : ISpatial { readonly Func<IDrawableMap, IEnumerable<TCharacter>> _getQuestProviders; readonly Func<TCharacter, IEnumerable<QuestID>> _getQuests; readonly UserQuestInformation _questInfo; Func<QuestID, bool> _hasFinishQuestReqs; Func<QuestID, bool> _hasStartQuestReqs; Action<Grh, TCharacter, ISpriteBatch> _indicatorDrawer; /// <summary> /// Initializes a new instance of the <see cref="QuestMapDrawingExtension{TCharacter}"/> class. /// </summary> /// <param name="questInfo">The quest info.</param> /// <param name="hasStartQuestReqs">The <see cref="Func{T,U}"/> used to determine if the user has the /// requirements to start a quest.</param> /// <param name="hasFinishQuestReqs">The <see cref="Func{T,U}"/> used to determine if the user has the /// requirements to finish a quest.</param> /// <param name="getQuestProviders">The <see cref="Func{T,U}"/> used to get the quest providers from /// a map.</param> /// <param name="getQuests">The <see cref="Func{T,U}"/> used to get the quests provided by /// a quest provider.</param> public QuestMapDrawingExtension(UserQuestInformation questInfo, Func<QuestID, bool> hasStartQuestReqs, Func<QuestID, bool> hasFinishQuestReqs, Func<IDrawableMap, IEnumerable<TCharacter>> getQuestProviders, Func<TCharacter, IEnumerable<QuestID>> getQuests) { _questInfo = questInfo; _hasStartQuestReqs = hasStartQuestReqs; _hasFinishQuestReqs = hasFinishQuestReqs; _getQuestProviders = getQuestProviders; _getQuests = getQuests; _indicatorDrawer = DefaultIndicatorDrawer; } /// <summary> /// Gets or sets the <see cref="Func{T,U}"/> used to determine if the user has the requirements to /// finish a quest. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception> public Func<QuestID, bool> HasFinishQuestReqs { get { return _hasFinishQuestReqs; } set { if (value == null) throw new ArgumentNullException("value"); _hasFinishQuestReqs = value; } } /// <summary> /// Gets or sets the <see cref="Func{T,U}"/> used to determine if the user has the requirements to /// start a quest. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception> public Func<QuestID, bool> HasStartQuestReqs { get { return _hasStartQuestReqs; } set { if (value == null) throw new ArgumentNullException("value"); _hasStartQuestReqs = value; } } /// <summary> /// Gets or sets the <see cref="Action{T,U,V}"/> used to draw the quest indicator. /// If set to null, the default drawing indicator will be used. /// </summary> public Action<Grh, TCharacter, ISpriteBatch> IndicatorDrawer { get { return _indicatorDrawer; } set { _indicatorDrawer = value ?? DefaultIndicatorDrawer; } } /// <summary> /// Gets or sets the indicator for a quest provider that has quests that the user can start. /// If null, the indicator will not be drawn. /// </summary> public Grh QuestAvailableCanStartIndicator { get; set; } /// <summary> /// Gets or sets the indicator for a quest provider that has quests but the user does not meet /// the requirements to start any of them. /// If null, the indicator will not be drawn. /// </summary> public Grh QuestAvailableCannotStartIndicator { get; set; } /// <summary> /// Gets the <see cref="UserQuestInformation"/> for the user the indicators are being drawn for. /// </summary> public UserQuestInformation QuestInfo { get { return _questInfo; } } /// <summary> /// Gets or sets the indicator for a quest provider that has quests that the user has started. /// If null, the indicator will not be drawn. /// </summary> public Grh QuestStartedIndicator { get; set; } /// <summary> /// Gets or sets the indicator for a quest provider that has quests that the user has active and /// can turn in. /// If null, the indicator will not be drawn. /// </summary> public Grh QuestTurnInIndicator { get; set; } /// <summary> /// Gets if the any of the provided quests has the status of /// being able to be started. /// </summary> /// <param name="incomplete">The incomplete quests.</param> /// <returns>The state of the respective quest-providing status.</returns> bool CheckStatusCanStart(IEnumerable<QuestID> incomplete) { return incomplete.Any(x => !QuestInfo.ActiveQuests.Contains(x) && HasStartQuestReqs(x)); } /// <summary> /// Gets if the any of the provided quests has the status of /// not being started. /// </summary> /// <param name="incomplete">The incomplete quests.</param> /// <returns>The state of the respective quest-providing status.</returns> bool CheckStatusCannotStart(IEnumerable<QuestID> incomplete) { return incomplete.Any(x => !QuestInfo.ActiveQuests.Contains(x)); } /// <summary> /// Gets if the any of the provided quests has the status of /// being started. /// </summary> /// <param name="incomplete">The incomplete quests.</param> /// <returns>The state of the respective quest-providing status.</returns> bool CheckStatusStarted(IEnumerable<QuestID> incomplete) { return incomplete.Any(x => QuestInfo.ActiveQuests.Contains(x)); } /// <summary> /// Gets if the any of the provided quests has the status of /// being able to be turned in. /// </summary> /// <param name="incomplete">The incomplete quests.</param> /// <returns>The state of the respective quest-providing status.</returns> bool CheckStatusTurnIn(IEnumerable<QuestID> incomplete) { return incomplete.Any(x => QuestInfo.ActiveQuests.Contains(x) && HasFinishQuestReqs(x)); } /// <summary> /// The default quest indicator drawer. /// </summary> /// <param name="grh">The <see cref="Grh"/> to draw.</param> /// <param name="c">The character the indicator is for.</param> /// <param name="sb">The <see cref="ISpriteBatch"/> to use to draw.</param> protected virtual void DefaultIndicatorDrawer(Grh grh, TCharacter c, ISpriteBatch sb) { var pos = new Vector2(c.Center.X, c.Position.Y) - new Vector2(grh.Size.X / 2f, grh.Size.Y + 12); grh.Draw(sb, pos); } /// <summary> /// When overridden in the derived class, handles drawing to the map after the given <see cref="MapRenderLayer"/> is drawn. /// </summary> /// <param name="map">The map the drawing is taking place on.</param> /// <param name="e">The <see cref="NetGore.Graphics.DrawableMapDrawLayerEventArgs"/> instance containing the event data.</param> protected override void HandleDrawAfterLayer(IDrawableMap map, DrawableMapDrawLayerEventArgs e) { // Draw after dynamic layer finishes if (e.Layer != MapRenderLayer.Dynamic) return; // Update the valid sprites var currentTime = map.GetTime(); if (QuestStartedIndicator != null) QuestStartedIndicator.Update(currentTime); if (QuestTurnInIndicator != null) QuestTurnInIndicator.Update(currentTime); if (QuestAvailableCannotStartIndicator != null) QuestAvailableCannotStartIndicator.Update(currentTime); if (QuestAvailableCanStartIndicator != null) QuestAvailableCanStartIndicator.Update(currentTime); // Get all the quest providers in the area of interest (visible area) foreach (var c in _getQuestProviders(map)) { // Get the provided quests we have not completed or if it's repeatable var incomplete = _getQuests(c).Where(x => !QuestInfo.CompletedQuests.Contains(x) || QuestInfo.RepeatableQuests.Contains(x)).ToImmutable(); // If they don't have any quests, continue if (incomplete.IsEmpty()) continue; // For each of the four indicators, start at the "highest priority" one and stop when we find // the first valid status that we can use if (CheckStatusTurnIn(incomplete)) { IndicatorDrawer(QuestTurnInIndicator, c, e.SpriteBatch); continue; } else if (CheckStatusCanStart(incomplete)) { IndicatorDrawer(QuestAvailableCanStartIndicator, c, e.SpriteBatch); continue; } else if (CheckStatusStarted(incomplete)) { IndicatorDrawer(QuestStartedIndicator, c, e.SpriteBatch); continue; } else if (CheckStatusCannotStart(incomplete)) { IndicatorDrawer(QuestAvailableCannotStartIndicator, c, e.SpriteBatch); continue; } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; namespace System.Reflection.Metadata.Ecma335 { internal enum MetadataStreamKind { Illegal, Compressed, Uncompressed, } [Flags] internal enum TableMask : ulong { Module = 1UL << TableIndex.Module, TypeRef = 1UL << TableIndex.TypeRef, TypeDef = 1UL << TableIndex.TypeDef, FieldPtr = 1UL << TableIndex.FieldPtr, Field = 1UL << TableIndex.Field, MethodPtr = 1UL << TableIndex.MethodPtr, MethodDef = 1UL << TableIndex.MethodDef, ParamPtr = 1UL << TableIndex.ParamPtr, Param = 1UL << TableIndex.Param, InterfaceImpl = 1UL << TableIndex.InterfaceImpl, MemberRef = 1UL << TableIndex.MemberRef, Constant = 1UL << TableIndex.Constant, CustomAttribute = 1UL << TableIndex.CustomAttribute, FieldMarshal = 1UL << TableIndex.FieldMarshal, DeclSecurity = 1UL << TableIndex.DeclSecurity, ClassLayout = 1UL << TableIndex.ClassLayout, FieldLayout = 1UL << TableIndex.FieldLayout, StandAloneSig = 1UL << TableIndex.StandAloneSig, EventMap = 1UL << TableIndex.EventMap, EventPtr = 1UL << TableIndex.EventPtr, Event = 1UL << TableIndex.Event, PropertyMap = 1UL << TableIndex.PropertyMap, PropertyPtr = 1UL << TableIndex.PropertyPtr, Property = 1UL << TableIndex.Property, MethodSemantics = 1UL << TableIndex.MethodSemantics, MethodImpl = 1UL << TableIndex.MethodImpl, ModuleRef = 1UL << TableIndex.ModuleRef, TypeSpec = 1UL << TableIndex.TypeSpec, ImplMap = 1UL << TableIndex.ImplMap, FieldRva = 1UL << TableIndex.FieldRva, EnCLog = 1UL << TableIndex.EncLog, EnCMap = 1UL << TableIndex.EncMap, Assembly = 1UL << TableIndex.Assembly, // AssemblyProcessor = 1UL << TableIndices.AssemblyProcessor, // AssemblyOS = 1UL << TableIndices.AssemblyOS, AssemblyRef = 1UL << TableIndex.AssemblyRef, // AssemblyRefProcessor = 1UL << TableIndices.AssemblyRefProcessor, // AssemblyRefOS = 1UL << TableIndices.AssemblyRefOS, File = 1UL << TableIndex.File, ExportedType = 1UL << TableIndex.ExportedType, ManifestResource = 1UL << TableIndex.ManifestResource, NestedClass = 1UL << TableIndex.NestedClass, GenericParam = 1UL << TableIndex.GenericParam, MethodSpec = 1UL << TableIndex.MethodSpec, GenericParamConstraint = 1UL << TableIndex.GenericParamConstraint, PtrTables = FieldPtr | MethodPtr | ParamPtr | EventPtr | PropertyPtr, V2_0_TablesMask = Module | TypeRef | TypeDef | FieldPtr | Field | MethodPtr | MethodDef | ParamPtr | Param | InterfaceImpl | MemberRef | Constant | CustomAttribute | FieldMarshal | DeclSecurity | ClassLayout | FieldLayout | StandAloneSig | EventMap | EventPtr | Event | PropertyMap | PropertyPtr | Property | MethodSemantics | MethodImpl | ModuleRef | TypeSpec | ImplMap | FieldRva | EnCLog | EnCMap | Assembly | AssemblyRef | File | ExportedType | ManifestResource | NestedClass | GenericParam | MethodSpec | GenericParamConstraint, } internal enum HeapSizeFlag : byte { StringHeapLarge = 0x01, // 4 byte uint indexes used for string heap offsets GuidHeapLarge = 0x02, // 4 byte uint indexes used for GUID heap offsets BlobHeapLarge = 0x04, // 4 byte uint indexes used for Blob heap offsets EnCDeltas = 0x20, // Indicates only EnC Deltas are present DeletedMarks = 0x80, // Indicates metadata might contain items marked deleted } internal enum StringKind : byte { Plain = (byte)(StringHandleType.String >> HeapHandleType.OffsetBitCount), Virtual = (byte)(StringHandleType.VirtualString >> HeapHandleType.OffsetBitCount), WinRTPrefixed = (byte)(StringHandleType.WinRTPrefixedString >> HeapHandleType.OffsetBitCount), DotTerminated = (byte)(StringHandleType.DotTerminatedString >> HeapHandleType.OffsetBitCount), } internal enum NamespaceKind : byte { Plain = (byte)(NamespaceHandleType.Namespace >> HeapHandleType.OffsetBitCount), Synthetic = (byte)(NamespaceHandleType.SyntheticNamespace >> HeapHandleType.OffsetBitCount), } internal static class StringHandleType { // NUL-terminated UTF8 string on a #String heap. internal const uint String = 0; // String on #String heap whose terminator is NUL and '.', whichever comes first. internal const uint DotTerminatedString = String | (1 << HeapHandleType.OffsetBitCount); // Reserved values that can be used for future strings: internal const uint ReservedString1 = String | (2 << HeapHandleType.OffsetBitCount); internal const uint ReservedString2 = String | (3 << HeapHandleType.OffsetBitCount); // Virtual string identified by a virtual index internal const uint VirtualString = HeapHandleType.VirtualBit | String; // Virtual string whose value is a "<WinRT>" prefixed string found at the specified heap offset. internal const uint WinRTPrefixedString = HeapHandleType.VirtualBit | String | (1 << HeapHandleType.OffsetBitCount); // Reserved virtual strings that can be used in future: internal const uint ReservedVirtualString1 = HeapHandleType.VirtualBit | String | (2 << HeapHandleType.OffsetBitCount); internal const uint ReservedVirtaulString2 = HeapHandleType.VirtualBit | String | (3 << HeapHandleType.OffsetBitCount); } internal static class NamespaceHandleType { // Namespace handle for namespace with types of its own internal const uint Namespace = 0; // Namespace handle for namespace with child namespaces but no types of its own internal const uint SyntheticNamespace = Namespace | (1 << HeapHandleType.OffsetBitCount); // Reserved namespaces that can be used in future: internal const uint ReservedNamespace1 = Namespace | (2 << HeapHandleType.OffsetBitCount); internal const uint ReservedNamespace2 = Namespace | (3 << HeapHandleType.OffsetBitCount); // Reserved virtual namespaces that can be used in future: internal const uint ReservedVirtualNamespace1 = HeapHandleType.VirtualBit | Namespace; internal const uint ReservedVirtualNamespace2 = HeapHandleType.VirtualBit | Namespace | (1 << HeapHandleType.OffsetBitCount); internal const uint ReservedVirtualNamespace3 = HeapHandleType.VirtualBit | Namespace | (2 << HeapHandleType.OffsetBitCount); internal const uint ReservedVirtualNamespace4 = HeapHandleType.VirtualBit | Namespace | (3 << HeapHandleType.OffsetBitCount); } internal static class HeapHandleType { // Heap offset values are limited to 29 bits (max compressed integer) internal const int OffsetBitCount = 29; internal const uint OffsetMask = (1 << OffsetBitCount) - 1; internal const uint VirtualBit = 0x80000000; internal const uint NonVirtualTypeMask = 3u << OffsetBitCount; internal const uint TypeMask = VirtualBit | NonVirtualTypeMask; internal static bool IsValidHeapOffset(uint offset) { return (offset & ~OffsetMask) == 0; } } internal static class HandleType { internal const uint Module = 0x00; internal const uint TypeRef = 0x01; internal const uint TypeDef = 0x02; internal const uint FieldDef = 0x04; internal const uint MethodDef = 0x06; internal const uint ParamDef = 0x08; internal const uint InterfaceImpl = 0x09; internal const uint MemberRef = 0x0a; internal const uint Constant = 0x0b; internal const uint CustomAttribute = 0x0c; internal const uint DeclSecurity = 0x0e; internal const uint Signature = 0x11; internal const uint EventMap = 0x12; internal const uint Event = 0x14; internal const uint PropertyMap = 0x15; internal const uint Property = 0x17; internal const uint MethodSemantics = 0x18; internal const uint MethodImpl = 0x19; internal const uint ModuleRef = 0x1a; internal const uint TypeSpec = 0x1b; internal const uint Assembly = 0x20; internal const uint AssemblyRef = 0x23; internal const uint File = 0x26; internal const uint ExportedType = 0x27; internal const uint ManifestResource = 0x28; internal const uint NestedClass = 0x29; internal const uint GenericParam = 0x2a; internal const uint MethodSpec = 0x2b; internal const uint GenericParamConstraint = 0x2c; internal const uint UserString = 0x70; // #UserString heap // The following values never appear in a token stored in metadata, // they are just helper values to identify the type of a handle. internal const uint Blob = 0x71; // #Blob heap internal const uint Guid = 0x72; // #Guid heap // #String heap and its modifications (up to 8 string kinds, virtaul and non-virtual) internal const uint String = 0x78; internal const uint DotTerminatedString = String | ((StringHandleType.DotTerminatedString & ~HeapHandleType.VirtualBit) >> HeapHandleType.OffsetBitCount); internal const uint ReservedString1 = String | ((StringHandleType.ReservedString1 & ~HeapHandleType.VirtualBit) >> HeapHandleType.OffsetBitCount); internal const uint ReservedString2 = String | ((StringHandleType.ReservedString1 & ~HeapHandleType.VirtualBit) >> HeapHandleType.OffsetBitCount); internal const uint VirtualString = VirtualBit | String; internal const uint WinRTPrefixedString = VirtualBit | String | ((StringHandleType.WinRTPrefixedString & ~HeapHandleType.VirtualBit) >> HeapHandleType.OffsetBitCount); internal const uint ReservedVirtualString1 = VirtualBit | String | ((StringHandleType.ReservedString1 & ~HeapHandleType.VirtualBit) >> HeapHandleType.OffsetBitCount); internal const uint ReservedVirtualString2 = VirtualBit | String | ((StringHandleType.ReservedString2 & ~HeapHandleType.VirtualBit) >> HeapHandleType.OffsetBitCount); internal const uint Namespace = 0x7c; internal const uint SyntheticNamespace = Namespace | ((NamespaceHandleType.SyntheticNamespace & ~HeapHandleType.VirtualBit) >> HeapHandleType.OffsetBitCount); internal const uint ReservedNamespace1 = Namespace | ((NamespaceHandleType.ReservedNamespace1 & ~HeapHandleType.VirtualBit) >> HeapHandleType.OffsetBitCount); internal const uint ReservedNamespace2 = Namespace | ((NamespaceHandleType.ReservedNamespace2 & ~HeapHandleType.VirtualBit) >> HeapHandleType.OffsetBitCount); internal const uint ReservedVirtualNamespace1 = VirtualBit | Namespace | ((NamespaceHandleType.ReservedVirtualNamespace1 & ~HeapHandleType.VirtualBit) >> HeapHandleType.OffsetBitCount); internal const uint ReservedVirtualNamespace2 = VirtualBit | Namespace | ((NamespaceHandleType.ReservedVirtualNamespace2 & ~HeapHandleType.VirtualBit) >> HeapHandleType.OffsetBitCount); internal const uint ReservedVirtualNamespace3 = VirtualBit | Namespace | ((NamespaceHandleType.ReservedVirtualNamespace3 & ~HeapHandleType.VirtualBit) >> HeapHandleType.OffsetBitCount); internal const uint ReservedVirtualNamespace4 = VirtualBit | Namespace | ((NamespaceHandleType.ReservedVirtualNamespace4 & ~HeapHandleType.VirtualBit) >> HeapHandleType.OffsetBitCount); internal const uint StringHeapTypeMask = HeapHandleType.NonVirtualTypeMask >> HeapHandleType.OffsetBitCount; internal const uint StringOrNamespaceMask = 0x7c; internal const uint HeapMask = 0x70; internal const uint TypeMask = 0x7F; /// <summary> /// Use the highest bit to mark tokens that are virtual (synthesized). /// We create virtual tokens to represent projected WinMD entities. /// </summary> internal const uint VirtualBit = 0x80; public static HandleKind ToHandleKind(uint handleType) { Debug.Assert((handleType & VirtualBit) == 0); // Do not surface special string and namespace token sub-types (e.g. dot terminated, winrt prefixed, synthetic) // in public-facing handle type. Pretend that all strings/namespaces are just plain strings/namespaces. if (handleType > String) { return (HandleKind)(handleType & ~StringHeapTypeMask); } return (HandleKind)handleType; } } internal static class TokenTypeIds { internal const uint Module = HandleType.Module << RowIdBitCount; internal const uint TypeRef = HandleType.TypeRef << RowIdBitCount; internal const uint TypeDef = HandleType.TypeDef << RowIdBitCount; internal const uint FieldDef = HandleType.FieldDef << RowIdBitCount; internal const uint MethodDef = HandleType.MethodDef << RowIdBitCount; internal const uint ParamDef = HandleType.ParamDef << RowIdBitCount; internal const uint InterfaceImpl = HandleType.InterfaceImpl << RowIdBitCount; internal const uint MemberRef = HandleType.MemberRef << RowIdBitCount; internal const uint Constant = HandleType.Constant << RowIdBitCount; internal const uint CustomAttribute = HandleType.CustomAttribute << RowIdBitCount; internal const uint DeclSecurity = HandleType.DeclSecurity << RowIdBitCount; internal const uint Signature = HandleType.Signature << RowIdBitCount; internal const uint EventMap = HandleType.EventMap << RowIdBitCount; internal const uint Event = HandleType.Event << RowIdBitCount; internal const uint PropertyMap = HandleType.PropertyMap << RowIdBitCount; internal const uint Property = HandleType.Property << RowIdBitCount; internal const uint MethodSemantics = HandleType.MethodSemantics << RowIdBitCount; internal const uint MethodImpl = HandleType.MethodImpl << RowIdBitCount; internal const uint ModuleRef = HandleType.ModuleRef << RowIdBitCount; internal const uint TypeSpec = HandleType.TypeSpec << RowIdBitCount; internal const uint Assembly = HandleType.Assembly << RowIdBitCount; internal const uint AssemblyRef = HandleType.AssemblyRef << RowIdBitCount; internal const uint File = HandleType.File << RowIdBitCount; internal const uint ExportedType = HandleType.ExportedType << RowIdBitCount; internal const uint ManifestResource = HandleType.ManifestResource << RowIdBitCount; internal const uint NestedClass = HandleType.NestedClass << RowIdBitCount; internal const uint GenericParam = HandleType.GenericParam << RowIdBitCount; internal const uint MethodSpec = HandleType.MethodSpec << RowIdBitCount; internal const uint GenericParamConstraint = HandleType.GenericParamConstraint << RowIdBitCount; internal const uint UserString = HandleType.UserString << RowIdBitCount; internal const int RowIdBitCount = 24; internal const uint RIDMask = (1 << RowIdBitCount) - 1; internal const uint TypeMask = HandleType.TypeMask << RowIdBitCount; /// <summary> /// Use the highest bit to mark tokens that are virtual (synthesized). /// We create virtual tokens to represent projected WinMD entities. /// </summary> internal const uint VirtualBit = 0x80000000; /// <summary> /// Returns true if the token value can escape the metadata reader. /// We don't allow virtual tokens and heap tokens other than UserString to escape /// since the token type ids are internal to the reader and not specified by ECMA spec. /// /// Spec (Partition III, 1.9 Metadata tokens): /// Many CIL instructions are followed by a "metadata token". This is a 4-byte value, that specifies a row in a /// metadata table, or a starting byte offset in the User String heap. /// /// For example, a value of 0x02 specifies the TypeDef table; a value of 0x70 specifies the User /// String heap.The value corresponds to the number assigned to that metadata table (see Partition II for the full /// list of tables) or to 0x70 for the User String heap.The least-significant 3 bytes specify the target row within that /// metadata table, or starting byte offset within the User String heap. /// </summary> internal static bool IsEntityOrUserStringToken(uint vToken) { return (vToken & TypeMask) <= UserString; } internal static bool IsEntityToken(uint vToken) { return (vToken & TypeMask) < UserString; } internal static bool IsValidRowId(uint rowId) { return (rowId & ~RIDMask) == 0; } internal static bool IsValidRowId(int rowId) { return (rowId & ~RIDMask) == 0; } } }
/* * REST API Documentation for Schoolbus * * API Sample * * OpenAPI spec version: v1 * * */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using SchoolBusAPI.Models; using Microsoft.EntityFrameworkCore; using SchoolBusAPI.Mappings; using SchoolBusAPI.ViewModels; using Microsoft.Extensions.Configuration; using Microsoft.AspNetCore.Http; using System.Net.Http; using System.Text; using Microsoft.AspNetCore.WebUtilities; using SchoolBusCommon; namespace SchoolBusAPI.Services.Impl { /// <summary> /// /// </summary> public class SchoolBusService : ServiceBase, ISchoolBusService { private readonly DbAppContext _context; private readonly IConfiguration Configuration; /// <summary> /// Create a service and set the database context /// </summary> public SchoolBusService(IHttpContextAccessor httpContextAccessor, IConfiguration configuration, DbAppContext context) : base(httpContextAccessor, context) { _context = context; Configuration = configuration; } /// <summary> /// Adjust a SchoolBus item to ensure child object data is in place correctly /// </summary> /// <param name="item"></param> private void AdjustSchoolBus(SchoolBus item) { if (item != null) { if (item.SchoolBusOwner != null) { int school_bus_owner_id = item.SchoolBusOwner.Id; bool school_bus_owner_exists = _context.SchoolBusOwners.Any(a => a.Id == school_bus_owner_id); if (school_bus_owner_exists) { SchoolBusOwner school_bus_owner = _context.SchoolBusOwners.First(a => a.Id == school_bus_owner_id); item.SchoolBusOwner = school_bus_owner; } else // invalid data { item.SchoolBusOwner = null; } } // adjust District. if (item.District != null) { int district_id = item.District.Id; var district_exists = _context.Districts.Any(a => a.Id == district_id); if (district_exists) { District district = _context.Districts.First(a => a.Id == district_id); item.District = district; } else { item.District = null; } } // adjust school district if (item.SchoolDistrict != null) { int schoolDistrict_id = item.SchoolDistrict.Id; bool schoolDistrict_exists = _context.SchoolDistricts.Any(a => a.Id == schoolDistrict_id); if (schoolDistrict_exists) { SchoolDistrict school_district = _context.SchoolDistricts.First(a => a.Id == schoolDistrict_id); item.SchoolDistrict = school_district; } else // invalid data { item.SchoolDistrict = null; } } // adjust home city if (item.HomeTerminalCity != null) { int city_id = item.HomeTerminalCity.Id; bool city_exists = _context.Cities.Any(a => a.Id == city_id); if (city_exists) { City city = _context.Cities.First(a => a.Id == city_id); item.HomeTerminalCity = city; } else // invalid data { item.HomeTerminalCity = null; } } // adjust inspector if (item.Inspector != null) { int inspector_id = item.Inspector.Id; bool inspector_exists = _context.Users.Any(a => a.Id == inspector_id); if (inspector_exists) { User inspector = _context.Users.First(a => a.Id == inspector_id); item.Inspector = inspector; } else // invalid data { item.Inspector = null; } } // adjust CCWData if (item.CCWData != null) { int ccwdata_id = item.CCWData.Id; bool ccwdata_exists = _context.CCWDatas.Any(a => a.Id == ccwdata_id); if (ccwdata_exists) { CCWData ccwdata = _context.CCWDatas.First(a => a.Id == ccwdata_id); item.CCWData = ccwdata; } else // invalid data { item.CCWData = null; } } } } /// <summary> /// Creates several school buses /// </summary> /// <remarks>Used for bulk creation of schoolbus records.</remarks> /// <param name="body"></param> /// <response code="201">SchoolBus items created</response> public virtual IActionResult SchoolbusesBulkPostAsync (SchoolBus[] items) { if (items == null) { return new BadRequestResult(); } foreach (SchoolBus item in items) { // adjust school bus owner AdjustSchoolBus(item); var exists = _context.SchoolBuss.Any(a => a.Id == item.Id); if (exists) { _context.SchoolBuss.Update(item); } else { _context.SchoolBuss.Add(item); } } // Save the changes _context.SaveChanges(); return new NoContentResult(); } /// <summary> /// Returns a single school bus object /// </summary> /// <remarks></remarks> /// <param name="id">Id of SchoolBus to fetch</param> /// <response code="200">OK</response> /// <response code="404">Not Found</response> public virtual IActionResult SchoolbusesIdGetAsync (int id) { bool exists = _context.SchoolBuss.Any(a => a.Id == id); if (exists) { var result = _context.SchoolBuss .Include(x => x.HomeTerminalCity) .Include(x => x.SchoolDistrict) .Include(x => x.SchoolBusOwner.PrimaryContact) .Include(x => x.District.Region) .Include(x => x.Inspector) .Include(x => x.CCWData) .First(a => a.Id == id); return new ObjectResult(result); } else { return new StatusCodeResult(404); } } /// <summary> /// Returns a collection of school buses /// </summary> /// <remarks></remarks> /// <response code="200">OK</response> public virtual IActionResult SchoolbusesGetAsync () { var result = _context.SchoolBuss .Include(x => x.HomeTerminalCity) .Include(x => x.SchoolDistrict) .Include(x => x.SchoolBusOwner.PrimaryContact) .Include(x => x.District.Region) .Include(x => x.Inspector) .Include(x => x.CCWData) .ToList(); return new ObjectResult(result); } /// <summary> /// /// </summary> /// <remarks>Returns attachments for a particular SchoolBus</remarks> /// <param name="id">id of SchoolBus to fetch attachments for</param> /// <response code="200">OK</response> /// <response code="404">SchoolBus not found</response> public virtual IActionResult SchoolbusesIdAttachmentsGetAsync (int id) { bool exists = _context.SchoolBuss.Any(a => a.Id == id); if (exists) { SchoolBus schoolBus = _context.SchoolBuss .Include(x => x.Attachments) .First(a => a.Id == id); var result = MappingExtensions.GetAttachmentListAsViewModel(schoolBus.Attachments); return new ObjectResult(result); } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// /// </summary> /// <remarks>Returns CCWData for a particular Schoolbus</remarks> /// <param name="id">id of SchoolBus to fetch CCWData for</param> /// <response code="200">OK</response> public virtual IActionResult SchoolbusesIdCcwdataGetAsync (int id) { // validate the bus id bool exists = _context.SchoolBuss.Any(a => a.Id == id); if (exists) { SchoolBus schoolbus = _context.SchoolBuss.Where(a => a.Id == id).First(); string regi = schoolbus.ICBCRegistrationNumber; // get CCW data for this bus. // could be none. // validate the bus id bool ccw_exists = _context.CCWDatas.Any(a => a.ICBCRegistrationNumber == regi); if (ccw_exists) { var result = _context.CCWDatas.Where(a => a.ICBCRegistrationNumber == regi).First(); return new ObjectResult(result); } else { // record not found CCWData[] nodata = new CCWData[0]; return new ObjectResult (nodata); } } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// /// </summary> /// <param name="id">id of SchoolBus to delete</param> /// <response code="200">OK</response> /// <response code="404">SchoolBus not found</response> public virtual IActionResult SchoolbusesIdDeletePostAsync (int id) { bool exists = _context.SchoolBuss.Any(a => a.Id == id); if (exists) { var item = _context.SchoolBuss.First(a => a.Id == id); if (item != null) { _context.SchoolBuss.Remove(item); // Save the changes _context.SaveChanges(); } return new ObjectResult(item); } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// /// </summary> /// <remarks>Returns History for a particular SchoolBus</remarks> /// <param name="id">id of SchoolBus to fetch SchoolBusHistory for</param> /// <response code="200">OK</response> public virtual IActionResult SchoolbusesIdHistoryGetAsync (int id, int? offset, int? limit) { bool exists = _context.SchoolBuss.Any(a => a.Id == id); if (exists) { SchoolBus schoolBus = _context.SchoolBuss .Include(x => x.History) .First(a => a.Id == id); List<History> data = schoolBus.History.OrderByDescending(y => y.LastUpdateTimestamp).ToList(); if (offset == null) { offset = 0; } if (limit == null) { limit = data.Count() - offset; } List<HistoryViewModel> result = new List<HistoryViewModel>(); for (int i = (int)offset; i < data.Count() && i < offset + limit; i++) { result.Add(data[i].ToViewModel(id)); } return new ObjectResult(result); } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// /// </summary> /// <remarks>Add a History record to the SchoolBus</remarks> /// <param name="id">id of SchoolBus to fetch History for</param> /// <param name="item"></param> /// <response code="201">History created</response> public virtual IActionResult SchoolbusesIdHistoryPostAsync(int id, History item) { HistoryViewModel result = new HistoryViewModel(); bool exists = _context.SchoolBuss.Any(a => a.Id == id); if (exists) { SchoolBus schoolBus = _context.SchoolBuss .Include(x => x.History) .First(a => a.Id == id); if (schoolBus.History == null) { schoolBus.History = new List<History>(); } // force add item.Id = 0; schoolBus.History.Add(item); _context.SchoolBuss.Update(schoolBus); _context.SaveChanges(); } result.HistoryText = item.HistoryText; result.Id = item.Id; result.LastUpdateTimestamp = item.LastUpdateTimestamp; result.LastUpdateUserid = item.LastUpdateUserid; result.AffectedEntityId = id; return new ObjectResult(result); } /// <summary> /// /// </summary> /// <remarks>Returns notes for a particular SchoolBus.</remarks> /// <param name="id">id of SchoolBus to fetch notes for</param> /// <response code="200">OK</response> /// <response code="404">SchoolBus not found</response> public virtual IActionResult SchoolbusesIdNotesGetAsync (int id) { bool exists = _context.SchoolBuss.Any(a => a.Id == id); if (exists) { SchoolBus schoolBus = _context.SchoolBuss .Include(x => x.Notes) .First(a => a.Id == id); var result = schoolBus.Notes; return new ObjectResult(result); } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// Returns a PDF Permit /// </summary> /// <param name="id"></param> /// <returns></returns> public virtual IActionResult SchoolbusesIdPdfpermitGetAsync (int id) { FileContentResult result = null; bool exists = _context.SchoolBuss.Any(a => a.Id == id); if (exists) { SchoolBus schoolBus = _context.SchoolBuss .Include(x => x.CCWData) .Include(x => x.SchoolBusOwner.PrimaryContact) .Include(x => x.SchoolDistrict) .First(a => a.Id == id); // construct the view model. PermitViewModel permitViewModel = new PermitViewModel(); // only do the ICBC fields if the CCW data is available. if (schoolBus.CCWData != null) { permitViewModel.IcbcMake = schoolBus.CCWData.ICBCMake; permitViewModel.IcbcModelYear = schoolBus.CCWData.ICBCModelYear; permitViewModel.IcbcRegistrationNumber = schoolBus.CCWData.ICBCRegistrationNumber; permitViewModel.VehicleIdentificationNumber = schoolBus.CCWData.ICBCVehicleIdentificationNumber; permitViewModel.SchoolBusOwnerAddressLine1 = schoolBus.CCWData.ICBCRegOwnerAddr1; // line 2 is a combination of the various fields that may contain data. List<string> strings = new List<string>(); if (! string.IsNullOrWhiteSpace (schoolBus.CCWData.ICBCRegOwnerAddr2)) { strings.Add(schoolBus.CCWData.ICBCRegOwnerAddr2); } if (!string.IsNullOrWhiteSpace(schoolBus.CCWData.ICBCRegOwnerCity)) { strings.Add(schoolBus.CCWData.ICBCRegOwnerCity); } if (!string.IsNullOrWhiteSpace(schoolBus.CCWData.ICBCRegOwnerProv)) { strings.Add(schoolBus.CCWData.ICBCRegOwnerProv); } if (!string.IsNullOrWhiteSpace(schoolBus.CCWData.ICBCRegOwnerPostalCode)) { strings.Add(schoolBus.CCWData.ICBCRegOwnerPostalCode); } if (strings.Count > 0) { permitViewModel.SchoolBusOwnerAddressLine2 = String.Join(", ", strings); } permitViewModel.SchoolBusOwnerPostalCode = schoolBus.CCWData.ICBCRegOwnerPostalCode; permitViewModel.SchoolBusOwnerProvince = schoolBus.CCWData.ICBCRegOwnerProv; permitViewModel.SchoolBusOwnerCity = schoolBus.CCWData.ICBCRegOwnerCity; permitViewModel.SchoolBusOwnerName = schoolBus.CCWData.ICBCRegOwnerName; } permitViewModel.PermitIssueDate = null; if (schoolBus.PermitIssueDate != null) { // Since the PDF template is raw HTML and won't convert a date object, we must adjust the time zone here. TimeZoneInfo tzi = null; try { // try the IANA timzeone first. tzi = TimeZoneInfo.FindSystemTimeZoneById("America / Vancouver"); } catch (Exception e) { tzi = null; } if (tzi == null) { try { tzi = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); } catch (Exception e) { tzi = null; } } DateTime dto = DateTime.UtcNow; if (tzi != null) { dto = TimeZoneInfo.ConvertTime((DateTime)schoolBus.PermitIssueDate, tzi); } else { dto = (DateTime) schoolBus.PermitIssueDate; } permitViewModel.PermitIssueDate = dto.ToString("yyyy-MM-dd"); } permitViewModel.PermitNumber = schoolBus.PermitNumber; permitViewModel.RestrictionsText = schoolBus.RestrictionsText; permitViewModel.SchoolBusMobilityAidCapacity = schoolBus.MobilityAidCapacity.ToString(); permitViewModel.UnitNumber = schoolBus.UnitNumber; permitViewModel.PermitClassCode = schoolBus.PermitClassCode; permitViewModel.BodyTypeCode = schoolBus.BodyTypeCode; permitViewModel.SchoolBusSeatingCapacity = schoolBus.SchoolBusSeatingCapacity; if (schoolBus.SchoolDistrict != null) { permitViewModel.SchoolDistrictshortName = schoolBus.SchoolDistrict.ShortName; } string payload = JsonConvert.SerializeObject(permitViewModel); // pass the request on to the PDF Micro Service string pdfHost = Configuration["PDF_SERVICE_NAME"]; string targetUrl = pdfHost + "/api/PDF/GetPDF"; // call the microservice try { HttpClient client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Post, targetUrl); request.Content = new StringContent(payload, Encoding.UTF8, "application/json"); request.Headers.Clear(); // transfer over the request headers. foreach (var item in Request.Headers) { string key = item.Key; string value = item.Value; request.Headers.Add(key, value); } Task<HttpResponseMessage> responseTask = client.SendAsync(request); responseTask.Wait(); HttpResponseMessage response = responseTask.Result; if (response.StatusCode == HttpStatusCode.OK) // success { var bytetask = response.Content.ReadAsByteArrayAsync(); bytetask.Wait(); result = new FileContentResult(bytetask.Result, "application/pdf"); result.FileDownloadName = "Permit-" + schoolBus.PermitNumber + ".pdf"; } } catch (Exception e) { result = null; } // check that the result has a value if (result != null) { return result; } else { return new StatusCodeResult(400); // problem occured } } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// Updates a single school bus object /// </summary> /// <remarks></remarks> /// <param name="id">Id of SchoolBus to fetch</param> /// <response code="200">OK</response> /// <response code="404">Not Found</response> public virtual IActionResult SchoolbusesIdPutAsync (int id, SchoolBus item) { // adjust school bus owner AdjustSchoolBus(item); bool exists = _context.SchoolBuss.Any(a => a.Id == id); if (exists && id == item.Id) { _context.SchoolBuss.Update(item); // Save the changes _context.SaveChanges(); return new ObjectResult(item); } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// /// </summary> /// <param name="item"></param> /// <response code="201">SchoolBus created</response> public virtual IActionResult SchoolbusesPostAsync(SchoolBus item) { // adjust school bus owner AdjustSchoolBus(item); bool exists = _context.SchoolBuss.Any(a => a.Id == item.Id); if (exists) { _context.SchoolBuss.Update(item); // Save the changes } else { // record not found _context.SchoolBuss.Add(item); } _context.SaveChanges(); return new ObjectResult(item); } /// <param name="id">id of SchoolBus to fetch Inspections for</param> /// <response code="200">OK</response> /// <response code="404">SchoolBus not found</response> public virtual IActionResult SchoolbusesIdInspectionsGetAsync(int id) { bool exists = _context.SchoolBuss.Any(a => a.Id == id); if (exists) { var items = _context.Inspections .Include(x => x.Inspector) .Include(x => x.SchoolBus) .Where(a => a.SchoolBus.Id == id); return new ObjectResult(items); } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// /// </summary> /// <remarks>Obtains a new permit number for the indicated Schoolbus. Returns the updated SchoolBus record.</remarks> /// <param name="id">id of SchoolBus to obtain a new permit number for</param> /// <response code="200">OK</response> public virtual IActionResult SchoolbusesIdNewpermitPutAsync(int id) { bool exists = _context.SchoolBuss.Any(a => a.Id == id); if (exists) { // get the current max permit number. int permit = 36000; var maxPermitRecord = _context.SchoolBuss .OrderByDescending(x => x.PermitNumber) .FirstOrDefault(x => x.PermitNumber != null); if (maxPermitRecord != null) { permit = (int)maxPermitRecord.PermitNumber + 1; } var item = _context.SchoolBuss .Include(x => x.HomeTerminalCity) .Include(x => x.SchoolDistrict) .Include(x => x.SchoolBusOwner.PrimaryContact) .Include(x => x.District.Region) .Include(x => x.Inspector) .Include(x => x.CCWData) .First(a => a.Id == id); item.PermitNumber = permit; item.PermitIssueDate = DateTime.UtcNow; _context.SchoolBuss.Update(item); _context.SaveChanges(); return new ObjectResult(item); } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// Searches school buses /// </summary> /// <remarks>Used for the search schoolbus page.</remarks> /// <param name="districts">Districts (array of id numbers)</param> /// <param name="inspectors">Assigned School Bus Inspectors (array of id numbers)</param> /// <param name="cities">Cities (array of id numbers)</param> /// <param name="schooldistricts">School Districts (array of id numbers)</param> /// <param name="owner"></param> /// <param name="regi">e Regi Number</param> /// <param name="vin">VIN</param> /// <param name="plate">License Plate String</param> /// <param name="includeInactive">True if Inactive schoolbuses will be returned</param> /// <param name="onlyReInspections">If true, only buses that need a re-inspection will be returned</param> /// <param name="startDate">Inspection start date</param> /// <param name="endDate">Inspection end date</param> /// <response code="200">OK</response> public IActionResult SchoolbusesSearchGetAsync(int?[] districts, int?[] inspectors, int?[] cities, int?[] schooldistricts, int? owner, string regi, string vin, string plate, bool? includeInactive, bool? onlyReInspections, DateTime? startDate, DateTime? endDate) { // Eager loading of related data var data = _context.SchoolBuss .Include(x => x.HomeTerminalCity) .Include(x => x.SchoolBusOwner) .Include(x => x.District) .Include(x => x.Inspector) .Select(x => x); bool keySearch = false; // do key search fields first. if (regi != null) { // first convert the regi to a number. int tempRegi; bool parsed = int.TryParse(regi, out tempRegi); if (parsed) { regi = tempRegi.ToString(); } data = data.Where(x => x.ICBCRegistrationNumber.Contains(regi)); keySearch = true; } if (vin != null) { // Normalize vin to ignore case and whitespaces vin = vin.Replace(" ", String.Empty).ToUpperInvariant(); data = data.Where(x => x.VehicleIdentificationNumber.ToUpperInvariant().Contains(vin)); keySearch = true; } if (plate != null) { // Normalize plate to ignore case and whitespaces plate = plate.Replace(" ", String.Empty).ToUpperInvariant(); data = data.Where(x => x.LicencePlateNumber.Replace(" ", String.Empty).ToUpperInvariant().Contains(plate)); keySearch = true; } // only search other fields if a key search was not done. if (!keySearch) { if (districts != null) { data = data.Where(x => districts.Contains(x.DistrictId)); } if (inspectors != null) { data = data.Where(x => inspectors.Contains(x.InspectorId)); } if (cities != null) { data = data.Where(x => cities.Contains(x.HomeTerminalCityId)); } if (schooldistricts != null) { data = data.Where(x => schooldistricts.Contains(x.SchoolDistrictId)); } if (owner != null) { data = data.Where(x => x.SchoolBusOwner.Id == owner); } if (includeInactive == null || (includeInactive != null && includeInactive == false)) { data = data.Where(x => x.Status.ToLower() == "active"); } if (onlyReInspections != null && onlyReInspections == true) { data = data.Where(x => x.NextInspectionTypeCode.ToLower() == "re-inspection"); } if (startDate != null) { data = data.Where(x => x.NextInspectionDate >= startDate); } if (endDate != null) { data = data.Where(x => x.NextInspectionDate <= endDate); } } var result = data.ToList(); return new ObjectResult(result); } } }
#region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Windows.Forms; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Autodesk.Revit.UI.Selection; #endregion // Namespaces namespace BipChecker { /// <summary> /// A collection of utility methods reused in several labs. /// </summary> static class Util { #region Formatting and message handlers public const string Caption = "Built-in Parameter Checker"; /// <summary> /// Return an English plural suffix 's' or /// nothing for the given number of items. /// </summary> public static string PluralSuffix( int n ) { return 1 == n ? "" : "s"; } /// <summary> /// Return a dot for zero items, or a colon for more. /// </summary> public static string DotOrColon( int n ) { return 0 < n ? ":" : "."; } /// <summary> /// Format a real number and return its string representation. /// </summary> public static string RealString( double a ) { return a.ToString( "0.##" ); } /// <summary> /// Format a point or vector and return its string representation. /// </summary> public static string PointString( XYZ p ) { return string.Format( "({0},{1},{2})", RealString( p.X ), RealString( p.Y ), RealString( p.Z ) ); } /// <summary> /// Return a description string for a given element. /// </summary> public static string ElementDescription( Element e ) { string description = ( null == e.Category ) ? e.GetType().Name : e.Category.Name; FamilyInstance fi = e as FamilyInstance; if( null != fi ) { description += " '" + fi.Symbol.Family.Name + "'"; } if( null != e.Name ) { description += " '" + e.Name + "'"; } return description; } /// <summary> /// Return a description string including element id for a given element. /// </summary> public static string ElementDescription( Element e, bool includeId ) { string description = ElementDescription( e ); if( includeId ) { description += " " + e.Id.IntegerValue.ToString(); } return description; } /// <summary> /// Revit TaskDialog wrapper for a short informational message. /// </summary> public static void InfoMsg( string msg ) { Debug.WriteLine( msg ); //WinForms.MessageBox.Show( msg, Caption, WinForms.MessageBoxButtons.OK, WinForms.MessageBoxIcon.Information ); TaskDialog.Show( Caption, msg, TaskDialogCommonButtons.Ok ); } /// <summary> /// Revit TaskDialog wrapper for a message /// with separate main instruction and content. /// </summary> public static void InfoMsg( string msg, string content ) { Debug.WriteLine( msg ); Debug.WriteLine( content ); TaskDialog d = new TaskDialog( Caption ); d.MainInstruction = msg; d.MainContent = content; d.Show(); } /// <summary> /// MessageBox wrapper for error message. /// </summary> public static void ErrorMsg( string msg ) { Debug.WriteLine( msg ); //WinForms.MessageBox.Show( msg, Caption, WinForms.MessageBoxButtons.OK, WinForms.MessageBoxIcon.Error ); TaskDialog d = new TaskDialog( Caption ); d.MainIcon = TaskDialogIcon.TaskDialogIconWarning; d.MainInstruction = msg; d.Show(); } /// <summary> /// MessageBox wrapper for question message. /// </summary> public static bool QuestionMsg( string msg ) { Debug.WriteLine( msg ); //bool rc = WinForms.DialogResult.Yes // == WinForms.MessageBox.Show( msg, Caption, WinForms.MessageBoxButtons.YesNo, WinForms.MessageBoxIcon.Question ); //Debug.WriteLine( rc ? "Yes" : "No" ); //return rc; TaskDialog d = new TaskDialog( Caption ); d.MainIcon = TaskDialogIcon.TaskDialogIconNone; d.MainInstruction = msg; //d.CommonButtons = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No; d.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Instance parameters"); d.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Type parameters"); //d.DefaultButton = TaskDialogResult.Yes; //return TaskDialogResult.Yes == d.Show(); return d.Show() == TaskDialogResult.CommandLink1; } /// <summary> /// MessageBox wrapper for question and cancel message. /// </summary> public static TaskDialogResult QuestionCancelMsg( string msg ) { Debug.WriteLine( msg ); //WinForms.DialogResult rc = WinForms.MessageBox.Show( msg, Caption, WinForms.MessageBoxButtons.YesNoCancel, WinForms.MessageBoxIcon.Question ); //Debug.WriteLine( rc.ToString() ); //return rc; TaskDialog d = new TaskDialog( Caption ); d.MainIcon = TaskDialogIcon.TaskDialogIconNone; d.MainInstruction = msg; d.CommonButtons = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No | TaskDialogCommonButtons.Cancel; d.DefaultButton = TaskDialogResult.Yes; return d.Show(); } #endregion // Formatting and message handlers #region Selection public static Element GetSingleSelectedElementOrPrompt( UIDocument uidoc ) { Element e = null; ICollection<ElementId> ids = uidoc.Selection.GetElementIds(); // 2015 if( 1 == ids.Count ) { foreach( ElementId id in ids ) { e = uidoc.Document.GetElement( id ); } } else { string sid; DialogResult result = DialogResult.OK; while( null == e && DialogResult.OK == result ) { using( ElementIdForm form = new ElementIdForm() ) { result = form.ShowDialog(); sid = form.ElementId; } if( DialogResult.OK == result ) { if( 0 == sid.Length ) { try { Reference r = uidoc.Selection.PickObject( ObjectType.Element, "Please pick an element" ); //e = r.Element; // 2011 e = uidoc.Document.GetElement( r ); // 2012 } catch( OperationCanceledException ) { } } else { int id; if( int.TryParse( sid, out id ) ) { ElementId elementId = new ElementId( id ); e = uidoc.Document.GetElement( elementId ); if( null == e ) { ErrorMsg( string.Format( "Invalid element id '{0}'.", sid ) ); } } else { e = uidoc.Document.GetElement( sid ); if( null == e ) { ErrorMsg( string.Format( "Invalid element id '{0}'.", sid ) ); } } } } } } return e; } /// <summary> /// A selection filter for a specific System.Type. /// </summary> class TypeSelectionFilter : ISelectionFilter { Type _type; public TypeSelectionFilter( Type type ) { _type = type; } /// <summary> /// Allow an element of the specified System.Type to be selected. /// </summary> /// <param name="element">A candidate element in selection operation.</param> /// <returns>Return true for specified System.Type, false for all other elements.</returns> public bool AllowElement( Element e ) { //return null != e.Category // && e.Category.Id.IntegerValue == ( int ) _bic; return e.GetType().Equals( _type ); } /// <summary> /// Allow all the reference to be selected /// </summary> /// <param name="refer">A candidate reference in selection operation.</param> /// <param name="point">The 3D position of the mouse on the candidate reference.</param> /// <returns>Return true to allow the user to select this candidate reference.</returns> public bool AllowReference( Reference r, XYZ p ) { return true; } } public static Element GetSingleSelectedElementOrPrompt( UIDocument uidoc, Type type ) { Element e = null; ICollection<ElementId> ids = uidoc.Selection.GetElementIds(); // 2015 if( 1 == ids.Count ) { Element e2 = null; foreach( ElementId id in ids ) { e2 = uidoc.Document.GetElement( id ); } Type t = e2.GetType(); if( t.Equals( type ) || t.IsSubclassOf( type ) ) { e = e2; } } if( null == e ) { try { Reference r = uidoc.Selection.PickObject( ObjectType.Element, new TypeSelectionFilter( type ), string.Format( "Please pick a {0} element", type.Name ) ); //e = r.Element; // 2011 e = uidoc.Document.GetElement( r ); // 2012 } catch( OperationCanceledException ) { } } return e; } #endregion // Selection #region Helpers for parameters /// <summary> /// Helper to return parameter value as string. /// One can also use param.AsValueString() to /// get the user interface representation. /// </summary> public static string GetParameterValue( Parameter param ) { string s; switch( param.StorageType ) { case StorageType.Double: // // the internal database unit for all lengths is feet. // for instance, if a given room perimeter is returned as // 102.36 as a double and the display unit is millimeters, // then the length will be displayed as // peri = 102.36220472440 // peri * 12 * 25.4 // 31200 mm // //s = param.AsValueString(); // value seen by user, in display units //s = param.AsDouble().ToString(); // if not using not using LabUtils.RealString() s = RealString( param.AsDouble() ); // raw database value in internal units, e.g. feet break; case StorageType.Integer: s = param.AsInteger().ToString(); break; case StorageType.String: s = param.AsString(); break; case StorageType.ElementId: s = param.AsElementId().IntegerValue.ToString(); break; case StorageType.None: s = "?NONE?"; break; default: s = "?ELSE?"; break; } return s; } static int _min_bic = 0; static int _max_bic = 0; static void SetMinAndMaxBuiltInCategory() { Array a = Enum.GetValues( typeof( BuiltInCategory ) ); _max_bic = a.Cast<int>().Max(); _min_bic = a.Cast<int>().Min(); } static string BuiltInCategoryString( int i ) { if( 0 == _min_bic ) { SetMinAndMaxBuiltInCategory(); } return ( _min_bic < i && i < _max_bic ) ? " " + ( (BuiltInCategory) i ).ToString() : string.Empty; } /// <summary> /// Helper to return parameter value as string, with additional /// support for element id to display the element type referred to. /// </summary> public static string GetParameterValue2( Parameter param, Document doc ) { string s; if( StorageType.ElementId == param.StorageType && null != doc ) { ElementId id = param.AsElementId(); int i = id.IntegerValue; if( 0 > i ) { s = i.ToString() + BuiltInCategoryString( i ); } else { Element e = doc.GetElement( id ); s = ElementDescription( e, true ); } } else { s = GetParameterValue( param ); } return s; } #endregion // Helpers for parameters } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections.Generic; using System.Xml; using System.Management.Automation.Internal; namespace Microsoft.PowerShell.Commands.Internal.Format { /// <summary> /// class to load the XML document into data structures. /// It encapsulates the file format specific code /// </summary> internal sealed partial class TypeInfoDataBaseLoader : XmlLoaderBase { private ListControlBody LoadListControl(XmlNode controlNode) { using (this.StackFrame(controlNode)) { ListControlBody listBody = new ListControlBody(); bool listViewEntriesFound = false; foreach (XmlNode n in controlNode.ChildNodes) { if (MatchNodeName(n, XmlTags.ListEntriesNode)) { if (listViewEntriesFound) { this.ProcessDuplicateNode(n); continue; } listViewEntriesFound = true; // now read the columns section LoadListControlEntries(n, listBody); if (listBody.defaultEntryDefinition == null) { return null; // fatal error } } else { this.ProcessUnknownNode(n); } } if (!listViewEntriesFound) { this.ReportMissingNode(XmlTags.ListEntriesNode); return null; // fatal error } return listBody; } } private void LoadListControlEntries(XmlNode listViewEntriesNode, ListControlBody listBody) { using (this.StackFrame(listViewEntriesNode)) { int entryIndex = 0; foreach (XmlNode n in listViewEntriesNode.ChildNodes) { if (MatchNodeName(n, XmlTags.ListEntryNode)) { ListControlEntryDefinition lved = LoadListControlEntryDefinition(n, entryIndex++); if (lved == null) { //Error at XPath {0} in file {1}: {2} failed to load. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.LoadTagFailed, ComputeCurrentXPath(), FilePath, XmlTags.ListEntryNode)); listBody.defaultEntryDefinition = null; return; // fatal error } // determine if we have a default entry and if it's already set if (lved.appliesTo == null) { if (listBody.defaultEntryDefinition == null) { listBody.defaultEntryDefinition = lved; } else { //Error at XPath {0} in file {1}: There cannot be more than one default {2}. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.TooManyDefaultShapeEntry, ComputeCurrentXPath(), FilePath, XmlTags.ListEntryNode)); listBody.defaultEntryDefinition = null; return; // fatal error } } else { listBody.optionalEntryList.Add(lved); } } else { this.ProcessUnknownNode(n); } } if (listBody.optionalEntryList == null) { //Error at XPath {0} in file {1}: There must be at least one default {2}. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NoDefaultShapeEntry, ComputeCurrentXPath(), FilePath, XmlTags.ListEntryNode)); } } } private ListControlEntryDefinition LoadListControlEntryDefinition(XmlNode listViewEntryNode, int index) { using (this.StackFrame(listViewEntryNode, index)) { bool appliesToNodeFound = false; // cardinality 0..1 bool bodyNodeFound = false; // cardinality 1 ListControlEntryDefinition lved = new ListControlEntryDefinition(); foreach (XmlNode n in listViewEntryNode.ChildNodes) { if (MatchNodeName(n, XmlTags.EntrySelectedByNode)) { if (appliesToNodeFound) { this.ProcessDuplicateNode(n); return null; //fatal } appliesToNodeFound = true; // optional section lved.appliesTo = LoadAppliesToSection(n, true); } else if (MatchNodeName(n, XmlTags.ListItemsNode)) { if (bodyNodeFound) { this.ProcessDuplicateNode(n); return null; //fatal } bodyNodeFound = true; LoadListControlItemDefinitions(lved, n); } else { this.ProcessUnknownNode(n); } } if (lved.itemDefinitionList == null) { //Error at XPath {0} in file {1}: Missing definition list. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NoDefinitionList, ComputeCurrentXPath(), FilePath)); return null; } return lved; } } private void LoadListControlItemDefinitions(ListControlEntryDefinition lved, XmlNode bodyNode) { using (this.StackFrame(bodyNode)) { int index = 0; foreach (XmlNode n in bodyNode.ChildNodes) { if (MatchNodeName(n, XmlTags.ListItemNode)) { index++; ListControlItemDefinition lvid = LoadListControlItemDefinition(n); if (lvid == null) { //Error at XPath {0} in file {1}: Invalid property entry. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.InvalidPropertyEntry, ComputeCurrentXPath(), FilePath)); lved.itemDefinitionList = null; return; //fatal } lved.itemDefinitionList.Add(lvid); } else { this.ProcessUnknownNode(n); } } // we must have at least a definition in th elist if (lved.itemDefinitionList.Count == 0) { //Error at XPath {0} in file {1}: At least one list view item must be specified. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NoListViewItem, ComputeCurrentXPath(), FilePath)); lved.itemDefinitionList = null; return; //fatal } } } private ListControlItemDefinition LoadListControlItemDefinition(XmlNode propertyEntryNode) { using (this.StackFrame(propertyEntryNode)) { // process Mshexpression, format string and text token ViewEntryNodeMatch match = new ViewEntryNodeMatch(this); List<XmlNode> unprocessedNodes = new List<XmlNode>(); if (!match.ProcessExpressionDirectives(propertyEntryNode, unprocessedNodes)) { return null; // fatal error } // process the remaining nodes TextToken labelToken = null; ExpressionToken condition = null; bool labelNodeFound = false; // cardinality 0..1 bool itemSelectionConditionNodeFound = false; // cardinality 0..1 foreach (XmlNode n in unprocessedNodes) { if (MatchNodeName(n, XmlTags.ItemSelectionConditionNode)) { if (itemSelectionConditionNodeFound) { this.ProcessDuplicateNode(n); return null; // fatal error } itemSelectionConditionNodeFound = true; condition = LoadItemSelectionCondition(n); if (condition == null) { return null; // fatal error } } else if (MatchNodeNameWithAttributes(n, XmlTags.LabelNode)) { if (labelNodeFound) { this.ProcessDuplicateNode(n); return null; // fatal error } labelNodeFound = true; labelToken = LoadLabel(n); if (labelToken == null) { return null; // fatal error } } else { this.ProcessUnknownNode(n); } } // finally build the item to return ListControlItemDefinition lvid = new ListControlItemDefinition(); // add the label lvid.label = labelToken; // add condition lvid.conditionToken = condition; // add either the text token or the MshExpression with optional format string if (match.TextToken != null) { lvid.formatTokenList.Add(match.TextToken); } else { FieldPropertyToken fpt = new FieldPropertyToken(); fpt.expression = match.Expression; fpt.fieldFormattingDirective.formatString = match.FormatString; lvid.formatTokenList.Add(fpt); } return lvid; } } private ExpressionToken LoadItemSelectionCondition(XmlNode itemNode) { using (this.StackFrame(itemNode)) { bool expressionNodeFound = false; // cardinality 1 ExpressionNodeMatch expressionMatch = new ExpressionNodeMatch(this); foreach (XmlNode n in itemNode.ChildNodes) { if (expressionMatch.MatchNode(n)) { if (expressionNodeFound) { this.ProcessDuplicateNode(n); return null; // fatal error } expressionNodeFound = true; if (!expressionMatch.ProcessNode(n)) return null; } else { this.ProcessUnknownNode(n); } } return expressionMatch.GenerateExpressionToken(); } } } }
// Options.cs // // Copyright (c) 2013 Brent Knowles (http://www.brentknowles.com) // // 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. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### using System; using appframe; using CoreUtilities; using System.Windows.Forms; using database; using System.Collections.Generic; namespace YOM2013 { public class Options : iConfig, IDisposable { #region variables_private Label WordSystem; string DatabaseName; Panel configPanel; #endregion const string columnID="id"; const string columnKey="key"; const string columnValue="value"; const string TableName = "generalsettings"; #region variables // public bool dualScreens_TallestHeight=false; // public bool autoSave=false; // if true on save we know it is safe to try to save (because interface exists) bool PanelWasMade = false; public string ConfigName { get { return Loc.Instance.GetString ("General");} } // a feeder array to setup the buttons. one array for each 'type' of config data struct checkBoxOptions { public string labelName; // the identifier for this field in the database under the "key" column public string columnKey; public bool defaultValue; public string toolTip; public checkBoxOptions(string labelname, string columnkey, string tooltip, bool defaultvalue) { labelName = labelname; columnKey = columnkey; toolTip = tooltip; defaultValue =defaultvalue; } } checkBoxOptions[] booleanValues = new checkBoxOptions[4] { new checkBoxOptions(Loc.Instance.GetString("Autosave?"), "autosave", "tt", true), new checkBoxOptions(Loc.Instance.GetString("Multiple Screens - Set Height to Highest?"), "multiscreenhigh", "tt", false), new checkBoxOptions(Loc.Instance.GetString ("Beta Updates (allows updating to beta versions)"), "betaversions","tt", false), new checkBoxOptions(Loc.Instance.GetString ("Increase Memory Usage (more layouts open at one time)"), "memory_high","tt", false) }; string dataPath = CoreUtilities.Constants.BLANK; #endregion public Options (string _DatabaseName) { this.DatabaseName = _DatabaseName; } public void Dispose () { } public bool Betaupdates { get { checkBoxOptions defaultValue = Array.Find (booleanValues, checkBoxOptions => checkBoxOptions.columnKey == "betaversions"); return GetOption ("betaversions", defaultValue.defaultValue); } } public bool Autosave { get { checkBoxOptions defaultValue = Array.Find (booleanValues,checkBoxOptions => checkBoxOptions.columnKey == "autosave"); return GetOption ("autosave", defaultValue.defaultValue); } } public bool MultipleScreenHigh { get { checkBoxOptions defaultValue = Array.Find (booleanValues,checkBoxOptions => checkBoxOptions.columnKey == "multiscreenhigh"); return GetOption ("multiscreenhigh", defaultValue.defaultValue); } } public bool HighMemory { get { checkBoxOptions defaultValue = Array.Find (booleanValues,checkBoxOptions => checkBoxOptions.columnKey == "memory_high"); return GetOption ("memory_high", defaultValue.defaultValue); } } private bool GetOption (string option, bool defaultValue) { BaseDatabase db = CreateDatabase (); bool result = defaultValue; if (db.Exists (TableName, columnKey, option)) { object o = db.GetValues(TableName, new string[1] {columnValue}, columnKey, option)[0][0]; if (o.ToString() == "1") result = true; else result = false; lg.Instance.Line("Options->GetConfigPanel", ProblemType.TEMPORARY, o.ToString()); } db.Dispose(); return result; // where option matches // where option matches the columnKey of the array (for default values) } public Panel GetConfigPanel () { // we need to revise this if plugins have been adding if (null != WordSystem) { UpdateCurrentWordSystem(WordSystem); } // if panel made then leave it alone if (PanelWasMade == true) return configPanel; PanelWasMade = true; configPanel = new Panel (); foreach (checkBoxOptions option in booleanValues) { lg.Instance.Line ("Options.GetConfigPane", ProblemType.TEMPORARY, option.labelName); CheckBox autoSave = new CheckBox (); autoSave.Name = option.columnKey; autoSave.Text = option.labelName; bool result = GetOption (option.columnKey, option.defaultValue); autoSave.Checked = result; configPanel.Controls.Add (autoSave); autoSave.Dock = DockStyle.Top; } GroupBox Info = new GroupBox(); Info.Text = Loc.Instance.GetString ("Info"); //Info.Font = new System.Drawing.Font(Info.Font.FontFamily, Info.Font.Size, System.Drawing.FontStyle.Bold); Info.Dock = DockStyle.Bottom; WordSystem = new Label (); WordSystem.AutoSize = false; WordSystem.Height = 200; UpdateCurrentWordSystem (WordSystem); Info.Controls.Add (WordSystem); WordSystem.Dock = DockStyle.Top; configPanel.Controls.Add (Info); return configPanel; } static void UpdateCurrentWordSystem (Label WordSystem) { if (Layout.LayoutDetails.Instance.WordSystemInUse == null) { // when a plugin unloads it needs to set the layoutsystem to the default WordSystem.Text = Loc.Instance.GetString ("No Word System Was Assigned. This is an error. Contact developer."); } else { WordSystem.Text = Loc.Instance.GetStringFmt ("Using: {0}. (NOTE: AddIns can deploy new word systems).", Layout.LayoutDetails.Instance.WordSystemInUse.ToString ()); } } private BaseDatabase CreateDatabase() { //BaseDatabase db = new SqlLiteDatabase (DatabaseName); BaseDatabase db = Layout.MasterOfLayouts.GetDatabaseType(DatabaseName); db.CreateTableIfDoesNotExist (TableName, new string[3] {columnID, columnKey, columnValue}, new string[3] { "INTEGER", "TEXT", "TEXT" }, columnID ); return db; } public void SaveRequested () { if (false == PanelWasMade) return; if (configPanel == null) { throw new Exception ("no config panel defined"); } BaseDatabase db = CreateDatabase (); // string result = (db as SqlLiteDatabase).BackupTable("",TableName ,null); // NewMessage.Show (result); //return; foreach (checkBoxOptions option in booleanValues) { CheckBox checker = (CheckBox)configPanel.Controls.Find (option.columnKey, true)[0]; if (checker != null) { // foreach GUIelement string key = option.columnKey; bool booleanvalue = checker.Checked; try { if (!db.Exists (TableName, columnKey, key)) { // if we were updating multiple AND we have to add a new key, we need to terminate the multiple update if (db.IsInMultipleUpdateMode() == true) db.UpdateMultiple_End(); db.InsertData (TableName, new string[2]{columnKey, columnValue}, new object[2] {key, booleanvalue}); } else { if (db.IsInMultipleUpdateMode() == false) db.UpdateMultiple_Start (); db.UpdateDataMultiple (TableName, new string[1] {columnValue}, new object[1] {booleanvalue}, columnKey, key); } } catch (Exception ex) { NewMessage.Show ("Are we in the middle of updating one value while inserting a new value? " + ex.ToString()); } } } if (db.IsInMultipleUpdateMode() == true) db.UpdateMultiple_End(); db.Dispose(); } } }
// // 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 Hyak.Common; namespace Microsoft.Azure.Management.DataFactories.Models { /// <summary> /// Specifying a schedule for the activity creates a series of tumbling /// windows. Tumbling windows are series of fixed-sized, non-overlapping /// and contiguous time intervals. Activity window is an instance of /// these logical tumbling windows for the activity. /// </summary> public partial class ActivityWindow { private string _activityName; /// <summary> /// Required. Pipeline activity name. /// </summary> public string ActivityName { get { return this._activityName; } set { this._activityName = value; } } private string _activityType; /// <summary> /// Required. The activity type which can be either user defined or /// registered. /// </summary> public string ActivityType { get { return this._activityType; } set { this._activityType = value; } } private string _dataFactoryName; /// <summary> /// Required. Data factory name. /// </summary> public string DataFactoryName { get { return this._dataFactoryName; } set { this._dataFactoryName = value; } } private System.TimeSpan? _duration; /// <summary> /// Optional. Duration of run. /// </summary> public System.TimeSpan? Duration { get { return this._duration; } set { this._duration = value; } } private IList<string> _inputDatasets; /// <summary> /// Required. The input datasets corresponding to the activity window. /// </summary> public IList<string> InputDatasets { get { return this._inputDatasets; } set { this._inputDatasets = value; } } private string _linkedServiceName; /// <summary> /// Required. The linked service the activity window is run on. /// </summary> public string LinkedServiceName { get { return this._linkedServiceName; } set { this._linkedServiceName = value; } } private IList<string> _outputDatasets; /// <summary> /// Required. The output datasets corresponding to the activity window. /// </summary> public IList<string> OutputDatasets { get { return this._outputDatasets; } set { this._outputDatasets = value; } } private int? _percentComplete; /// <summary> /// Optional. Pecent completion of activity window execution. /// </summary> public int? PercentComplete { get { return this._percentComplete; } set { this._percentComplete = value; } } private string _pipelineName; /// <summary> /// Required. Pipeline name. /// </summary> public string PipelineName { get { return this._pipelineName; } set { this._pipelineName = value; } } private string _resourceGroupName; /// <summary> /// Required. Resource group name. /// </summary> public string ResourceGroupName { get { return this._resourceGroupName; } set { this._resourceGroupName = value; } } private int _runAttempts; /// <summary> /// Required. Number of activity run attempts. /// </summary> public int RunAttempts { get { return this._runAttempts; } set { this._runAttempts = value; } } private System.DateTime? _runEnd; /// <summary> /// Optional. End time of the last run. /// </summary> public System.DateTime? RunEnd { get { return this._runEnd; } set { this._runEnd = value; } } private System.DateTime? _runStart; /// <summary> /// Optional. Start time of the last run. /// </summary> public System.DateTime? RunStart { get { return this._runStart; } set { this._runStart = value; } } private DateTime _windowEnd; /// <summary> /// Required. Start time of the activity window. /// </summary> public DateTime WindowEnd { get { return this._windowEnd; } set { this._windowEnd = value; } } private DateTime _windowStart; /// <summary> /// Required. Start time of the activity window. /// </summary> public DateTime WindowStart { get { return this._windowStart; } set { this._windowStart = value; } } private string _windowState; /// <summary> /// Required. Window state. /// </summary> public string WindowState { get { return this._windowState; } set { this._windowState = value; } } private string _windowSubstate; /// <summary> /// Required. Window substate. /// </summary> public string WindowSubstate { get { return this._windowSubstate; } set { this._windowSubstate = value; } } /// <summary> /// Initializes a new instance of the ActivityWindow class. /// </summary> public ActivityWindow() { this.InputDatasets = new LazyList<string>(); this.OutputDatasets = new LazyList<string>(); } } }
// 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.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics.Tracing; using Xunit; #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. using Microsoft.Diagnostics.Tracing.Session; #endif using System.Diagnostics; namespace BasicEventSourceTests { internal enum Color { Red, Blue, Green }; internal enum ColorUInt32 : uint { Red, Blue, Green }; internal enum ColorByte : byte { Red, Blue, Green }; internal enum ColorSByte : sbyte { Red, Blue, Green }; internal enum ColorInt16 : short { Red, Blue, Green }; internal enum ColorUInt16 : ushort { Red, Blue, Green }; internal enum ColorInt64 : long { Red, Blue, Green }; internal enum ColorUInt64 : ulong { Red, Blue, Green }; public class TestsWrite { [EventData] private struct PartB_UserInfo { public string UserName { get; set; } } /// <summary> /// Tests the EventSource.Write[T] method (can only use the self-describing mechanism). /// Tests the EventListener code path /// </summary> [Fact] public void Test_Write_T_EventListener() { Test_Write_T(new EventListenerListener()); } /// <summary> /// Tests the EventSource.Write[T] method (can only use the self-describing mechanism). /// Tests the EventListener code path using events instead of virtual callbacks. /// </summary> [Fact] public void Test_Write_T_EventListener_UseEvents() { Test_Write_T(new EventListenerListener(true)); } #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. /// <summary> /// Tests the EventSource.Write[T] method (can only use the self-describing mechanism). /// Tests the ETW code path /// </summary> [Fact] public void Test_Write_T_ETW() { Test_Write_T(new EtwListener()); } #endif //USE_ETW /// <summary> /// Te /// </summary> /// <param name="listener"></param> private void Test_Write_T(Listener listener) { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var logger = new EventSource("EventSourceName")) { var tests = new List<SubTest>(); /*************************************************************************/ tests.Add(new SubTest("Write/Basic/String", delegate () { logger.Write("Greeting", new { msg = "Hello, world!" }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("Greeting", evt.EventName); Assert.Equal(evt.PayloadValue(0, "msg"), "Hello, world!"); })); /*************************************************************************/ decimal myMoney = 300; tests.Add(new SubTest("Write/Basic/decimal", delegate () { logger.Write("Decimal", new { money = myMoney }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("Decimal", evt.EventName); var eventMoney = evt.PayloadValue(0, "money"); // TOD FIX ME - Fix TraceEvent to return decimal instead of double. //Assert.Equal((decimal)eventMoney, (decimal)300); })); /*************************************************************************/ DateTime now = DateTime.Now; tests.Add(new SubTest("Write/Basic/DateTime", delegate () { logger.Write("DateTime", new { nowTime = now }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("DateTime", evt.EventName); var eventNow = evt.PayloadValue(0, "nowTime"); Assert.Equal(eventNow, now); })); /*************************************************************************/ byte[] byteArray = { 0, 1, 2, 3 }; tests.Add(new SubTest("Write/Basic/byte[]", delegate () { logger.Write("Bytes", new { bytes = byteArray }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("Bytes", evt.EventName); var eventArray = evt.PayloadValue(0, "bytes"); Array.Equals(eventArray, byteArray); })); /*************************************************************************/ tests.Add(new SubTest("Write/Basic/PartBOnly", delegate () { // log just a PartB logger.Write("UserInfo", new EventSourceOptions { Keywords = EventKeywords.None }, new { _1 = new PartB_UserInfo { UserName = "Someone Else" } }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("UserInfo", evt.EventName); var structValue = evt.PayloadValue(0, "PartB_UserInfo"); var structValueAsDictionary = structValue as IDictionary<string, object>; Assert.NotNull(structValueAsDictionary); Assert.Equal(structValueAsDictionary["UserName"], "Someone Else"); })); /*************************************************************************/ tests.Add(new SubTest("Write/Basic/PartBAndC", delegate () { // log a PartB and a PartC logger.Write("Duration", new EventSourceOptions { Keywords = EventKeywords.None }, new { _1 = new PartB_UserInfo { UserName = "Myself" }, msec = 10 }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("Duration", evt.EventName); var structValue = evt.PayloadValue(0, "PartB_UserInfo"); var structValueAsDictionary = structValue as IDictionary<string, object>; Assert.NotNull(structValueAsDictionary); Assert.Equal(structValueAsDictionary["UserName"], "Myself"); Assert.Equal(evt.PayloadValue(1, "msec"), 10); })); /*************************************************************************/ /*************************** ENUM TESTING *******************************/ /*************************************************************************/ /*************************************************************************/ GenerateEnumTest<Color>(ref tests, logger, Color.Green); GenerateEnumTest<ColorUInt32>(ref tests, logger, ColorUInt32.Green); GenerateEnumTest<ColorByte>(ref tests, logger, ColorByte.Green); GenerateEnumTest<ColorSByte>(ref tests, logger, ColorSByte.Green); GenerateEnumTest<ColorInt16>(ref tests, logger, ColorInt16.Green); GenerateEnumTest<ColorUInt16>(ref tests, logger, ColorUInt16.Green); GenerateEnumTest<ColorInt64>(ref tests, logger, ColorInt64.Green); GenerateEnumTest<ColorUInt64>(ref tests, logger, ColorUInt64.Green); /*************************************************************************/ /*************************** ARRAY TESTING *******************************/ /*************************************************************************/ /*************************************************************************/ GenerateArrayTest<Boolean>(ref tests, logger, new Boolean[] { false, true, false }); GenerateArrayTest<byte>(ref tests, logger, new byte[] { 1, 10, 100 }); GenerateArrayTest<sbyte>(ref tests, logger, new sbyte[] { 1, 10, 100 }); GenerateArrayTest<Int16>(ref tests, logger, new Int16[] { 1, 10, 100 }); GenerateArrayTest<UInt16>(ref tests, logger, new UInt16[] { 1, 10, 100 }); GenerateArrayTest<Int32>(ref tests, logger, new Int32[] { 1, 10, 100 }); GenerateArrayTest<UInt32>(ref tests, logger, new UInt32[] { 1, 10, 100 }); GenerateArrayTest<Int64>(ref tests, logger, new Int64[] { 1, 10, 100 }); GenerateArrayTest<UInt64>(ref tests, logger, new UInt64[] { 1, 10, 100 }); GenerateArrayTest<Char>(ref tests, logger, new Char[] { 'a', 'c', 'b' }); GenerateArrayTest<Double>(ref tests, logger, new Double[] { 1, 10, 100 }); GenerateArrayTest<Single>(ref tests, logger, new Single[] { 1, 10, 100 }); GenerateArrayTest<IntPtr>(ref tests, logger, new IntPtr[] { (IntPtr)1, (IntPtr)10, (IntPtr)100 }); GenerateArrayTest<UIntPtr>(ref tests, logger, new UIntPtr[] { (UIntPtr)1, (UIntPtr)10, (UIntPtr)100 }); GenerateArrayTest<Guid>(ref tests, logger, new Guid[] { Guid.Empty, new Guid("121a11ee-3bcb-49cc-b425-f4906fb14f72") }); /*************************************************************************/ /*********************** DICTIONARY TESTING ******************************/ /*************************************************************************/ var dict = new Dictionary<string, string>() { { "elem1", "10" }, { "elem2", "20" } }; var dictInt = new Dictionary<string, int>() { { "elem1", 10 }, { "elem2", 20 } }; /*************************************************************************/ tests.Add(new SubTest("Write/Dict/EventWithStringDict_C", delegate() { // log a dictionary logger.Write("EventWithStringDict_C", new { myDict = dict, s = "end" }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithStringDict_C", evt.EventName); var keyValues = evt.PayloadValue(0, "myDict"); IDictionary<string, object> vDict = GetDictionaryFromKeyValueArray(keyValues); Assert.Equal(vDict["elem1"], "10"); Assert.Equal(vDict["elem2"], "20"); Assert.Equal(evt.PayloadValue(1, "s"), "end"); })); /*************************************************************************/ tests.Add(new SubTest("Write/Dict/EventWithStringDict_BC", delegate() { // log a PartB and a dictionary as a PartC logger.Write("EventWithStringDict_BC", new { PartB_UserInfo = new { UserName = "Me", LogTime = "Now" }, PartC_Dict = dict, s = "end" }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithStringDict_BC", evt.EventName); var structValue = evt.PayloadValue(0, "PartB_UserInfo"); var structValueAsDictionary = structValue as IDictionary<string, object>; Assert.NotNull(structValueAsDictionary); Assert.Equal(structValueAsDictionary["UserName"], "Me"); Assert.Equal(structValueAsDictionary["LogTime"], "Now"); var keyValues = evt.PayloadValue(1, "PartC_Dict"); var vDict = GetDictionaryFromKeyValueArray(keyValues); Assert.NotNull(dict); Assert.Equal(vDict["elem1"], "10"); // string values. Assert.Equal(vDict["elem2"], "20"); Assert.Equal(evt.PayloadValue(2, "s"), "end"); })); /*************************************************************************/ tests.Add(new SubTest("Write/Dict/EventWithIntDict_BC", delegate() { // log a Dict<string, int> as a PartC logger.Write("EventWithIntDict_BC", new { PartB_UserInfo = new { UserName = "Me", LogTime = "Now" }, PartC_Dict = dictInt, s = "end" }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithIntDict_BC", evt.EventName); var structValue = evt.PayloadValue(0, "PartB_UserInfo"); var structValueAsDictionary = structValue as IDictionary<string, object>; Assert.NotNull(structValueAsDictionary); Assert.Equal(structValueAsDictionary["UserName"], "Me"); Assert.Equal(structValueAsDictionary["LogTime"], "Now"); var keyValues = evt.PayloadValue(1, "PartC_Dict"); var vDict = GetDictionaryFromKeyValueArray(keyValues); Assert.NotNull(vDict); Assert.Equal(vDict["elem1"], 10); // Notice they are integers, not strings. Assert.Equal(vDict["elem2"], 20); Assert.Equal(evt.PayloadValue(2, "s"), "end"); })); /*************************************************************************/ /**************************** Empty Event TESTING ************************/ /*************************************************************************/ tests.Add(new SubTest("Write/Basic/Message", delegate () { logger.Write("EmptyEvent"); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EmptyEvent", evt.EventName); })); /*************************************************************************/ /**************************** EventSourceOptions TESTING *****************/ /*************************************************************************/ EventSourceOptions options = new EventSourceOptions(); options.Level = EventLevel.LogAlways; options.Keywords = EventKeywords.All; options.Opcode = EventOpcode.Info; options.Tags = EventTags.None; tests.Add(new SubTest("Write/Basic/MessageOptions", delegate () { logger.Write("EmptyEvent", options); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EmptyEvent", evt.EventName); })); tests.Add(new SubTest("Write/Basic/WriteOfTWithOptios", delegate () { logger.Write("OptionsEvent", options, new { OptionsEvent = "test options!" }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("OptionsEvent", evt.EventName); Assert.Equal(evt.PayloadValue(0, "OptionsEvent"), "test options!"); })); tests.Add(new SubTest("Write/Basic/WriteOfTWithRefOptios", delegate () { var v = new { OptionsEvent = "test ref options!" }; logger.Write("RefOptionsEvent", ref options, ref v); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("RefOptionsEvent", evt.EventName); Assert.Equal(evt.PayloadValue(0, "OptionsEvent"), "test ref options!"); })); tests.Add(new SubTest("Write/Basic/WriteOfTWithNullString", delegate () { string nullString = null; logger.Write("NullStringEvent", new { a = (string)null, b = nullString }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("NullStringEvent", evt.EventName); Assert.Equal(evt.PayloadValue(0, "a"), ""); Assert.Equal(evt.PayloadValue(1, "b"), ""); })); Guid activityId = new Guid("00000000-0000-0000-0000-000000000001"); Guid relActivityId = new Guid("00000000-0000-0000-0000-000000000002"); tests.Add(new SubTest("Write/Basic/WriteOfTWithOptios", delegate () { var v = new { ActivityMsg = "test activity!" }; logger.Write("ActivityEvent", ref options, ref activityId, ref relActivityId, ref v); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("ActivityEvent", evt.EventName); Assert.Equal(evt.PayloadValue(0, "ActivityMsg"), "test activity!"); })); // If you only wish to run one or several of the tests you can filter them here by // Uncommenting the following line. // tests = tests.FindAll(test => Regex.IsMatch(test.Name, "Write/Basic/EventII")); // Here is where we actually run tests. First test the ETW path EventTestHarness.RunTests(tests, listener, logger); } TestUtilities.CheckNoEventSourcesRunning("Stop"); } /// <summary> /// This is not a user error but it is something unusual. /// You can use the Write API in a EventSource that was did not /// Declare SelfDescribingSerialization. In that case THOSE /// events MUST use SelfDescribing serialization. /// </summary> [Fact] public void Test_Write_T_In_Manifest_Serialization() { var listenerGenerators = new Func<Listener>[] { #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. () => new EtwListener(), #endif // USE_ETW () => new EventListenerListener() }; foreach (Func<Listener> listenerGenerator in listenerGenerators) { var events = new List<Event>(); using (var listener = listenerGenerator()) { Debug.WriteLine("Testing Listener " + listener); // Create an eventSource with manifest based serialization using (var logger = new SdtEventSources.EventSourceTest()) { listener.OnEvent = delegate (Event data) { events.Add(data); }; listener.EventSourceSynchronousEnable(logger); // Use the Write<T> API. This is OK logger.Write("MyTestEvent", new { arg1 = 3, arg2 = "hi" }); } } Assert.Equal(events.Count, 1); Event _event = events[0]; Assert.Equal("MyTestEvent", _event.EventName); Assert.Equal(3, (int)_event.PayloadValue(0, "arg1")); Assert.Equal("hi", (string)_event.PayloadValue(1, "arg2")); } } private void GenerateEnumTest<T>(ref List<SubTest> tests, EventSource logger, T enumValue) { string subTestName = enumValue.GetType().ToString(); tests.Add(new SubTest("Write/Enum/EnumEvent" + subTestName, delegate () { T c = enumValue; // log an array logger.Write("EnumEvent" + subTestName, new { b = "start", v = c, s = "end" }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EnumEvent" + subTestName, evt.EventName); Assert.Equal(evt.PayloadValue(0, "b"), "start"); if (evt.IsEtw) { var value = evt.PayloadValue(1, "v"); Assert.Equal(2, int.Parse(value.ToString())); // Green has the int value of 2. } else { Assert.Equal(evt.PayloadValue(1, "v"), enumValue); } Assert.Equal(evt.PayloadValue(2, "s"), "end"); })); } private void GenerateArrayTest<T>(ref List<SubTest> tests, EventSource logger, T[] array) { string typeName = array.GetType().GetElementType().ToString(); tests.Add(new SubTest("Write/Array/" + typeName, delegate () { // log an array logger.Write("SomeEvent" + typeName, new { a = array, s = "end" }); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("SomeEvent" + typeName, evt.EventName); var eventArray = evt.PayloadValue(0, "a"); Array.Equals(array, eventArray); Assert.Equal("end", evt.PayloadValue(1, "s")); })); } /// <summary> /// Convert an array of key value pairs (as ETW structs) into a dictionary with those values. /// </summary> /// <param name="structValue"></param> /// <returns></returns> private IDictionary<string, object> GetDictionaryFromKeyValueArray(object structValue) { var ret = new Dictionary<string, object>(); var asArray = structValue as object[]; Assert.NotNull(asArray); foreach (var item in asArray) { var keyValue = item as IDictionary<string, object>; Assert.Equal(keyValue.Count, 2); ret.Add((string)keyValue["Key"], keyValue["Value"]); } return ret; } } }
/* * Copyright 2010-2014 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. */ /* * Do not modify this file. This file is generated from the config-2014-11-12.normal.json service model. */ using System; using Amazon.Runtime; namespace Amazon.ConfigService { /// <summary> /// Constants used for properties of type ChronologicalOrder. /// </summary> public class ChronologicalOrder : ConstantClass { /// <summary> /// Constant Forward for ChronologicalOrder /// </summary> public static readonly ChronologicalOrder Forward = new ChronologicalOrder("Forward"); /// <summary> /// Constant Reverse for ChronologicalOrder /// </summary> public static readonly ChronologicalOrder Reverse = new ChronologicalOrder("Reverse"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public ChronologicalOrder(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ChronologicalOrder FindValue(string value) { return FindValue<ChronologicalOrder>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ChronologicalOrder(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type ComplianceType. /// </summary> public class ComplianceType : ConstantClass { /// <summary> /// Constant COMPLIANT for ComplianceType /// </summary> public static readonly ComplianceType COMPLIANT = new ComplianceType("COMPLIANT"); /// <summary> /// Constant INSUFFICIENT_DATA for ComplianceType /// </summary> public static readonly ComplianceType INSUFFICIENT_DATA = new ComplianceType("INSUFFICIENT_DATA"); /// <summary> /// Constant NON_COMPLIANT for ComplianceType /// </summary> public static readonly ComplianceType NON_COMPLIANT = new ComplianceType("NON_COMPLIANT"); /// <summary> /// Constant NOT_APPLICABLE for ComplianceType /// </summary> public static readonly ComplianceType NOT_APPLICABLE = new ComplianceType("NOT_APPLICABLE"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public ComplianceType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ComplianceType FindValue(string value) { return FindValue<ComplianceType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ComplianceType(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type ConfigRuleState. /// </summary> public class ConfigRuleState : ConstantClass { /// <summary> /// Constant ACTIVE for ConfigRuleState /// </summary> public static readonly ConfigRuleState ACTIVE = new ConfigRuleState("ACTIVE"); /// <summary> /// Constant DELETING for ConfigRuleState /// </summary> public static readonly ConfigRuleState DELETING = new ConfigRuleState("DELETING"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public ConfigRuleState(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ConfigRuleState FindValue(string value) { return FindValue<ConfigRuleState>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ConfigRuleState(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type ConfigurationItemStatus. /// </summary> public class ConfigurationItemStatus : ConstantClass { /// <summary> /// Constant Deleted for ConfigurationItemStatus /// </summary> public static readonly ConfigurationItemStatus Deleted = new ConfigurationItemStatus("Deleted"); /// <summary> /// Constant Discovered for ConfigurationItemStatus /// </summary> public static readonly ConfigurationItemStatus Discovered = new ConfigurationItemStatus("Discovered"); /// <summary> /// Constant Failed for ConfigurationItemStatus /// </summary> public static readonly ConfigurationItemStatus Failed = new ConfigurationItemStatus("Failed"); /// <summary> /// Constant Ok for ConfigurationItemStatus /// </summary> public static readonly ConfigurationItemStatus Ok = new ConfigurationItemStatus("Ok"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public ConfigurationItemStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ConfigurationItemStatus FindValue(string value) { return FindValue<ConfigurationItemStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ConfigurationItemStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type DeliveryStatus. /// </summary> public class DeliveryStatus : ConstantClass { /// <summary> /// Constant Failure for DeliveryStatus /// </summary> public static readonly DeliveryStatus Failure = new DeliveryStatus("Failure"); /// <summary> /// Constant Not_Applicable for DeliveryStatus /// </summary> public static readonly DeliveryStatus Not_Applicable = new DeliveryStatus("Not_Applicable"); /// <summary> /// Constant Success for DeliveryStatus /// </summary> public static readonly DeliveryStatus Success = new DeliveryStatus("Success"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public DeliveryStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static DeliveryStatus FindValue(string value) { return FindValue<DeliveryStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator DeliveryStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type EventSource. /// </summary> public class EventSource : ConstantClass { /// <summary> /// Constant AwsConfig for EventSource /// </summary> public static readonly EventSource AwsConfig = new EventSource("aws.config"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public EventSource(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static EventSource FindValue(string value) { return FindValue<EventSource>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator EventSource(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type MaximumExecutionFrequency. /// </summary> public class MaximumExecutionFrequency : ConstantClass { /// <summary> /// Constant One_Hour for MaximumExecutionFrequency /// </summary> public static readonly MaximumExecutionFrequency One_Hour = new MaximumExecutionFrequency("One_Hour"); /// <summary> /// Constant Six_Hours for MaximumExecutionFrequency /// </summary> public static readonly MaximumExecutionFrequency Six_Hours = new MaximumExecutionFrequency("Six_Hours"); /// <summary> /// Constant Three_Hours for MaximumExecutionFrequency /// </summary> public static readonly MaximumExecutionFrequency Three_Hours = new MaximumExecutionFrequency("Three_Hours"); /// <summary> /// Constant Twelve_Hours for MaximumExecutionFrequency /// </summary> public static readonly MaximumExecutionFrequency Twelve_Hours = new MaximumExecutionFrequency("Twelve_Hours"); /// <summary> /// Constant TwentyFour_Hours for MaximumExecutionFrequency /// </summary> public static readonly MaximumExecutionFrequency TwentyFour_Hours = new MaximumExecutionFrequency("TwentyFour_Hours"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public MaximumExecutionFrequency(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static MaximumExecutionFrequency FindValue(string value) { return FindValue<MaximumExecutionFrequency>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator MaximumExecutionFrequency(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type MessageType. /// </summary> public class MessageType : ConstantClass { /// <summary> /// Constant ConfigurationItemChangeNotification for MessageType /// </summary> public static readonly MessageType ConfigurationItemChangeNotification = new MessageType("ConfigurationItemChangeNotification"); /// <summary> /// Constant ConfigurationSnapshotDeliveryCompleted for MessageType /// </summary> public static readonly MessageType ConfigurationSnapshotDeliveryCompleted = new MessageType("ConfigurationSnapshotDeliveryCompleted"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public MessageType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static MessageType FindValue(string value) { return FindValue<MessageType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator MessageType(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type Owner. /// </summary> public class Owner : ConstantClass { /// <summary> /// Constant AWS for Owner /// </summary> public static readonly Owner AWS = new Owner("AWS"); /// <summary> /// Constant CUSTOM_LAMBDA for Owner /// </summary> public static readonly Owner CUSTOM_LAMBDA = new Owner("CUSTOM_LAMBDA"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public Owner(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static Owner FindValue(string value) { return FindValue<Owner>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator Owner(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type RecorderStatus. /// </summary> public class RecorderStatus : ConstantClass { /// <summary> /// Constant Failure for RecorderStatus /// </summary> public static readonly RecorderStatus Failure = new RecorderStatus("Failure"); /// <summary> /// Constant Pending for RecorderStatus /// </summary> public static readonly RecorderStatus Pending = new RecorderStatus("Pending"); /// <summary> /// Constant Success for RecorderStatus /// </summary> public static readonly RecorderStatus Success = new RecorderStatus("Success"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public RecorderStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static RecorderStatus FindValue(string value) { return FindValue<RecorderStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator RecorderStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type ResourceType. /// </summary> public class ResourceType : ConstantClass { /// <summary> /// Constant AWSCloudTrailTrail for ResourceType /// </summary> public static readonly ResourceType AWSCloudTrailTrail = new ResourceType("AWS::CloudTrail::Trail"); /// <summary> /// Constant AWSEC2CustomerGateway for ResourceType /// </summary> public static readonly ResourceType AWSEC2CustomerGateway = new ResourceType("AWS::EC2::CustomerGateway"); /// <summary> /// Constant AWSEC2EIP for ResourceType /// </summary> public static readonly ResourceType AWSEC2EIP = new ResourceType("AWS::EC2::EIP"); /// <summary> /// Constant AWSEC2Instance for ResourceType /// </summary> public static readonly ResourceType AWSEC2Instance = new ResourceType("AWS::EC2::Instance"); /// <summary> /// Constant AWSEC2InternetGateway for ResourceType /// </summary> public static readonly ResourceType AWSEC2InternetGateway = new ResourceType("AWS::EC2::InternetGateway"); /// <summary> /// Constant AWSEC2NetworkAcl for ResourceType /// </summary> public static readonly ResourceType AWSEC2NetworkAcl = new ResourceType("AWS::EC2::NetworkAcl"); /// <summary> /// Constant AWSEC2NetworkInterface for ResourceType /// </summary> public static readonly ResourceType AWSEC2NetworkInterface = new ResourceType("AWS::EC2::NetworkInterface"); /// <summary> /// Constant AWSEC2RouteTable for ResourceType /// </summary> public static readonly ResourceType AWSEC2RouteTable = new ResourceType("AWS::EC2::RouteTable"); /// <summary> /// Constant AWSEC2SecurityGroup for ResourceType /// </summary> public static readonly ResourceType AWSEC2SecurityGroup = new ResourceType("AWS::EC2::SecurityGroup"); /// <summary> /// Constant AWSEC2Subnet for ResourceType /// </summary> public static readonly ResourceType AWSEC2Subnet = new ResourceType("AWS::EC2::Subnet"); /// <summary> /// Constant AWSEC2Volume for ResourceType /// </summary> public static readonly ResourceType AWSEC2Volume = new ResourceType("AWS::EC2::Volume"); /// <summary> /// Constant AWSEC2VPC for ResourceType /// </summary> public static readonly ResourceType AWSEC2VPC = new ResourceType("AWS::EC2::VPC"); /// <summary> /// Constant AWSEC2VPNConnection for ResourceType /// </summary> public static readonly ResourceType AWSEC2VPNConnection = new ResourceType("AWS::EC2::VPNConnection"); /// <summary> /// Constant AWSEC2VPNGateway for ResourceType /// </summary> public static readonly ResourceType AWSEC2VPNGateway = new ResourceType("AWS::EC2::VPNGateway"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public ResourceType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ResourceType FindValue(string value) { return FindValue<ResourceType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ResourceType(string value) { return FindValue(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.Diagnostics; using System.Dynamic.Utils; namespace System.Linq.Expressions.Interpreter { internal abstract class SubInstruction : Instruction { private static Instruction s_Int16, s_Int32, s_Int64, s_UInt16, s_UInt32, s_UInt64, s_Single, s_Double; public override int ConsumedStack => 2; public override int ProducedStack => 1; public override string InstructionName => "Sub"; private SubInstruction() { } private sealed class SubInt16 : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = unchecked((short)((short)l - (short)r)); } frame.StackIndex--; return 1; } } private sealed class SubInt32 : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(unchecked((int)l - (int)r)); } frame.StackIndex--; return 1; } } private sealed class SubInt64 : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = unchecked((long)l - (long)r); } frame.StackIndex--; return 1; } } private sealed class SubUInt16 : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = unchecked((ushort)((ushort)l - (ushort)r)); } frame.StackIndex--; return 1; } } private sealed class SubUInt32 : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = unchecked((uint)l - (uint)r); } frame.StackIndex--; return 1; } } private sealed class SubUInt64 : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = unchecked((ulong)l - (ulong)r); } frame.StackIndex--; return 1; } } private sealed class SubSingle : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (float)l - (float)r; } frame.StackIndex--; return 1; } } private sealed class SubDouble : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (double)l - (double)r; } frame.StackIndex--; return 1; } } public static Instruction Create(Type type) { Debug.Assert(type.IsArithmetic()); switch (type.GetNonNullableType().GetTypeCode()) { case TypeCode.Int16: return s_Int16 ?? (s_Int16 = new SubInt16()); case TypeCode.Int32: return s_Int32 ?? (s_Int32 = new SubInt32()); case TypeCode.Int64: return s_Int64 ?? (s_Int64 = new SubInt64()); case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new SubUInt16()); case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new SubUInt32()); case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new SubUInt64()); case TypeCode.Single: return s_Single ?? (s_Single = new SubSingle()); case TypeCode.Double: return s_Double ?? (s_Double = new SubDouble()); default: throw ContractUtils.Unreachable; } } } internal abstract class SubOvfInstruction : Instruction { private static Instruction s_Int16, s_Int32, s_Int64, s_UInt16, s_UInt32, s_UInt64; public override int ConsumedStack => 2; public override int ProducedStack => 1; public override string InstructionName => "SubOvf"; private SubOvfInstruction() { } private sealed class SubOvfInt16 : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = checked((short)((short)l - (short)r)); } frame.StackIndex--; return 1; } } private sealed class SubOvfInt32 : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(checked((int)l - (int)r)); } frame.StackIndex--; return 1; } } private sealed class SubOvfInt64 : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = checked((long)l - (long)r); } frame.StackIndex--; return 1; } } private sealed class SubOvfUInt16 : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = checked((ushort)((ushort)l - (ushort)r)); } frame.StackIndex--; return 1; } } private sealed class SubOvfUInt32 : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = checked((uint)l - (uint)r); } frame.StackIndex--; return 1; } } private sealed class SubOvfUInt64 : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = checked((ulong)l - (ulong)r); } frame.StackIndex--; return 1; } } public static Instruction Create(Type type) { Debug.Assert(type.IsArithmetic()); switch (type.GetNonNullableType().GetTypeCode()) { case TypeCode.Int16: return s_Int16 ?? (s_Int16 = new SubOvfInt16()); case TypeCode.Int32: return s_Int32 ?? (s_Int32 = new SubOvfInt32()); case TypeCode.Int64: return s_Int64 ?? (s_Int64 = new SubOvfInt64()); case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new SubOvfUInt16()); case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new SubOvfUInt32()); case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new SubOvfUInt64()); default: return SubInstruction.Create(type); } } } }
// 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.Data.Common; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Text; namespace System.Data.OleDb { internal static class ODB { // OleDbCommand static internal void CommandParameterStatus(StringBuilder builder, int index, DBStatus status) { switch (status) { case DBStatus.S_OK: case DBStatus.S_ISNULL: case DBStatus.S_IGNORE: break; case DBStatus.E_BADACCESSOR: builder.Append(SR.Format(SR.OleDb_CommandParameterBadAccessor, index.ToString(CultureInfo.InvariantCulture), "")); builder.Append(Environment.NewLine); break; case DBStatus.E_CANTCONVERTVALUE: builder.Append(SR.Format(SR.OleDb_CommandParameterCantConvertValue, index.ToString(CultureInfo.InvariantCulture), "")); builder.Append(Environment.NewLine); break; case DBStatus.E_SIGNMISMATCH: builder.Append(SR.Format(SR.OleDb_CommandParameterSignMismatch, index.ToString(CultureInfo.InvariantCulture), "")); builder.Append(Environment.NewLine); break; case DBStatus.E_DATAOVERFLOW: builder.Append(SR.Format(SR.OleDb_CommandParameterDataOverflow, index.ToString(CultureInfo.InvariantCulture), "")); builder.Append(Environment.NewLine); break; case DBStatus.E_CANTCREATE: Debug.Assert(false, "CommandParameterStatus: unexpected E_CANTCREATE"); goto default; case DBStatus.E_UNAVAILABLE: builder.Append(SR.Format(SR.OleDb_CommandParameterUnavailable, index.ToString(CultureInfo.InvariantCulture), "")); builder.Append(Environment.NewLine); break; case DBStatus.E_PERMISSIONDENIED: Debug.Assert(false, "CommandParameterStatus: unexpected E_PERMISSIONDENIED"); goto default; case DBStatus.E_INTEGRITYVIOLATION: Debug.Assert(false, "CommandParameterStatus: unexpected E_INTEGRITYVIOLATION"); goto default; case DBStatus.E_SCHEMAVIOLATION: Debug.Assert(false, "CommandParameterStatus: unexpected E_SCHEMAVIOLATION"); goto default; case DBStatus.E_BADSTATUS: Debug.Assert(false, "CommandParameterStatus: unexpected E_BADSTATUS"); goto default; case DBStatus.S_DEFAULT: builder.Append(SR.Format(SR.OleDb_CommandParameterDefault, index.ToString(CultureInfo.InvariantCulture), "")); builder.Append(Environment.NewLine); break; default: builder.Append(SR.Format(SR.OleDb_CommandParameterError, index.ToString(CultureInfo.InvariantCulture), status.ToString())); builder.Append(Environment.NewLine); break; } } static internal Exception CommandParameterStatus(string value, Exception inner) { if (ADP.IsEmpty(value)) { return inner; } return ADP.InvalidOperation(value, inner); } static internal Exception UninitializedParameters(int index, OleDbType dbtype) { return ADP.InvalidOperation(SR.Format(SR.OleDb_UninitializedParameters, index.ToString(CultureInfo.InvariantCulture), dbtype.ToString())); } static internal Exception BadStatus_ParamAcc(int index, DBBindStatus status) { return ADP.DataAdapter(SR.Format(SR.OleDb_BadStatus_ParamAcc, index.ToString(CultureInfo.InvariantCulture), status.ToString())); } static internal Exception NoProviderSupportForParameters(string provider, Exception inner) { return ADP.DataAdapter(SR.Format(SR.OleDb_NoProviderSupportForParameters, provider), inner); } static internal Exception NoProviderSupportForSProcResetParameters(string provider) { return ADP.DataAdapter(SR.Format(SR.OleDb_NoProviderSupportForSProcResetParameters, provider)); } // OleDbProperties static internal void PropsetSetFailure(StringBuilder builder, string description, OleDbPropertyStatus status) { if (OleDbPropertyStatus.Ok == status) { return; } switch (status) { case OleDbPropertyStatus.NotSupported: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(SR.Format(SR.OleDb_PropertyNotSupported, description)); break; case OleDbPropertyStatus.BadValue: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(SR.Format(SR.OleDb_PropertyBadValue, description)); break; case OleDbPropertyStatus.BadOption: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(SR.Format(SR.OleDb_PropertyBadOption, description)); break; case OleDbPropertyStatus.BadColumn: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(SR.Format(SR.OleDb_PropertyBadColumn, description)); break; case OleDbPropertyStatus.NotAllSettable: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(SR.Format(SR.OleDb_PropertyNotAllSettable, description)); break; case OleDbPropertyStatus.NotSettable: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(SR.Format(SR.OleDb_PropertyNotSettable, description)); break; case OleDbPropertyStatus.NotSet: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(SR.Format(SR.OleDb_PropertyNotSet, description)); break; case OleDbPropertyStatus.Conflicting: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(SR.Format(SR.OleDb_PropertyConflicting, description)); break; case OleDbPropertyStatus.NotAvailable: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(SR.Format(SR.OleDb_PropertyNotAvailable, description)); break; default: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(SR.Format(SR.OleDb_PropertyStatusUnknown, ((int)status).ToString(CultureInfo.InvariantCulture))); break; } } static internal Exception PropsetSetFailure(string value, Exception inner) { if (ADP.IsEmpty(value)) { return inner; } return ADP.InvalidOperation(value, inner); } // OleDbConnection static internal ArgumentException SchemaRowsetsNotSupported(string provider) { return ADP.Argument(SR.Format(SR.OleDb_SchemaRowsetsNotSupported, "IDBSchemaRowset", provider)); } static internal OleDbException NoErrorInformation(string provider, OleDbHResult hr, Exception inner) { OleDbException e; if (!ADP.IsEmpty(provider)) { e = new OleDbException(SR.Format(SR.OleDb_NoErrorInformation2, provider, ODB.ELookup(hr)), hr, inner); } else { e = new OleDbException(SR.Format(SR.OleDb_NoErrorInformation, ODB.ELookup(hr)), hr, inner); } ADP.TraceExceptionAsReturnValue(e); return e; } static internal InvalidOperationException MDACNotAvailable(Exception inner) { return ADP.DataAdapter(SR.Format(SR.OleDb_MDACNotAvailable), inner); } static internal ArgumentException MSDASQLNotSupported() { return ADP.Argument(SR.Format(SR.OleDb_MSDASQLNotSupported)); } static internal InvalidOperationException CommandTextNotSupported(string provider, Exception inner) { return ADP.DataAdapter(SR.Format(SR.OleDb_CommandTextNotSupported, provider), inner); } static internal InvalidOperationException PossiblePromptNotUserInteractive() { return ADP.DataAdapter(SR.Format(SR.OleDb_PossiblePromptNotUserInteractive)); } static internal InvalidOperationException ProviderUnavailable(string provider, Exception inner) { //return new OleDbException(SR.Format(SR.OleDb_ProviderUnavailable, provider), (int)OleDbHResult.CO_E_CLASSSTRING, inner); return ADP.DataAdapter(SR.Format(SR.OleDb_ProviderUnavailable, provider), inner); } static internal InvalidOperationException TransactionsNotSupported(string provider, Exception inner) { return ADP.DataAdapter(SR.Format(SR.OleDb_TransactionsNotSupported, provider), inner); } static internal ArgumentException AsynchronousNotSupported() { return ADP.Argument(SR.Format(SR.OleDb_AsynchronousNotSupported)); } static internal ArgumentException NoProviderSpecified() { return ADP.Argument(SR.Format(SR.OleDb_NoProviderSpecified)); } static internal ArgumentException InvalidProviderSpecified() { return ADP.Argument(SR.Format(SR.OleDb_InvalidProviderSpecified)); } static internal ArgumentException InvalidRestrictionsDbInfoKeywords(string parameter) { return ADP.Argument(SR.Format(SR.OleDb_InvalidRestrictionsDbInfoKeywords), parameter); } static internal ArgumentException InvalidRestrictionsDbInfoLiteral(string parameter) { return ADP.Argument(SR.Format(SR.OleDb_InvalidRestrictionsDbInfoLiteral), parameter); } static internal ArgumentException InvalidRestrictionsSchemaGuids(string parameter) { return ADP.Argument(SR.Format(SR.OleDb_InvalidRestrictionsSchemaGuids), parameter); } static internal ArgumentException NotSupportedSchemaTable(Guid schema, OleDbConnection connection) { return ADP.Argument(SR.Format(SR.OleDb_NotSupportedSchemaTable, OleDbSchemaGuid.GetTextFromValue(schema), connection.Provider)); } // OleDbParameter static internal Exception InvalidOleDbType(OleDbType value) { return ADP.InvalidEnumerationValue(typeof(OleDbType), (int)value); } // Getting Data static internal InvalidOperationException BadAccessor() { return ADP.DataAdapter(SR.Format(SR.OleDb_BadAccessor)); } static internal InvalidCastException ConversionRequired() { return ADP.InvalidCast(); } static internal InvalidCastException CantConvertValue() { return ADP.InvalidCast(SR.Format(SR.OleDb_CantConvertValue)); } static internal InvalidOperationException SignMismatch(Type type) { return ADP.DataAdapter(SR.Format(SR.OleDb_SignMismatch, type.Name)); } static internal InvalidOperationException DataOverflow(Type type) { return ADP.DataAdapter(SR.Format(SR.OleDb_DataOverflow, type.Name)); } static internal InvalidOperationException CantCreate(Type type) { return ADP.DataAdapter(SR.Format(SR.OleDb_CantCreate, type.Name)); } static internal InvalidOperationException Unavailable(Type type) { return ADP.DataAdapter(SR.Format(SR.OleDb_Unavailable, type.Name)); } static internal InvalidOperationException UnexpectedStatusValue(DBStatus status) { return ADP.DataAdapter(SR.Format(SR.OleDb_UnexpectedStatusValue, status.ToString())); } static internal InvalidOperationException GVtUnknown(int wType) { return ADP.DataAdapter(SR.Format(SR.OleDb_GVtUnknown, wType.ToString("X4", CultureInfo.InvariantCulture), wType.ToString(CultureInfo.InvariantCulture))); } static internal InvalidOperationException SVtUnknown(int wType) { return ADP.DataAdapter(SR.Format(SR.OleDb_SVtUnknown, wType.ToString("X4", CultureInfo.InvariantCulture), wType.ToString(CultureInfo.InvariantCulture))); } // OleDbDataReader static internal InvalidOperationException BadStatusRowAccessor(int i, DBBindStatus rowStatus) { return ADP.DataAdapter(SR.Format(SR.OleDb_BadStatusRowAccessor, i.ToString(CultureInfo.InvariantCulture), rowStatus.ToString())); } static internal InvalidOperationException ThreadApartmentState(Exception innerException) { return ADP.InvalidOperation(SR.Format(SR.OleDb_ThreadApartmentState), innerException); } // OleDbDataAdapter static internal ArgumentException Fill_NotADODB(string parameter) { return ADP.Argument(SR.Format(SR.OleDb_Fill_NotADODB), parameter); } static internal ArgumentException Fill_EmptyRecordSet(string parameter, Exception innerException) { return ADP.Argument(SR.Format(SR.OleDb_Fill_EmptyRecordSet, "IRowset"), parameter, innerException); } static internal ArgumentException Fill_EmptyRecord(string parameter, Exception innerException) { return ADP.Argument(SR.Format(SR.OleDb_Fill_EmptyRecord), parameter, innerException); } static internal string NoErrorMessage(OleDbHResult errorcode) { return SR.Format(SR.OleDb_NoErrorMessage, ODB.ELookup(errorcode)); } static internal string FailedGetDescription(OleDbHResult errorcode) { return SR.Format(SR.OleDb_FailedGetDescription, ODB.ELookup(errorcode)); } static internal string FailedGetSource(OleDbHResult errorcode) { return SR.Format(SR.OleDb_FailedGetSource, ODB.ELookup(errorcode)); } static internal InvalidOperationException DBBindingGetVector() { return ADP.InvalidOperation(SR.Format(SR.OleDb_DBBindingGetVector)); } static internal OleDbHResult GetErrorDescription(UnsafeNativeMethods.IErrorInfo errorInfo, OleDbHResult hresult, out string message) { OleDbHResult hr = errorInfo.GetDescription(out message); if (((int)hr < 0) && ADP.IsEmpty(message)) { message = FailedGetDescription(hr) + Environment.NewLine + ODB.ELookup(hresult); } if (ADP.IsEmpty(message)) { message = ODB.ELookup(hresult); } return hr; } // OleDbEnumerator internal static ArgumentException ISourcesRowsetNotSupported() { throw ADP.Argument(SR.OleDb_ISourcesRowsetNotSupported); } // OleDbMetaDataFactory static internal InvalidOperationException IDBInfoNotSupported() { return ADP.InvalidOperation(SR.Format(SR.OleDb_IDBInfoNotSupported)); } // explictly used error codes internal const int ADODB_AlreadyClosedError = unchecked((int)0x800A0E78); internal const int ADODB_NextResultError = unchecked((int)0x800A0CB3); // internal command states internal const int InternalStateExecuting = (int)(ConnectionState.Open | ConnectionState.Executing); internal const int InternalStateFetching = (int)(ConnectionState.Open | ConnectionState.Fetching); internal const int InternalStateClosed = (int)(ConnectionState.Closed); internal const int ExecutedIMultipleResults = 0; internal const int ExecutedIRowset = 1; internal const int ExecutedIRow = 2; internal const int PrepareICommandText = 3; // internal connection states, a superset of the command states internal const int InternalStateExecutingNot = (int)~(ConnectionState.Executing); internal const int InternalStateFetchingNot = (int)~(ConnectionState.Fetching); internal const int InternalStateConnecting = (int)(ConnectionState.Connecting); internal const int InternalStateOpen = (int)(ConnectionState.Open); // constants used to trigger from binding as WSTR to BYREF|WSTR // used by OleDbCommand, OleDbDataReader internal const int LargeDataSize = (1 << 13); // 8K internal const int CacheIncrement = 10; // constants used by OleDbDataReader internal static readonly IntPtr DBRESULTFLAG_DEFAULT = IntPtr.Zero; internal const short VARIANT_TRUE = -1; internal const short VARIANT_FALSE = 0; // OleDbConnection constants internal const int CLSCTX_ALL = /*CLSCTX_INPROC_SERVER*/1 | /*CLSCTX_INPROC_HANDLER*/2 | /*CLSCTX_LOCAL_SERVER*/4 | /*CLSCTX_REMOTE_SERVER*/16; internal const int MaxProgIdLength = 255; internal const int DBLITERAL_CATALOG_SEPARATOR = 3; internal const int DBLITERAL_QUOTE_PREFIX = 15; internal const int DBLITERAL_QUOTE_SUFFIX = 28; internal const int DBLITERAL_SCHEMA_SEPARATOR = 27; internal const int DBLITERAL_TABLE_NAME = 17; internal const int DBPROP_ACCESSORDER = 0xe7; internal const int DBPROP_AUTH_CACHE_AUTHINFO = 0x5; internal const int DBPROP_AUTH_ENCRYPT_PASSWORD = 0x6; internal const int DBPROP_AUTH_INTEGRATED = 0x7; internal const int DBPROP_AUTH_MASK_PASSWORD = 0x8; internal const int DBPROP_AUTH_PASSWORD = 0x9; internal const int DBPROP_AUTH_PERSIST_ENCRYPTED = 0xa; internal const int DBPROP_AUTH_PERSIST_SENSITIVE_AUTHINFO = 0xb; internal const int DBPROP_AUTH_USERID = 0xc; internal const int DBPROP_CATALOGLOCATION = 0x16; internal const int DBPROP_COMMANDTIMEOUT = 0x22; internal const int DBPROP_CONNECTIONSTATUS = 0xf4; internal const int DBPROP_CURRENTCATALOG = 0x25; internal const int DBPROP_DATASOURCENAME = 0x26; internal const int DBPROP_DBMSNAME = 0x28; internal const int DBPROP_DBMSVER = 0x29; internal const int DBPROP_GROUPBY = 0x2c; internal const int DBPROP_HIDDENCOLUMNS = 0x102; internal const int DBPROP_IColumnsRowset = 0x7b; internal const int DBPROP_IDENTIFIERCASE = 0x2e; internal const int DBPROP_INIT_ASYNCH = 0xc8; internal const int DBPROP_INIT_BINDFLAGS = 0x10e; internal const int DBPROP_INIT_CATALOG = 0xe9; internal const int DBPROP_INIT_DATASOURCE = 0x3b; internal const int DBPROP_INIT_GENERALTIMEOUT = 0x11c; internal const int DBPROP_INIT_HWND = 0x3c; internal const int DBPROP_INIT_IMPERSONATION_LEVEL = 0x3d; internal const int DBPROP_INIT_LCID = 0xba; internal const int DBPROP_INIT_LOCATION = 0x3e; internal const int DBPROP_INIT_LOCKOWNER = 0x10f; internal const int DBPROP_INIT_MODE = 0x3f; internal const int DBPROP_INIT_OLEDBSERVICES = 0xf8; internal const int DBPROP_INIT_PROMPT = 0x40; internal const int DBPROP_INIT_PROTECTION_LEVEL = 0x41; internal const int DBPROP_INIT_PROVIDERSTRING = 0xa0; internal const int DBPROP_INIT_TIMEOUT = 0x42; internal const int DBPROP_IRow = 0x107; internal const int DBPROP_MAXROWS = 0x49; internal const int DBPROP_MULTIPLERESULTS = 0xc4; internal const int DBPROP_ORDERBYCOLUNSINSELECT = 0x55; internal const int DBPROP_PROVIDERFILENAME = 0x60; internal const int DBPROP_QUOTEDIDENTIFIERCASE = 0x64; internal const int DBPROP_RESETDATASOURCE = 0xf7; internal const int DBPROP_SQLSUPPORT = 0x6d; internal const int DBPROP_UNIQUEROWS = 0xee; // property status internal const int DBPROPSTATUS_OK = 0; internal const int DBPROPSTATUS_NOTSUPPORTED = 1; internal const int DBPROPSTATUS_BADVALUE = 2; internal const int DBPROPSTATUS_BADOPTION = 3; internal const int DBPROPSTATUS_BADCOLUMN = 4; internal const int DBPROPSTATUS_NOTALLSETTABLE = 5; internal const int DBPROPSTATUS_NOTSETTABLE = 6; internal const int DBPROPSTATUS_NOTSET = 7; internal const int DBPROPSTATUS_CONFLICTING = 8; internal const int DBPROPSTATUS_NOTAVAILABLE = 9; internal const int DBPROPOPTIONS_REQUIRED = 0; internal const int DBPROPOPTIONS_OPTIONAL = 1; internal const int DBPROPFLAGS_WRITE = 0x400; internal const int DBPROPFLAGS_SESSION = 0x1000; // misc. property values internal const int DBPROPVAL_AO_RANDOM = 2; internal const int DBPROPVAL_CL_END = 2; internal const int DBPROPVAL_CL_START = 1; internal const int DBPROPVAL_CS_COMMUNICATIONFAILURE = 2; internal const int DBPROPVAL_CS_INITIALIZED = 1; internal const int DBPROPVAL_CS_UNINITIALIZED = 0; internal const int DBPROPVAL_GB_COLLATE = 16; internal const int DBPROPVAL_GB_CONTAINS_SELECT = 4; internal const int DBPROPVAL_GB_EQUALS_SELECT = 2; internal const int DBPROPVAL_GB_NO_RELATION = 8; internal const int DBPROPVAL_GB_NOT_SUPPORTED = 1; internal const int DBPROPVAL_IC_LOWER = 2; internal const int DBPROPVAL_IC_MIXED = 8; internal const int DBPROPVAL_IC_SENSITIVE = 4; internal const int DBPROPVAL_IC_UPPER = 1; internal const int DBPROPVAL_IN_ALLOWNULL = 0x00000000; /*internal const int DBPROPVAL_IN_DISALLOWNULL = 0x00000001; internal const int DBPROPVAL_IN_IGNORENULL = 0x00000002; internal const int DBPROPVAL_IN_IGNOREANYNULL = 0x00000004;*/ internal const int DBPROPVAL_MR_NOTSUPPORTED = 0; internal const int DBPROPVAL_RD_RESETALL = unchecked((int)0xffffffff); internal const int DBPROPVAL_OS_RESOURCEPOOLING = 0x00000001; internal const int DBPROPVAL_OS_TXNENLISTMENT = 0x00000002; internal const int DBPROPVAL_OS_CLIENTCURSOR = 0x00000004; internal const int DBPROPVAL_OS_AGR_AFTERSESSION = 0x00000008; internal const int DBPROPVAL_SQL_ODBC_MINIMUM = 1; internal const int DBPROPVAL_SQL_ESCAPECLAUSES = 0x00000100; // OLE DB providers never return pGuid-style bindings. // They are provided as a convenient shortcut for consumers supplying bindings all covered by the same GUID (for example, when creating bindings to access data). internal const int DBKIND_GUID_NAME = 0; internal const int DBKIND_GUID_PROPID = 1; internal const int DBKIND_NAME = 2; internal const int DBKIND_PGUID_NAME = 3; internal const int DBKIND_PGUID_PROPID = 4; internal const int DBKIND_PROPID = 5; internal const int DBKIND_GUID = 6; internal const int DBCOLUMNFLAGS_ISBOOKMARK = 0x01; internal const int DBCOLUMNFLAGS_ISLONG = 0x80; internal const int DBCOLUMNFLAGS_ISFIXEDLENGTH = 0x10; internal const int DBCOLUMNFLAGS_ISNULLABLE = 0x20; internal const int DBCOLUMNFLAGS_ISROWSET = 0x100000; internal const int DBCOLUMNFLAGS_ISROW = 0x200000; internal const int DBCOLUMNFLAGS_ISROWSET_DBCOLUMNFLAGS_ISROW = /*DBCOLUMNFLAGS_ISROWSET*/0x100000 | /*DBCOLUMNFLAGS_ISROW*/0x200000; internal const int DBCOLUMNFLAGS_ISLONG_DBCOLUMNFLAGS_ISSTREAM = /*DBCOLUMNFLAGS_ISLONG*/0x80 | /*DBCOLUMNFLAGS_ISSTREAM*/0x80000; internal const int DBCOLUMNFLAGS_ISROWID_DBCOLUMNFLAGS_ISROWVER = /*DBCOLUMNFLAGS_ISROWID*/0x100 | /*DBCOLUMNFLAGS_ISROWVER*/0x200; internal const int DBCOLUMNFLAGS_WRITE_DBCOLUMNFLAGS_WRITEUNKNOWN = /*DBCOLUMNFLAGS_WRITE*/0x4 | /*DBCOLUMNFLAGS_WRITEUNKNOWN*/0x8; internal const int DBCOLUMNFLAGS_ISNULLABLE_DBCOLUMNFLAGS_MAYBENULL = /*DBCOLUMNFLAGS_ISNULLABLE*/0x20 | /*DBCOLUMNFLAGS_MAYBENULL*/0x40; // accessor constants internal const int DBACCESSOR_ROWDATA = 0x2; internal const int DBACCESSOR_PARAMETERDATA = 0x4; // commandbuilder constants internal const int DBPARAMTYPE_INPUT = 0x01; internal const int DBPARAMTYPE_INPUTOUTPUT = 0x02; internal const int DBPARAMTYPE_OUTPUT = 0x03; internal const int DBPARAMTYPE_RETURNVALUE = 0x04; // parameter constants /*internal const int DBPARAMIO_NOTPARAM = 0; internal const int DBPARAMIO_INPUT = 0x1; internal const int DBPARAMIO_OUTPUT = 0x2;*/ /*internal const int DBPARAMFLAGS_ISINPUT = 0x1; internal const int DBPARAMFLAGS_ISOUTPUT = 0x2; internal const int DBPARAMFLAGS_ISSIGNED = 0x10; internal const int DBPARAMFLAGS_ISNULLABLE = 0x40; internal const int DBPARAMFLAGS_ISLONG = 0x80;*/ internal const int ParameterDirectionFlag = 3; // values of the searchable column in the provider types schema rowset internal const uint DB_UNSEARCHABLE = 1; internal const uint DB_LIKE_ONLY = 2; internal const uint DB_ALL_EXCEPT_LIKE = 3; internal const uint DB_SEARCHABLE = 4; static internal readonly IntPtr DB_INVALID_HACCESSOR = ADP.PtrZero; static internal readonly IntPtr DB_NULL_HCHAPTER = ADP.PtrZero; static internal readonly IntPtr DB_NULL_HROW = ADP.PtrZero; /*static internal readonly int SizeOf_tagDBPARAMINFO = Marshal.SizeOf(typeof(tagDBPARAMINFO));*/ static internal readonly int SizeOf_tagDBBINDING = Marshal.SizeOf(typeof(tagDBBINDING)); static internal readonly int SizeOf_tagDBCOLUMNINFO = Marshal.SizeOf(typeof(tagDBCOLUMNINFO)); static internal readonly int SizeOf_tagDBLITERALINFO = Marshal.SizeOf(typeof(tagDBLITERALINFO)); static internal readonly int SizeOf_tagDBPROPSET = Marshal.SizeOf(typeof(tagDBPROPSET)); static internal readonly int SizeOf_tagDBPROP = Marshal.SizeOf(typeof(tagDBPROP)); static internal readonly int SizeOf_tagDBPROPINFOSET = Marshal.SizeOf(typeof(tagDBPROPINFOSET)); static internal readonly int SizeOf_tagDBPROPINFO = Marshal.SizeOf(typeof(tagDBPROPINFO)); static internal readonly int SizeOf_tagDBPROPIDSET = Marshal.SizeOf(typeof(tagDBPROPIDSET)); static internal readonly int SizeOf_Guid = Marshal.SizeOf(typeof(Guid)); static internal readonly int SizeOf_Variant = 8 + (2 * ADP.PtrSize); // 16 on 32bit, 24 on 64bit static internal readonly int OffsetOf_tagDBPROP_Status = Marshal.OffsetOf(typeof(tagDBPROP), "dwStatus").ToInt32(); static internal readonly int OffsetOf_tagDBPROP_Value = Marshal.OffsetOf(typeof(tagDBPROP), "vValue").ToInt32(); static internal readonly int OffsetOf_tagDBPROPSET_Properties = Marshal.OffsetOf(typeof(tagDBPROPSET), "rgProperties").ToInt32(); static internal readonly int OffsetOf_tagDBPROPINFO_Value = Marshal.OffsetOf(typeof(tagDBPROPINFO), "vValue").ToInt32(); static internal readonly int OffsetOf_tagDBPROPIDSET_PropertySet = Marshal.OffsetOf(typeof(tagDBPROPIDSET), "guidPropertySet").ToInt32(); static internal readonly int OffsetOf_tagDBLITERALINFO_it = Marshal.OffsetOf(typeof(tagDBLITERALINFO), "it").ToInt32(); static internal readonly int OffsetOf_tagDBBINDING_obValue = Marshal.OffsetOf(typeof(tagDBBINDING), "obValue").ToInt32(); static internal readonly int OffsetOf_tagDBBINDING_wType = Marshal.OffsetOf(typeof(tagDBBINDING), "wType").ToInt32(); static internal Guid IID_NULL = Guid.Empty; static internal Guid IID_IUnknown = new Guid(0x00000000, 0x0000, 0x0000, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); static internal Guid IID_IDBInitialize = new Guid(0x0C733A8B, 0x2A1C, 0x11CE, 0xAD, 0xE5, 0x00, 0xAA, 0x00, 0x44, 0x77, 0x3D); static internal Guid IID_IDBCreateSession = new Guid(0x0C733A5D, 0x2A1C, 0x11CE, 0xAD, 0xE5, 0x00, 0xAA, 0x00, 0x44, 0x77, 0x3D); static internal Guid IID_IDBCreateCommand = new Guid(0x0C733A1D, 0x2A1C, 0x11CE, 0xAD, 0xE5, 0x00, 0xAA, 0x00, 0x44, 0x77, 0x3D); static internal Guid IID_ICommandText = new Guid(0x0C733A27, 0x2A1C, 0x11CE, 0xAD, 0xE5, 0x00, 0xAA, 0x00, 0x44, 0x77, 0x3D); static internal Guid IID_IMultipleResults = new Guid(0x0C733A90, 0x2A1C, 0x11CE, 0xAD, 0xE5, 0x00, 0xAA, 0x00, 0x44, 0x77, 0x3D); static internal Guid IID_IRow = new Guid(0x0C733AB4, 0x2A1C, 0x11CE, 0xAD, 0xE5, 0x00, 0xAA, 0x00, 0x44, 0x77, 0x3D); static internal Guid IID_IRowset = new Guid(0x0C733A7C, 0x2A1C, 0x11CE, 0xAD, 0xE5, 0x00, 0xAA, 0x00, 0x44, 0x77, 0x3D); static internal Guid IID_ISQLErrorInfo = new Guid(0x0C733A74, 0x2A1C, 0x11CE, 0xAD, 0xE5, 0x00, 0xAA, 0x00, 0x44, 0x77, 0x3D); static internal Guid CLSID_DataLinks = new Guid(0x2206CDB2, 0x19C1, 0x11D1, 0x89, 0xE0, 0x00, 0xC0, 0x4F, 0xD7, 0xA8, 0x29); static internal Guid DBGUID_DEFAULT = new Guid(0xc8b521fb, 0x5cf3, 0x11ce, 0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d); static internal Guid DBGUID_ROWSET = new Guid(0xc8b522f6, 0x5cf3, 0x11ce, 0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d); static internal Guid DBGUID_ROW = new Guid(0xc8b522f7, 0x5cf3, 0x11ce, 0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d); static internal Guid DBGUID_ROWDEFAULTSTREAM = new Guid(0x0C733AB7, 0x2A1C, 0x11CE, 0xAD, 0xE5, 0x00, 0xAA, 0x00, 0x44, 0x77, 0x3D); static internal readonly Guid CLSID_MSDASQL = new Guid(0xc8b522cb, 0x5cf3, 0x11ce, 0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d); static internal readonly object DBCOL_SPECIALCOL = new Guid(0xc8b52232, 0x5cf3, 0x11ce, 0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d); static internal readonly char[] ErrorTrimCharacters = new char[] { '\r', '\n', '\0' }; // used by ConnectionString hashtable, must be all lowercase internal const string Asynchronous_Processing = "asynchronous processing"; internal const string AttachDBFileName = "attachdbfilename"; internal const string Connect_Timeout = "connect timeout"; internal const string Data_Source = "data source"; internal const string File_Name = "file name"; internal const string Initial_Catalog = "initial catalog"; internal const string Password = "password"; internal const string Persist_Security_Info = "persist security info"; internal const string Provider = "provider"; internal const string Pwd = "pwd"; internal const string User_ID = "user id"; // used by OleDbConnection as property names internal const string Current_Catalog = "current catalog"; internal const string DBMS_Version = "dbms version"; internal const string Properties = "Properties"; // used by OleDbConnection to create and verify OLE DB Services internal const string DataLinks_CLSID = "CLSID\\{2206CDB2-19C1-11D1-89E0-00C04FD7A829}\\InprocServer32"; internal const string OLEDB_SERVICES = "OLEDB_SERVICES"; // used by OleDbConnection to eliminate post-open detection of 'Microsoft OLE DB Provider for ODBC Drivers' internal const string DefaultDescription_MSDASQL = "microsoft ole db provider for odbc drivers"; internal const string MSDASQL = "msdasql"; internal const string MSDASQLdot = "msdasql."; // used by OleDbPermission internal const string _Add = "add"; internal const string _Keyword = "keyword"; internal const string _Name = "name"; internal const string _Value = "value"; // IColumnsRowset column names internal const string DBCOLUMN_BASECATALOGNAME = "DBCOLUMN_BASECATALOGNAME"; internal const string DBCOLUMN_BASECOLUMNNAME = "DBCOLUMN_BASECOLUMNNAME"; internal const string DBCOLUMN_BASESCHEMANAME = "DBCOLUMN_BASESCHEMANAME"; internal const string DBCOLUMN_BASETABLENAME = "DBCOLUMN_BASETABLENAME"; internal const string DBCOLUMN_COLUMNSIZE = "DBCOLUMN_COLUMNSIZE"; internal const string DBCOLUMN_FLAGS = "DBCOLUMN_FLAGS"; internal const string DBCOLUMN_GUID = "DBCOLUMN_GUID"; internal const string DBCOLUMN_IDNAME = "DBCOLUMN_IDNAME"; internal const string DBCOLUMN_ISAUTOINCREMENT = "DBCOLUMN_ISAUTOINCREMENT"; internal const string DBCOLUMN_ISUNIQUE = "DBCOLUMN_ISUNIQUE"; internal const string DBCOLUMN_KEYCOLUMN = "DBCOLUMN_KEYCOLUMN"; internal const string DBCOLUMN_NAME = "DBCOLUMN_NAME"; internal const string DBCOLUMN_NUMBER = "DBCOLUMN_NUMBER"; internal const string DBCOLUMN_PRECISION = "DBCOLUMN_PRECISION"; internal const string DBCOLUMN_PROPID = "DBCOLUMN_PROPID"; internal const string DBCOLUMN_SCALE = "DBCOLUMN_SCALE"; internal const string DBCOLUMN_TYPE = "DBCOLUMN_TYPE"; internal const string DBCOLUMN_TYPEINFO = "DBCOLUMN_TYPEINFO"; // ISchemaRowset.GetRowset(OleDbSchemaGuid.Indexes) column names internal const string PRIMARY_KEY = "PRIMARY_KEY"; internal const string UNIQUE = "UNIQUE"; internal const string COLUMN_NAME = "COLUMN_NAME"; internal const string NULLS = "NULLS"; internal const string INDEX_NAME = "INDEX_NAME"; // ISchemaRowset.GetSchemaRowset(OleDbSchemaGuid.Procedure_Parameters) column names internal const string PARAMETER_NAME = "PARAMETER_NAME"; internal const string ORDINAL_POSITION = "ORDINAL_POSITION"; internal const string PARAMETER_TYPE = "PARAMETER_TYPE"; internal const string IS_NULLABLE = "IS_NULLABLE"; internal const string DATA_TYPE = "DATA_TYPE"; internal const string CHARACTER_MAXIMUM_LENGTH = "CHARACTER_MAXIMUM_LENGTH"; internal const string NUMERIC_PRECISION = "NUMERIC_PRECISION"; internal const string NUMERIC_SCALE = "NUMERIC_SCALE"; internal const string TYPE_NAME = "TYPE_NAME"; // DataTable.Select to sort on ordinal position for OleDbSchemaGuid.Procedure_Parameters internal const string ORDINAL_POSITION_ASC = "ORDINAL_POSITION ASC"; // OleDbConnection.GetOleDbSchemmaTable(OleDbSchemaGuid.SchemaGuids) table and column names internal const string SchemaGuids = "SchemaGuids"; internal const string Schema = "Schema"; internal const string RestrictionSupport = "RestrictionSupport"; // OleDbConnection.GetOleDbSchemmaTable(OleDbSchemaGuid.DbInfoKeywords) table and column names internal const string DbInfoKeywords = "DbInfoKeywords"; internal const string Keyword = "Keyword"; // Debug error string writeline static internal string ELookup(OleDbHResult hr) { StringBuilder builder = new StringBuilder(); builder.Append(hr.ToString()); if ((0 < builder.Length) && Char.IsDigit(builder[0])) { builder.Length = 0; } builder.Append("(0x"); builder.Append(((int)hr).ToString("X8", CultureInfo.InvariantCulture)); builder.Append(")"); return builder.ToString(); } #if DEBUG static readonly private Hashtable g_wlookpup = new Hashtable(); static internal string WLookup(short id) { string value = (string)g_wlookpup[id]; if (null == value) { value = "0x" + ((short)id).ToString("X2", CultureInfo.InvariantCulture) + " " + ((short)id); value += " " + ((DBTypeEnum)id).ToString(); g_wlookpup[id] = value; } return value; } private enum DBTypeEnum { EMPTY = 0, // NULL = 1, // I2 = 2, // I4 = 3, // R4 = 4, // R8 = 5, // CY = 6, // DATE = 7, // BSTR = 8, // IDISPATCH = 9, // ERROR = 10, // BOOL = 11, // VARIANT = 12, // IUNKNOWN = 13, // DECIMAL = 14, // I1 = 16, // UI1 = 17, // UI2 = 18, // UI4 = 19, // I8 = 20, // UI8 = 21, // FILETIME = 64, // 2.0 GUID = 72, // BYTES = 128, // STR = 129, // WSTR = 130, // NUMERIC = 131, // with potential overflow UDT = 132, // should never be encountered DBDATE = 133, // DBTIME = 134, // DBTIMESTAMP = 135, // granularity reduced from 1ns to 100ns (sql is 3.33 milli seconds) HCHAPTER = 136, // 1.5 PROPVARIANT = 138, // 2.0 - as variant VARNUMERIC = 139, // 2.0 - as string else ConversionException BYREF_I2 = 0x4002, BYREF_I4 = 0x4003, BYREF_R4 = 0x4004, BYREF_R8 = 0x4005, BYREF_CY = 0x4006, BYREF_DATE = 0x4007, BYREF_BSTR = 0x4008, BYREF_IDISPATCH = 0x4009, BYREF_ERROR = 0x400a, BYREF_BOOL = 0x400b, BYREF_VARIANT = 0x400c, BYREF_IUNKNOWN = 0x400d, BYREF_DECIMAL = 0x400e, BYREF_I1 = 0x4010, BYREF_UI1 = 0x4011, BYREF_UI2 = 0x4012, BYREF_UI4 = 0x4013, BYREF_I8 = 0x4014, BYREF_UI8 = 0x4015, BYREF_FILETIME = 0x4040, BYREF_GUID = 0x4048, BYREF_BYTES = 0x4080, BYREF_STR = 0x4081, BYREF_WSTR = 0x4082, BYREF_NUMERIC = 0x4083, BYREF_UDT = 0x4084, BYREF_DBDATE = 0x4085, BYREF_DBTIME = 0x4086, BYREF_DBTIMESTAMP = 0x4087, BYREF_HCHAPTER = 0x4088, BYREF_PROPVARIANT = 0x408a, BYREF_VARNUMERIC = 0x408b, VECTOR = 0x1000, ARRAY = 0x2000, BYREF = 0x4000, // RESERVED = 0x8000, // SystemException } #endif } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // 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 { using System.Reflection; using NLog.Targets; using System; using System.Globalization; using NLog.Config; #if ASYNC_SUPPORTED using System.Threading.Tasks; #endif using Xunit; public class LoggerTests : NLogTestBase { [Fact] public void TraceTest() { // test all possible overloads of the Trace() method for (int enabled = 0; enabled < 2; ++enabled) { if (enabled == 0) { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' levels='' writeTo='debug' /> </rules> </nlog>"); } else { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' levels='Trace' writeTo='debug' /> </rules> </nlog>"); } Logger logger = LogManager.GetLogger("A"); logger.Trace("message"); if (enabled == 1) AssertDebugLastMessage("debug", "message"); logger.Trace("message{0}", (ulong)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", (ulong)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Trace("message{0}", (long)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", (long)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Trace("message{0}", (uint)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", (uint)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Trace("message{0}", 1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", 2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Trace("message{0}", (ushort)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", (ushort)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Trace("message{0}", (sbyte)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", (sbyte)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Trace("message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string"); logger.Trace("message{0}", (short)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", (short)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Trace("message{0}", (byte)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", (byte)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Trace("message{0}", 'c'); if (enabled == 1) AssertDebugLastMessage("debug", "messagec"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", 'd'); if (enabled == 1) AssertDebugLastMessage("debug", "messaged"); logger.Trace("message{0}", "ddd"); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee"); logger.Trace("message{0}{1}", "ddd", 1); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1"); logger.Trace(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2"); logger.Trace("message{0}{1}{2}", "ddd", 1, "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee"); logger.Trace(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff"); logger.Trace("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg"); logger.Trace("message{0}", true); if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", false); if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", (float)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", 2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); logger.Trace(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); #pragma warning disable 0618 // Obsolete method requires testing until removed. logger.TraceException("message", new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "message"); #pragma warning restore 0618 logger.Trace("message", new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "message"); logger.Trace(delegate { return "message from lambda"; }); if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda"); if (enabled == 0) AssertDebugCounter("debug", 0); } } [Fact] public void DebugTest() { // test all possible overloads of the Debug() method for (int enabled = 0; enabled < 2; ++enabled) { if (enabled == 0) { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' levels='' writeTo='debug' /> </rules> </nlog>"); } else { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' levels='Debug' writeTo='debug' /> </rules> </nlog>"); } Logger logger = LogManager.GetLogger("A"); logger.Debug("message"); if (enabled == 1) AssertDebugLastMessage("debug", "message"); logger.Debug("message{0}", (ulong)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", (ulong)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Debug("message{0}", (long)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", (long)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Debug("message{0}", (uint)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", (uint)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Debug("message{0}", 1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", 2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Debug("message{0}", (ushort)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", (ushort)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Debug("message{0}", (sbyte)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", (sbyte)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Debug("message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string"); logger.Debug("message{0}", (short)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", (short)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Debug("message{0}", (byte)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", (byte)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Debug("message{0}", 'c'); if (enabled == 1) AssertDebugLastMessage("debug", "messagec"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", 'd'); if (enabled == 1) AssertDebugLastMessage("debug", "messaged"); logger.Debug("message{0}", "ddd"); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee"); logger.Debug("message{0}{1}", "ddd", 1); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1"); logger.Debug(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2"); logger.Debug("message{0}{1}{2}", "ddd", 1, "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee"); logger.Debug(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff"); logger.Debug("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg"); logger.Debug("message{0}", true); if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", false); if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", (float)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", 2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); logger.Debug(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); #pragma warning disable 0618 // Obsolete method requires testing until completely removed. logger.DebugException("message", new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "message"); #pragma warning restore 0618 logger.Debug(delegate { return "message from lambda"; }); if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda"); if (enabled == 0) AssertDebugCounter("debug", 0); } } [Fact] public void InfoTest() { // test all possible overloads of the Info() method for (int enabled = 0; enabled < 2; ++enabled) { if (enabled == 0) { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' levels='' writeTo='debug' /> </rules> </nlog>"); } else { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' levels='Info' writeTo='debug' /> </rules> </nlog>"); } Logger logger = LogManager.GetLogger("A"); logger.Info("message"); if (enabled == 1) AssertDebugLastMessage("debug", "message"); logger.Info("message{0}", (ulong)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Info(CultureInfo.InvariantCulture, "message{0}", (ulong)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Info("message{0}", (long)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Info(CultureInfo.InvariantCulture, "message{0}", (long)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Info("message{0}", (uint)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Info(CultureInfo.InvariantCulture, "message{0}", (uint)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Info("message{0}", 1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Info(CultureInfo.InvariantCulture, "message{0}", 2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Info("message{0}", (ushort)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Info(CultureInfo.InvariantCulture, "message{0}", (ushort)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Info("message{0}", (sbyte)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Info(CultureInfo.InvariantCulture, "message{0}", (sbyte)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Info("message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string"); logger.Info(CultureInfo.InvariantCulture, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string"); logger.Info("message{0}", (short)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Info(CultureInfo.InvariantCulture, "message{0}", (short)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Info("message{0}", (byte)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Info(CultureInfo.InvariantCulture, "message{0}", (byte)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Info("message{0}", 'c'); if (enabled == 1) AssertDebugLastMessage("debug", "messagec"); logger.Info(CultureInfo.InvariantCulture, "message{0}", 'd'); if (enabled == 1) AssertDebugLastMessage("debug", "messaged"); logger.Info("message{0}", "ddd"); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd"); logger.Info(CultureInfo.InvariantCulture, "message{0}", "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee"); logger.Info("message{0}{1}", "ddd", 1); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1"); logger.Info(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2"); logger.Info("message{0}{1}{2}", "ddd", 1, "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee"); logger.Info(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff"); logger.Info("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg"); logger.Info("message{0}", true); if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue"); logger.Info(CultureInfo.InvariantCulture, "message{0}", false); if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse"); logger.Info(CultureInfo.InvariantCulture, "message{0}", (float)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); logger.Info(CultureInfo.InvariantCulture, "message{0}", 2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); logger.Info(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); #pragma warning disable 0618 // Obsolete method requires testing until removed. logger.InfoException("message", new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "message"); #pragma warning restore 0618 logger.Info("message", new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "message"); logger.Info(delegate { return "message from lambda"; }); if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda"); if (enabled == 0) AssertDebugCounter("debug", 0); } } [Fact] public void WarnTest() { // test all possible overloads of the Warn() method for (int enabled = 0; enabled < 2; ++enabled) { if (enabled == 0) { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' levels='' writeTo='debug' /> </rules> </nlog>"); } else { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); } Logger logger = LogManager.GetLogger("A"); logger.Warn("message"); if (enabled == 1) AssertDebugLastMessage("debug", "message"); logger.Warn("message{0}", (ulong)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", (ulong)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Warn("message{0}", (long)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", (long)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Warn("message{0}", (uint)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", (uint)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Warn("message{0}", 1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", 2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Warn("message{0}", (ushort)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", (ushort)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Warn("message{0}", (sbyte)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", (sbyte)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Warn("message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string"); logger.Warn("message{0}", (short)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", (short)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Warn("message{0}", (byte)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", (byte)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Warn("message{0}", 'c'); if (enabled == 1) AssertDebugLastMessage("debug", "messagec"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", 'd'); if (enabled == 1) AssertDebugLastMessage("debug", "messaged"); logger.Warn("message{0}", "ddd"); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee"); logger.Warn("message{0}{1}", "ddd", 1); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1"); logger.Warn(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2"); logger.Warn("message{0}{1}{2}", "ddd", 1, "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee"); logger.Warn(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff"); logger.Warn("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg"); logger.Warn("message{0}", true); if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", false); if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", (float)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", 2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); logger.Warn(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); #pragma warning disable 0618 // Obsolete method requires testing until removed. logger.WarnException("message", new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "message"); #pragma warning restore 0618 logger.Warn("message", new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "message"); logger.Warn(delegate { return "message from lambda"; }); if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda"); if (enabled == 0) AssertDebugCounter("debug", 0); } } [Fact] public void ErrorTest() { // test all possible overloads of the Error() method for (int enabled = 0; enabled < 2; ++enabled) { if (enabled == 0) { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' levels='' writeTo='debug' /> </rules> </nlog>"); } else { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' levels='Error' writeTo='debug' /> </rules> </nlog>"); } Logger logger = LogManager.GetLogger("A"); logger.Error("message"); if (enabled == 1) AssertDebugLastMessage("debug", "message"); logger.Error("message{0}", (ulong)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Error(CultureInfo.InvariantCulture, "message{0}", (ulong)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Error("message{0}", (long)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Error(CultureInfo.InvariantCulture, "message{0}", (long)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Error("message{0}", (uint)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Error(CultureInfo.InvariantCulture, "message{0}", (uint)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Error("message{0}", 1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Error(CultureInfo.InvariantCulture, "message{0}", 2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Error("message{0}", (ushort)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Error(CultureInfo.InvariantCulture, "message{0}", (ushort)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Error("message{0}", (sbyte)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Error(CultureInfo.InvariantCulture, "message{0}", (sbyte)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Error("message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string"); logger.Error(CultureInfo.InvariantCulture, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string"); logger.Error("message{0}", (short)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Error(CultureInfo.InvariantCulture, "message{0}", (short)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Error("message{0}", (byte)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Error(CultureInfo.InvariantCulture, "message{0}", (byte)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Error("message{0}", 'c'); if (enabled == 1) AssertDebugLastMessage("debug", "messagec"); logger.Error(CultureInfo.InvariantCulture, "message{0}", 'd'); if (enabled == 1) AssertDebugLastMessage("debug", "messaged"); logger.Error("message{0}", "ddd"); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd"); logger.Error(CultureInfo.InvariantCulture, "message{0}", "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee"); logger.Error("message{0}{1}", "ddd", 1); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1"); logger.Error(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2"); logger.Error("message{0}{1}{2}", "ddd", 1, "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee"); logger.Error(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff"); logger.Error("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg"); logger.Error("message{0}", true); if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue"); logger.Error(CultureInfo.InvariantCulture, "message{0}", false); if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse"); logger.Error(CultureInfo.InvariantCulture, "message{0}", (float)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); logger.Error(CultureInfo.InvariantCulture, "message{0}", 2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); logger.Error(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); #pragma warning disable 0618 // Obsolete method requires testing until completely removed. logger.ErrorException("message", new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "message"); #pragma warning restore 0618 logger.Error("message", new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "message"); logger.Error(delegate { return "message from lambda"; }); if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda"); if (enabled == 0) AssertDebugCounter("debug", 0); } } [Fact] public void FatalTest() { // test all possible overloads of the Fatal() method for (int enabled = 0; enabled < 2; ++enabled) { if (enabled == 0) { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' levels='' writeTo='debug' /> </rules> </nlog>"); } else { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); } Logger logger = LogManager.GetLogger("A"); logger.Fatal("message"); if (enabled == 1) AssertDebugLastMessage("debug", "message"); logger.Fatal("message{0}", (ulong)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (ulong)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Fatal("message{0}", (long)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (long)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Fatal("message{0}", (uint)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (uint)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Fatal("message{0}", 1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", 2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Fatal("message{0}", (ushort)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (ushort)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Fatal("message{0}", (sbyte)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (sbyte)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Fatal("message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string"); logger.Fatal("message{0}", (short)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (short)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Fatal("message{0}", (byte)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (byte)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Fatal("message{0}", 'c'); if (enabled == 1) AssertDebugLastMessage("debug", "messagec"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", 'd'); if (enabled == 1) AssertDebugLastMessage("debug", "messaged"); logger.Fatal("message{0}", "ddd"); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee"); logger.Fatal("message{0}{1}", "ddd", 1); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2"); logger.Fatal("message{0}{1}{2}", "ddd", 1, "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff"); logger.Fatal("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg"); logger.Fatal("message{0}", true); if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", false); if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (float)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", 2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); #pragma warning disable 0618 // Obsolete method requires testing until removed. logger.FatalException("message", new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "message"); #pragma warning restore 0618 logger.Fatal("message", new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "message"); logger.Fatal(delegate { return "message from lambda"; }); if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda"); if (enabled == 0) AssertDebugCounter("debug", 0); } } [Fact] public void LogTest() { // test all possible overloads of the Log(level) method foreach (LogLevel level in new LogLevel[] { LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal }) { for (int enabled = 0; enabled < 2; ++enabled) { if (enabled == 0) { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' levels='' writeTo='debug' /> </rules> </nlog>"); } else { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' levels='" + level.Name + @"' writeTo='debug' /> </rules> </nlog>"); } Logger logger = LogManager.GetLogger("A"); logger.Log(level, "message"); if (enabled == 1) AssertDebugLastMessage("debug", "message"); logger.Log(level, "message{0}", (ulong)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (ulong)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Log(level, "message{0}", (long)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (long)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Log(level, "message{0}", (uint)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (uint)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Log(level, "message{0}", (int)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (int)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Log(level, "message{0}", (ushort)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (ushort)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Log(level, "message{0}", (sbyte)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (sbyte)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Log(level, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", this); if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string"); logger.Log(level, "message{0}", (short)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (short)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Log(level, "message{0}", (byte)1); if (enabled == 1) AssertDebugLastMessage("debug", "message1"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (byte)2); if (enabled == 1) AssertDebugLastMessage("debug", "message2"); logger.Log(level, "message{0}", 'c'); if (enabled == 1) AssertDebugLastMessage("debug", "messagec"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", 'd'); if (enabled == 1) AssertDebugLastMessage("debug", "messaged"); logger.Log(level, "message{0}", "ddd"); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee"); logger.Log(level, "message{0}{1}", "ddd", 1); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2"); logger.Log(level, "message{0}{1}{2}", "ddd", 1, "eee"); if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff"); logger.Log(level, "message{0}{1}{2}{3}", "eee", 2, "fff", "ggg"); if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg"); logger.Log(level, "message{0}", true); if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", false); if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (float)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (double)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (decimal)2.5); if (enabled == 1) AssertDebugLastMessage("debug", "message2.5"); logger.Log(level, "message", new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "message"); #pragma warning disable 0618 // Obsolete method requires testing until removed. logger.LogException(level, "message", new Exception("test")); if (enabled == 1) AssertDebugLastMessage("debug", "message"); #pragma warning restore 0618 logger.Log(level, delegate { return "message from lambda"; }); if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda"); if (enabled == 0) AssertDebugCounter("debug", 0); } } } [Fact] public void SwallowTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' levels='Error' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("A"); bool warningFix = true; bool executed = false; logger.Swallow(() => executed = true); Assert.True(executed); Assert.Equal(1, logger.Swallow(() => 1)); Assert.Equal(1, logger.Swallow(() => 1, 2)); #if ASYNC_SUPPORTED executed = false; logger.SwallowAsync(async () => { await Task.Delay(20); executed = true; }).Wait(); Assert.True(executed); Assert.Equal(1, logger.SwallowAsync(async () => { await Task.Delay(20); return 1; }).Result); Assert.Equal(1, logger.SwallowAsync(async () => { await Task.Delay(20); return 1; }, 2).Result); #endif AssertDebugCounter("debug", 0); logger.Swallow(() => { throw new InvalidOperationException("Test message 1"); }); AssertDebugLastMessageContains("debug", "Test message 1"); Assert.Equal(0, logger.Swallow(() => { if (warningFix) throw new InvalidOperationException("Test message 2"); return 1; })); AssertDebugLastMessageContains("debug", "Test message 2"); Assert.Equal(2, logger.Swallow(() => { if (warningFix) throw new InvalidOperationException("Test message 3"); return 1; }, 2)); AssertDebugLastMessageContains("debug", "Test message 3"); #if ASYNC_SUPPORTED logger.SwallowAsync(async () => { await Task.Delay(20); throw new InvalidOperationException("Test message 4"); }).Wait(); AssertDebugLastMessageContains("debug", "Test message 4"); Assert.Equal(0, logger.SwallowAsync(async () => { await Task.Delay(20); if (warningFix) throw new InvalidOperationException("Test message 5"); return 1; }).Result); AssertDebugLastMessageContains("debug", "Test message 5"); Assert.Equal(2, logger.SwallowAsync(async () => { await Task.Delay(20); if (warningFix) throw new InvalidOperationException("Test message 6"); return 1; }, 2).Result); AssertDebugLastMessageContains("debug", "Test message 6"); #endif } [Fact] public void StringFormatWillNotCauseExceptions() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minLevel='Info' writeTo='debug' /> </rules> </nlog>"); Logger l = LogManager.GetLogger("StringFormatWillNotCauseExceptions"); // invalid format string l.Info("aaaa {0"); AssertDebugLastMessage("debug", "aaaa {0"); } [Fact] public void MultipleLoggersWithSameNameShouldBothReceiveMessages() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='first' type='Debug' layout='${message}' /> <target name='second' type='Debug' layout='${message}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='first' /> <logger name='*' minlevel='Debug' writeTo='second' /> </rules> </nlog>"); var logger = LogManager.GetLogger("A"); const string logMessage = "Anything"; logger.Debug(logMessage); AssertDebugLastMessage("first", logMessage); AssertDebugLastMessage("second", logMessage); } [Fact] public void When_Logging_LogEvent_Without_Level_Defined_No_Exception_Should_Be_Thrown() { var config = new LoggingConfiguration(); var target = new MyTarget(); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, target)); LogManager.Configuration = config; var logger = LogManager.GetLogger("A"); Assert.Throws<InvalidOperationException>(() => logger.Log(new LogEventInfo())); } public abstract class BaseWrapper { public void Log(string what) { InternalLog(what); } protected abstract void InternalLog(string what); } [Fact] public void Log_LoggerWrappedAndStackTraceEnabled_UserStackFrameIsCurrentMethod() { LoggingConfiguration config = new LoggingConfiguration(); MyTarget target = new MyTarget(); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, target)); LogManager.Configuration = config; MyWrapper wrapper = new MyWrapper(); wrapper.Log("test"); Assert.Equal(MethodBase.GetCurrentMethod(), target.LastEvent.UserStackFrame.GetMethod()); } public class MyWrapper : BaseWrapper { private readonly Logger wrapperLogger; public MyWrapper() { wrapperLogger = LogManager.GetLogger("WrappedLogger"); } protected override void InternalLog(string what) { LogEventInfo info = new LogEventInfo(LogLevel.Warn, wrapperLogger.Name, what); // Provide BaseWrapper as wrapper type. // Expected: UserStackFrame should point to the method that calls a // method of BaseWrapper. wrapperLogger.Log(typeof(BaseWrapper), info); } } public class MyTarget : TargetWithLayout { public MyTarget() { // enforce creation of stack trace Layout = "${stacktrace}"; } public LogEventInfo LastEvent { get; private set; } protected override void Write(LogEventInfo logEvent) { LastEvent = logEvent; base.Write(logEvent); } } public override string ToString() { return "object-to-string"; } } }
// 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.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Security.Cryptography; namespace Internal.Cryptography { internal static partial class OidLookup { private static readonly ConcurrentDictionary<string, string> s_lateBoundOidToFriendlyName = new ConcurrentDictionary<string, string>(); private static readonly ConcurrentDictionary<string, string> s_lateBoundFriendlyNameToOid = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase); // // Attempts to map a friendly name to an OID. Returns null if not a known name. // public static string ToFriendlyName(string oid, OidGroup oidGroup, bool fallBackToAllGroups) { if (oid == null) throw new ArgumentNullException(nameof(oid)); string mappedName; bool shouldUseCache = ShouldUseCache(oidGroup); // On Unix shouldUseCache is always true, so no matter what OidGroup is passed in the Windows // friendly name will be returned. // // On Windows shouldUseCache is only true for OidGroup.All, because otherwise the OS may filter // out the answer based on the group criteria. if (shouldUseCache) { if (s_oidToFriendlyName.TryGetValue(oid, out mappedName) || s_compatOids.TryGetValue(oid, out mappedName) || s_lateBoundOidToFriendlyName.TryGetValue(oid, out mappedName)) { return mappedName; } } mappedName = NativeOidToFriendlyName(oid, oidGroup, fallBackToAllGroups); if (shouldUseCache && mappedName != null) { s_lateBoundOidToFriendlyName.TryAdd(oid, mappedName); // Don't add the reverse here. Just because oid => name doesn't mean name => oid. // And don't bother doing the reverse lookup proactively, just wait until they ask for it. } return mappedName; } // // Attempts to retrieve the friendly name for an OID. Returns null if not a known or valid OID. // public static string ToOid(string friendlyName, OidGroup oidGroup, bool fallBackToAllGroups) { if (friendlyName == null) throw new ArgumentNullException(nameof(friendlyName)); if (friendlyName.Length == 0) return null; string mappedOid; bool shouldUseCache = ShouldUseCache(oidGroup); if (shouldUseCache) { if (s_friendlyNameToOid.TryGetValue(friendlyName, out mappedOid) || s_lateBoundFriendlyNameToOid.TryGetValue(friendlyName, out mappedOid)) { return mappedOid; } } mappedOid = NativeFriendlyNameToOid(friendlyName, oidGroup, fallBackToAllGroups); if (shouldUseCache && mappedOid != null) { s_lateBoundFriendlyNameToOid.TryAdd(friendlyName, mappedOid); // Don't add the reverse here. Friendly Name => OID is a case insensitive search, // so the casing provided as input here may not be the 'correct' one. Just let // ToFriendlyName capture the response and cache it itself. } return mappedOid; } /// <summary>Expected size of <see cref="s_friendlyNameToOid"/>.</summary> private const int FriendlyNameToOidCount = 103; // This table was originally built by extracting every szOID #define out of wincrypt.h, // and running them through new Oid(string) on Windows 10. Then, take the list of everything // which produced a FriendlyName value, and run it through two other languages. If all 3 agree // on the mapping, consider the value to be non-localized. // // This original list was produced on English (Win10), cross-checked with Spanish (Win8.1) and // Japanese (Win10). // // Sometimes wincrypt.h has more than one OID which results in the same name. The OIDs whose value // doesn't roundtrip (new Oid(new Oid(value).FriendlyName).Value) are contained in s_compatOids. // // X-Plat: The names (and casing) in this table come from Windows. Part of the intent of this table // is to prevent issues wherein an identifier is different between CoreFX\Windows and CoreFX\Unix; // since any existing code would be using the Windows identifier, it is the de facto standard. private static readonly Dictionary<string, string> s_friendlyNameToOid = new Dictionary<string, string>(FriendlyNameToOidCount, StringComparer.OrdinalIgnoreCase) { { "3des", "1.2.840.113549.3.7" }, { "aes128", "2.16.840.1.101.3.4.1.2" }, { "aes128wrap", "2.16.840.1.101.3.4.1.5" }, { "aes192", "2.16.840.1.101.3.4.1.22" }, { "aes192wrap", "2.16.840.1.101.3.4.1.25" }, { "aes256", "2.16.840.1.101.3.4.1.42" }, { "aes256wrap", "2.16.840.1.101.3.4.1.45" }, { "brainpoolP160r1", "1.3.36.3.3.2.8.1.1.1" }, { "brainpoolP160t1", "1.3.36.3.3.2.8.1.1.2" }, { "brainpoolP192r1", "1.3.36.3.3.2.8.1.1.3" }, { "brainpoolP192t1", "1.3.36.3.3.2.8.1.1.4" }, { "brainpoolP224r1", "1.3.36.3.3.2.8.1.1.5" }, { "brainpoolP224t1", "1.3.36.3.3.2.8.1.1.6" }, { "brainpoolP256r1", "1.3.36.3.3.2.8.1.1.7" }, { "brainpoolP256t1", "1.3.36.3.3.2.8.1.1.8" }, { "brainpoolP320r1", "1.3.36.3.3.2.8.1.1.9" }, { "brainpoolP320t1", "1.3.36.3.3.2.8.1.1.10" }, { "brainpoolP384r1", "1.3.36.3.3.2.8.1.1.11" }, { "brainpoolP384t1", "1.3.36.3.3.2.8.1.1.12" }, { "brainpoolP512r1", "1.3.36.3.3.2.8.1.1.13" }, { "brainpoolP512t1", "1.3.36.3.3.2.8.1.1.14" }, { "C", "2.5.4.6" }, { "CMS3DESwrap", "1.2.840.113549.1.9.16.3.6" }, { "CMSRC2wrap", "1.2.840.113549.1.9.16.3.7" }, { "CN", "2.5.4.3" }, { "CPS", "1.3.6.1.5.5.7.2.1" }, { "DC", "0.9.2342.19200300.100.1.25" }, { "des", "1.3.14.3.2.7" }, { "Description", "2.5.4.13" }, { "DH", "1.2.840.10046.2.1" }, { "dnQualifier", "2.5.4.46" }, { "DSA", "1.2.840.10040.4.1" }, { "dsaSHA1", "1.3.14.3.2.27" }, { "E", "1.2.840.113549.1.9.1" }, { "ec192wapi", "1.2.156.11235.1.1.2.1" }, { "ECC", "1.2.840.10045.2.1" }, { "ECDH_STD_SHA1_KDF", "1.3.133.16.840.63.0.2" }, { "ECDH_STD_SHA256_KDF", "1.3.132.1.11.1" }, { "ECDH_STD_SHA384_KDF", "1.3.132.1.11.2" }, { "ECDSA_P256", "1.2.840.10045.3.1.7" }, { "ECDSA_P384", "1.3.132.0.34" }, { "ECDSA_P521", "1.3.132.0.35" }, { "ESDH", "1.2.840.113549.1.9.16.3.5" }, { "G", "2.5.4.42" }, { "I", "2.5.4.43" }, { "L", "2.5.4.7" }, { "md2", "1.2.840.113549.2.2" }, { "md2RSA", "1.2.840.113549.1.1.2" }, { "md4", "1.2.840.113549.2.4" }, { "md4RSA", "1.2.840.113549.1.1.3" }, { "md5", "1.2.840.113549.2.5" }, { "md5RSA", "1.2.840.113549.1.1.4" }, { "mgf1", "1.2.840.113549.1.1.8" }, { "mosaicKMandUpdSig", "2.16.840.1.101.2.1.1.20" }, { "mosaicUpdatedSig", "2.16.840.1.101.2.1.1.19" }, { "nistP192", "1.2.840.10045.3.1.1" }, { "nistP224", "1.3.132.0.33" }, { "NO_SIGN", "1.3.6.1.5.5.7.6.2" }, { "O", "2.5.4.10" }, { "OU", "2.5.4.11" }, { "Phone", "2.5.4.20" }, { "POBox", "2.5.4.18" }, { "PostalCode", "2.5.4.17" }, { "rc2", "1.2.840.113549.3.2" }, { "rc4", "1.2.840.113549.3.4" }, { "RSA", "1.2.840.113549.1.1.1" }, { "RSAES_OAEP", "1.2.840.113549.1.1.7" }, { "RSASSA-PSS", "1.2.840.113549.1.1.10" }, { "S", "2.5.4.8" }, { "secP160k1", "1.3.132.0.9" }, { "secP160r1", "1.3.132.0.8" }, { "secP160r2", "1.3.132.0.30" }, { "secP192k1", "1.3.132.0.31" }, { "secP224k1", "1.3.132.0.32" }, { "secP256k1", "1.3.132.0.10" }, { "SERIALNUMBER", "2.5.4.5" }, { "sha1", "1.3.14.3.2.26" }, { "sha1DSA", "1.2.840.10040.4.3" }, { "sha1ECDSA", "1.2.840.10045.4.1" }, { "sha1RSA", "1.2.840.113549.1.1.5" }, { "sha256", "2.16.840.1.101.3.4.2.1" }, { "sha256ECDSA", "1.2.840.10045.4.3.2" }, { "sha256RSA", "1.2.840.113549.1.1.11" }, { "sha384", "2.16.840.1.101.3.4.2.2" }, { "sha384ECDSA", "1.2.840.10045.4.3.3" }, { "sha384RSA", "1.2.840.113549.1.1.12" }, { "sha512", "2.16.840.1.101.3.4.2.3" }, { "sha512ECDSA", "1.2.840.10045.4.3.4" }, { "sha512RSA", "1.2.840.113549.1.1.13" }, { "SN", "2.5.4.4" }, { "specifiedECDSA", "1.2.840.10045.4.3" }, { "STREET", "2.5.4.9" }, { "T", "2.5.4.12" }, { "TPMManufacturer", "2.23.133.2.1" }, { "TPMModel", "2.23.133.2.2" }, { "TPMVersion", "2.23.133.2.3" }, { "wtls9", "2.23.43.1.4.9" }, { "X21Address", "2.5.4.24" }, { "x962P192v2", "1.2.840.10045.3.1.2" }, { "x962P192v3", "1.2.840.10045.3.1.3" }, { "x962P239v1", "1.2.840.10045.3.1.4" }, { "x962P239v2", "1.2.840.10045.3.1.5" }, { "x962P239v3", "1.2.840.10045.3.1.6" }, }; private static readonly Dictionary<string, string> s_oidToFriendlyName = InvertWithDefaultComparer(s_friendlyNameToOid); private static readonly Dictionary<string, string> s_compatOids = new Dictionary<string, string> { { "1.2.840.113549.1.3.1", "DH" }, { "1.3.14.3.2.12", "DSA" }, { "1.3.14.3.2.13", "sha1DSA" }, { "1.3.14.3.2.15", "shaRSA" }, { "1.3.14.3.2.18", "sha" }, { "1.3.14.3.2.2", "md4RSA" }, { "1.3.14.3.2.22", "RSA_KEYX" }, { "1.3.14.3.2.29", "sha1RSA" }, { "1.3.14.3.2.3", "md5RSA" }, { "1.3.14.3.2.4", "md4RSA" }, { "1.3.14.7.2.3.1", "md2RSA" }, }; private static Dictionary<string, string> InvertWithDefaultComparer(Dictionary<string, string> source) { var result = new Dictionary<string, string>(source.Count); foreach (KeyValuePair<string, string> item in source) { result.Add(item.Value, item.Key); } return result; } #if DEBUG static OidLookup() { // Validate we hardcoded the right dictionary size Debug.Assert(s_friendlyNameToOid.Count == FriendlyNameToOidCount, $"Expected {nameof(s_friendlyNameToOid)}.{nameof(s_friendlyNameToOid.Count)} == {FriendlyNameToOidCount}, got {s_friendlyNameToOid.Count}"); Debug.Assert(s_oidToFriendlyName.Count == FriendlyNameToOidCount, $"Expected {nameof(s_oidToFriendlyName)}.{nameof(s_oidToFriendlyName.Count)} == {FriendlyNameToOidCount}, got {s_oidToFriendlyName.Count}"); ExtraStaticDebugValidation(); } static partial void ExtraStaticDebugValidation(); #endif } }
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Text; using System.Web; using Nop.Core.Data; using Nop.Core.Infrastructure; namespace Nop.Core { /// <summary> /// Represents a common helper /// </summary> public partial class WebHelper : IWebHelper { #region Fields private readonly HttpContextBase _httpContext; private readonly string[] _staticFileExtensions; #endregion #region Constructor /// <summary> /// Ctor /// </summary> /// <param name="httpContext">HTTP context</param> public WebHelper(HttpContextBase httpContext) { this._httpContext = httpContext; this._staticFileExtensions = new[] { ".axd", ".ashx", ".bmp", ".css", ".gif", ".htm", ".html", ".ico", ".jpeg", ".jpg", ".js", ".png", ".rar", ".zip" }; } #endregion #region Utilities protected virtual Boolean IsRequestAvailable(HttpContextBase httpContext) { if (httpContext == null) return false; try { if (httpContext.Request == null) return false; } catch (HttpException) { return false; } return true; } protected virtual bool TryWriteWebConfig() { try { // In medium trust, "UnloadAppDomain" is not supported. Touch web.config // to force an AppDomain restart. File.SetLastWriteTimeUtc(CommonHelper.MapPath("~/web.config"), DateTime.UtcNow); return true; } catch { return false; } } protected virtual bool TryWriteGlobalAsax() { try { //When a new plugin is dropped in the Plugins folder and is installed into nopCommerce, //even if the plugin has registered routes for its controllers, //these routes will not be working as the MVC framework couldn't //find the new controller types and couldn't instantiate the requested controller. //That's why you get these nasty errors //i.e "Controller does not implement IController". //The issue is described here: http://www.nopcommerce.com/boards/t/10969/nop-20-plugin.aspx?p=4#51318 //The solution is to touch global.asax file File.SetLastWriteTimeUtc(CommonHelper.MapPath("~/global.asax"), DateTime.UtcNow); return true; } catch { return false; } } #endregion #region Methods /// <summary> /// Get URL referrer /// </summary> /// <returns>URL referrer</returns> public virtual string GetUrlReferrer() { string referrerUrl = string.Empty; //URL referrer is null in some case (for example, in IE 8) if (IsRequestAvailable(_httpContext) && _httpContext.Request.UrlReferrer != null) referrerUrl = _httpContext.Request.UrlReferrer.PathAndQuery; return referrerUrl; } /// <summary> /// Get context IP address /// </summary> /// <returns>URL referrer</returns> public virtual string GetCurrentIpAddress() { if (!IsRequestAvailable(_httpContext)) return string.Empty; var result = ""; try { if (_httpContext.Request.Headers != null) { //The X-Forwarded-For (XFF) HTTP header field is a de facto standard //for identifying the originating IP address of a client //connecting to a web server through an HTTP proxy or load balancer. var forwardedHttpHeader = "X-FORWARDED-FOR"; if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["ForwardedHTTPheader"])) { //but in some cases server use other HTTP header //in these cases an administrator can specify a custom Forwarded HTTP header //e.g. CF-Connecting-IP, X-FORWARDED-PROTO, etc forwardedHttpHeader = ConfigurationManager.AppSettings["ForwardedHTTPheader"]; } //it's used for identifying the originating IP address of a client connecting to a web server //through an HTTP proxy or load balancer. string xff = _httpContext.Request.Headers.AllKeys .Where(x => forwardedHttpHeader.Equals(x, StringComparison.InvariantCultureIgnoreCase)) .Select(k => _httpContext.Request.Headers[k]) .FirstOrDefault(); //if you want to exclude private IP addresses, then see http://stackoverflow.com/questions/2577496/how-can-i-get-the-clients-ip-address-in-asp-net-mvc if (!String.IsNullOrEmpty(xff)) { string lastIp = xff.Split(new[] { ',' }).FirstOrDefault(); result = lastIp; } } if (String.IsNullOrEmpty(result) && _httpContext.Request.UserHostAddress != null) { result = _httpContext.Request.UserHostAddress; } } catch { return result; } //some validation if (result == "::1") result = "127.0.0.1"; //remove port if (!String.IsNullOrEmpty(result)) { int index = result.IndexOf(":", StringComparison.InvariantCultureIgnoreCase); if (index > 0) result = result.Substring(0, index); } return result; } /// <summary> /// Gets this page name /// </summary> /// <param name="includeQueryString">Value indicating whether to include query strings</param> /// <returns>Page name</returns> public virtual string GetThisPageUrl(bool includeQueryString) { bool useSsl = IsCurrentConnectionSecured(); return GetThisPageUrl(includeQueryString, useSsl); } /// <summary> /// Gets this page name /// </summary> /// <param name="includeQueryString">Value indicating whether to include query strings</param> /// <param name="useSsl">Value indicating whether to get SSL protected page</param> /// <returns>Page name</returns> public virtual string GetThisPageUrl(bool includeQueryString, bool useSsl) { if (!IsRequestAvailable(_httpContext)) return string.Empty; //get the host considering using SSL var url = GetStoreHost(useSsl).TrimEnd('/'); //get full URL with or without query string url += includeQueryString ? _httpContext.Request.RawUrl : _httpContext.Request.Path; return url.ToLowerInvariant(); } /// <summary> /// Gets a value indicating whether current connection is secured /// </summary> /// <returns>true - secured, false - not secured</returns> public virtual bool IsCurrentConnectionSecured() { bool useSsl = false; if (IsRequestAvailable(_httpContext)) { //when your hosting uses a load balancer on their server then the Request.IsSecureConnection is never got set to true //1. use HTTP_CLUSTER_HTTPS? if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Use_HTTP_CLUSTER_HTTPS"]) && Convert.ToBoolean(ConfigurationManager.AppSettings["Use_HTTP_CLUSTER_HTTPS"])) { useSsl = ServerVariables("HTTP_CLUSTER_HTTPS") == "on"; } //2. use HTTP_X_FORWARDED_PROTO? else if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Use_HTTP_X_FORWARDED_PROTO"]) && Convert.ToBoolean(ConfigurationManager.AppSettings["Use_HTTP_X_FORWARDED_PROTO"])) { useSsl = string.Equals(ServerVariables("HTTP_X_FORWARDED_PROTO"), "https", StringComparison.OrdinalIgnoreCase); } else { useSsl = _httpContext.Request.IsSecureConnection; } } return useSsl; } /// <summary> /// Gets server variable by name /// </summary> /// <param name="name">Name</param> /// <returns>Server variable</returns> public virtual string ServerVariables(string name) { string result = string.Empty; try { if (!IsRequestAvailable(_httpContext)) return result; //put this method is try-catch //as described here http://www.nopcommerce.com/boards/t/21356/multi-store-roadmap-lets-discuss-update-done.aspx?p=6#90196 if (_httpContext.Request.ServerVariables[name] != null) { result = _httpContext.Request.ServerVariables[name]; } } catch { result = string.Empty; } return result; } /// <summary> /// Gets store host location /// </summary> /// <param name="useSsl">Use SSL</param> /// <returns>Store host location</returns> public virtual string GetStoreHost(bool useSsl) { var result = ""; var httpHost = ServerVariables("HTTP_HOST"); if (!String.IsNullOrEmpty(httpHost)) { result = "http://" + httpHost; if (!result.EndsWith("/")) result += "/"; } if (DataSettingsHelper.DatabaseIsInstalled()) { #region Database is installed //let's resolve IWorkContext here. //Do not inject it via constructor because it'll cause circular references var storeContext = EngineContext.Current.Resolve<IStoreContext>(); var currentStore = storeContext.CurrentStore; if (currentStore == null) throw new Exception("Current store cannot be loaded"); if (String.IsNullOrWhiteSpace(httpHost)) { //HTTP_HOST variable is not available. //This scenario is possible only when HttpContext is not available (for example, running in a schedule task) //in this case use URL of a store entity configured in admin area result = currentStore.Url; if (!result.EndsWith("/")) result += "/"; } if (useSsl) { result = !String.IsNullOrWhiteSpace(currentStore.SecureUrl) ? //Secure URL specified. //So a store owner don't want it to be detected automatically. //In this case let's use the specified secure URL currentStore.SecureUrl : //Secure URL is not specified. //So a store owner wants it to be detected automatically. result.Replace("http:/", "https:/"); } else { if (currentStore.SslEnabled && !String.IsNullOrWhiteSpace(currentStore.SecureUrl)) { //SSL is enabled in this store and secure URL is specified. //So a store owner don't want it to be detected automatically. //In this case let's use the specified non-secure URL result = currentStore.Url; } } #endregion } else { #region Database is not installed if (useSsl) { //Secure URL is not specified. //So a store owner wants it to be detected automatically. result = result.Replace("http:/", "https:/"); } #endregion } if (!result.EndsWith("/")) result += "/"; return result.ToLowerInvariant(); } /// <summary> /// Gets store location /// </summary> /// <returns>Store location</returns> public virtual string GetStoreLocation() { bool useSsl = IsCurrentConnectionSecured(); return GetStoreLocation(useSsl); } /// <summary> /// Gets store location /// </summary> /// <param name="useSsl">Use SSL</param> /// <returns>Store location</returns> public virtual string GetStoreLocation(bool useSsl) { //return HostingEnvironment.ApplicationVirtualPath; string result = GetStoreHost(useSsl); if (result.EndsWith("/")) result = result.Substring(0, result.Length - 1); if (IsRequestAvailable(_httpContext)) result = result + _httpContext.Request.ApplicationPath; if (!result.EndsWith("/")) result += "/"; return result.ToLowerInvariant(); } /// <summary> /// Returns true if the requested resource is one of the typical resources that needn't be processed by the cms engine. /// </summary> /// <param name="request">HTTP Request</param> /// <returns>True if the request targets a static resource file.</returns> /// <remarks> /// These are the file extensions considered to be static resources: /// .css /// .gif /// .png /// .jpg /// .jpeg /// .js /// .axd /// .ashx /// </remarks> public virtual bool IsStaticResource(HttpRequest request) { if (request == null) throw new ArgumentNullException("request"); string path = request.Path; string extension = VirtualPathUtility.GetExtension(path); if (extension == null) return false; return _staticFileExtensions.Contains(extension); } /// <summary> /// Modifies query string /// </summary> /// <param name="url">Url to modify</param> /// <param name="queryStringModification">Query string modification</param> /// <param name="anchor">Anchor</param> /// <returns>New url</returns> public virtual string ModifyQueryString(string url, string queryStringModification, string anchor) { if (url == null) url = string.Empty; url = url.ToLowerInvariant(); if (queryStringModification == null) queryStringModification = string.Empty; queryStringModification = queryStringModification.ToLowerInvariant(); if (anchor == null) anchor = string.Empty; anchor = anchor.ToLowerInvariant(); string str = string.Empty; string str2 = string.Empty; if (url.Contains("#")) { str2 = url.Substring(url.IndexOf("#") + 1); url = url.Substring(0, url.IndexOf("#")); } if (url.Contains("?")) { str = url.Substring(url.IndexOf("?") + 1); url = url.Substring(0, url.IndexOf("?")); } if (!string.IsNullOrEmpty(queryStringModification)) { if (!string.IsNullOrEmpty(str)) { var dictionary = new Dictionary<string, string>(); foreach (string str3 in str.Split(new[] { '&' })) { if (!string.IsNullOrEmpty(str3)) { string[] strArray = str3.Split(new[] { '=' }); if (strArray.Length == 2) { if (!dictionary.ContainsKey(strArray[0])) { //do not add value if it already exists //two the same query parameters? theoretically it's not possible. //but MVC has some ugly implementation for checkboxes and we can have two values //find more info here: http://www.mindstorminteractive.com/topics/jquery-fix-asp-net-mvc-checkbox-truefalse-value/ //we do this validation just to ensure that the first one is not overridden dictionary[strArray[0]] = strArray[1]; } } else { dictionary[str3] = null; } } } foreach (string str4 in queryStringModification.Split(new[] { '&' })) { if (!string.IsNullOrEmpty(str4)) { string[] strArray2 = str4.Split(new[] { '=' }); if (strArray2.Length == 2) { dictionary[strArray2[0]] = strArray2[1]; } else { dictionary[str4] = null; } } } var builder = new StringBuilder(); foreach (string str5 in dictionary.Keys) { if (builder.Length > 0) { builder.Append("&"); } builder.Append(str5); if (dictionary[str5] != null) { builder.Append("="); builder.Append(dictionary[str5]); } } str = builder.ToString(); } else { str = queryStringModification; } } if (!string.IsNullOrEmpty(anchor)) { str2 = anchor; } return (url + (string.IsNullOrEmpty(str) ? "" : ("?" + str)) + (string.IsNullOrEmpty(str2) ? "" : ("#" + str2))).ToLowerInvariant(); } /// <summary> /// Remove query string from url /// </summary> /// <param name="url">Url to modify</param> /// <param name="queryString">Query string to remove</param> /// <returns>New url</returns> public virtual string RemoveQueryString(string url, string queryString) { if (url == null) url = string.Empty; url = url.ToLowerInvariant(); if (queryString == null) queryString = string.Empty; queryString = queryString.ToLowerInvariant(); string str = string.Empty; if (url.Contains("?")) { str = url.Substring(url.IndexOf("?") + 1); url = url.Substring(0, url.IndexOf("?")); } if (!string.IsNullOrEmpty(queryString)) { if (!string.IsNullOrEmpty(str)) { var dictionary = new Dictionary<string, string>(); foreach (string str3 in str.Split(new[] { '&' })) { if (!string.IsNullOrEmpty(str3)) { string[] strArray = str3.Split(new[] { '=' }); if (strArray.Length == 2) { dictionary[strArray[0]] = strArray[1]; } else { dictionary[str3] = null; } } } dictionary.Remove(queryString); var builder = new StringBuilder(); foreach (string str5 in dictionary.Keys) { if (builder.Length > 0) { builder.Append("&"); } builder.Append(str5); if (dictionary[str5] != null) { builder.Append("="); builder.Append(dictionary[str5]); } } str = builder.ToString(); } } return (url + (string.IsNullOrEmpty(str) ? "" : ("?" + str))); } /// <summary> /// Gets query string value by name /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name">Parameter name</param> /// <returns>Query string value</returns> public virtual T QueryString<T>(string name) { string queryParam = null; if (IsRequestAvailable(_httpContext) && _httpContext.Request.QueryString[name] != null) queryParam = _httpContext.Request.QueryString[name]; if (!String.IsNullOrEmpty(queryParam)) return CommonHelper.To<T>(queryParam); return default(T); } /// <summary> /// Restart application domain /// </summary> /// <param name="makeRedirect">A value indicating whether we should made redirection after restart</param> /// <param name="redirectUrl">Redirect URL; empty string if you want to redirect to the current page URL</param> public virtual void RestartAppDomain(bool makeRedirect = false, string redirectUrl = "") { if (CommonHelper.GetTrustLevel() > AspNetHostingPermissionLevel.Medium) { //full trust HttpRuntime.UnloadAppDomain(); TryWriteGlobalAsax(); } else { //medium trust bool success = TryWriteWebConfig(); if (!success) { throw new NopException("nopCommerce needs to be restarted due to a configuration change, but was unable to do so." + Environment.NewLine + "To prevent this issue in the future, a change to the web server configuration is required:" + Environment.NewLine + "- run the application in a full trust environment, or" + Environment.NewLine + "- give the application write access to the 'web.config' file."); } success = TryWriteGlobalAsax(); if (!success) { throw new NopException("nopCommerce needs to be restarted due to a configuration change, but was unable to do so." + Environment.NewLine + "To prevent this issue in the future, a change to the web server configuration is required:" + Environment.NewLine + "- run the application in a full trust environment, or" + Environment.NewLine + "- give the application write access to the 'Global.asax' file."); } } // If setting up extensions/modules requires an AppDomain restart, it's very unlikely the // current request can be processed correctly. So, we redirect to the same URL, so that the // new request will come to the newly started AppDomain. if (_httpContext != null && makeRedirect) { if (String.IsNullOrEmpty(redirectUrl)) redirectUrl = GetThisPageUrl(true); _httpContext.Response.Redirect(redirectUrl, true /*endResponse*/); } } /// <summary> /// Gets a value that indicates whether the client is being redirected to a new location /// </summary> public virtual bool IsRequestBeingRedirected { get { var response = _httpContext.Response; return response.IsRequestBeingRedirected; } } /// <summary> /// Gets or sets a value that indicates whether the client is being redirected to a new location using POST /// </summary> public virtual bool IsPostBeingDone { get { if (_httpContext.Items["nop.IsPOSTBeingDone"] == null) return false; return Convert.ToBoolean(_httpContext.Items["nop.IsPOSTBeingDone"]); } set { _httpContext.Items["nop.IsPOSTBeingDone"] = value; } } #endregion } }
/* * Copyright (c) 2012 Jason Parrott * * 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.Unix; using System.Net.Sockets; using System.Text; using System.Diagnostics; using System.Reflection; using System.Threading; using System.IO; using System.Collections.Generic; namespace MonoDaemon { class MainClass { public static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Please provide a name for this daemon and a path to dll files to load. Aborting."); return; } string tName = args[0]; string tDllPath = args[1]; Console.WriteLine("Starting up MonoDaemon..."); foreach (string tPath in Directory.GetFiles(tDllPath, "*.dll")) { Assembly.LoadFile(tPath); Console.WriteLine("Loaded assembly " + tPath); } Mono.Unix.Native.Syscall.unlink(tName); UnixEndPoint tEndpoint = new UnixEndPoint(tName); Socket tSocket = new Socket(tEndpoint.AddressFamily, SocketType.Stream, 0); Console.CancelKeyPress += (sender, e) => { if (tSocket.Connected) { tSocket.Close(); } }; tSocket.Bind(tEndpoint); tSocket.Listen(255); while (true) { Socket tConnection = tSocket.Accept(); Console.WriteLine("Got request."); Thread tThread = new Thread(handleRequest); tThread.Start(tConnection); } } private static void handleRequest(object pData) { Console.WriteLine("Handling"); Socket tConnection = (Socket)pData; byte[] tBytes = new byte[256]; Buffer tBuffer = new Buffer(tBytes); while (true) { try { Request tRequest = new Request(tBuffer, tConnection); do { if (tBuffer.Index >= tBuffer.Length - 1) { tBuffer.Length = tConnection.Receive(tBytes, 256, SocketFlags.None); tBuffer.Index = 0; } if (tBuffer.Length == 0) { goto finish; } try { if (!tRequest.Parse()) { break; } } catch (OutOfBytesException) { //goto finish; } } while (true); if (tRequest.IsFinished) { break; } } catch (SocketException e) { Console.WriteLine(e); break; } catch (Exception e) { Console.WriteLine(e); break; } GC.Collect(); } finish: { if (tConnection.Connected) { tConnection.Close(); } Console.WriteLine("Shutting Down Thread"); } GC.Collect(); } private class Buffer { private byte[] mBytes; public int Index = 0; public int Length = 0; public Buffer(byte[] pBytes) { mBytes = pBytes; } public byte Get() { if (Index >= Length) { throw new OutOfBytesException(); } return mBytes[Index++]; } } private class OutOfBytesException : Exception { } private class Request { private const byte END = 0x00; private const byte STATE_STATIC_SET_PROPERTY = 0x01; private const byte STATE_STATIC_GET_PROPERTY = 0x02; private const byte STATE_STATIC_CALL = 0x03; private const byte STATE_NEW_CLASS = 0x04; private const byte STATE_DESTROY_CLASS = 0x05; private const byte STATE_GET_CLASS_PROPERTY = 0x06; private const byte STATE_SET_CLASS_PROPERTY = 0x07; private const byte STATE_CALL_CLASS_METHOD = 0x08; private const byte STATE_TYPE = 0x20; private const byte STATE_ARGUMENT = 0x40; private const byte TYPE_NULL = 0x01; private const byte TYPE_POINTER = 0x02; private const byte TYPE_EXCEPTION = 0x03; private const byte TYPE_STRING = 0x04; private const byte TYPE_INT = 0x05; private const byte TYPE_FLOAT = 0x06; private const byte TYPE_BOOL = 0x07; private const byte TYPE_VOID = 0x08; private Socket mConnection; private byte mState = END; private bool mIsFinished = false; public Request(Buffer pBuffer, Socket pConnection) { Buffer = pBuffer; mConnection = pConnection; } public Buffer Buffer; private byte get() { return Buffer.Get(); } public bool IsFinished { get { return mIsFinished; } } private int toInt(byte[] pBytes) { if (BitConverter.IsLittleEndian) { Array.Reverse(pBytes); } return BitConverter.ToInt32(pBytes, 0); } private uint toUInt(byte[] pBytes) { if (BitConverter.IsLittleEndian) { Array.Reverse(pBytes); } return BitConverter.ToUInt32(pBytes, 0); } private float toFloat(byte[] pBytes) { if (BitConverter.IsLittleEndian) { Array.Reverse(pBytes); } return BitConverter.ToSingle(pBytes, 0); } private double toDouble(byte[] pBytes) { if (BitConverter.IsLittleEndian) { Array.Reverse(pBytes); } return BitConverter.ToDouble(pBytes, 0); } private string toASCIIString(byte[] pBytes) { return Encoding.ASCII.GetString(pBytes); } private string toUTF8String(byte[] pBytes) { return Encoding.UTF8.GetString(pBytes); } private byte[] fromInt(int pInt) { byte[] tBytes = BitConverter.GetBytes(pInt); if (BitConverter.IsLittleEndian) { Array.Reverse(tBytes); } return tBytes; } private byte[] fromUInt(uint pInt) { byte[] tBytes = BitConverter.GetBytes(pInt); if (BitConverter.IsLittleEndian) { Array.Reverse(tBytes); } return tBytes; } private byte[] fromFloat(float pFloat) { byte[] tBytes = BitConverter.GetBytes(pFloat); if (BitConverter.IsLittleEndian) { Array.Reverse(tBytes); } return tBytes; } private byte[] fromDouble(double pFloat) { byte[] tBytes = BitConverter.GetBytes(pFloat); if (BitConverter.IsLittleEndian) { Array.Reverse(tBytes); } return tBytes; } private byte[] fromBool(bool pBool) { return new byte[] { pBool ? (byte)0x01 : (byte)0x00 }; } private byte[] fromASCIIString(string pString) { return Encoding.ASCII.GetBytes(pString + "\0x00"); } private byte[] fromUTF8String(string pString) { byte[] tBytes = (new UTF8Encoding(false)).GetBytes(pString); Array.Resize<byte>(ref tBytes, tBytes.Length + 1); tBytes[tBytes.Length - 1] = (byte)0x00; return tBytes; } private byte[] fromObject(object pObject, byte pType) { switch (pType) { case TYPE_NULL: return new byte[] {}; case TYPE_POINTER: return fromInt(pObject.GetHashCode()); case TYPE_INT: return fromInt(System.Convert.ToInt32(pObject)); case TYPE_FLOAT: return fromFloat(System.Convert.ToSingle(pObject)); case TYPE_BOOL: return fromBool((bool)pObject); case TYPE_STRING: return fromUTF8String((string)pObject); default: return new byte[] {}; } } private byte getType(object pObject) { if (pObject == null) { return TYPE_NULL; } if (pObject is string) { return TYPE_STRING; } Type tType = pObject.GetType(); if (tType.IsPrimitive) { if (pObject is int) { return TYPE_INT; } else if (pObject is long) { return TYPE_INT; } else if (pObject is float) { return TYPE_FLOAT; } else if (pObject is double) { return TYPE_FLOAT; } else if (pObject is bool) { return TYPE_BOOL; } else { return TYPE_POINTER; } } else { return TYPE_POINTER; } } private byte[] merge(byte[][] pBytes) { int tSize = 0; for (int i = 0, il = pBytes.Length; i < il; i++) { tSize += pBytes[i].Length; } byte[] tBytes = new byte[tSize]; int tIndex = 0; for (int i = 0, il = pBytes.Length; i < il; i++) { for (int j = 0, jl = pBytes[i].Length; j < jl; j++) { tBytes[tIndex++] = pBytes[i][j]; } } return tBytes; } private class PersistanceTracker { public object Object; public int Count; public PersistanceTracker(object pObject, int pCount) { Object = pObject; Count = pCount; } } private void persistObject(object pObject, int pHash) { if (pObject == null) { return; } if (!pObject.GetType().IsPrimitive && !(pObject is string)) { if (mObjects.ContainsKey(pHash)) { mObjects[pHash].Count++; } else { mObjects[pHash] = new PersistanceTracker(pObject, 1); } } } private void persistObject(object pObject) { if (pObject == null) { return; } int tHash = pObject.GetHashCode(); persistObject(pObject, tHash); } private void unPersistObject(int pHash) { if (!mObjects.ContainsKey(pHash)) { return; } if (--mObjects[pHash].Count == 0) { mObjects.Remove(pHash); } } private List<byte> mArgumentsBuffer = new List<byte>(64); private byte mArgumentType = END; private byte[] getArgumentBytes(int pSize) { while (mArgumentsBuffer.Count < pSize) { mArgumentsBuffer.Add(get()); } byte[] tBytes = mArgumentsBuffer.ToArray(); mArgumentsBuffer.Clear(); return tBytes; } private object[] getArugments() { List<object> tArgs = new List<object>(); while (true) { if (mArgumentType == END) mArgumentType = get(); switch (mArgumentType) { case END: goto finish; case TYPE_NULL: tArgs.Add(null); break; case TYPE_POINTER: int tObjectPointer = toInt(getArgumentBytes(4)); tArgs.Add(mObjects[tObjectPointer]); break; case TYPE_STRING: while (true) { byte tStringByte = get(); if (tStringByte == END) { tArgs.Add(toUTF8String(mArgumentsBuffer.ToArray())); mArgumentsBuffer.Clear(); break; } else { mArgumentsBuffer.Add(tStringByte); } } break; case TYPE_BOOL: if (get() == (byte)0x00) { tArgs.Add(false); } else { tArgs.Add(true); } break; case TYPE_INT: tArgs.Add(toInt(getArgumentBytes(4))); break; case TYPE_FLOAT: tArgs.Add(toFloat(getArgumentBytes(4))); break; default: throw new Exception("Invalid argument type: " + mArgumentType); } mArgumentType = END; } finish: {}; return tArgs.ToArray(); } /** * Communication protocol is as follows. * * Requests: * 0x00 = end * When all ends have been popped, communication is over. * 0x01 = static set to class property * 0x02 = static get to class property * 0x03 = static calling of class method * 0x04 = new class * 0x05 = destroy class * 0x06 = get class property * 0x07 = set class property * 0x08 = call class method * 0x70 = start argument * type{ends with 0x00} * length{4 bytes} * data{length} * * Response: * 0x00 = end * When all ends have been popped, communication is over. * 0xFF = error * 0x01 = type * type () */ public bool Parse() { switch (mState) { case END: parseCommand(); break; } return true; } private void parseCommand() { mState = get(); parseCurrent(); } private void parseCurrent() { switch (mState) { case END: mIsFinished = true; break; case STATE_STATIC_SET_PROPERTY: break; case STATE_STATIC_GET_PROPERTY: break; case STATE_STATIC_CALL: parseStaticCall(); break; case STATE_NEW_CLASS: parseNewClass(); break; case STATE_DESTROY_CLASS: parseDestroyClass(); break; case STATE_GET_CLASS_PROPERTY: parseGetClassProperty(); break; case STATE_SET_CLASS_PROPERTY: parseSetClassProperty(); break; case STATE_CALL_CLASS_METHOD: parseCallClassMethod(); break; default: break; } } private List<byte> mNewClassNameBytes = new List<byte>(64); private string mNewClassName = null; private Dictionary<int, PersistanceTracker> mObjects = new Dictionary<int, PersistanceTracker>(64); private void parseNewClass() { while (true) { if (mNewClassName == null) { byte tByte = get(); if (tByte == END) { mNewClassName = toASCIIString(mNewClassNameBytes.ToArray()); mNewClassNameBytes.Clear(); } else { mNewClassNameBytes.Add(tByte); } } else { if (mIsGettingArgs) { mArgs = getArugments(); mIsGettingArgs = false; } else { byte tByte = get(); if (tByte == END) { mState = END; Type tType = Type.GetType(mNewClassName); object tObject = Activator.CreateInstance(tType, mArgs); int tHash = tObject.GetHashCode(); mArgs = null; mNewClassName = null; persistObject(tObject, tHash); mConnection.Send(fromInt(tHash)); return; } else if (tByte == STATE_ARGUMENT) { mIsGettingArgs = true; } } } } } private void parseDestroyClass() { while (true) { mClassParserBuffer.Add(get()); if (mClassParserBuffer.Count == 4) { unPersistObject(toInt(mClassParserBuffer.ToArray())); mClassParserBuffer.Clear(); mState = END; return; } } } private void parseStaticCall() { mState = END; } private List<byte> mClassParserBuffer = new List<byte>(64); private int mClassObject = -1; private string mCallClassMethodMethod = null; private object[] mArgs = null; private bool mIsGettingArgs = false; private Type[] getObjectTypes(object[] pObjects) { if (pObjects == null) { return new Type[0]; } Type[] tTypes = new Type[pObjects.Length]; for (int i = 0, il = pObjects.Length; i < il; i++) { tTypes[i] = pObjects[i].GetType(); } return tTypes; } private void parseCallClassMethod() { while (true) { if (mClassObject == -1) { byte tByte = get(); mClassParserBuffer.Add(tByte); if (mClassParserBuffer.Count == 4) { mClassObject = toInt(mClassParserBuffer.ToArray()); mClassParserBuffer.Clear(); } } else if (mCallClassMethodMethod == null) { byte tByte = get(); if (tByte == END) { mCallClassMethodMethod = toASCIIString(mClassParserBuffer.ToArray()); mClassParserBuffer.Clear(); } else { mClassParserBuffer.Add(tByte); } } else { if (mIsGettingArgs) { mArgs = getArugments(); mIsGettingArgs = false; } else { byte tByte = get(); if (tByte == END) { object tObject = mObjects[mClassObject].Object; MethodInfo tMethodInfo = tObject.GetType().GetMethod(mCallClassMethodMethod, getObjectTypes(mArgs)); object tReturn = tMethodInfo.Invoke(tObject, mArgs); byte[] tBytes; byte tType; if (tMethodInfo.ReturnType == typeof(void)) { tType = TYPE_VOID; tBytes = new byte[0]; } else { tType = getType(tReturn); persistObject(tReturn); tBytes = fromObject(tReturn, tType); } mCallClassMethodMethod = null; mArgs = null; mClassObject = -1; mState = END; mConnection.Send(merge(new byte[][] { new byte[] { tType }, tBytes })); return; } else if (tByte == STATE_ARGUMENT) { mIsGettingArgs = true; } } } } } private string mClassPropertyName = null; private void parseGetClassProperty() { while (true) { if (mClassObject == -1) { byte tByte = get(); mClassParserBuffer.Add(tByte); if (mClassParserBuffer.Count == 4) { mClassObject = toInt(mClassParserBuffer.ToArray()); mClassParserBuffer.Clear(); } } else if (mClassPropertyName == null) { byte tByte = get(); if (tByte == END) { mClassPropertyName = toASCIIString(mClassParserBuffer.ToArray()); mClassParserBuffer.Clear(); object tObject = mObjects[mClassObject].Object; MemberInfo[] tMemberInfoList = tObject.GetType().GetMember(mClassPropertyName); object tValue; foreach (MemberInfo tMemberInfo in tMemberInfoList) { switch (tMemberInfo.MemberType) { case MemberTypes.Field: FieldInfo tFieldInfo = (FieldInfo)tMemberInfo; tValue = tFieldInfo.GetValue(tObject); break; case MemberTypes.Property: PropertyInfo tPropertyInfo = (PropertyInfo)tMemberInfo; tValue = tPropertyInfo.GetValue(tObject, null); break; default: continue; } byte tType = getType(tValue); persistObject(tValue); byte[] tBytes = fromObject(tValue, tType); mClassPropertyName = null; mClassObject = -1; mState = END; mConnection.Send(merge(new byte[][] { new byte[] { tType }, tBytes })); return; } throw new Exception("No property with the name: " + mClassPropertyName); } else { mClassParserBuffer.Add(tByte); } } } } private void parseSetClassProperty() { mState = END; } } } }
namespace android.bluetooth { [global::MonoJavaBridge.JavaClass()] public sealed partial class BluetoothClass : java.lang.Object, android.os.Parcelable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static BluetoothClass() { InitJNI(); } internal BluetoothClass(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public partial class Device : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Device() { InitJNI(); } protected Device(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public partial class Major : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Major() { InitJNI(); } protected Major(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _Major1023; public Major() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.bluetooth.BluetoothClass.Device.Major.staticClass, global::android.bluetooth.BluetoothClass.Device.Major._Major1023); Init(@__env, handle); } public static int MISC { get { return 0; } } public static int COMPUTER { get { return 256; } } public static int PHONE { get { return 512; } } public static int NETWORKING { get { return 768; } } public static int AUDIO_VIDEO { get { return 1024; } } public static int PERIPHERAL { get { return 1280; } } public static int IMAGING { get { return 1536; } } public static int WEARABLE { get { return 1792; } } public static int TOY { get { return 2048; } } public static int HEALTH { get { return 2304; } } public static int UNCATEGORIZED { get { return 7936; } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.bluetooth.BluetoothClass.Device.Major.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/bluetooth/BluetoothClass$Device$Major")); global::android.bluetooth.BluetoothClass.Device.Major._Major1023 = @__env.GetMethodIDNoThrow(global::android.bluetooth.BluetoothClass.Device.Major.staticClass, "<init>", "()V"); } } internal static global::MonoJavaBridge.MethodId _Device1024; public Device() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.bluetooth.BluetoothClass.Device.staticClass, global::android.bluetooth.BluetoothClass.Device._Device1024); Init(@__env, handle); } public static int COMPUTER_UNCATEGORIZED { get { return 256; } } public static int COMPUTER_DESKTOP { get { return 260; } } public static int COMPUTER_SERVER { get { return 264; } } public static int COMPUTER_LAPTOP { get { return 268; } } public static int COMPUTER_HANDHELD_PC_PDA { get { return 272; } } public static int COMPUTER_PALM_SIZE_PC_PDA { get { return 276; } } public static int COMPUTER_WEARABLE { get { return 280; } } public static int PHONE_UNCATEGORIZED { get { return 512; } } public static int PHONE_CELLULAR { get { return 516; } } public static int PHONE_CORDLESS { get { return 520; } } public static int PHONE_SMART { get { return 524; } } public static int PHONE_MODEM_OR_GATEWAY { get { return 528; } } public static int PHONE_ISDN { get { return 532; } } public static int AUDIO_VIDEO_UNCATEGORIZED { get { return 1024; } } public static int AUDIO_VIDEO_WEARABLE_HEADSET { get { return 1028; } } public static int AUDIO_VIDEO_HANDSFREE { get { return 1032; } } public static int AUDIO_VIDEO_MICROPHONE { get { return 1040; } } public static int AUDIO_VIDEO_LOUDSPEAKER { get { return 1044; } } public static int AUDIO_VIDEO_HEADPHONES { get { return 1048; } } public static int AUDIO_VIDEO_PORTABLE_AUDIO { get { return 1052; } } public static int AUDIO_VIDEO_CAR_AUDIO { get { return 1056; } } public static int AUDIO_VIDEO_SET_TOP_BOX { get { return 1060; } } public static int AUDIO_VIDEO_HIFI_AUDIO { get { return 1064; } } public static int AUDIO_VIDEO_VCR { get { return 1068; } } public static int AUDIO_VIDEO_VIDEO_CAMERA { get { return 1072; } } public static int AUDIO_VIDEO_CAMCORDER { get { return 1076; } } public static int AUDIO_VIDEO_VIDEO_MONITOR { get { return 1080; } } public static int AUDIO_VIDEO_VIDEO_DISPLAY_AND_LOUDSPEAKER { get { return 1084; } } public static int AUDIO_VIDEO_VIDEO_CONFERENCING { get { return 1088; } } public static int AUDIO_VIDEO_VIDEO_GAMING_TOY { get { return 1096; } } public static int WEARABLE_UNCATEGORIZED { get { return 1792; } } public static int WEARABLE_WRIST_WATCH { get { return 1796; } } public static int WEARABLE_PAGER { get { return 1800; } } public static int WEARABLE_JACKET { get { return 1804; } } public static int WEARABLE_HELMET { get { return 1808; } } public static int WEARABLE_GLASSES { get { return 1812; } } public static int TOY_UNCATEGORIZED { get { return 2048; } } public static int TOY_ROBOT { get { return 2052; } } public static int TOY_VEHICLE { get { return 2056; } } public static int TOY_DOLL_ACTION_FIGURE { get { return 2060; } } public static int TOY_CONTROLLER { get { return 2064; } } public static int TOY_GAME { get { return 2068; } } public static int HEALTH_UNCATEGORIZED { get { return 2304; } } public static int HEALTH_BLOOD_PRESSURE { get { return 2308; } } public static int HEALTH_THERMOMETER { get { return 2312; } } public static int HEALTH_WEIGHING { get { return 2316; } } public static int HEALTH_GLUCOSE { get { return 2320; } } public static int HEALTH_PULSE_OXIMETER { get { return 2324; } } public static int HEALTH_PULSE_RATE { get { return 2328; } } public static int HEALTH_DATA_DISPLAY { get { return 2332; } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.bluetooth.BluetoothClass.Device.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/bluetooth/BluetoothClass$Device")); global::android.bluetooth.BluetoothClass.Device._Device1024 = @__env.GetMethodIDNoThrow(global::android.bluetooth.BluetoothClass.Device.staticClass, "<init>", "()V"); } } [global::MonoJavaBridge.JavaClass()] public sealed partial class Service : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Service() { InitJNI(); } internal Service(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _Service1025; public Service() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.bluetooth.BluetoothClass.Service.staticClass, global::android.bluetooth.BluetoothClass.Service._Service1025); Init(@__env, handle); } public static int LIMITED_DISCOVERABILITY { get { return 8192; } } public static int POSITIONING { get { return 65536; } } public static int NETWORKING { get { return 131072; } } public static int RENDER { get { return 262144; } } public static int CAPTURE { get { return 524288; } } public static int OBJECT_TRANSFER { get { return 1048576; } } public static int AUDIO { get { return 2097152; } } public static int TELEPHONY { get { return 4194304; } } public static int INFORMATION { get { return 8388608; } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.bluetooth.BluetoothClass.Service.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/bluetooth/BluetoothClass$Service")); global::android.bluetooth.BluetoothClass.Service._Service1025 = @__env.GetMethodIDNoThrow(global::android.bluetooth.BluetoothClass.Service.staticClass, "<init>", "()V"); } } internal static global::MonoJavaBridge.MethodId _equals1026; public sealed override bool equals(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.bluetooth.BluetoothClass._equals1026, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.bluetooth.BluetoothClass.staticClass, global::android.bluetooth.BluetoothClass._equals1026, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toString1027; public sealed override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.bluetooth.BluetoothClass._toString1027)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.bluetooth.BluetoothClass.staticClass, global::android.bluetooth.BluetoothClass._toString1027)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _hashCode1028; public sealed override int hashCode() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.bluetooth.BluetoothClass._hashCode1028); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.bluetooth.BluetoothClass.staticClass, global::android.bluetooth.BluetoothClass._hashCode1028); } internal static global::MonoJavaBridge.MethodId _writeToParcel1029; public void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.bluetooth.BluetoothClass._writeToParcel1029, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.bluetooth.BluetoothClass.staticClass, global::android.bluetooth.BluetoothClass._writeToParcel1029, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _describeContents1030; public int describeContents() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.bluetooth.BluetoothClass._describeContents1030); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.bluetooth.BluetoothClass.staticClass, global::android.bluetooth.BluetoothClass._describeContents1030); } internal static global::MonoJavaBridge.MethodId _hasService1031; public bool hasService(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.bluetooth.BluetoothClass._hasService1031, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.bluetooth.BluetoothClass.staticClass, global::android.bluetooth.BluetoothClass._hasService1031, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getMajorDeviceClass1032; public int getMajorDeviceClass() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.bluetooth.BluetoothClass._getMajorDeviceClass1032); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.bluetooth.BluetoothClass.staticClass, global::android.bluetooth.BluetoothClass._getMajorDeviceClass1032); } internal static global::MonoJavaBridge.MethodId _getDeviceClass1033; public int getDeviceClass() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.bluetooth.BluetoothClass._getDeviceClass1033); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.bluetooth.BluetoothClass.staticClass, global::android.bluetooth.BluetoothClass._getDeviceClass1033); } internal static global::MonoJavaBridge.FieldId _CREATOR1034; public static global::android.os.Parcelable_Creator CREATOR { get { return default(global::android.os.Parcelable_Creator); } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.bluetooth.BluetoothClass.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/bluetooth/BluetoothClass")); global::android.bluetooth.BluetoothClass._equals1026 = @__env.GetMethodIDNoThrow(global::android.bluetooth.BluetoothClass.staticClass, "equals", "(Ljava/lang/Object;)Z"); global::android.bluetooth.BluetoothClass._toString1027 = @__env.GetMethodIDNoThrow(global::android.bluetooth.BluetoothClass.staticClass, "toString", "()Ljava/lang/String;"); global::android.bluetooth.BluetoothClass._hashCode1028 = @__env.GetMethodIDNoThrow(global::android.bluetooth.BluetoothClass.staticClass, "hashCode", "()I"); global::android.bluetooth.BluetoothClass._writeToParcel1029 = @__env.GetMethodIDNoThrow(global::android.bluetooth.BluetoothClass.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V"); global::android.bluetooth.BluetoothClass._describeContents1030 = @__env.GetMethodIDNoThrow(global::android.bluetooth.BluetoothClass.staticClass, "describeContents", "()I"); global::android.bluetooth.BluetoothClass._hasService1031 = @__env.GetMethodIDNoThrow(global::android.bluetooth.BluetoothClass.staticClass, "hasService", "(I)Z"); global::android.bluetooth.BluetoothClass._getMajorDeviceClass1032 = @__env.GetMethodIDNoThrow(global::android.bluetooth.BluetoothClass.staticClass, "getMajorDeviceClass", "()I"); global::android.bluetooth.BluetoothClass._getDeviceClass1033 = @__env.GetMethodIDNoThrow(global::android.bluetooth.BluetoothClass.staticClass, "getDeviceClass", "()I"); } } }
// // ContextBackendHandler.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // Alex Corrado <corrado@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // 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 Xwt.Backends; using Xwt.Drawing; using System.Drawing; using System.Collections.Generic; using System.Linq; #if MONOMAC using nint = System.Int32; using nfloat = System.Single; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using MonoMac.CoreGraphics; using MonoMac.AppKit; #else using CoreGraphics; using AppKit; #endif namespace Xwt.Mac { class CGContextBackend { public CGContext Context; public CGSize Size; public CGAffineTransform? InverseViewTransform; public Stack<ContextStatus> StatusStack = new Stack<ContextStatus> (); public ContextStatus CurrentStatus = new ContextStatus (); public double ScaleFactor = 1; public StyleSet Styles; } class ContextStatus { public object Pattern; } public class MacContextBackendHandler: ContextBackendHandler { const double degrees = System.Math.PI / 180d; public override double GetScaleFactor (object backend) { var ct = (CGContextBackend) backend; return ct.ScaleFactor; } public override void Save (object backend) { var ct = (CGContextBackend) backend; ct.Context.SaveState (); ct.StatusStack.Push (ct.CurrentStatus); var newStatus = new ContextStatus (); newStatus.Pattern = ct.CurrentStatus.Pattern; ct.CurrentStatus = newStatus; } public override void Restore (object backend) { var ct = (CGContextBackend) backend; ct.Context.RestoreState (); ct.CurrentStatus = ct.StatusStack.Pop (); } public override void SetGlobalAlpha (object backend, double alpha) { ((CGContextBackend)backend).Context.SetAlpha ((float)alpha); } public override void SetStyles (object backend, StyleSet styles) { ((CGContextBackend)backend).Styles = styles; } public override void Arc (object backend, double xc, double yc, double radius, double angle1, double angle2) { CGContext ctx = ((CGContextBackend)backend).Context; ctx.AddArc ((float)xc, (float)yc, (float)radius, (float)(angle1 * degrees), (float)(angle2 * degrees), false); } public override void ArcNegative (object backend, double xc, double yc, double radius, double angle1, double angle2) { CGContext ctx = ((CGContextBackend)backend).Context; ctx.AddArc ((float)xc, (float)yc, (float)radius, (float)(angle1 * degrees), (float)(angle2 * degrees), true); } public override void Clip (object backend) { ((CGContextBackend)backend).Context.Clip (); } public override void ClipPreserve (object backend) { CGContext ctx = ((CGContextBackend)backend).Context; using (CGPath oldPath = ctx.CopyPath ()) { ctx.Clip (); ctx.AddPath (oldPath); } } public override void ClosePath (object backend) { ((CGContextBackend)backend).Context.ClosePath (); } public override void CurveTo (object backend, double x1, double y1, double x2, double y2, double x3, double y3) { ((CGContextBackend)backend).Context.AddCurveToPoint ((float)x1, (float)y1, (float)x2, (float)y2, (float)x3, (float)y3); } public override void Fill (object backend) { CGContextBackend gc = (CGContextBackend)backend; CGContext ctx = gc.Context; SetupContextForDrawing (ctx); if (gc.CurrentStatus.Pattern is GradientInfo) { MacGradientBackendHandler.Draw (ctx, ((GradientInfo)gc.CurrentStatus.Pattern)); } else if (gc.CurrentStatus.Pattern is ImagePatternInfo) { SetupPattern (gc); ctx.DrawPath (CGPathDrawingMode.Fill); } else { ctx.DrawPath (CGPathDrawingMode.Fill); } } public override void FillPreserve (object backend) { CGContext ctx = ((CGContextBackend)backend).Context; using (CGPath oldPath = ctx.CopyPath ()) { Fill (backend); ctx.AddPath (oldPath); } } public override void LineTo (object backend, double x, double y) { ((CGContextBackend)backend).Context.AddLineToPoint ((float)x, (float)y); } public override void MoveTo (object backend, double x, double y) { ((CGContextBackend)backend).Context.MoveTo ((float)x, (float)y); } public override void NewPath (object backend) { ((CGContextBackend)backend).Context.BeginPath (); } public override void Rectangle (object backend, double x, double y, double width, double height) { ((CGContextBackend)backend).Context.AddRect (new CGRect ((nfloat)x, (nfloat)y, (nfloat)width, (nfloat)height)); } public override void RelCurveTo (object backend, double dx1, double dy1, double dx2, double dy2, double dx3, double dy3) { CGContext ctx = ((CGContextBackend)backend).Context; CGPoint p = ctx.GetPathCurrentPoint (); ctx.AddCurveToPoint ((float)(p.X + dx1), (float)(p.Y + dy1), (float)(p.X + dx2), (float)(p.Y + dy2), (float)(p.X + dx3), (float)(p.Y + dy3)); } public override void RelLineTo (object backend, double dx, double dy) { CGContext ctx = ((CGContextBackend)backend).Context; CGPoint p = ctx.GetPathCurrentPoint (); ctx.AddLineToPoint ((float)(p.X + dx), (float)(p.Y + dy)); } public override void RelMoveTo (object backend, double dx, double dy) { CGContext ctx = ((CGContextBackend)backend).Context; CGPoint p = ctx.GetPathCurrentPoint (); ctx.MoveTo ((float)(p.X + dx), (float)(p.Y + dy)); } public override void Stroke (object backend) { CGContext ctx = ((CGContextBackend)backend).Context; SetupContextForDrawing (ctx); ctx.DrawPath (CGPathDrawingMode.Stroke); } public override void StrokePreserve (object backend) { CGContext ctx = ((CGContextBackend)backend).Context; SetupContextForDrawing (ctx); using (CGPath oldPath = ctx.CopyPath ()) { ctx.DrawPath (CGPathDrawingMode.Stroke); ctx.AddPath (oldPath); } } public override void SetColor (object backend, Xwt.Drawing.Color color) { CGContextBackend gc = (CGContextBackend)backend; gc.CurrentStatus.Pattern = null; CGContext ctx = gc.Context; ctx.SetFillColorSpace (Util.DeviceRGBColorSpace); ctx.SetStrokeColorSpace (Util.DeviceRGBColorSpace); ctx.SetFillColor ((float)color.Red, (float)color.Green, (float)color.Blue, (float)color.Alpha); ctx.SetStrokeColor ((float)color.Red, (float)color.Green, (float)color.Blue, (float)color.Alpha); } public override void SetLineWidth (object backend, double width) { ((CGContextBackend)backend).Context.SetLineWidth ((float)width); } public override void SetLineDash (object backend, double offset, params double[] pattern) { var array = new nfloat[pattern.Length]; for (int n=0; n<pattern.Length; n++) array [n] = (float) pattern[n]; ((CGContextBackend)backend).Context.SetLineDash ((nfloat)offset, array); } public override void SetPattern (object backend, object p) { CGContextBackend gc = (CGContextBackend)backend; var toolkit = ApplicationContext.Toolkit; gc.CurrentStatus.Pattern = toolkit.GetSafeBackend (p); } void SetupPattern (CGContextBackend gc) { gc.Context.SetPatternPhase (new CGSize (0, 0)); if (gc.CurrentStatus.Pattern is GradientInfo) return; if (gc.CurrentStatus.Pattern is ImagePatternInfo) { var pi = (ImagePatternInfo) gc.CurrentStatus.Pattern; var bounds = new CGRect (CGPoint.Empty, new CGSize (pi.Image.Size.Width, pi.Image.Size.Height)); var t = CGAffineTransform.Multiply (CGAffineTransform.MakeScale (1f, -1f), gc.Context.GetCTM ()); CGPattern pattern; if (pi.Image is CustomImage) { pattern = new CGPattern (bounds, t, bounds.Width, bounds.Height, CGPatternTiling.ConstantSpacing, true, c => { c.TranslateCTM (0, bounds.Height); c.ScaleCTM (1f, -1f); ((CustomImage)pi.Image).DrawInContext (c); }); } else { var empty = CGRect.Empty; CGImage cgimg = pi.Image.AsCGImage (ref empty, null, null); pattern = new CGPattern (bounds, t, bounds.Width, bounds.Height, CGPatternTiling.ConstantSpacing, true, c => c.DrawImage (bounds, cgimg)); } CGContext ctx = gc.Context; var alpha = new[] { (nfloat)pi.Alpha }; ctx.SetFillColorSpace (Util.PatternColorSpace); ctx.SetStrokeColorSpace (Util.PatternColorSpace); ctx.SetFillPattern (pattern, alpha); ctx.SetStrokePattern (pattern, alpha); } } public override void DrawTextLayout (object backend, TextLayout layout, double x, double y) { CGContext ctx = ((CGContextBackend)backend).Context; SetupContextForDrawing (ctx); var li = ApplicationContext.Toolkit.GetSafeBackend (layout); MacTextLayoutBackendHandler.Draw (ctx, li, x, y); } public override void DrawImage (object backend, ImageDescription img, double x, double y) { var srcRect = new Rectangle (Point.Zero, img.Size); var destRect = new Rectangle (x, y, img.Size.Width, img.Size.Height); DrawImage (backend, img, srcRect, destRect); } public override void DrawImage (object backend, ImageDescription img, Rectangle srcRect, Rectangle destRect) { var cb = (CGContextBackend)backend; CGContext ctx = cb.Context; // Add the styles that have been globaly set to the context img.Styles = img.Styles.AddRange (cb.Styles); NSImage image = img.ToNSImage (); ctx.SaveState (); ctx.SetAlpha ((float)img.Alpha); double rx = destRect.Width / srcRect.Width; double ry = destRect.Height / srcRect.Height; ctx.AddRect (new CGRect ((nfloat)destRect.X, (nfloat)destRect.Y, (nfloat)destRect.Width, (nfloat)destRect.Height)); ctx.Clip (); ctx.TranslateCTM ((float)(destRect.X - (srcRect.X * rx)), (float)(destRect.Y - (srcRect.Y * ry))); ctx.ScaleCTM ((float)rx, (float)ry); if (image is CustomImage) { ((CustomImage)image).DrawInContext ((CGContextBackend)backend); } else { var rr = new CGRect (0, 0, image.Size.Width, image.Size.Height); ctx.ScaleCTM (1f, -1f); ctx.DrawImage (new CGRect (0, -image.Size.Height, image.Size.Width, image.Size.Height), image.AsCGImage (ref rr, NSGraphicsContext.CurrentContext, null)); } ctx.RestoreState (); } public override void Rotate (object backend, double angle) { ((CGContextBackend)backend).Context.RotateCTM ((float)(angle * degrees)); } public override void Scale (object backend, double scaleX, double scaleY) { ((CGContextBackend)backend).Context.ScaleCTM ((float)scaleX, (float)scaleY); } public override void Translate (object backend, double tx, double ty) { ((CGContextBackend)backend).Context.TranslateCTM ((float)tx, (float)ty); } public override void ModifyCTM (object backend, Matrix m) { CGAffineTransform t = new CGAffineTransform ((float)m.M11, (float)m.M12, (float)m.M21, (float)m.M22, (float)m.OffsetX, (float)m.OffsetY); ((CGContextBackend)backend).Context.ConcatCTM (t); } public override Matrix GetCTM (object backend) { CGAffineTransform t = GetContextTransform ((CGContextBackend)backend); Matrix ctm = new Matrix (t.xx, t.yx, t.xy, t.yy, t.x0, t.y0); return ctm; } public override object CreatePath () { return new CGPath (); } public override object CopyPath (object backend) { return ((CGContextBackend)backend).Context.CopyPath (); } public override void AppendPath (object backend, object otherBackend) { CGContext dest = ((CGContextBackend)backend).Context; CGContextBackend src = otherBackend as CGContextBackend; if (src != null) { using (var path = src.Context.CopyPath ()) dest.AddPath (path); } else { dest.AddPath ((CGPath)otherBackend); } } public override bool IsPointInFill (object backend, double x, double y) { return ((CGContextBackend)backend).Context.PathContainsPoint (new CGPoint ((nfloat)x, (nfloat)y), CGPathDrawingMode.Fill); } public override bool IsPointInStroke (object backend, double x, double y) { return ((CGContextBackend)backend).Context.PathContainsPoint (new CGPoint ((nfloat)x, (nfloat)y), CGPathDrawingMode.Stroke); } public override void Dispose (object backend) { ((CGContextBackend)backend).Context.Dispose (); } static CGAffineTransform GetContextTransform (CGContextBackend gc) { CGAffineTransform t = gc.Context.GetCTM (); // The CTM returned above actually includes the full view transform. // We only want the transform that is applied to the context, so concat // the inverse of the view transform to nullify that part. if (gc.InverseViewTransform.HasValue) t.Multiply (gc.InverseViewTransform.Value); return t; } static void SetupContextForDrawing (CGContext ctx) { if (ctx.IsPathEmpty ()) return; // setup pattern drawing to better match the behavior of Cairo var drawPoint = ctx.GetCTM ().TransformPoint (ctx.GetPathBoundingBox ().Location); var patternPhase = new CGSize (drawPoint.X, drawPoint.Y); if (patternPhase != CGSize.Empty) ctx.SetPatternPhase (patternPhase); } } }
// Authors: // Rafael Mizrahi <rafim@mainsoft.com> // Erez Lotan <erezl@mainsoft.com> // Oren Gurfinkel <oreng@mainsoft.com> // Ofer Borstein // // Copyright (c) 2004 Mainsoft Co. // // 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 NUnit.Framework; using System; using System.Data; using GHTUtils; using GHTUtils.Base; namespace tests.system_data_dll.System_Data { [TestFixture] public class DataRelation_ctor_SDclmsDclms : GHTBase { [Test] public void Main() { DataRelation_ctor_SDclmsDclms tc = new DataRelation_ctor_SDclmsDclms(); Exception exp = null; try { tc.BeginTest("DataRelation_CTor_SDclmsDclms"); tc.run(); } catch(Exception ex) { exp = ex; } finally { tc.EndTest(exp); } } //Activate This Construntor to log All To Standard output //public TestClass():base(true){} //Activate this constructor to log Failures to a log file //public TestClass(System.IO.TextWriter tw):base(tw, false){} //Activate this constructor to log All to a log file //public TestClass(System.IO.TextWriter tw):base(tw, true){} //BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES public void run() { Exception exp = null; DataSet ds = new DataSet(); DataTable dtChild = GHTUtils.DataProvider.CreateChildDataTable(); DataTable dtParent = GHTUtils.DataProvider.CreateParentDataTable(); ds.Tables.Add(dtParent); ds.Tables.Add(dtChild); DataRelation dRel; //check some exception try { BeginCase("DataRelation - CTor ArgumentException, two columns child"); exp = new Exception(); try { dRel = new DataRelation("MyRelation",new DataColumn[] {dtParent.Columns[0]},new DataColumn[] {dtChild.Columns[0],dtChild.Columns[2]}); } catch (ArgumentException ex){exp = ex;} Compare(exp.GetType().FullName ,typeof(ArgumentException).FullName ); exp=null; } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} dRel = new DataRelation("MyRelation",new DataColumn[] {dtParent.Columns[0],dtParent.Columns[1]},new DataColumn[] {dtChild.Columns[0],dtChild.Columns[2]}); try { BeginCase("DataRelation - Add Relation ArgumentException, fail on creating child Constraints"); exp = new Exception(); try { ds.Relations.Add(dRel); } catch (ArgumentException ex){exp = ex;} Compare(exp.GetType().FullName ,typeof(ArgumentException).FullName ); exp=null; } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("DataRelation ArgumentException - parent Constraints"); Compare(dtParent.Constraints.Count ,1); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("DataRelation ArgumentException - child Constraints"); Compare(dtChild.Constraints.Count ,0); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("DataRelation ArgumentException - DataSet.Relation count"); Compare(ds.Relations.Count ,1); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} //begin to check the relation ctor dtParent.Constraints.Clear(); dtChild.Constraints.Clear(); ds.Relations.Clear(); dRel = new DataRelation("MyRelation",new DataColumn[] {dtParent.Columns[0]},new DataColumn[] {dtChild.Columns[0]}); ds.Relations.Add(dRel); try { BeginCase("DataSet DataRelation count"); Compare(ds.Relations.Count ,1); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("DataRelation - CTor"); Compare(dRel == null ,false ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("DataRelation - parent Constraints"); Compare(dtParent.Constraints.Count ,1); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("DataRelation - child Constraints"); Compare(dtChild.Constraints.Count ,1); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("DataRelation - child relations"); Compare(dtParent.ChildRelations[0] ,dRel); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("DataRelation - parent relations"); Compare(dtChild.ParentRelations[0],dRel ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("DataRelation - name"); Compare(dRel.RelationName ,"MyRelation" ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Reflection; using System.Reflection.Emit; using System.Diagnostics; namespace XSharp.MacroCompiler { internal enum WellKnownMembers { System_Decimal_Zero, System_String_Concat, System_String_Concat_Object, System_String_Equals, System_String_op_Equality, System_String_op_Inequality, System_String_CompareOrdinal, System_Object_Equals, System_Decimal_ctor, System_DateTime_ctor, System_Array_get_Length, System_IDisposable_Dispose, System_Threading_Monitor_Enter, System_Threading_Monitor_Exit, XSharp___Array_ctor, XSharp___Float_ctor, XSharp___Date_ctor, XSharp___Symbol_ctor, XSharp___Currency_ctor, XSharp___Binary_ctor, XSharp___Array___ArrayNew, XSharp_RT_Functions_POW, XSharp_RT_Functions___InternalSend, XSharp_RT_Functions_IVarGet, XSharp_RT_Functions_IVarPut, XSharp_RT_Functions___MemVarGet, XSharp_RT_Functions___MemVarPut, XSharp_RT_Functions___FieldGet, XSharp_RT_Functions___FieldSet, XSharp_RT_Functions___FieldGetWa, XSharp_RT_Functions___FieldSetWa, XSharp_RT_Functions___VarGet, XSharp_RT_Functions___VarPut, XSharp_Core_Functions_Instr, XSharp_RT_Functions___StringCompare, XSharp_RT_Functions___StringEquals, XSharp_RT_Functions___StringNotEquals, XSharp_RT_Functions___pushWorkarea, XSharp_RT_Functions___popWorkarea, XSharp_RT_Functions_Evaluate, XSharp_Core_Functions_Chr, XSharp_Internal_CompilerServices_EnterBeginSequence, XSharp_Internal_CompilerServices_ExitBeginSequence, XSharp_Error_WrapRawException, XSharp_RT_Functions___MemVarGetSafe, XSharp_RT_Functions___VarGetSafe, XSharp_VFP_Functions___FoxArrayAccess_1, XSharp_VFP_Functions___FoxArrayAccess_2, } public static partial class Compilation { static string[] MemberNames = { "System.Decimal.Zero", "System.String.Concat$(System.String,System.String)", "System.String.Concat$(System.Object,System.Object)", "System.String.Equals$(System.String,System.String)", "System.String.op_Equality$(System.String,System.String)", "System.String.op_Inequality$(System.String,System.String)", "System.String.CompareOrdinal$(System.String,System.String)", "System.Object.Equals$(System.Object,System.Object)", "System.Decimal.@ctor(System.Int32[])", "System.DateTime.@ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)", "System.Array.get_Length", "System.IDisposable.Dispose", "System.Threading.Monitor.Enter$(System.Object,System.Boolean&)", "System.Threading.Monitor.Exit$(System.Object)", "XSharp.__Array.@ctor(XSharp.__Usual[])|Vulcan.__Array.@ctor(XSharp.__Usual[])", "XSharp.__Float.@ctor(System.Double,System.Int32,System.Int32)|Vulcan.__VOFloat.@ctor(System.Double,System.Int32,System.Int32)", "XSharp.__Date.@ctor(System.Int32,System.Int32,System.Int32)|Vulcan.__VODate.@ctor(System.Int32,System.Int32,System.Int32)", "XSharp.__Symbol.@ctor(System.String)|Vulcan.__Symbol.@ctor(System.String)", "XSharp.__Currency.@ctor(System.Decimal)", "XSharp.__Binary.@ctor(System.Byte[])", "XSharp.__Array.__ArrayNew$(System.Int32[])", XSharpQualifiedTypeNames.Functions+".POW|"+VulcanQualifiedTypeNames.Functions+".POW", XSharpQualifiedFunctionNames.InternalSend+"|"+VulcanQualifiedFunctionNames.InternalSend, XSharpQualifiedFunctionNames.IVarGet+"|"+VulcanQualifiedFunctionNames.IVarGet, XSharpQualifiedFunctionNames.IVarPut+"|"+VulcanQualifiedFunctionNames.IVarPut, XSharpQualifiedFunctionNames.MemVarGet+"|"+VulcanQualifiedFunctionNames.MemVarGet, XSharpQualifiedFunctionNames.MemVarPut+"|"+VulcanQualifiedFunctionNames.MemVarPut, XSharpQualifiedFunctionNames.FieldGet+"|"+VulcanQualifiedFunctionNames.FieldGet, XSharpQualifiedFunctionNames.FieldSet+"|"+VulcanQualifiedFunctionNames.FieldSet, XSharpQualifiedFunctionNames.FieldGetWa+"|"+VulcanQualifiedFunctionNames.FieldGetWa, XSharpQualifiedFunctionNames.FieldSetWa+"|"+VulcanQualifiedFunctionNames.FieldSetWa, XSharpQualifiedFunctionNames.VarGet+"|"+VulcanQualifiedFunctionNames.VarGet, XSharpQualifiedFunctionNames.VarPut+"|"+VulcanQualifiedFunctionNames.VarPut, XSharpQualifiedFunctionNames.InStr+"|"+VulcanQualifiedFunctionNames.InStr, XSharpQualifiedFunctionNames.StringCompare+"|"+VulcanQualifiedFunctionNames.StringCompare, XSharpQualifiedFunctionNames.StringEquals+"|"+VulcanQualifiedFunctionNames.StringEquals, XSharpQualifiedFunctionNames.StringNotEquals+"|"+VulcanQualifiedFunctionNames.StringNotEquals, XSharpQualifiedFunctionNames.PushWorkarea+"|"+VulcanQualifiedFunctionNames.PushWorkarea, XSharpQualifiedFunctionNames.PopWorkarea+"|"+VulcanQualifiedFunctionNames.PopWorkarea, XSharpQualifiedFunctionNames.Evaluate+"|"+VulcanQualifiedFunctionNames.Evaluate, XSharpQualifiedFunctionNames.Chr+"|"+VulcanQualifiedFunctionNames.Chr, XSharpQualifiedFunctionNames.EnterSequence+"|"+VulcanQualifiedFunctionNames.EnterSequence, XSharpQualifiedFunctionNames.ExitSequence+"|"+VulcanQualifiedFunctionNames.ExitSequence, XSharpQualifiedFunctionNames.WrapException+"|"+VulcanQualifiedFunctionNames.WrapException, XSharpQualifiedFunctionNames.MemVarGetSafe, XSharpQualifiedFunctionNames.VarGetSafe, XSharpQualifiedFunctionNames.FoxArrayAccess_1, XSharpQualifiedFunctionNames.FoxArrayAccess_2, }; static MemberSymbol[] WellKnownMemberSymbols; static MemberSymbol FindMember(string names) { foreach (var proto in names.Split('|')) { var name = proto.Replace("$", "").Split('(').First(); var s = Binder.LookupFullName(name.Replace("global::", "").Split('.').Select(n => n.Replace('@', '.')).ToArray()); if (s == null) continue; if (s is SymbolList) { var isStatic = proto.Contains('$'); var args = proto.Replace(")", "").Split('(').Last().Split(','); var argTypes = args.Select(x => Binder.LookupFullName(x) as TypeSymbol).ToArray(); s = (s as SymbolList).Symbols.Find(x => (x as MethodBaseSymbol)?.MethodBase.GetParameters().Length == args.Length && (x as MethodBaseSymbol)?.MethodBase.IsStatic == isStatic && (x as MethodBaseSymbol)?.MethodBase.GetParameters().All(y => args[y.Position] == "*" || y.ParameterType == argTypes[y.Position].Type) == true); Debug.Assert(s is MethodBaseSymbol); } Debug.Assert(s is MemberSymbol); return s as MemberSymbol; } return null; } internal static void InitializeWellKnownMembers() { var memberSymbols = new MemberSymbol[MemberNames.Length]; lock (MemberNames) { foreach (var m in (WellKnownMembers[])Enum.GetValues(typeof(WellKnownMembers))) { var names = MemberNames[(int)m]; var flatname = names.Replace("global::", "").Replace('.', '_').Replace("`", "_T").Replace("$", "").Replace("@", "").Split('|', '(').First(); Debug.Assert(m.ToString().StartsWith(flatname)); memberSymbols[(int)m] = FindMember(names); if (names.IndexOf("VFP") == -1 ) { Debug.Assert(memberSymbols[(int)m] != null); } else if (XSharp.RuntimeState.Dialect == XSharpDialect.FoxPro) { Debug.Assert(memberSymbols[(int)m] != null); } } } Interlocked.CompareExchange(ref WellKnownMemberSymbols, memberSymbols, null); } internal static MemberSymbol Get(WellKnownMembers kind) { Debug.Assert(WellKnownMemberSymbols != null); return WellKnownMemberSymbols[(int)kind]; } // Useful for testing internal static bool Override(WellKnownMembers kind, string proto = null) { if (proto == null) { WellKnownMemberSymbols[(int)kind] = FindMember(MemberNames[(int)kind]); return true; } var name = proto.Replace("$", "").Split('(').First(); var s = Binder.LookupName(name); if (s == null) return false; if (s is SymbolList) { var isStatic = proto.Contains('$'); var args = proto.Replace(")", "").Split('(').Last().Split(','); var argTypes = args.Select(x => Binder.LookupFullName(x) as TypeSymbol).ToArray(); s = (s as SymbolList).Symbols.Find(x => (x as MethodBaseSymbol)?.MethodBase.GetParameters().Length == args.Length && (x as MethodBaseSymbol)?.MethodBase.IsStatic == isStatic && (x as MethodBaseSymbol)?.MethodBase.GetParameters().All(y => args[y.Position] == "*" || y.ParameterType == argTypes[y.Position].Type) == true); if (!(s is MethodBaseSymbol)) return false; } if (!(s is MemberSymbol)) return false; WellKnownMemberSymbols[(int)kind] = s as MemberSymbol; return true; } } }
/* * Copyright 2012-2016 The Pkcs11Interop Project * * 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. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <jimrich@jimrich.sk> */ using System; using System.IO; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.HighLevelAPI41; using Net.Pkcs11Interop.HighLevelAPI41.MechanismParams; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Net.Pkcs11Interop.Tests.HighLevelAPI41 { /// <summary> /// Encryption and decryption tests. /// </summary> [TestClass] public class _19_EncryptAndDecryptTest { /// <summary> /// Single-part encryption and decryption test. /// </summary> [TestMethod] public void _01_EncryptAndDecryptSinglePartTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking)) { // Find first slot with token present Slot slot = Helpers.GetUsableSlot(pkcs11); // Open RW session using (Session session = slot.OpenSession(false)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate symetric key ObjectHandle generatedKey = Helpers.GenerateKey(session); // Generate random initialization vector byte[] iv = session.GenerateRandom(8); // Specify encryption mechanism with initialization vector as parameter Mechanism mechanism = new Mechanism(CKM.CKM_DES3_CBC, iv); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password"); // Encrypt data byte[] encryptedData = session.Encrypt(mechanism, generatedKey, sourceData); // Do something interesting with encrypted data // Decrypt data byte[] decryptedData = session.Decrypt(mechanism, generatedKey, encryptedData); // Do something interesting with decrypted data Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData)); session.DestroyObject(generatedKey); session.Logout(); } } } /// <summary> /// Multi-part encryption and decryption test. /// </summary> [TestMethod] public void _02_EncryptAndDecryptMultiPartTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking)) { // Find first slot with token present Slot slot = Helpers.GetUsableSlot(pkcs11); // Open RW session using (Session session = slot.OpenSession(false)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate symetric key ObjectHandle generatedKey = Helpers.GenerateKey(session); // Generate random initialization vector byte[] iv = session.GenerateRandom(8); // Specify encryption mechanism with initialization vector as parameter Mechanism mechanism = new Mechanism(CKM.CKM_DES3_CBC, iv); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password"); byte[] encryptedData = null; byte[] decryptedData = null; // Multipart encryption can be used i.e. for encryption of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData), outputStream = new MemoryStream()) { // Encrypt data // Note that in real world application we would rather use bigger read buffer i.e. 4096 session.Encrypt(mechanism, generatedKey, inputStream, outputStream, 8); // Read whole output stream to the byte array so we can compare results more easily encryptedData = outputStream.ToArray(); } // Do something interesting with encrypted data // Multipart decryption can be used i.e. for decryption of streamed data using (MemoryStream inputStream = new MemoryStream(encryptedData), outputStream = new MemoryStream()) { // Decrypt data // Note that in real world application we would rather use bigger read buffer i.e. 4096 session.Decrypt(mechanism, generatedKey, inputStream, outputStream, 8); // Read whole output stream to the byte array so we can compare results more easily decryptedData = outputStream.ToArray(); } // Do something interesting with decrypted data Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData)); session.DestroyObject(generatedKey); session.Logout(); } } } /// <summary> /// Single-part encryption and decryption test with CKM_RSA_PKCS_OAEP mechanism. /// </summary> [TestMethod] public void _03_EncryptAndDecryptSinglePartOaepTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking)) { // Find first slot with token present Slot slot = Helpers.GetUsableSlot(pkcs11); // Open RW session using (Session session = slot.OpenSession(false)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate key pair ObjectHandle publicKey = null; ObjectHandle privateKey = null; Helpers.GenerateKeyPair(session, out publicKey, out privateKey); // Specify mechanism parameters CkRsaPkcsOaepParams mechanismParams = new CkRsaPkcsOaepParams((uint)CKM.CKM_SHA_1, (uint)CKG.CKG_MGF1_SHA1, (uint)CKZ.CKZ_DATA_SPECIFIED, null); // Specify encryption mechanism with parameters Mechanism mechanism = new Mechanism(CKM.CKM_RSA_PKCS_OAEP, mechanismParams); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); // Encrypt data byte[] encryptedData = session.Encrypt(mechanism, publicKey, sourceData); // Do something interesting with encrypted data // Decrypt data byte[] decryptedData = session.Decrypt(mechanism, privateKey, encryptedData); // Do something interesting with decrypted data Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData)); session.DestroyObject(privateKey); session.DestroyObject(publicKey); session.Logout(); } } } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using Android.App; using Android.Content; using Android.Content.Res; using Android.Graphics; using Android.Graphics.Drawables; using Android.Support.V4.App; using Android.Util; using Android.Views; using Android.Widget; using Xamarin.Forms.Platform.Android.AppCompat; using FragmentManager = Android.Support.V4.App.FragmentManager; namespace Xamarin.Forms.Platform.Android { public class Platform : BindableObject, IPlatform, INavigation, IDisposable, IPlatformLayout { internal const string CloseContextActionsSignalName = "Xamarin.CloseContextActions"; internal static readonly BindableProperty RendererProperty = BindableProperty.CreateAttached("Renderer", typeof(IVisualElementRenderer), typeof(Platform), default(IVisualElementRenderer), propertyChanged: (bindable, oldvalue, newvalue) => { var view = bindable as VisualElement; if (view != null) view.IsPlatformEnabled = newvalue != null; }); internal static readonly BindableProperty PageContextProperty = BindableProperty.CreateAttached("PageContext", typeof(Context), typeof(Platform), null); IMasterDetailPageController MasterDetailPageController => CurrentMasterDetailPage as IMasterDetailPageController; readonly Context _context; readonly PlatformRenderer _renderer; readonly ToolbarTracker _toolbarTracker = new ToolbarTracker(); NavigationPage _currentNavigationPage; TabbedPage _currentTabbedPage; Color _defaultActionBarTitleTextColor; bool _disposed; bool _ignoreAndroidSelection; Page _navigationPageCurrentPage; NavigationModel _navModel = new NavigationModel(); internal Platform(Context context) { _context = context; _defaultActionBarTitleTextColor = SetDefaultActionBarTitleTextColor(); _renderer = new PlatformRenderer(context, this); FormsApplicationActivity.BackPressed += HandleBackPressed; _toolbarTracker.CollectionChanged += ToolbarTrackerOnCollectionChanged; } #region IPlatform implementation internal Page Page { get; private set; } #endregion ActionBar ActionBar { get { return ((Activity)_context).ActionBar; } } MasterDetailPage CurrentMasterDetailPage { get; set; } NavigationPage CurrentNavigationPage { get { return _currentNavigationPage; } set { if (_currentNavigationPage == value) return; if (_currentNavigationPage != null) { _currentNavigationPage.Pushed -= CurrentNavigationPageOnPushed; _currentNavigationPage.Popped -= CurrentNavigationPageOnPopped; _currentNavigationPage.PoppedToRoot -= CurrentNavigationPageOnPoppedToRoot; _currentNavigationPage.PropertyChanged -= CurrentNavigationPageOnPropertyChanged; } RegisterNavPageCurrent(null); _currentNavigationPage = value; if (_currentNavigationPage != null) { _currentNavigationPage.Pushed += CurrentNavigationPageOnPushed; _currentNavigationPage.Popped += CurrentNavigationPageOnPopped; _currentNavigationPage.PoppedToRoot += CurrentNavigationPageOnPoppedToRoot; _currentNavigationPage.PropertyChanged += CurrentNavigationPageOnPropertyChanged; RegisterNavPageCurrent(_currentNavigationPage.CurrentPage); } UpdateActionBarBackgroundColor(); UpdateActionBarTextColor(); UpdateActionBarUpImageColor(); UpdateActionBarTitle(); } } TabbedPage CurrentTabbedPage { get { return _currentTabbedPage; } set { if (_currentTabbedPage == value) return; if (_currentTabbedPage != null) { _currentTabbedPage.PagesChanged -= CurrentTabbedPageChildrenChanged; _currentTabbedPage.PropertyChanged -= CurrentTabbedPageOnPropertyChanged; if (value == null) ActionBar.RemoveAllTabs(); } _currentTabbedPage = value; if (_currentTabbedPage != null) { _currentTabbedPage.PagesChanged += CurrentTabbedPageChildrenChanged; _currentTabbedPage.PropertyChanged += CurrentTabbedPageOnPropertyChanged; } UpdateActionBarTitle(); ActionBar.NavigationMode = value == null ? ActionBarNavigationMode.Standard : ActionBarNavigationMode.Tabs; CurrentTabbedPageChildrenChanged(null, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } #pragma warning disable 618 // Eventually we will need to determine how to handle the v7 ActionBarDrawerToggle for AppCompat ActionBarDrawerToggle MasterDetailPageToggle { get; set; } #pragma warning restore 618 void IDisposable.Dispose() { if (_disposed) return; _disposed = true; SetPage(null); FormsApplicationActivity.BackPressed -= HandleBackPressed; _toolbarTracker.CollectionChanged -= ToolbarTrackerOnCollectionChanged; _toolbarTracker.Target = null; CurrentNavigationPage = null; CurrentMasterDetailPage = null; CurrentTabbedPage = null; } void INavigation.InsertPageBefore(Page page, Page before) { throw new InvalidOperationException("InsertPageBefore is not supported globally on Android, please use a NavigationPage."); } IReadOnlyList<Page> INavigation.ModalStack => _navModel.Modals.ToList(); IReadOnlyList<Page> INavigation.NavigationStack => new List<Page>(); Task<Page> INavigation.PopAsync() { return ((INavigation)this).PopAsync(true); } Task<Page> INavigation.PopAsync(bool animated) { throw new InvalidOperationException("PopAsync is not supported globally on Android, please use a NavigationPage."); } Task<Page> INavigation.PopModalAsync() { return ((INavigation)this).PopModalAsync(true); } Task<Page> INavigation.PopModalAsync(bool animated) { Page modal = _navModel.PopModal(); modal.SendDisappearing(); var source = new TaskCompletionSource<Page>(); IVisualElementRenderer modalRenderer = GetRenderer(modal); if (modalRenderer != null) { if (animated) { modalRenderer.ViewGroup.Animate().Alpha(0).ScaleX(0.8f).ScaleY(0.8f).SetDuration(250).SetListener(new GenericAnimatorListener { OnEnd = a => { modalRenderer.ViewGroup.RemoveFromParent(); modalRenderer.Dispose(); source.TrySetResult(modal); _navModel.CurrentPage?.SendAppearing(); } }); } else { modalRenderer.ViewGroup.RemoveFromParent(); modalRenderer.Dispose(); source.TrySetResult(modal); _navModel.CurrentPage?.SendAppearing(); } } _toolbarTracker.Target = _navModel.Roots.Last(); UpdateActionBar(); return source.Task; } Task INavigation.PopToRootAsync() { return ((INavigation)this).PopToRootAsync(true); } Task INavigation.PopToRootAsync(bool animated) { throw new InvalidOperationException("PopToRootAsync is not supported globally on Android, please use a NavigationPage."); } Task INavigation.PushAsync(Page root) { return ((INavigation)this).PushAsync(root, true); } Task INavigation.PushAsync(Page root, bool animated) { throw new InvalidOperationException("PushAsync is not supported globally on Android, please use a NavigationPage."); } Task INavigation.PushModalAsync(Page modal) { return ((INavigation)this).PushModalAsync(modal, true); } async Task INavigation.PushModalAsync(Page modal, bool animated) { _navModel.CurrentPage?.SendDisappearing(); _navModel.PushModal(modal); modal.Platform = this; await PresentModal(modal, animated); // Verify that the modal is still on the stack if (_navModel.CurrentPage == modal) modal.SendAppearing(); _toolbarTracker.Target = _navModel.Roots.Last(); UpdateActionBar(); } void INavigation.RemovePage(Page page) { throw new InvalidOperationException("RemovePage is not supported globally on Android, please use a NavigationPage."); } public static IVisualElementRenderer CreateRenderer(VisualElement element) { UpdateGlobalContext(element); IVisualElementRenderer renderer = Registrar.Registered.GetHandler<IVisualElementRenderer>(element.GetType()) ?? new DefaultRenderer(); renderer.SetElement(element); return renderer; } public static IVisualElementRenderer GetRenderer(VisualElement bindable) { return (IVisualElementRenderer)bindable.GetValue(RendererProperty); } public static void SetRenderer(VisualElement bindable, IVisualElementRenderer value) { bindable.SetValue(RendererProperty, value); } public void UpdateActionBarTextColor() { SetActionBarTextColor(); } protected override void OnBindingContextChanged() { SetInheritedBindingContext(Page, BindingContext); base.OnBindingContextChanged(); } internal static IVisualElementRenderer CreateRenderer(VisualElement element, FragmentManager fragmentManager) { UpdateGlobalContext(element); IVisualElementRenderer renderer = Registrar.Registered.GetHandler<IVisualElementRenderer>(element.GetType()) ?? new DefaultRenderer(); var managesFragments = renderer as IManageFragments; managesFragments?.SetFragmentManager(fragmentManager); renderer.SetElement(element); return renderer; } internal static Context GetPageContext(BindableObject bindable) { return (Context)bindable.GetValue(PageContextProperty); } internal ViewGroup GetViewGroup() { return _renderer; } internal void PrepareMenu(IMenu menu) { foreach (ToolbarItem item in _toolbarTracker.ToolbarItems) item.PropertyChanged -= HandleToolbarItemPropertyChanged; menu.Clear(); if (!ShouldShowActionBarTitleArea()) return; foreach (ToolbarItem item in _toolbarTracker.ToolbarItems) { item.PropertyChanged += HandleToolbarItemPropertyChanged; if (item.Order == ToolbarItemOrder.Secondary) { IMenuItem menuItem = menu.Add(item.Text); menuItem.SetEnabled(item.IsEnabled); menuItem.SetOnMenuItemClickListener(new GenericMenuClickListener(item.Activate)); } else { IMenuItem menuItem = menu.Add(item.Text); if (!string.IsNullOrEmpty(item.Icon)) { Drawable iconBitmap = _context.Resources.GetDrawable(item.Icon); if (iconBitmap != null) menuItem.SetIcon(iconBitmap); } menuItem.SetEnabled(item.IsEnabled); menuItem.SetShowAsAction(ShowAsAction.Always); menuItem.SetOnMenuItemClickListener(new GenericMenuClickListener(item.Activate)); } } } internal async void SendHomeClicked() { if (UpButtonShouldNavigate()) { if (NavAnimationInProgress) return; NavAnimationInProgress = true; await CurrentNavigationPage.PopAsync(); NavAnimationInProgress = false; } else if (CurrentMasterDetailPage != null) { if (MasterDetailPageController.ShouldShowSplitMode && CurrentMasterDetailPage.IsPresented) return; CurrentMasterDetailPage.IsPresented = !CurrentMasterDetailPage.IsPresented; } } internal void SetPage(Page newRoot) { var layout = false; if (Page != null) { _renderer.RemoveAllViews(); foreach (IVisualElementRenderer rootRenderer in _navModel.Roots.Select(GetRenderer)) rootRenderer.Dispose(); _navModel = new NavigationModel(); layout = true; } if (newRoot == null) return; _navModel.Push(newRoot, null); Page = newRoot; Page.Platform = this; AddChild(Page, layout); ((Application)Page.RealParent).NavigationProxy.Inner = this; _toolbarTracker.Target = newRoot; UpdateActionBar(); } internal static void SetPageContext(BindableObject bindable, Context context) { bindable.SetValue(PageContextProperty, context); } internal void UpdateActionBar() { List<Page> relevantAncestors = AncestorPagesOfPage(_navModel.CurrentPage); IEnumerable<NavigationPage> navPages = relevantAncestors.OfType<NavigationPage>(); if (navPages.Count() > 1) throw new Exception("Android only allows one navigation page on screen at a time"); NavigationPage navPage = navPages.FirstOrDefault(); IEnumerable<TabbedPage> tabbedPages = relevantAncestors.OfType<TabbedPage>(); if (tabbedPages.Count() > 1) throw new Exception("Android only allows one tabbed page on screen at a time"); TabbedPage tabbedPage = tabbedPages.FirstOrDefault(); CurrentMasterDetailPage = relevantAncestors.OfType<MasterDetailPage>().FirstOrDefault(); CurrentNavigationPage = navPage; CurrentTabbedPage = tabbedPage; if (navPage != null && navPage.CurrentPage == null) { throw new InvalidOperationException("NavigationPage must have a root Page before being used. Either call PushAsync with a valid Page, or pass a Page to the constructor before usage."); } UpdateActionBarTitle(); if (ShouldShowActionBarTitleArea() || tabbedPage != null) ShowActionBar(); else HideActionBar(); UpdateMasterDetailToggle(); } internal void UpdateActionBarBackgroundColor() { if (!((Activity)_context).ActionBar.IsShowing) return; Color colorToUse = Color.Default; if (CurrentNavigationPage != null) { #pragma warning disable 618 // Make sure Tint still works if (CurrentNavigationPage.Tint != Color.Default) colorToUse = CurrentNavigationPage.Tint; #pragma warning restore 618 else if (CurrentNavigationPage.BarBackgroundColor != Color.Default) colorToUse = CurrentNavigationPage.BarBackgroundColor; } using (Drawable drawable = colorToUse == Color.Default ? GetActionBarBackgroundDrawable() : new ColorDrawable(colorToUse.ToAndroid())) ((Activity)_context).ActionBar.SetBackgroundDrawable(drawable); } internal void UpdateMasterDetailToggle(bool update = false) { if (CurrentMasterDetailPage == null) { if (MasterDetailPageToggle == null) return; // clear out the icon ClearMasterDetailToggle(); return; } if (!CurrentMasterDetailPage.ShouldShowToolbarButton() || string.IsNullOrEmpty(CurrentMasterDetailPage.Master.Icon) || (MasterDetailPageController.ShouldShowSplitMode && CurrentMasterDetailPage.IsPresented)) { //clear out existing icon; ClearMasterDetailToggle(); return; } if (MasterDetailPageToggle == null || update) { ClearMasterDetailToggle(); GetNewMasterDetailToggle(); } bool state; if (CurrentNavigationPage == null) state = true; else state = !UpButtonShouldNavigate(); if (state == MasterDetailPageToggle.DrawerIndicatorEnabled) return; MasterDetailPageToggle.DrawerIndicatorEnabled = state; MasterDetailPageToggle.SyncState(); } internal void UpdateNavigationTitleBar() { UpdateActionBarTitle(); UpdateActionBar(); UpdateActionBarUpImageColor(); } void AddChild(VisualElement view, bool layout = false) { if (GetRenderer(view) != null) return; SetPageContext(view, _context); IVisualElementRenderer renderView = CreateRenderer(view); SetRenderer(view, renderView); if (layout) view.Layout(new Rectangle(0, 0, _context.FromPixels(_renderer.Width), _context.FromPixels(_renderer.Height))); _renderer.AddView(renderView.ViewGroup); } #pragma warning disable 618 // This may need to be updated to work with TabLayout/AppCompat ActionBar.Tab AddTab(Page page, int index) #pragma warning restore 618 { ActionBar actionBar = ((Activity)_context).ActionBar; TabbedPage currentTabs = CurrentTabbedPage; var atab = actionBar.NewTab(); atab.SetText(page.Title); atab.TabSelected += (sender, e) => { if (!_ignoreAndroidSelection) currentTabs.CurrentPage = page; }; actionBar.AddTab(atab, index); page.PropertyChanged += PagePropertyChanged; return atab; } List<Page> AncestorPagesOfPage(Page root) { var result = new List<Page>(); if (root == null) return result; if (root is IPageContainer<Page>) { var navPage = (IPageContainer<Page>)root; result.AddRange(AncestorPagesOfPage(navPage.CurrentPage)); } else if (root is MasterDetailPage) result.AddRange(AncestorPagesOfPage(((MasterDetailPage)root).Detail)); else { foreach (Page page in root.InternalChildren.OfType<Page>()) result.AddRange(AncestorPagesOfPage(page)); } result.Add(root); return result; } void ClearMasterDetailToggle() { if (MasterDetailPageToggle == null) return; MasterDetailPageToggle.DrawerIndicatorEnabled = false; MasterDetailPageToggle.SyncState(); MasterDetailPageToggle.Dispose(); MasterDetailPageToggle = null; } void CurrentNavigationPageOnPopped(object sender, NavigationEventArgs eventArg) { UpdateNavigationTitleBar(); } void CurrentNavigationPageOnPoppedToRoot(object sender, EventArgs eventArgs) { UpdateNavigationTitleBar(); } void CurrentNavigationPageOnPropertyChanged(object sender, PropertyChangedEventArgs e) { #pragma warning disable 618 // Make sure Tint still works if (e.PropertyName == NavigationPage.TintProperty.PropertyName) #pragma warning restore 618 UpdateActionBarBackgroundColor(); else if (e.PropertyName == NavigationPage.BarBackgroundColorProperty.PropertyName) UpdateActionBarBackgroundColor(); else if (e.PropertyName == NavigationPage.BarTextColorProperty.PropertyName) { UpdateActionBarTextColor(); UpdateActionBarUpImageColor(); } else if (e.PropertyName == NavigationPage.CurrentPageProperty.PropertyName) RegisterNavPageCurrent(CurrentNavigationPage.CurrentPage); } void CurrentNavigationPageOnPushed(object sender, NavigationEventArgs eventArg) { UpdateNavigationTitleBar(); } void CurrentTabbedPageChildrenChanged(object sender, NotifyCollectionChangedEventArgs e) { if (CurrentTabbedPage == null) return; _ignoreAndroidSelection = true; e.Apply((o, index, create) => AddTab((Page)o, index), (o, index) => RemoveTab((Page)o, index), Reset); if (CurrentTabbedPage.CurrentPage != null) { Page page = CurrentTabbedPage.CurrentPage; int index = TabbedPage.GetIndex(page); if (index >= 0 && index < CurrentTabbedPage.Children.Count) ActionBar.GetTabAt(index).Select(); } _ignoreAndroidSelection = false; } void CurrentTabbedPageOnPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName != "CurrentPage") return; UpdateActionBar(); // If we switch tabs while pushing a new page, UpdateActionBar() can set currentTabbedPage to null if (_currentTabbedPage == null) return; NavAnimationInProgress = true; Page page = _currentTabbedPage.CurrentPage; if (page == null) { ActionBar.SelectTab(null); NavAnimationInProgress = false; return; } int index = TabbedPage.GetIndex(page); if (ActionBar.SelectedNavigationIndex == index || index >= ActionBar.NavigationItemCount) { NavAnimationInProgress = false; return; } ActionBar.SelectTab(ActionBar.GetTabAt(index)); NavAnimationInProgress = false; } Drawable GetActionBarBackgroundDrawable() { int[] backgroundDataArray = { global::Android.Resource.Attribute.Background }; using (var outVal = new TypedValue()) { _context.Theme.ResolveAttribute(global::Android.Resource.Attribute.ActionBarStyle, outVal, true); TypedArray actionBarStyle = _context.Theme.ObtainStyledAttributes(outVal.ResourceId, backgroundDataArray); Drawable result = actionBarStyle.GetDrawable(0); actionBarStyle.Recycle(); return result; } } void GetNewMasterDetailToggle() { int icon = ResourceManager.GetDrawableByName(CurrentMasterDetailPage.Master.Icon); var drawer = GetRenderer(CurrentMasterDetailPage) as MasterDetailRenderer; if (drawer == null) return; #pragma warning disable 618 // Eventually we will need to determine how to handle the v7 ActionBarDrawerToggle for AppCompat MasterDetailPageToggle = new ActionBarDrawerToggle(_context as Activity, drawer, icon, 0, 0); #pragma warning restore 618 MasterDetailPageToggle.SyncState(); } bool HandleBackPressed(object sender, EventArgs e) { if (NavAnimationInProgress) return true; Page root = _navModel.Roots.Last(); bool handled = root.SendBackButtonPressed(); return handled; } void HandleToolbarItemPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == MenuItem.IsEnabledProperty.PropertyName) (_context as Activity).InvalidateOptionsMenu(); else if (e.PropertyName == MenuItem.TextProperty.PropertyName) (_context as Activity).InvalidateOptionsMenu(); else if (e.PropertyName == MenuItem.IconProperty.PropertyName) (_context as Activity).InvalidateOptionsMenu(); } void HideActionBar() { ReloadToolbarItems(); UpdateActionBarHomeAsUp(ActionBar); ActionBar.Hide(); } void NavigationPageCurrentPageOnPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == NavigationPage.HasNavigationBarProperty.PropertyName) UpdateActionBar(); else if (e.PropertyName == Page.TitleProperty.PropertyName) UpdateActionBarTitle(); } void PagePropertyChanged(object sender, PropertyChangedEventArgs args) { if (args.PropertyName == Page.TitleProperty.PropertyName) { ActionBar actionBar = ((Activity)_context).ActionBar; TabbedPage currentTabs = CurrentTabbedPage; if (currentTabs == null || actionBar.TabCount == 0) return; var page = sender as Page; var atab = actionBar.GetTabAt(currentTabs.Children.IndexOf(page)); atab.SetText(page.Title); } } Task PresentModal(Page modal, bool animated) { IVisualElementRenderer modalRenderer = GetRenderer(modal); if (modalRenderer == null) { SetPageContext(modal, _context); modalRenderer = CreateRenderer(modal); SetRenderer(modal, modalRenderer); if (modal.BackgroundColor == Color.Default && modal.BackgroundImage == null) modalRenderer.ViewGroup.SetWindowBackground(); } modalRenderer.Element.Layout(new Rectangle(0, 0, _context.FromPixels(_renderer.Width), _context.FromPixels(_renderer.Height))); _renderer.AddView(modalRenderer.ViewGroup); var source = new TaskCompletionSource<bool>(); NavAnimationInProgress = true; if (animated) { modalRenderer.ViewGroup.Alpha = 0; modalRenderer.ViewGroup.ScaleX = 0.8f; modalRenderer.ViewGroup.ScaleY = 0.8f; modalRenderer.ViewGroup.Animate().Alpha(1).ScaleX(1).ScaleY(1).SetDuration(250).SetListener(new GenericAnimatorListener { OnEnd = a => { source.TrySetResult(false); NavAnimationInProgress = false; }, OnCancel = a => { source.TrySetResult(true); NavAnimationInProgress = false; } }); } else { NavAnimationInProgress = false; source.TrySetResult(true); } return source.Task; } void RegisterNavPageCurrent(Page page) { if (_navigationPageCurrentPage != null) _navigationPageCurrentPage.PropertyChanged -= NavigationPageCurrentPageOnPropertyChanged; _navigationPageCurrentPage = page; if (_navigationPageCurrentPage != null) _navigationPageCurrentPage.PropertyChanged += NavigationPageCurrentPageOnPropertyChanged; } void ReloadToolbarItems() { var activity = (Activity)_context; activity.InvalidateOptionsMenu(); } void RemoveTab(Page page, int index) { ActionBar actionBar = ((Activity)_context).ActionBar; page.PropertyChanged -= PagePropertyChanged; actionBar.RemoveTabAt(index); } void Reset() { ActionBar.RemoveAllTabs(); if (CurrentTabbedPage == null) return; var i = 0; foreach (Page tab in CurrentTabbedPage.Children.OfType<Page>()) { var realTab = AddTab(tab, i++); if (tab == CurrentTabbedPage.CurrentPage) realTab.Select(); } } void SetActionBarTextColor() { Color navigationBarTextColor = CurrentNavigationPage == null ? Color.Default : CurrentNavigationPage.BarTextColor; TextView actionBarTitleTextView = null; int actionBarTitleId = _context.Resources.GetIdentifier("action_bar_title", "id", "android"); if (actionBarTitleId > 0) actionBarTitleTextView = ((Activity)_context).FindViewById<TextView>(actionBarTitleId); if (actionBarTitleTextView != null && navigationBarTextColor != Color.Default) actionBarTitleTextView.SetTextColor(navigationBarTextColor.ToAndroid()); else if (actionBarTitleTextView != null && navigationBarTextColor == Color.Default) actionBarTitleTextView.SetTextColor(_defaultActionBarTitleTextColor.ToAndroid()); } Color SetDefaultActionBarTitleTextColor() { var defaultTitleTextColor = new Color(); TextView actionBarTitleTextView = null; int actionBarTitleId = _context.Resources.GetIdentifier("action_bar_title", "id", "android"); if (actionBarTitleId > 0) actionBarTitleTextView = ((Activity)_context).FindViewById<TextView>(actionBarTitleId); if (actionBarTitleTextView != null) { ColorStateList defaultTitleColorList = actionBarTitleTextView.TextColors; string defaultColorHex = defaultTitleColorList.DefaultColor.ToString("X"); defaultTitleTextColor = Color.FromHex(defaultColorHex); } return defaultTitleTextColor; } bool ShouldShowActionBarTitleArea() { if (Forms.TitleBarVisibility == AndroidTitleBarVisibility.Never) return false; bool hasMasterDetailPage = CurrentMasterDetailPage != null; bool navigated = CurrentNavigationPage != null && ((INavigationPageController)CurrentNavigationPage).StackDepth > 1; bool navigationPageHasNavigationBar = CurrentNavigationPage != null && NavigationPage.GetHasNavigationBar(CurrentNavigationPage.CurrentPage); return navigationPageHasNavigationBar || (hasMasterDetailPage && !navigated); } bool ShouldUpdateActionBarUpColor() { bool hasMasterDetailPage = CurrentMasterDetailPage != null; bool navigated = CurrentNavigationPage != null && ((INavigationPageController)CurrentNavigationPage).StackDepth > 1; return (hasMasterDetailPage && navigated) || !hasMasterDetailPage; } void ShowActionBar() { ReloadToolbarItems(); UpdateActionBarHomeAsUp(ActionBar); ActionBar.Show(); UpdateActionBarBackgroundColor(); UpdateActionBarTextColor(); } void ToolbarTrackerOnCollectionChanged(object sender, EventArgs eventArgs) { ReloadToolbarItems(); } bool UpButtonShouldNavigate() { if (CurrentNavigationPage == null) return false; bool pagePushed = ((INavigationPageController)CurrentNavigationPage).StackDepth > 1; bool pushedPageHasBackButton = NavigationPage.GetHasBackButton(CurrentNavigationPage.CurrentPage); return pagePushed && pushedPageHasBackButton; } void UpdateActionBarHomeAsUp(ActionBar actionBar) { bool showHomeAsUp = ShouldShowActionBarTitleArea() && (CurrentMasterDetailPage != null || UpButtonShouldNavigate()); actionBar.SetDisplayHomeAsUpEnabled(showHomeAsUp); } void UpdateActionBarTitle() { Page view = null; if (CurrentNavigationPage != null) view = CurrentNavigationPage.CurrentPage; else if (CurrentTabbedPage != null) view = CurrentTabbedPage.CurrentPage; if (view == null) return; ActionBar actionBar = ((Activity)_context).ActionBar; var useLogo = false; var showHome = false; var showTitle = false; if (ShouldShowActionBarTitleArea()) { actionBar.Title = view.Title; FileImageSource titleIcon = NavigationPage.GetTitleIcon(view); if (!string.IsNullOrWhiteSpace(titleIcon)) { actionBar.SetLogo(_context.Resources.GetDrawable(titleIcon)); useLogo = true; showHome = true; showTitle = true; } else { showHome = true; showTitle = true; } } ActionBarDisplayOptions options = 0; if (useLogo) options = options | ActionBarDisplayOptions.UseLogo; if (showHome) options = options | ActionBarDisplayOptions.ShowHome; if (showTitle) options = options | ActionBarDisplayOptions.ShowTitle; actionBar.SetDisplayOptions(options, ActionBarDisplayOptions.UseLogo | ActionBarDisplayOptions.ShowTitle | ActionBarDisplayOptions.ShowHome); UpdateActionBarHomeAsUp(actionBar); } void UpdateActionBarUpImageColor() { Color navigationBarTextColor = CurrentNavigationPage == null ? Color.Default : CurrentNavigationPage.BarTextColor; ImageView actionBarUpImageView = null; int actionBarUpId = _context.Resources.GetIdentifier("up", "id", "android"); if (actionBarUpId > 0) actionBarUpImageView = ((Activity)_context).FindViewById<ImageView>(actionBarUpId); if (actionBarUpImageView != null && navigationBarTextColor != Color.Default) { if (ShouldUpdateActionBarUpColor()) actionBarUpImageView.SetColorFilter(navigationBarTextColor.ToAndroid(), PorterDuff.Mode.SrcIn); else actionBarUpImageView.SetColorFilter(null); } else if (actionBarUpImageView != null && navigationBarTextColor == Color.Default) actionBarUpImageView.SetColorFilter(null); } static void UpdateGlobalContext(VisualElement view) { Element parent = view; while (!Application.IsApplicationOrNull(parent.RealParent)) parent = parent.RealParent; var rootPage = parent as Page; if (rootPage != null) { Context context = GetPageContext(rootPage); if (context != null) Forms.Context = context; } } internal class DefaultRenderer : VisualElementRenderer<View> { } #region IPlatformEngine implementation void IPlatformLayout.OnLayout(bool changed, int l, int t, int r, int b) { if (changed) { // ActionBar title text color resets on rotation, make sure to update UpdateActionBarTextColor(); foreach (Page modal in _navModel.Roots.ToList()) modal.Layout(new Rectangle(0, 0, _context.FromPixels(r - l), _context.FromPixels(b - t))); } foreach (IVisualElementRenderer view in _navModel.Roots.Select(GetRenderer)) view.UpdateLayout(); } SizeRequest IPlatform.GetNativeSize(VisualElement view, double widthConstraint, double heightConstraint) { Performance.Start(); // FIXME: potential crash IVisualElementRenderer viewRenderer = GetRenderer(view); // negative numbers have special meanings to android they don't to us widthConstraint = widthConstraint <= -1 ? double.PositiveInfinity : _context.ToPixels(widthConstraint); heightConstraint = heightConstraint <= -1 ? double.PositiveInfinity : _context.ToPixels(heightConstraint); int width = !double.IsPositiveInfinity(widthConstraint) ? MeasureSpecFactory.MakeMeasureSpec((int)widthConstraint, MeasureSpecMode.AtMost) : MeasureSpecFactory.MakeMeasureSpec(0, MeasureSpecMode.Unspecified); int height = !double.IsPositiveInfinity(heightConstraint) ? MeasureSpecFactory.MakeMeasureSpec((int)heightConstraint, MeasureSpecMode.AtMost) : MeasureSpecFactory.MakeMeasureSpec(0, MeasureSpecMode.Unspecified); SizeRequest rawResult = viewRenderer.GetDesiredSize(width, height); if (rawResult.Minimum == Size.Zero) rawResult.Minimum = rawResult.Request; var result = new SizeRequest(new Size(_context.FromPixels(rawResult.Request.Width), _context.FromPixels(rawResult.Request.Height)), new Size(_context.FromPixels(rawResult.Minimum.Width), _context.FromPixels(rawResult.Minimum.Height))); Performance.Stop(); return result; } bool _navAnimationInProgress; internal bool NavAnimationInProgress { get { return _navAnimationInProgress; } set { if (_navAnimationInProgress == value) return; _navAnimationInProgress = value; if (value) MessagingCenter.Send(this, CloseContextActionsSignalName); } } #endregion } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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.Globalization; using System.IO; using System.Net; using System.Web; using ASC.Core; using ASC.Core.Tenants; using ASC.Web.Core.Files; using ASC.Web.Files.Classes; using ASC.Web.Files.Resources; using ASC.Web.Studio.Utility; using Newtonsoft.Json; using static ASC.Web.Core.Files.DocumentService; namespace ASC.Web.Files.Services.DocumentService { public static class DocumentServiceConnector { public static string GenerateRevisionId(string expectedKey) { return Web.Core.Files.DocumentService.GenerateRevisionId(expectedKey); } public static int GetConvertedUri(string documentUri, string fromExtension, string toExtension, string documentRevisionId, string password, ThumbnailData thumbnail, SpreadsheetLayout spreadsheetLayout, bool isAsync, out string convertedDocumentUri) { Global.Logger.DebugFormat("DocService convert from {0} to {1} - {2}", fromExtension, toExtension, documentUri); try { return Web.Core.Files.DocumentService.GetConvertedUri( FilesLinkUtility.DocServiceConverterUrl, documentUri, fromExtension, toExtension, GenerateRevisionId(documentRevisionId), password, thumbnail, spreadsheetLayout, isAsync, FileUtility.SignatureSecret, out convertedDocumentUri); } catch (Exception ex) { throw CustomizeError(ex); } } public static bool Command(CommandMethod method, string docKeyForTrack, object fileId = null, string callbackUrl = null, string[] users = null, MetaData meta = null) { Global.Logger.DebugFormat("DocService command {0} fileId '{1}' docKey '{2}' callbackUrl '{3}' users '{4}' meta '{5}'", method, fileId, docKeyForTrack, callbackUrl, users != null ? string.Join(", ", users) : null, JsonConvert.SerializeObject(meta)); try { var commandResponse = CommandRequest( FilesLinkUtility.DocServiceCommandUrl, method, GenerateRevisionId(docKeyForTrack), callbackUrl, users, meta, FileUtility.SignatureSecret); if (commandResponse.Error == CommandResponse.ErrorTypes.NoError) { return true; } Global.Logger.ErrorFormat("DocService command response: '{0}' {1}", commandResponse.Error, commandResponse.ErrorString); } catch (Exception e) { Global.Logger.Error("DocService command error", e); } return false; } public static string DocbuilderRequest(string requestKey, string inputScript, bool isAsync, out Dictionary<string, string> urls) { string scriptUrl = null; if (!string.IsNullOrEmpty(inputScript)) { using (var stream = new MemoryStream()) using (var writer = new StreamWriter(stream)) { writer.Write(inputScript); writer.Flush(); stream.Position = 0; scriptUrl = PathProvider.GetTempUrl(stream, ".docbuilder"); } scriptUrl = ReplaceCommunityAdress(scriptUrl); requestKey = null; } Global.Logger.DebugFormat("DocService builder requestKey {0} async {1}", requestKey, isAsync); try { return Web.Core.Files.DocumentService.DocbuilderRequest( FilesLinkUtility.DocServiceDocbuilderUrl, GenerateRevisionId(requestKey), scriptUrl, isAsync, FileUtility.SignatureSecret, out urls); } catch (Exception ex) { throw CustomizeError(ex); } } public static string GetVersion() { Global.Logger.DebugFormat("DocService request version"); try { var commandResponse = CommandRequest( FilesLinkUtility.DocServiceCommandUrl, CommandMethod.Version, GenerateRevisionId(null), null, null, null, FileUtility.SignatureSecret); var version = commandResponse.Version; if (string.IsNullOrEmpty(version)) { version = "0"; } if (commandResponse.Error == CommandResponse.ErrorTypes.NoError) { return version; } Global.Logger.ErrorFormat("DocService command response: '{0}' {1}", commandResponse.Error, commandResponse.ErrorString); } catch (Exception e) { Global.Logger.Error("DocService command error", e); } return "4.1.5.1"; } public static void CheckDocServiceUrl() { if (!string.IsNullOrEmpty(FilesLinkUtility.DocServiceHealthcheckUrl)) { try { if (!HealthcheckRequest(FilesLinkUtility.DocServiceHealthcheckUrl)) { throw new Exception("bad status"); } } catch (Exception ex) { Global.Logger.Error("Healthcheck DocService check error", ex); throw new Exception("Healthcheck url: " + ex.Message); } } if (!string.IsNullOrEmpty(FilesLinkUtility.DocServiceConverterUrl)) { string convertedFileUri; try { const string fileExtension = ".docx"; var toExtension = FileUtility.GetInternalExtension(fileExtension); var url = PathProvider.GetEmptyFileUrl(fileExtension); var fileUri = ReplaceCommunityAdress(url); var key = GenerateRevisionId(Guid.NewGuid().ToString()); Web.Core.Files.DocumentService.GetConvertedUri(FilesLinkUtility.DocServiceConverterUrl, fileUri, fileExtension, toExtension, key, null, null, null, false, FileUtility.SignatureSecret, out convertedFileUri); } catch (Exception ex) { Global.Logger.Error("Converter DocService check error", ex); throw new Exception("Converter url: " + ex.Message); } try { var request = (HttpWebRequest)WebRequest.Create(convertedFileUri); using (var response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) { throw new Exception("Converted url is not available"); } } } catch (Exception ex) { Global.Logger.Error("Document DocService check error", ex); throw new Exception("Document server: " + ex.Message); } } if (!string.IsNullOrEmpty(FilesLinkUtility.DocServiceCommandUrl)) { try { var key = GenerateRevisionId(Guid.NewGuid().ToString()); CommandRequest(FilesLinkUtility.DocServiceCommandUrl, CommandMethod.Version, key, null, null, null, FileUtility.SignatureSecret); } catch (Exception ex) { Global.Logger.Error("Command DocService check error", ex); throw new Exception("Command url: " + ex.Message); } } if (!string.IsNullOrEmpty(FilesLinkUtility.DocServiceDocbuilderUrl)) { try { var storeTemplate = Global.GetStoreTemplate(); var scriptUri = storeTemplate.GetUri("", "test.docbuilder"); var scriptUrl = CommonLinkUtility.GetFullAbsolutePath(scriptUri.ToString()); scriptUrl = ReplaceCommunityAdress(scriptUrl); Dictionary<string, string> urls; Web.Core.Files.DocumentService.DocbuilderRequest(FilesLinkUtility.DocServiceDocbuilderUrl, null, scriptUrl, false, FileUtility.SignatureSecret, out urls); } catch (Exception ex) { Global.Logger.Error("DocService check error", ex); throw new Exception("Docbuilder url: " + ex.Message); } } } public static string ReplaceCommunityAdress(string url) { var docServicePortalUrl = FilesLinkUtility.DocServicePortalUrl; if (string.IsNullOrEmpty(url)) { return url; } if (string.IsNullOrEmpty(docServicePortalUrl)) { Tenant tenant; if (!TenantExtra.Saas || string.IsNullOrEmpty((tenant = CoreContext.TenantManager.GetCurrentTenant()).MappedDomain) || !url.StartsWith("https://" + tenant.MappedDomain)) { return url; } docServicePortalUrl = "https://" + tenant.GetTenantDomain(false); } var uri = new UriBuilder(url); if (new UriBuilder(CommonLinkUtility.ServerRootPath).Host != uri.Host) { return url; } var urlRewriterQuery = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port; var query = HttpUtility.ParseQueryString(uri.Query); query[HttpRequestExtensions.UrlRewriterHeader] = urlRewriterQuery; uri.Query = query.ToString(); var communityUrl = new UriBuilder(docServicePortalUrl); uri.Scheme = communityUrl.Scheme; uri.Host = communityUrl.Host; uri.Port = communityUrl.Port; return uri.ToString(); } public static string ReplaceDocumentAdress(string url) { if (string.IsNullOrEmpty(url)) { return url; } var uri = new UriBuilder(url).ToString(); var externalUri = new UriBuilder(CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.DocServiceUrl)).ToString(); var internalUri = new UriBuilder(CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.DocServiceUrlInternal)).ToString(); if (uri.StartsWith(internalUri, true, CultureInfo.InvariantCulture) || !uri.StartsWith(externalUri, true, CultureInfo.InvariantCulture)) { return url; } uri = uri.Replace(externalUri, FilesLinkUtility.DocServiceUrlInternal); return uri; } private static Exception CustomizeError(Exception ex) { var error = FilesCommonResource.ErrorMassage_DocServiceException; if (!string.IsNullOrEmpty(ex.Message)) error += string.Format(" ({0})", ex.Message); Global.Logger.Error("DocService error", ex); return new Exception(error, 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. namespace System.ServiceModel.Syndication { using System; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Threading.Tasks; using System.Xml; [DataContract] public abstract class ServiceDocumentFormatter { private ServiceDocument _document; protected ServiceDocumentFormatter() { } protected ServiceDocumentFormatter(ServiceDocument documentToWrite) { if (documentToWrite == null) { throw new ArgumentNullException(nameof(documentToWrite)); } _document = documentToWrite; } public ServiceDocument Document { get { return _document; } } public abstract string Version { get; } public abstract bool CanRead(XmlReader reader); public abstract void ReadFrom(System.Xml.XmlReader reader); public abstract void WriteTo(System.Xml.XmlWriter writer); public virtual Task ReadFromAsync(XmlReader reader) { throw new NotImplementedException(); } public virtual Task WriteToAsync(XmlWriter writer) { throw new NotImplementedException(); } internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, CategoriesDocument categories) { if (categories == null) { throw new ArgumentNullException(nameof(categories)); } Atom10FeedFormatter.CloseBuffer(buffer, writer); categories.LoadElementExtensions(buffer); } internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, ResourceCollectionInfo collection) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } Atom10FeedFormatter.CloseBuffer(buffer, writer); collection.LoadElementExtensions(buffer); } internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, Workspace workspace) { if (workspace == null) { throw new ArgumentNullException(nameof(workspace)); } Atom10FeedFormatter.CloseBuffer(buffer, writer); workspace.LoadElementExtensions(buffer); } internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, ServiceDocument document) { if (document == null) { throw new ArgumentNullException(nameof(document)); } Atom10FeedFormatter.CloseBuffer(buffer, writer); document.LoadElementExtensions(buffer); } protected static SyndicationCategory CreateCategory(InlineCategoriesDocument inlineCategories) { if (inlineCategories == null) { throw new ArgumentNullException(nameof(inlineCategories)); } return inlineCategories.CreateCategory(); } protected static ResourceCollectionInfo CreateCollection(Workspace workspace) { if (workspace == null) { throw new ArgumentNullException(nameof(workspace)); } return workspace.CreateResourceCollection(); } protected static InlineCategoriesDocument CreateInlineCategories(ResourceCollectionInfo collection) { return collection.CreateInlineCategoriesDocument(); } protected static ReferencedCategoriesDocument CreateReferencedCategories(ResourceCollectionInfo collection) { return collection.CreateReferencedCategoriesDocument(); } protected static Workspace CreateWorkspace(ServiceDocument document) { if (document == null) { throw new ArgumentNullException(nameof(document)); } return document.CreateWorkspace(); } protected static void LoadElementExtensions(XmlReader reader, CategoriesDocument categories, int maxExtensionSize) { if (categories == null) { throw new ArgumentNullException(nameof(categories)); } categories.LoadElementExtensions(XmlReaderWrapper.CreateFromReader(reader), maxExtensionSize); } protected static void LoadElementExtensions(XmlReader reader, ResourceCollectionInfo collection, int maxExtensionSize) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } collection.LoadElementExtensions(XmlReaderWrapper.CreateFromReader(reader), maxExtensionSize); } protected static void LoadElementExtensions(XmlReader reader, Workspace workspace, int maxExtensionSize) { if (workspace == null) { throw new ArgumentNullException(nameof(workspace)); } workspace.LoadElementExtensions(XmlReaderWrapper.CreateFromReader(reader), maxExtensionSize); } protected static void LoadElementExtensions(XmlReader reader, ServiceDocument document, int maxExtensionSize) { if (document == null) { throw new ArgumentNullException(nameof(document)); } document.LoadElementExtensions(XmlReaderWrapper.CreateFromReader(reader), maxExtensionSize); } protected static bool TryParseAttribute(string name, string ns, string value, ServiceDocument document, string version) { if (document == null) { throw new ArgumentNullException(nameof(document)); } return document.TryParseAttribute(name, ns, value, version); } protected static bool TryParseAttribute(string name, string ns, string value, ResourceCollectionInfo collection, string version) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } return collection.TryParseAttribute(name, ns, value, version); } protected static bool TryParseAttribute(string name, string ns, string value, CategoriesDocument categories, string version) { if (categories == null) { throw new ArgumentNullException(nameof(categories)); } return categories.TryParseAttribute(name, ns, value, version); } protected static bool TryParseAttribute(string name, string ns, string value, Workspace workspace, string version) { if (workspace == null) { throw new ArgumentNullException(nameof(workspace)); } return workspace.TryParseAttribute(name, ns, value, version); } protected static bool TryParseElement(XmlReader reader, ResourceCollectionInfo collection, string version) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } return collection.TryParseElement(XmlReaderWrapper.CreateFromReader(reader), version); } protected static bool TryParseElement(XmlReader reader, ServiceDocument document, string version) { if (document == null) { throw new ArgumentNullException(nameof(document)); } return document.TryParseElement(XmlReaderWrapper.CreateFromReader(reader), version); } protected static bool TryParseElement(XmlReader reader, Workspace workspace, string version) { if (workspace == null) { throw new ArgumentNullException(nameof(workspace)); } return workspace.TryParseElement(XmlReaderWrapper.CreateFromReader(reader), version); } protected static bool TryParseElement(XmlReader reader, CategoriesDocument categories, string version) { if (categories == null) { throw new ArgumentNullException(nameof(categories)); } return categories.TryParseElement(XmlReaderWrapper.CreateFromReader(reader), version); } protected static void WriteAttributeExtensions(XmlWriter writer, ServiceDocument document, string version) { if (document == null) { throw new ArgumentNullException(nameof(document)); } document.WriteAttributeExtensions(writer, version); } protected static void WriteAttributeExtensions(XmlWriter writer, Workspace workspace, string version) { if (workspace == null) { throw new ArgumentNullException(nameof(workspace)); } workspace.WriteAttributeExtensions(writer, version); } protected static void WriteAttributeExtensions(XmlWriter writer, ResourceCollectionInfo collection, string version) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } collection.WriteAttributeExtensions(writer, version); } protected static void WriteAttributeExtensions(XmlWriter writer, CategoriesDocument categories, string version) { if (categories == null) { throw new ArgumentNullException(nameof(categories)); } categories.WriteAttributeExtensions(writer, version); } protected static void WriteElementExtensions(XmlWriter writer, ServiceDocument document, string version) { if (document == null) { throw new ArgumentNullException(nameof(document)); } document.WriteElementExtensions(writer, version); } protected static void WriteElementExtensions(XmlWriter writer, Workspace workspace, string version) { if (workspace == null) { throw new ArgumentNullException(nameof(workspace)); } workspace.WriteElementExtensions(writer, version); } protected static void WriteElementExtensions(XmlWriter writer, ResourceCollectionInfo collection, string version) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } collection.WriteElementExtensions(writer, version); } protected static void WriteElementExtensions(XmlWriter writer, CategoriesDocument categories, string version) { if (categories == null) { throw new ArgumentNullException(nameof(categories)); } categories.WriteElementExtensions(writer, version); } protected static Task WriteAttributeExtensionsAsync(XmlWriter writer, ServiceDocument document, string version) { if (document == null) { throw new ArgumentNullException(nameof(document)); } return document.WriteAttributeExtensionsAsync(writer, version); } protected static Task WriteAttributeExtensionsAsync(XmlWriter writer, Workspace workspace, string version) { if (workspace == null) { throw new ArgumentNullException(nameof(workspace)); } return workspace.WriteAttributeExtensionsAsync(writer, version); } protected static Task WriteAttributeExtensionsAsync(XmlWriter writer, ResourceCollectionInfo collection, string version) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } return collection.WriteAttributeExtensionsAsync(writer, version); } protected static Task WriteAttributeExtensionsAsync(XmlWriter writer, CategoriesDocument categories, string version) { if (categories == null) { throw new ArgumentNullException(nameof(categories)); } return categories.WriteAttributeExtensionsAsync(writer, version); } protected static Task WriteElementExtensionsAsync(XmlWriter writer, ServiceDocument document, string version) { if (document == null) { throw new ArgumentNullException(nameof(document)); } return document.WriteElementExtensionsAsync(writer, version); } protected static Task WriteElementExtensionsAsync(XmlWriter writer, Workspace workspace, string version) { if (workspace == null) { throw new ArgumentNullException(nameof(workspace)); } return workspace.WriteElementExtensionsAsync(writer, version); } protected static Task WriteElementExtensionsAsync(XmlWriter writer, ResourceCollectionInfo collection, string version) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } return collection.WriteElementExtensionsAsync(writer, version); } protected static Task WriteElementExtensionsAsync(XmlWriter writer, CategoriesDocument categories, string version) { if (categories == null) { throw new ArgumentNullException(nameof(categories)); } return categories.WriteElementExtensionsAsync(writer, version); } protected virtual ServiceDocument CreateDocumentInstance() { return new ServiceDocument(); } protected virtual void SetDocument(ServiceDocument document) { _document = document; } } }
using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Text; using System.Threading; using OpenHome.Net.Core; using OpenHome.Net.ControlPoint; namespace OpenHome.Net.ControlPoint.Proxies { public interface ICpProxyOpenhomeOrgSubscriptionLongPoll1 : ICpProxy, IDisposable { void SyncSubscribe(String aClientId, String aUdn, String aService, uint aRequestedDuration, out String aSid, out uint aDuration); void BeginSubscribe(String aClientId, String aUdn, String aService, uint aRequestedDuration, CpProxy.CallbackAsyncComplete aCallback); void EndSubscribe(IntPtr aAsyncHandle, out String aSid, out uint aDuration); void SyncUnsubscribe(String aSid); void BeginUnsubscribe(String aSid, CpProxy.CallbackAsyncComplete aCallback); void EndUnsubscribe(IntPtr aAsyncHandle); void SyncRenew(String aSid, uint aRequestedDuration, out uint aDuration); void BeginRenew(String aSid, uint aRequestedDuration, CpProxy.CallbackAsyncComplete aCallback); void EndRenew(IntPtr aAsyncHandle, out uint aDuration); void SyncGetPropertyUpdates(String aClientId, out String aUpdates); void BeginGetPropertyUpdates(String aClientId, CpProxy.CallbackAsyncComplete aCallback); void EndGetPropertyUpdates(IntPtr aAsyncHandle, out String aUpdates); } internal class SyncSubscribeOpenhomeOrgSubscriptionLongPoll1 : SyncProxyAction { private CpProxyOpenhomeOrgSubscriptionLongPoll1 iService; private String iSid; private uint iDuration; public SyncSubscribeOpenhomeOrgSubscriptionLongPoll1(CpProxyOpenhomeOrgSubscriptionLongPoll1 aProxy) { iService = aProxy; } public String Sid() { return iSid; } public uint Duration() { return iDuration; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndSubscribe(aAsyncHandle, out iSid, out iDuration); } }; internal class SyncUnsubscribeOpenhomeOrgSubscriptionLongPoll1 : SyncProxyAction { private CpProxyOpenhomeOrgSubscriptionLongPoll1 iService; public SyncUnsubscribeOpenhomeOrgSubscriptionLongPoll1(CpProxyOpenhomeOrgSubscriptionLongPoll1 aProxy) { iService = aProxy; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndUnsubscribe(aAsyncHandle); } }; internal class SyncRenewOpenhomeOrgSubscriptionLongPoll1 : SyncProxyAction { private CpProxyOpenhomeOrgSubscriptionLongPoll1 iService; private uint iDuration; public SyncRenewOpenhomeOrgSubscriptionLongPoll1(CpProxyOpenhomeOrgSubscriptionLongPoll1 aProxy) { iService = aProxy; } public uint Duration() { return iDuration; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndRenew(aAsyncHandle, out iDuration); } }; internal class SyncGetPropertyUpdatesOpenhomeOrgSubscriptionLongPoll1 : SyncProxyAction { private CpProxyOpenhomeOrgSubscriptionLongPoll1 iService; private String iUpdates; public SyncGetPropertyUpdatesOpenhomeOrgSubscriptionLongPoll1(CpProxyOpenhomeOrgSubscriptionLongPoll1 aProxy) { iService = aProxy; } public String Updates() { return iUpdates; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndGetPropertyUpdates(aAsyncHandle, out iUpdates); } }; /// <summary> /// Proxy for the openhome.org:SubscriptionLongPoll:1 UPnP service /// </summary> public class CpProxyOpenhomeOrgSubscriptionLongPoll1 : CpProxy, IDisposable, ICpProxyOpenhomeOrgSubscriptionLongPoll1 { private OpenHome.Net.Core.Action iActionSubscribe; private OpenHome.Net.Core.Action iActionUnsubscribe; private OpenHome.Net.Core.Action iActionRenew; private OpenHome.Net.Core.Action iActionGetPropertyUpdates; /// <summary> /// Constructor /// </summary> /// <remarks>Use CpProxy::[Un]Subscribe() to enable/disable querying of state variable and reporting of their changes.</remarks> /// <param name="aDevice">The device to use</param> public CpProxyOpenhomeOrgSubscriptionLongPoll1(CpDevice aDevice) : base("openhome-org", "SubscriptionLongPoll", 1, aDevice) { OpenHome.Net.Core.Parameter param; List<String> allowedValues = new List<String>(); iActionSubscribe = new OpenHome.Net.Core.Action("Subscribe"); param = new ParameterString("ClientId", allowedValues); iActionSubscribe.AddInputParameter(param); param = new ParameterString("Udn", allowedValues); iActionSubscribe.AddInputParameter(param); param = new ParameterString("Service", allowedValues); iActionSubscribe.AddInputParameter(param); param = new ParameterUint("RequestedDuration"); iActionSubscribe.AddInputParameter(param); param = new ParameterString("Sid", allowedValues); iActionSubscribe.AddOutputParameter(param); param = new ParameterUint("Duration"); iActionSubscribe.AddOutputParameter(param); iActionUnsubscribe = new OpenHome.Net.Core.Action("Unsubscribe"); param = new ParameterString("Sid", allowedValues); iActionUnsubscribe.AddInputParameter(param); iActionRenew = new OpenHome.Net.Core.Action("Renew"); param = new ParameterString("Sid", allowedValues); iActionRenew.AddInputParameter(param); param = new ParameterUint("RequestedDuration"); iActionRenew.AddInputParameter(param); param = new ParameterUint("Duration"); iActionRenew.AddOutputParameter(param); iActionGetPropertyUpdates = new OpenHome.Net.Core.Action("GetPropertyUpdates"); param = new ParameterString("ClientId", allowedValues); iActionGetPropertyUpdates.AddInputParameter(param); param = new ParameterString("Updates", allowedValues); iActionGetPropertyUpdates.AddOutputParameter(param); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aClientId"></param> /// <param name="aUdn"></param> /// <param name="aService"></param> /// <param name="aRequestedDuration"></param> /// <param name="aSid"></param> /// <param name="aDuration"></param> public void SyncSubscribe(String aClientId, String aUdn, String aService, uint aRequestedDuration, out String aSid, out uint aDuration) { SyncSubscribeOpenhomeOrgSubscriptionLongPoll1 sync = new SyncSubscribeOpenhomeOrgSubscriptionLongPoll1(this); BeginSubscribe(aClientId, aUdn, aService, aRequestedDuration, sync.AsyncComplete()); sync.Wait(); sync.ReportError(); aSid = sync.Sid(); aDuration = sync.Duration(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndSubscribe().</remarks> /// <param name="aClientId"></param> /// <param name="aUdn"></param> /// <param name="aService"></param> /// <param name="aRequestedDuration"></param> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginSubscribe(String aClientId, String aUdn, String aService, uint aRequestedDuration, CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionSubscribe, aCallback); int inIndex = 0; invocation.AddInput(new ArgumentString((ParameterString)iActionSubscribe.InputParameter(inIndex++), aClientId)); invocation.AddInput(new ArgumentString((ParameterString)iActionSubscribe.InputParameter(inIndex++), aUdn)); invocation.AddInput(new ArgumentString((ParameterString)iActionSubscribe.InputParameter(inIndex++), aService)); invocation.AddInput(new ArgumentUint((ParameterUint)iActionSubscribe.InputParameter(inIndex++), aRequestedDuration)); int outIndex = 0; invocation.AddOutput(new ArgumentString((ParameterString)iActionSubscribe.OutputParameter(outIndex++))); invocation.AddOutput(new ArgumentUint((ParameterUint)iActionSubscribe.OutputParameter(outIndex++))); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> /// <param name="aSid"></param> /// <param name="aDuration"></param> public void EndSubscribe(IntPtr aAsyncHandle, out String aSid, out uint aDuration) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } uint index = 0; aSid = Invocation.OutputString(aAsyncHandle, index++); aDuration = Invocation.OutputUint(aAsyncHandle, index++); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aSid"></param> public void SyncUnsubscribe(String aSid) { SyncUnsubscribeOpenhomeOrgSubscriptionLongPoll1 sync = new SyncUnsubscribeOpenhomeOrgSubscriptionLongPoll1(this); BeginUnsubscribe(aSid, sync.AsyncComplete()); sync.Wait(); sync.ReportError(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndUnsubscribe().</remarks> /// <param name="aSid"></param> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginUnsubscribe(String aSid, CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionUnsubscribe, aCallback); int inIndex = 0; invocation.AddInput(new ArgumentString((ParameterString)iActionUnsubscribe.InputParameter(inIndex++), aSid)); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> public void EndUnsubscribe(IntPtr aAsyncHandle) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aSid"></param> /// <param name="aRequestedDuration"></param> /// <param name="aDuration"></param> public void SyncRenew(String aSid, uint aRequestedDuration, out uint aDuration) { SyncRenewOpenhomeOrgSubscriptionLongPoll1 sync = new SyncRenewOpenhomeOrgSubscriptionLongPoll1(this); BeginRenew(aSid, aRequestedDuration, sync.AsyncComplete()); sync.Wait(); sync.ReportError(); aDuration = sync.Duration(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndRenew().</remarks> /// <param name="aSid"></param> /// <param name="aRequestedDuration"></param> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginRenew(String aSid, uint aRequestedDuration, CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionRenew, aCallback); int inIndex = 0; invocation.AddInput(new ArgumentString((ParameterString)iActionRenew.InputParameter(inIndex++), aSid)); invocation.AddInput(new ArgumentUint((ParameterUint)iActionRenew.InputParameter(inIndex++), aRequestedDuration)); int outIndex = 0; invocation.AddOutput(new ArgumentUint((ParameterUint)iActionRenew.OutputParameter(outIndex++))); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> /// <param name="aDuration"></param> public void EndRenew(IntPtr aAsyncHandle, out uint aDuration) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } uint index = 0; aDuration = Invocation.OutputUint(aAsyncHandle, index++); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aClientId"></param> /// <param name="aUpdates"></param> public void SyncGetPropertyUpdates(String aClientId, out String aUpdates) { SyncGetPropertyUpdatesOpenhomeOrgSubscriptionLongPoll1 sync = new SyncGetPropertyUpdatesOpenhomeOrgSubscriptionLongPoll1(this); BeginGetPropertyUpdates(aClientId, sync.AsyncComplete()); sync.Wait(); sync.ReportError(); aUpdates = sync.Updates(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndGetPropertyUpdates().</remarks> /// <param name="aClientId"></param> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginGetPropertyUpdates(String aClientId, CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionGetPropertyUpdates, aCallback); int inIndex = 0; invocation.AddInput(new ArgumentString((ParameterString)iActionGetPropertyUpdates.InputParameter(inIndex++), aClientId)); int outIndex = 0; invocation.AddOutput(new ArgumentString((ParameterString)iActionGetPropertyUpdates.OutputParameter(outIndex++))); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> /// <param name="aUpdates"></param> public void EndGetPropertyUpdates(IntPtr aAsyncHandle, out String aUpdates) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } uint index = 0; aUpdates = Invocation.OutputString(aAsyncHandle, index++); } /// <summary> /// Must be called for each class instance. Must be called before Core.Library.Close(). /// </summary> public void Dispose() { lock (this) { if (iHandle == IntPtr.Zero) return; DisposeProxy(); iHandle = IntPtr.Zero; } iActionSubscribe.Dispose(); iActionUnsubscribe.Dispose(); iActionRenew.Dispose(); iActionGetPropertyUpdates.Dispose(); } } }
namespace AutoShrinkingGroups { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.kryptonRibbon = new ComponentFactory.Krypton.Ribbon.KryptonRibbon(); this.kryptonContextMenuItem1 = new ComponentFactory.Krypton.Toolkit.KryptonContextMenuItem(); this.kryptonRibbonTab1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonTab(); this.kryptonRibbonGroup1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup(); this.kryptonRibbonGroupTriple1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple(); this.kryptonRibbonGroupButton1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton2 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton3 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupSeparator1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupSeparator(); this.kryptonRibbonGroupTriple2 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple(); this.kryptonRibbonGroupButton4 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton5 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton6 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroup2 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup(); this.kryptonRibbonGroupTriple3 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple(); this.kryptonRibbonGroupButton7 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton8 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton9 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupSeparator2 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupSeparator(); this.kryptonRibbonGroupTriple4 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple(); this.kryptonRibbonGroupButton10 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton11 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton12 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroup3 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup(); this.kryptonRibbonGroupTriple5 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple(); this.kryptonRibbonGroupButton13 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton14 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton15 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupSeparator3 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupSeparator(); this.kryptonRibbonGroupTriple6 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple(); this.kryptonRibbonGroupButton16 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton17 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton18 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonTab2 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonTab(); this.kryptonRibbonGroup4 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup(); this.kryptonRibbonGroupLines1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupLines(); this.kryptonRibbonGroupButton19 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton20 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton21 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton22 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton31 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton32 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton37 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton38 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroup5 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup(); this.kryptonRibbonGroupLines2 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupLines(); this.kryptonRibbonGroupButton23 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton24 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton25 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton26 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton33 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton34 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton39 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton40 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroup6 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup(); this.kryptonRibbonGroupLines3 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupLines(); this.kryptonRibbonGroupButton27 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton28 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton29 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton35 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton36 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton41 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonTab3 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonTab(); this.kryptonRibbonGroup7 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup(); this.kryptonRibbonGroupLines4 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupLines(); this.kryptonRibbonGroupCluster1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster(); this.kryptonRibbonGroupClusterButton1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton2 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton5 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupCluster2 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster(); this.kryptonRibbonGroupClusterButton3 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton4 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton6 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupCluster3 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster(); this.kryptonRibbonGroupClusterButton7 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton8 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton49 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupCluster4 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster(); this.kryptonRibbonGroupClusterButton9 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton10 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton11 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton12 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupSeparator4 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupSeparator(); this.kryptonRibbonGroupLines6 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupLines(); this.kryptonRibbonGroupCluster9 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster(); this.kryptonRibbonGroupClusterButton25 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton26 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton27 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupCluster10 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster(); this.kryptonRibbonGroupClusterButton28 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton29 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton30 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupCluster11 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster(); this.kryptonRibbonGroupClusterButton31 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton32 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupCluster12 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster(); this.kryptonRibbonGroupClusterButton33 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton34 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton35 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton36 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroup8 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup(); this.kryptonRibbonGroupLines5 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupLines(); this.kryptonRibbonGroupCluster5 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster(); this.kryptonRibbonGroupClusterButton13 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton14 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupCluster6 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster(); this.kryptonRibbonGroupClusterButton15 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton16 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupCluster7 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster(); this.kryptonRibbonGroupClusterButton18 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.kryptonRibbonGroupClusterButton19 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton(); this.panelFill = new ComponentFactory.Krypton.Toolkit.KryptonPanel(); this.groupShrinkInfo = new ComponentFactory.Krypton.Toolkit.KryptonGroup(); this.labelAutoShrinkage = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.labelAutoInstructions = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.kryptonManager = new ComponentFactory.Krypton.Toolkit.KryptonManager(this.components); ((System.ComponentModel.ISupportInitialize)(this.kryptonRibbon)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.panelFill)).BeginInit(); this.panelFill.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.groupShrinkInfo)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.groupShrinkInfo.Panel)).BeginInit(); this.groupShrinkInfo.Panel.SuspendLayout(); this.groupShrinkInfo.SuspendLayout(); this.SuspendLayout(); // // kryptonRibbon // this.kryptonRibbon.HideRibbonSize = new System.Drawing.Size(100, 250); this.kryptonRibbon.Name = "kryptonRibbon"; this.kryptonRibbon.RibbonAppButton.AppButtonMenuItems.AddRange(new ComponentFactory.Krypton.Toolkit.KryptonContextMenuItemBase[] { this.kryptonContextMenuItem1}); this.kryptonRibbon.RibbonAppButton.AppButtonShowRecentDocs = false; this.kryptonRibbon.RibbonTabs.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonTab[] { this.kryptonRibbonTab1, this.kryptonRibbonTab2, this.kryptonRibbonTab3}); this.kryptonRibbon.SelectedTab = this.kryptonRibbonTab1; this.kryptonRibbon.Size = new System.Drawing.Size(772, 114); this.kryptonRibbon.TabIndex = 0; // // kryptonContextMenuItem1 // this.kryptonContextMenuItem1.Image = ((System.Drawing.Image)(resources.GetObject("kryptonContextMenuItem1.Image"))); this.kryptonContextMenuItem1.Text = "E&xit"; this.kryptonContextMenuItem1.Click += new System.EventHandler(this.appMenu_Click); // // kryptonRibbonTab1 // this.kryptonRibbonTab1.Groups.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup[] { this.kryptonRibbonGroup1, this.kryptonRibbonGroup2, this.kryptonRibbonGroup3}); this.kryptonRibbonTab1.Text = "Triples"; // // kryptonRibbonGroup1 // this.kryptonRibbonGroup1.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupContainer[] { this.kryptonRibbonGroupTriple1, this.kryptonRibbonGroupSeparator1, this.kryptonRibbonGroupTriple2}); // // kryptonRibbonGroupTriple1 // this.kryptonRibbonGroupTriple1.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupButton1, this.kryptonRibbonGroupButton2, this.kryptonRibbonGroupButton3}); // // kryptonRibbonGroupTriple2 // this.kryptonRibbonGroupTriple2.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupButton4, this.kryptonRibbonGroupButton5, this.kryptonRibbonGroupButton6}); // // kryptonRibbonGroup2 // this.kryptonRibbonGroup2.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupContainer[] { this.kryptonRibbonGroupTriple3, this.kryptonRibbonGroupSeparator2, this.kryptonRibbonGroupTriple4}); // // kryptonRibbonGroupTriple3 // this.kryptonRibbonGroupTriple3.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupButton7, this.kryptonRibbonGroupButton8, this.kryptonRibbonGroupButton9}); // // kryptonRibbonGroupTriple4 // this.kryptonRibbonGroupTriple4.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupButton10, this.kryptonRibbonGroupButton11, this.kryptonRibbonGroupButton12}); // // kryptonRibbonGroup3 // this.kryptonRibbonGroup3.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupContainer[] { this.kryptonRibbonGroupTriple5, this.kryptonRibbonGroupSeparator3, this.kryptonRibbonGroupTriple6}); // // kryptonRibbonGroupTriple5 // this.kryptonRibbonGroupTriple5.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupButton13, this.kryptonRibbonGroupButton14, this.kryptonRibbonGroupButton15}); // // kryptonRibbonGroupTriple6 // this.kryptonRibbonGroupTriple6.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupButton16, this.kryptonRibbonGroupButton17, this.kryptonRibbonGroupButton18}); // // kryptonRibbonTab2 // this.kryptonRibbonTab2.Groups.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup[] { this.kryptonRibbonGroup4, this.kryptonRibbonGroup5, this.kryptonRibbonGroup6}); this.kryptonRibbonTab2.Text = "Lines"; // // kryptonRibbonGroup4 // this.kryptonRibbonGroup4.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupContainer[] { this.kryptonRibbonGroupLines1}); // // kryptonRibbonGroupLines1 // this.kryptonRibbonGroupLines1.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupButton19, this.kryptonRibbonGroupButton20, this.kryptonRibbonGroupButton21, this.kryptonRibbonGroupButton22, this.kryptonRibbonGroupButton31, this.kryptonRibbonGroupButton32, this.kryptonRibbonGroupButton37, this.kryptonRibbonGroupButton38}); // // kryptonRibbonGroup5 // this.kryptonRibbonGroup5.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupContainer[] { this.kryptonRibbonGroupLines2}); // // kryptonRibbonGroupLines2 // this.kryptonRibbonGroupLines2.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupButton23, this.kryptonRibbonGroupButton24, this.kryptonRibbonGroupButton25, this.kryptonRibbonGroupButton26, this.kryptonRibbonGroupButton33, this.kryptonRibbonGroupButton34, this.kryptonRibbonGroupButton39, this.kryptonRibbonGroupButton40}); // // kryptonRibbonGroup6 // this.kryptonRibbonGroup6.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupContainer[] { this.kryptonRibbonGroupLines3}); // // kryptonRibbonGroupLines3 // this.kryptonRibbonGroupLines3.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupButton27, this.kryptonRibbonGroupButton28, this.kryptonRibbonGroupButton29, this.kryptonRibbonGroupButton35, this.kryptonRibbonGroupButton36, this.kryptonRibbonGroupButton41}); // // kryptonRibbonTab3 // this.kryptonRibbonTab3.Groups.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup[] { this.kryptonRibbonGroup7, this.kryptonRibbonGroup8}); this.kryptonRibbonTab3.Text = "Clusters"; // // kryptonRibbonGroup7 // this.kryptonRibbonGroup7.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupContainer[] { this.kryptonRibbonGroupLines4, this.kryptonRibbonGroupSeparator4, this.kryptonRibbonGroupLines6}); // // kryptonRibbonGroupLines4 // this.kryptonRibbonGroupLines4.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupCluster1, this.kryptonRibbonGroupCluster2, this.kryptonRibbonGroupCluster3, this.kryptonRibbonGroupCluster4}); // // kryptonRibbonGroupCluster1 // this.kryptonRibbonGroupCluster1.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupClusterButton1, this.kryptonRibbonGroupClusterButton2, this.kryptonRibbonGroupClusterButton5}); // // kryptonRibbonGroupClusterButton1 // this.kryptonRibbonGroupClusterButton1.TextLine = "AB"; // // kryptonRibbonGroupClusterButton2 // this.kryptonRibbonGroupClusterButton2.TextLine = "AB"; // // kryptonRibbonGroupClusterButton5 // this.kryptonRibbonGroupClusterButton5.TextLine = "AB"; // // kryptonRibbonGroupCluster2 // this.kryptonRibbonGroupCluster2.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupClusterButton3, this.kryptonRibbonGroupClusterButton4, this.kryptonRibbonGroupClusterButton6}); // // kryptonRibbonGroupClusterButton3 // this.kryptonRibbonGroupClusterButton3.TextLine = "AB"; // // kryptonRibbonGroupClusterButton4 // this.kryptonRibbonGroupClusterButton4.TextLine = "AB"; // // kryptonRibbonGroupClusterButton6 // this.kryptonRibbonGroupClusterButton6.TextLine = "AB"; // // kryptonRibbonGroupCluster3 // this.kryptonRibbonGroupCluster3.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupClusterButton7, this.kryptonRibbonGroupClusterButton8, this.kryptonRibbonGroupClusterButton49}); // // kryptonRibbonGroupClusterButton7 // this.kryptonRibbonGroupClusterButton7.TextLine = "AB"; // // kryptonRibbonGroupClusterButton8 // this.kryptonRibbonGroupClusterButton8.TextLine = "AB"; // // kryptonRibbonGroupClusterButton49 // this.kryptonRibbonGroupClusterButton49.TextLine = "AB"; // // kryptonRibbonGroupCluster4 // this.kryptonRibbonGroupCluster4.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupClusterButton9, this.kryptonRibbonGroupClusterButton10, this.kryptonRibbonGroupClusterButton11, this.kryptonRibbonGroupClusterButton12}); // // kryptonRibbonGroupClusterButton9 // this.kryptonRibbonGroupClusterButton9.TextLine = "AB"; // // kryptonRibbonGroupClusterButton10 // this.kryptonRibbonGroupClusterButton10.TextLine = "AB"; // // kryptonRibbonGroupClusterButton11 // this.kryptonRibbonGroupClusterButton11.TextLine = "AB"; // // kryptonRibbonGroupClusterButton12 // this.kryptonRibbonGroupClusterButton12.TextLine = "AB"; // // kryptonRibbonGroupLines6 // this.kryptonRibbonGroupLines6.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupCluster9, this.kryptonRibbonGroupCluster10, this.kryptonRibbonGroupCluster11, this.kryptonRibbonGroupCluster12}); // // kryptonRibbonGroupCluster9 // this.kryptonRibbonGroupCluster9.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupClusterButton25, this.kryptonRibbonGroupClusterButton26, this.kryptonRibbonGroupClusterButton27}); // // kryptonRibbonGroupClusterButton25 // this.kryptonRibbonGroupClusterButton25.TextLine = "AB"; // // kryptonRibbonGroupClusterButton26 // this.kryptonRibbonGroupClusterButton26.TextLine = "AB"; // // kryptonRibbonGroupClusterButton27 // this.kryptonRibbonGroupClusterButton27.TextLine = "AB"; // // kryptonRibbonGroupCluster10 // this.kryptonRibbonGroupCluster10.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupClusterButton28, this.kryptonRibbonGroupClusterButton29, this.kryptonRibbonGroupClusterButton30}); // // kryptonRibbonGroupClusterButton28 // this.kryptonRibbonGroupClusterButton28.TextLine = "AB"; // // kryptonRibbonGroupClusterButton29 // this.kryptonRibbonGroupClusterButton29.TextLine = "AB"; // // kryptonRibbonGroupClusterButton30 // this.kryptonRibbonGroupClusterButton30.TextLine = "AB"; // // kryptonRibbonGroupCluster11 // this.kryptonRibbonGroupCluster11.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupClusterButton31, this.kryptonRibbonGroupClusterButton32}); // // kryptonRibbonGroupClusterButton31 // this.kryptonRibbonGroupClusterButton31.TextLine = "AB"; // // kryptonRibbonGroupClusterButton32 // this.kryptonRibbonGroupClusterButton32.TextLine = "AB"; // // kryptonRibbonGroupCluster12 // this.kryptonRibbonGroupCluster12.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupClusterButton33, this.kryptonRibbonGroupClusterButton34, this.kryptonRibbonGroupClusterButton35, this.kryptonRibbonGroupClusterButton36}); // // kryptonRibbonGroupClusterButton33 // this.kryptonRibbonGroupClusterButton33.TextLine = "AB"; // // kryptonRibbonGroupClusterButton34 // this.kryptonRibbonGroupClusterButton34.TextLine = "AB"; // // kryptonRibbonGroupClusterButton35 // this.kryptonRibbonGroupClusterButton35.TextLine = "AB"; // // kryptonRibbonGroupClusterButton36 // this.kryptonRibbonGroupClusterButton36.TextLine = "AB"; // // kryptonRibbonGroup8 // this.kryptonRibbonGroup8.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupContainer[] { this.kryptonRibbonGroupLines5}); // // kryptonRibbonGroupLines5 // this.kryptonRibbonGroupLines5.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupCluster5, this.kryptonRibbonGroupCluster6, this.kryptonRibbonGroupCluster7}); // // kryptonRibbonGroupCluster5 // this.kryptonRibbonGroupCluster5.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupClusterButton13, this.kryptonRibbonGroupClusterButton14}); // // kryptonRibbonGroupClusterButton13 // this.kryptonRibbonGroupClusterButton13.TextLine = "AB"; // // kryptonRibbonGroupClusterButton14 // this.kryptonRibbonGroupClusterButton14.TextLine = "AB"; // // kryptonRibbonGroupCluster6 // this.kryptonRibbonGroupCluster6.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupClusterButton15, this.kryptonRibbonGroupClusterButton16}); // // kryptonRibbonGroupClusterButton15 // this.kryptonRibbonGroupClusterButton15.TextLine = "AB"; // // kryptonRibbonGroupClusterButton16 // this.kryptonRibbonGroupClusterButton16.TextLine = "AB"; // // kryptonRibbonGroupCluster7 // this.kryptonRibbonGroupCluster7.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupClusterButton18, this.kryptonRibbonGroupClusterButton19}); // // kryptonRibbonGroupClusterButton18 // this.kryptonRibbonGroupClusterButton18.TextLine = "AB"; // // kryptonRibbonGroupClusterButton19 // this.kryptonRibbonGroupClusterButton19.TextLine = "AB"; // // panelFill // this.panelFill.Controls.Add(this.groupShrinkInfo); this.panelFill.Dock = System.Windows.Forms.DockStyle.Fill; this.panelFill.Location = new System.Drawing.Point(0, 114); this.panelFill.Name = "panelFill"; this.panelFill.Size = new System.Drawing.Size(772, 281); this.panelFill.TabIndex = 1; // // groupShrinkInfo // this.groupShrinkInfo.GroupBackStyle = ComponentFactory.Krypton.Toolkit.PaletteBackStyle.PanelAlternate; this.groupShrinkInfo.Location = new System.Drawing.Point(12, 16); this.groupShrinkInfo.Name = "groupShrinkInfo"; // // groupShrinkInfo.Panel // this.groupShrinkInfo.Panel.Controls.Add(this.labelAutoShrinkage); this.groupShrinkInfo.Panel.Controls.Add(this.labelAutoInstructions); this.groupShrinkInfo.Size = new System.Drawing.Size(279, 217); this.groupShrinkInfo.TabIndex = 9; // // labelAutoShrinkage // this.labelAutoShrinkage.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.TitlePanel; this.labelAutoShrinkage.Location = new System.Drawing.Point(4, 4); this.labelAutoShrinkage.Name = "labelAutoShrinkage"; this.labelAutoShrinkage.Size = new System.Drawing.Size(251, 28); this.labelAutoShrinkage.TabIndex = 1; this.labelAutoShrinkage.Values.Text = "Automatic Shrinking Groups"; // // labelAutoInstructions // this.labelAutoInstructions.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel; this.labelAutoInstructions.Location = new System.Drawing.Point(4, 37); this.labelAutoInstructions.Name = "labelAutoInstructions"; this.labelAutoInstructions.Size = new System.Drawing.Size(262, 140); this.labelAutoInstructions.TabIndex = 2; this.labelAutoInstructions.Values.Text = resources.GetString("labelAutoInstructions.Values.Text"); // // kryptonManager // this.kryptonManager.GlobalPaletteMode = ComponentFactory.Krypton.Toolkit.PaletteModeManager.Office2010Silver; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(772, 395); this.Controls.Add(this.panelFill); this.Controls.Add(this.kryptonRibbon); this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(154, 385); this.Name = "Form1"; this.Text = "Auto Shrinking Groups"; ((System.ComponentModel.ISupportInitialize)(this.kryptonRibbon)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.panelFill)).EndInit(); this.panelFill.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.groupShrinkInfo.Panel)).EndInit(); this.groupShrinkInfo.Panel.ResumeLayout(false); this.groupShrinkInfo.Panel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.groupShrinkInfo)).EndInit(); this.groupShrinkInfo.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private ComponentFactory.Krypton.Ribbon.KryptonRibbon kryptonRibbon; private ComponentFactory.Krypton.Toolkit.KryptonPanel panelFill; private ComponentFactory.Krypton.Toolkit.KryptonManager kryptonManager; private ComponentFactory.Krypton.Ribbon.KryptonRibbonTab kryptonRibbonTab1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup kryptonRibbonGroup1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple kryptonRibbonGroupTriple1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton2; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton3; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple kryptonRibbonGroupTriple2; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton4; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton5; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton6; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup kryptonRibbonGroup2; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple kryptonRibbonGroupTriple3; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton7; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton8; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton9; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple kryptonRibbonGroupTriple4; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton10; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton11; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton12; private ComponentFactory.Krypton.Ribbon.KryptonRibbonTab kryptonRibbonTab2; private ComponentFactory.Krypton.Ribbon.KryptonRibbonTab kryptonRibbonTab3; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupSeparator kryptonRibbonGroupSeparator1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupSeparator kryptonRibbonGroupSeparator2; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup kryptonRibbonGroup3; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple kryptonRibbonGroupTriple5; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton13; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton14; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton15; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupSeparator kryptonRibbonGroupSeparator3; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple kryptonRibbonGroupTriple6; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton16; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton17; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton18; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup kryptonRibbonGroup4; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupLines kryptonRibbonGroupLines1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton19; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton20; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton21; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton22; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton31; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton32; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton37; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton38; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup kryptonRibbonGroup5; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupLines kryptonRibbonGroupLines2; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton23; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton24; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton25; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton26; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton33; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton34; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton39; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton40; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup kryptonRibbonGroup6; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupLines kryptonRibbonGroupLines3; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton27; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton28; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton29; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton35; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton36; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton41; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup kryptonRibbonGroup7; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupLines kryptonRibbonGroupLines4; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster kryptonRibbonGroupCluster1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton2; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton5; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster kryptonRibbonGroupCluster2; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton3; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton4; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton6; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster kryptonRibbonGroupCluster3; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton7; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton8; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster kryptonRibbonGroupCluster4; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton9; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton10; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton11; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton12; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupSeparator kryptonRibbonGroupSeparator4; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupLines kryptonRibbonGroupLines6; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster kryptonRibbonGroupCluster9; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton25; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton26; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton27; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster kryptonRibbonGroupCluster10; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton28; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton29; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton30; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster kryptonRibbonGroupCluster11; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton31; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton32; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster kryptonRibbonGroupCluster12; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton33; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton34; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton35; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton49; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton36; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup kryptonRibbonGroup8; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupLines kryptonRibbonGroupLines5; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster kryptonRibbonGroupCluster5; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton13; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton14; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster kryptonRibbonGroupCluster6; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton15; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton16; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupCluster kryptonRibbonGroupCluster7; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton18; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupClusterButton kryptonRibbonGroupClusterButton19; private ComponentFactory.Krypton.Toolkit.KryptonGroup groupShrinkInfo; private ComponentFactory.Krypton.Toolkit.KryptonLabel labelAutoShrinkage; private ComponentFactory.Krypton.Toolkit.KryptonLabel labelAutoInstructions; private ComponentFactory.Krypton.Toolkit.KryptonContextMenuItem kryptonContextMenuItem1; } }
namespace RealArtists.ChargeBee.Models { using System; using System.Collections.Generic; using System.ComponentModel; using System.Net.Http; using Newtonsoft.Json.Linq; using RealArtists.ChargeBee.Api; using RealArtists.ChargeBee.Filters.Enums; using RealArtists.ChargeBee.Internal; using RealArtists.ChargeBee.Models.Enums; public class CustomerActions : ApiResourceActions { public CustomerActions(ChargeBeeApi api) : base(api) { } public Customer.CreateRequest Create() { string url = BuildUrl("customers"); return new Customer.CreateRequest(Api, url, HttpMethod.Post); } public Customer.CustomerListRequest List() { string url = BuildUrl("customers"); return new Customer.CustomerListRequest(Api, url); } public EntityRequest<Type> Retrieve(string id) { string url = BuildUrl("customers", id); return new EntityRequest<Type>(Api, url, HttpMethod.Get); } public Customer.UpdateRequest Update(string id) { string url = BuildUrl("customers", id); return new Customer.UpdateRequest(Api, url, HttpMethod.Post); } public Customer.UpdatePaymentMethodRequest UpdatePaymentMethod(string id) { string url = BuildUrl("customers", id, "update_payment_method"); return new Customer.UpdatePaymentMethodRequest(Api, url, HttpMethod.Post); } public Customer.UpdateBillingInfoRequest UpdateBillingInfo(string id) { string url = BuildUrl("customers", id, "update_billing_info"); return new Customer.UpdateBillingInfoRequest(Api, url, HttpMethod.Post); } public Customer.AssignPaymentRoleRequest AssignPaymentRole(string id) { string url = BuildUrl("customers", id, "assign_payment_role"); return new Customer.AssignPaymentRoleRequest(Api, url, HttpMethod.Post); } public Customer.AddContactRequest AddContact(string id) { string url = BuildUrl("customers", id, "add_contact"); return new Customer.AddContactRequest(Api, url, HttpMethod.Post); } public Customer.UpdateContactRequest UpdateContact(string id) { string url = BuildUrl("customers", id, "update_contact"); return new Customer.UpdateContactRequest(Api, url, HttpMethod.Post); } public Customer.DeleteContactRequest DeleteContact(string id) { string url = BuildUrl("customers", id, "delete_contact"); return new Customer.DeleteContactRequest(Api, url, HttpMethod.Post); } public Customer.AddPromotionalCreditsRequest AddPromotionalCredits(string id) { string url = BuildUrl("customers", id, "add_promotional_credits"); return new Customer.AddPromotionalCreditsRequest(Api, url, HttpMethod.Post); } public Customer.DeductPromotionalCreditsRequest DeductPromotionalCredits(string id) { string url = BuildUrl("customers", id, "deduct_promotional_credits"); return new Customer.DeductPromotionalCreditsRequest(Api, url, HttpMethod.Post); } public Customer.SetPromotionalCreditsRequest SetPromotionalCredits(string id) { string url = BuildUrl("customers", id, "set_promotional_credits"); return new Customer.SetPromotionalCreditsRequest(Api, url, HttpMethod.Post); } public Customer.RecordExcessPaymentRequest RecordExcessPayment(string id) { string url = BuildUrl("customers", id, "record_excess_payment"); return new Customer.RecordExcessPaymentRequest(Api, url, HttpMethod.Post); } public Customer.DeleteRequest Delete(string id) { string url = BuildUrl("customers", id, "delete"); return new Customer.DeleteRequest(Api, url, HttpMethod.Post); } public Customer.MoveRequest Move() { string url = BuildUrl("customers", "move"); return new Customer.MoveRequest(Api, url, HttpMethod.Post); } public Customer.ChangeBillingDateRequest ChangeBillingDate(string id) { string url = BuildUrl("customers", id, "change_billing_date"); return new Customer.ChangeBillingDateRequest(Api, url, HttpMethod.Post); } } public class Customer : Resource { public string Id { get { return GetValue<string>("id", true); } } public string FirstName { get { return GetValue<string>("first_name", false); } } public string LastName { get { return GetValue<string>("last_name", false); } } public string Email { get { return GetValue<string>("email", false); } } public string Phone { get { return GetValue<string>("phone", false); } } public string Company { get { return GetValue<string>("company", false); } } public string VatNumber { get { return GetValue<string>("vat_number", false); } } public AutoCollectionEnum AutoCollection { get { return GetEnum<AutoCollectionEnum>("auto_collection", true); } } public int NetTermDays { get { return GetValue<int>("net_ter_days", true); } } public bool AllowDirectDebit { get { return GetValue<bool>("allow_direct_debit", true); } } public DateTime CreatedAt { get { return (DateTime)GetDateTime("created_at", true); } } public string CreatedFromIp { get { return GetValue<string>("created_fro_ip", false); } } public TaxabilityEnum? Taxability { get { return GetEnum<TaxabilityEnum>("taxability", false); } } public EntityCodeEnum? EntityCode { get { return GetEnum<EntityCodeEnum>("entity_code", false); } } public string ExemptNumber { get { return GetValue<string>("exempt_number", false); } } public long? ResourceVersion { get { return GetValue<long?>("resource_version", false); } } public DateTime? UpdatedAt { get { return GetDateTime("updated_at", false); } } public string Locale { get { return GetValue<string>("locale", false); } } public bool? ConsolidatedInvoicing { get { return GetValue<bool?>("consolidated_invoicing", false); } } public int? BillingDate { get { return GetValue<int?>("billing_date", false); } } public BillingDateModeEnum? BillingDateMode { get { return GetEnum<BillingDateModeEnum>("billing_date_mode", false); } } public BillingDayOfWeekEnum? BillingDayOfWeek { get { return GetEnum<BillingDayOfWeekEnum>("billing_day_of_week", false); } } public BillingDayOfWeekModeEnum? BillingDayOfWeekMode { get { return GetEnum<BillingDayOfWeekModeEnum>("billing_day_of_week_mode", false); } } public FraudFlagEnum? FraudFlag { get { return GetEnum<FraudFlagEnum>("fraud_flag", false); } } public string PrimaryPaymentSourceId { get { return GetValue<string>("primary_payment_source_id", false); } } public string BackupPaymentSourceId { get { return GetValue<string>("backup_payment_source_id", false); } } public CustomerBillingAddress BillingAddress { get { return GetSubResource<CustomerBillingAddress>("billing_address"); } } public List<CustomerReferralUrl> ReferralUrls { get { return GetResourceList<CustomerReferralUrl>("referral_urls"); } } public List<CustomerContact> Contacts { get { return GetResourceList<CustomerContact>("contacts"); } } public CustomerPaymentMethod PaymentMethod { get { return GetSubResource<CustomerPaymentMethod>("payment_method"); } } public string InvoiceNotes { get { return GetValue<string>("invoice_notes", false); } } public string PreferredCurrencyCode { get { return GetValue<string>("preferred_currency_code", false); } } public int PromotionalCredits { get { return GetValue<int>("promotional_credits", true); } } public int UnbilledCharges { get { return GetValue<int>("unbilled_charges", true); } } public int RefundableCredits { get { return GetValue<int>("refundable_credits", true); } } public int ExcessPayments { get { return GetValue<int>("excess_payments", true); } } public JToken MetaData { get { return GetJToken("meta_data", false); } } public bool Deleted { get { return GetValue<bool>("deleted", true); } } public bool? RegisteredForGst { get { return GetValue<bool?>("registered_for_gst", false); } } public class CreateRequest : EntityRequest<CreateRequest> { public CreateRequest(ChargeBeeApi api, string url, HttpMethod method) : base(api, url, method) { } public CreateRequest Id(string id) { _params.AddOpt("id", id); return this; } public CreateRequest FirstName(string firstName) { _params.AddOpt("first_name", firstName); return this; } public CreateRequest LastName(string lastName) { _params.AddOpt("last_name", lastName); return this; } public CreateRequest Email(string email) { _params.AddOpt("email", email); return this; } public CreateRequest PreferredCurrencyCode(string preferredCurrencyCode) { _params.AddOpt("preferred_currency_code", preferredCurrencyCode); return this; } public CreateRequest Phone(string phone) { _params.AddOpt("phone", phone); return this; } public CreateRequest Company(string company) { _params.AddOpt("company", company); return this; } public CreateRequest AutoCollection(AutoCollectionEnum autoCollection) { _params.AddOpt("auto_collection", autoCollection); return this; } public CreateRequest NetTermDays(int netTermDays) { _params.AddOpt("net_ter_days", netTermDays); return this; } public CreateRequest AllowDirectDebit(bool allowDirectDebit) { _params.AddOpt("allow_direct_debit", allowDirectDebit); return this; } public CreateRequest VatNumber(string vatNumber) { _params.AddOpt("vat_number", vatNumber); return this; } public CreateRequest RegisteredForGst(bool registeredForGst) { _params.AddOpt("registered_for_gst", registeredForGst); return this; } public CreateRequest Taxability(ChargeBee.Models.Enums.TaxabilityEnum taxability) { _params.AddOpt("taxability", taxability); return this; } public CreateRequest Locale(string locale) { _params.AddOpt("locale", locale); return this; } public CreateRequest EntityCode(ChargeBee.Models.Enums.EntityCodeEnum entityCode) { _params.AddOpt("entity_code", entityCode); return this; } public CreateRequest ExemptNumber(string exemptNumber) { _params.AddOpt("exempt_number", exemptNumber); return this; } public CreateRequest MetaData(JToken metaData) { _params.AddOpt("meta_data", metaData); return this; } public CreateRequest ConsolidatedInvoicing(bool consolidatedInvoicing) { _params.AddOpt("consolidated_invoicing", consolidatedInvoicing); return this; } public CreateRequest InvoiceNotes(string invoiceNotes) { _params.AddOpt("invoice_notes", invoiceNotes); return this; } public CreateRequest CardGatewayAccountId(string cardGatewayAccountId) { _params.AddOpt("card[gateway_account_id]", cardGatewayAccountId); return this; } public CreateRequest PaymentMethodType(ChargeBee.Models.Enums.TypeEnum paymentMethodType) { _params.AddOpt("payment_method[type]", paymentMethodType); return this; } public CreateRequest PaymentMethodGatewayAccountId(string paymentMethodGatewayAccountId) { _params.AddOpt("payment_method[gateway_account_id]", paymentMethodGatewayAccountId); return this; } public CreateRequest PaymentMethodReferenceId(string paymentMethodReferenceId) { _params.AddOpt("payment_method[reference_id]", paymentMethodReferenceId); return this; } public CreateRequest PaymentMethodTmpToken(string paymentMethodTmpToken) { _params.AddOpt("payment_method[tmp_token]", paymentMethodTmpToken); return this; } public CreateRequest CardFirstName(string cardFirstName) { _params.AddOpt("card[first_name]", cardFirstName); return this; } public CreateRequest CardLastName(string cardLastName) { _params.AddOpt("card[last_name]", cardLastName); return this; } public CreateRequest CardNumber(string cardNumber) { _params.AddOpt("card[number]", cardNumber); return this; } public CreateRequest CardExpiryMonth(int cardExpiryMonth) { _params.AddOpt("card[expiry_month]", cardExpiryMonth); return this; } public CreateRequest CardExpiryYear(int cardExpiryYear) { _params.AddOpt("card[expiry_year]", cardExpiryYear); return this; } public CreateRequest CardCvv(string cardCvv) { _params.AddOpt("card[cvv]", cardCvv); return this; } public CreateRequest CardBillingAddr1(string cardBillingAddr1) { _params.AddOpt("card[billing_addr1]", cardBillingAddr1); return this; } public CreateRequest CardBillingAddr2(string cardBillingAddr2) { _params.AddOpt("card[billing_addr2]", cardBillingAddr2); return this; } public CreateRequest CardBillingCity(string cardBillingCity) { _params.AddOpt("card[billing_city]", cardBillingCity); return this; } public CreateRequest CardBillingStateCode(string cardBillingStateCode) { _params.AddOpt("card[billing_state_code]", cardBillingStateCode); return this; } public CreateRequest CardBillingState(string cardBillingState) { _params.AddOpt("card[billing_state]", cardBillingState); return this; } public CreateRequest CardBillingZip(string cardBillingZip) { _params.AddOpt("card[billing_zip]", cardBillingZip); return this; } public CreateRequest CardBillingCountry(string cardBillingCountry) { _params.AddOpt("card[billing_country]", cardBillingCountry); return this; } public CreateRequest BillingAddressFirstName(string billingAddressFirstName) { _params.AddOpt("billing_address[first_name]", billingAddressFirstName); return this; } public CreateRequest BillingAddressLastName(string billingAddressLastName) { _params.AddOpt("billing_address[last_name]", billingAddressLastName); return this; } public CreateRequest BillingAddressEmail(string billingAddressEmail) { _params.AddOpt("billing_address[email]", billingAddressEmail); return this; } public CreateRequest BillingAddressCompany(string billingAddressCompany) { _params.AddOpt("billing_address[company]", billingAddressCompany); return this; } public CreateRequest BillingAddressPhone(string billingAddressPhone) { _params.AddOpt("billing_address[phone]", billingAddressPhone); return this; } public CreateRequest BillingAddressLine1(string billingAddressLine1) { _params.AddOpt("billing_address[line1]", billingAddressLine1); return this; } public CreateRequest BillingAddressLine2(string billingAddressLine2) { _params.AddOpt("billing_address[line2]", billingAddressLine2); return this; } public CreateRequest BillingAddressLine3(string billingAddressLine3) { _params.AddOpt("billing_address[line3]", billingAddressLine3); return this; } public CreateRequest BillingAddressCity(string billingAddressCity) { _params.AddOpt("billing_address[city]", billingAddressCity); return this; } public CreateRequest BillingAddressStateCode(string billingAddressStateCode) { _params.AddOpt("billing_address[state_code]", billingAddressStateCode); return this; } public CreateRequest BillingAddressState(string billingAddressState) { _params.AddOpt("billing_address[state]", billingAddressState); return this; } public CreateRequest BillingAddressZip(string billingAddressZip) { _params.AddOpt("billing_address[zip]", billingAddressZip); return this; } public CreateRequest BillingAddressCountry(string billingAddressCountry) { _params.AddOpt("billing_address[country]", billingAddressCountry); return this; } public CreateRequest BillingAddressValidationStatus(ValidationStatusEnum billingAddressValidationStatus) { _params.AddOpt("billing_address[validation_status]", billingAddressValidationStatus); return this; } } public class CustomerListRequest : ListRequestBase<CustomerListRequest> { public CustomerListRequest(ChargeBeeApi api, string url) : base(api, url) { } public CustomerListRequest IncludeDeleted(bool includeDeleted) { _params.AddOpt("include_deleted", includeDeleted); return this; } public StringFilter<CustomerListRequest> Id() { return new StringFilter<CustomerListRequest>("id", this).SupportsMultiOperators(true); } public StringFilter<CustomerListRequest> FirstName() { return new StringFilter<CustomerListRequest>("first_name", this).SupportsPresenceOperator(true); } public StringFilter<CustomerListRequest> LastName() { return new StringFilter<CustomerListRequest>("last_name", this).SupportsPresenceOperator(true); } public StringFilter<CustomerListRequest> Email() { return new StringFilter<CustomerListRequest>("email", this).SupportsPresenceOperator(true); } public StringFilter<CustomerListRequest> Company() { return new StringFilter<CustomerListRequest>("company", this).SupportsPresenceOperator(true); } public StringFilter<CustomerListRequest> Phone() { return new StringFilter<CustomerListRequest>("phone", this).SupportsPresenceOperator(true); } public EnumFilter<AutoCollectionEnum, CustomerListRequest> AutoCollection() { return new EnumFilter<AutoCollectionEnum, CustomerListRequest>("auto_collection", this); } public EnumFilter<ChargeBee.Models.Enums.TaxabilityEnum, CustomerListRequest> Taxability() { return new EnumFilter<ChargeBee.Models.Enums.TaxabilityEnum, CustomerListRequest>("taxability", this); } public TimestampFilter<CustomerListRequest> CreatedAt() { return new TimestampFilter<CustomerListRequest>("created_at", this); } public TimestampFilter<CustomerListRequest> UpdatedAt() { return new TimestampFilter<CustomerListRequest>("updated_at", this); } public CustomerListRequest SortByCreatedAt(SortOrderEnum order) { _params.AddOpt("sort_by[" + order.ToString().ToLower() + "]", "created_at"); return this; } } public class UpdateRequest : EntityRequest<UpdateRequest> { public UpdateRequest(ChargeBeeApi api, string url, HttpMethod method) : base(api, url, method) { } public UpdateRequest FirstName(string firstName) { _params.AddOpt("first_name", firstName); return this; } public UpdateRequest LastName(string lastName) { _params.AddOpt("last_name", lastName); return this; } public UpdateRequest Email(string email) { _params.AddOpt("email", email); return this; } public UpdateRequest PreferredCurrencyCode(string preferredCurrencyCode) { _params.AddOpt("preferred_currency_code", preferredCurrencyCode); return this; } public UpdateRequest Phone(string phone) { _params.AddOpt("phone", phone); return this; } public UpdateRequest Company(string company) { _params.AddOpt("company", company); return this; } public UpdateRequest AutoCollection(AutoCollectionEnum autoCollection) { _params.AddOpt("auto_collection", autoCollection); return this; } public UpdateRequest AllowDirectDebit(bool allowDirectDebit) { _params.AddOpt("allow_direct_debit", allowDirectDebit); return this; } public UpdateRequest NetTermDays(int netTermDays) { _params.AddOpt("net_ter_days", netTermDays); return this; } public UpdateRequest Taxability(ChargeBee.Models.Enums.TaxabilityEnum taxability) { _params.AddOpt("taxability", taxability); return this; } public UpdateRequest Locale(string locale) { _params.AddOpt("locale", locale); return this; } public UpdateRequest EntityCode(ChargeBee.Models.Enums.EntityCodeEnum entityCode) { _params.AddOpt("entity_code", entityCode); return this; } public UpdateRequest ExemptNumber(string exemptNumber) { _params.AddOpt("exempt_number", exemptNumber); return this; } public UpdateRequest InvoiceNotes(string invoiceNotes) { _params.AddOpt("invoice_notes", invoiceNotes); return this; } public UpdateRequest MetaData(JToken metaData) { _params.AddOpt("meta_data", metaData); return this; } public UpdateRequest FraudFlag(FraudFlagEnum fraudFlag) { _params.AddOpt("fraud_flag", fraudFlag); return this; } public UpdateRequest ConsolidatedInvoicing(bool consolidatedInvoicing) { _params.AddOpt("consolidated_invoicing", consolidatedInvoicing); return this; } } public class UpdatePaymentMethodRequest : EntityRequest<UpdatePaymentMethodRequest> { public UpdatePaymentMethodRequest(ChargeBeeApi api, string url, HttpMethod method) : base(api, url, method) { } public UpdatePaymentMethodRequest PaymentMethodType(TypeEnum paymentMethodType) { _params.Add("payment_method[type]", paymentMethodType); return this; } public UpdatePaymentMethodRequest PaymentMethodGatewayAccountId(string paymentMethodGatewayAccountId) { _params.AddOpt("payment_method[gateway_account_id]", paymentMethodGatewayAccountId); return this; } public UpdatePaymentMethodRequest PaymentMethodReferenceId(string paymentMethodReferenceId) { _params.AddOpt("payment_method[reference_id]", paymentMethodReferenceId); return this; } public UpdatePaymentMethodRequest PaymentMethodTmpToken(string paymentMethodTmpToken) { _params.AddOpt("payment_method[tmp_token]", paymentMethodTmpToken); return this; } } public class UpdateBillingInfoRequest : EntityRequest<UpdateBillingInfoRequest> { public UpdateBillingInfoRequest(ChargeBeeApi api, string url, HttpMethod method) : base(api, url, method) { } public UpdateBillingInfoRequest VatNumber(string vatNumber) { _params.AddOpt("vat_number", vatNumber); return this; } public UpdateBillingInfoRequest RegisteredForGst(bool registeredForGst) { _params.AddOpt("registered_for_gst", registeredForGst); return this; } public UpdateBillingInfoRequest BillingAddressFirstName(string billingAddressFirstName) { _params.AddOpt("billing_address[first_name]", billingAddressFirstName); return this; } public UpdateBillingInfoRequest BillingAddressLastName(string billingAddressLastName) { _params.AddOpt("billing_address[last_name]", billingAddressLastName); return this; } public UpdateBillingInfoRequest BillingAddressEmail(string billingAddressEmail) { _params.AddOpt("billing_address[email]", billingAddressEmail); return this; } public UpdateBillingInfoRequest BillingAddressCompany(string billingAddressCompany) { _params.AddOpt("billing_address[company]", billingAddressCompany); return this; } public UpdateBillingInfoRequest BillingAddressPhone(string billingAddressPhone) { _params.AddOpt("billing_address[phone]", billingAddressPhone); return this; } public UpdateBillingInfoRequest BillingAddressLine1(string billingAddressLine1) { _params.AddOpt("billing_address[line1]", billingAddressLine1); return this; } public UpdateBillingInfoRequest BillingAddressLine2(string billingAddressLine2) { _params.AddOpt("billing_address[line2]", billingAddressLine2); return this; } public UpdateBillingInfoRequest BillingAddressLine3(string billingAddressLine3) { _params.AddOpt("billing_address[line3]", billingAddressLine3); return this; } public UpdateBillingInfoRequest BillingAddressCity(string billingAddressCity) { _params.AddOpt("billing_address[city]", billingAddressCity); return this; } public UpdateBillingInfoRequest BillingAddressStateCode(string billingAddressStateCode) { _params.AddOpt("billing_address[state_code]", billingAddressStateCode); return this; } public UpdateBillingInfoRequest BillingAddressState(string billingAddressState) { _params.AddOpt("billing_address[state]", billingAddressState); return this; } public UpdateBillingInfoRequest BillingAddressZip(string billingAddressZip) { _params.AddOpt("billing_address[zip]", billingAddressZip); return this; } public UpdateBillingInfoRequest BillingAddressCountry(string billingAddressCountry) { _params.AddOpt("billing_address[country]", billingAddressCountry); return this; } public UpdateBillingInfoRequest BillingAddressValidationStatus(ValidationStatusEnum billingAddressValidationStatus) { _params.AddOpt("billing_address[validation_status]", billingAddressValidationStatus); return this; } } public class AssignPaymentRoleRequest : EntityRequest<AssignPaymentRoleRequest> { public AssignPaymentRoleRequest(ChargeBeeApi api, string url, HttpMethod method) : base(api, url, method) { } public AssignPaymentRoleRequest PaymentSourceId(string paymentSourceId) { _params.Add("payment_source_id", paymentSourceId); return this; } public AssignPaymentRoleRequest Role(RoleEnum role) { _params.Add("role", role); return this; } } public class AddContactRequest : EntityRequest<AddContactRequest> { public AddContactRequest(ChargeBeeApi api, string url, HttpMethod method) : base(api, url, method) { } public AddContactRequest ContactId(string contactId) { _params.AddOpt("contact[id]", contactId); return this; } public AddContactRequest ContactFirstName(string contactFirstName) { _params.AddOpt("contact[first_name]", contactFirstName); return this; } public AddContactRequest ContactLastName(string contactLastName) { _params.AddOpt("contact[last_name]", contactLastName); return this; } public AddContactRequest ContactEmail(string contactEmail) { _params.Add("contact[email]", contactEmail); return this; } public AddContactRequest ContactPhone(string contactPhone) { _params.AddOpt("contact[phone]", contactPhone); return this; } public AddContactRequest ContactLabel(string contactLabel) { _params.AddOpt("contact[label]", contactLabel); return this; } public AddContactRequest ContactEnabled(bool contactEnabled) { _params.AddOpt("contact[enabled]", contactEnabled); return this; } public AddContactRequest ContactSendBillingEmail(bool contactSendBillingEmail) { _params.AddOpt("contact[send_billing_email]", contactSendBillingEmail); return this; } public AddContactRequest ContactSendAccountEmail(bool contactSendAccountEmail) { _params.AddOpt("contact[send_account_email]", contactSendAccountEmail); return this; } } public class UpdateContactRequest : EntityRequest<UpdateContactRequest> { public UpdateContactRequest(ChargeBeeApi api, string url, HttpMethod method) : base(api, url, method) { } public UpdateContactRequest ContactId(string contactId) { _params.Add("contact[id]", contactId); return this; } public UpdateContactRequest ContactFirstName(string contactFirstName) { _params.AddOpt("contact[first_name]", contactFirstName); return this; } public UpdateContactRequest ContactLastName(string contactLastName) { _params.AddOpt("contact[last_name]", contactLastName); return this; } public UpdateContactRequest ContactEmail(string contactEmail) { _params.AddOpt("contact[email]", contactEmail); return this; } public UpdateContactRequest ContactPhone(string contactPhone) { _params.AddOpt("contact[phone]", contactPhone); return this; } public UpdateContactRequest ContactLabel(string contactLabel) { _params.AddOpt("contact[label]", contactLabel); return this; } public UpdateContactRequest ContactEnabled(bool contactEnabled) { _params.AddOpt("contact[enabled]", contactEnabled); return this; } public UpdateContactRequest ContactSendBillingEmail(bool contactSendBillingEmail) { _params.AddOpt("contact[send_billing_email]", contactSendBillingEmail); return this; } public UpdateContactRequest ContactSendAccountEmail(bool contactSendAccountEmail) { _params.AddOpt("contact[send_account_email]", contactSendAccountEmail); return this; } } public class DeleteContactRequest : EntityRequest<DeleteContactRequest> { public DeleteContactRequest(ChargeBeeApi api, string url, HttpMethod method) : base(api, url, method) { } public DeleteContactRequest ContactId(string contactId) { _params.Add("contact[id]", contactId); return this; } } public class AddPromotionalCreditsRequest : EntityRequest<AddPromotionalCreditsRequest> { public AddPromotionalCreditsRequest(ChargeBeeApi api, string url, HttpMethod method) : base(api, url, method) { } public AddPromotionalCreditsRequest Amount(int amount) { _params.Add("amount", amount); return this; } public AddPromotionalCreditsRequest CurrencyCode(string currencyCode) { _params.AddOpt("currency_code", currencyCode); return this; } public AddPromotionalCreditsRequest Description(string description) { _params.Add("description", description); return this; } public AddPromotionalCreditsRequest CreditType(ChargeBee.Models.Enums.CreditTypeEnum creditType) { _params.AddOpt("credit_type", creditType); return this; } public AddPromotionalCreditsRequest Reference(string reference) { _params.AddOpt("reference", reference); return this; } } public class DeductPromotionalCreditsRequest : EntityRequest<DeductPromotionalCreditsRequest> { public DeductPromotionalCreditsRequest(ChargeBeeApi api, string url, HttpMethod method) : base(api, url, method) { } public DeductPromotionalCreditsRequest Amount(int amount) { _params.Add("amount", amount); return this; } public DeductPromotionalCreditsRequest CurrencyCode(string currencyCode) { _params.AddOpt("currency_code", currencyCode); return this; } public DeductPromotionalCreditsRequest Description(string description) { _params.Add("description", description); return this; } public DeductPromotionalCreditsRequest CreditType(ChargeBee.Models.Enums.CreditTypeEnum creditType) { _params.AddOpt("credit_type", creditType); return this; } public DeductPromotionalCreditsRequest Reference(string reference) { _params.AddOpt("reference", reference); return this; } } public class SetPromotionalCreditsRequest : EntityRequest<SetPromotionalCreditsRequest> { public SetPromotionalCreditsRequest(ChargeBeeApi api, string url, HttpMethod method) : base(api, url, method) { } public SetPromotionalCreditsRequest Amount(int amount) { _params.Add("amount", amount); return this; } public SetPromotionalCreditsRequest CurrencyCode(string currencyCode) { _params.AddOpt("currency_code", currencyCode); return this; } public SetPromotionalCreditsRequest Description(string description) { _params.Add("description", description); return this; } public SetPromotionalCreditsRequest CreditType(ChargeBee.Models.Enums.CreditTypeEnum creditType) { _params.AddOpt("credit_type", creditType); return this; } public SetPromotionalCreditsRequest Reference(string reference) { _params.AddOpt("reference", reference); return this; } } public class RecordExcessPaymentRequest : EntityRequest<RecordExcessPaymentRequest> { public RecordExcessPaymentRequest(ChargeBeeApi api, string url, HttpMethod method) : base(api, url, method) { } public RecordExcessPaymentRequest Comment(string comment) { _params.AddOpt("comment", comment); return this; } public RecordExcessPaymentRequest TransactionAmount(int transactionAmount) { _params.Add("transaction[amount]", transactionAmount); return this; } public RecordExcessPaymentRequest TransactionCurrencyCode(string transactionCurrencyCode) { _params.AddOpt("transaction[currency_code]", transactionCurrencyCode); return this; } public RecordExcessPaymentRequest TransactionDate(long transactionDate) { _params.Add("transaction[date]", transactionDate); return this; } public RecordExcessPaymentRequest TransactionPaymentMethod(ChargeBee.Models.Enums.PaymentMethodEnum transactionPaymentMethod) { _params.Add("transaction[payment_method]", transactionPaymentMethod); return this; } public RecordExcessPaymentRequest TransactionReferenceNumber(string transactionReferenceNumber) { _params.AddOpt("transaction[reference_number]", transactionReferenceNumber); return this; } } public class DeleteRequest : EntityRequest<DeleteRequest> { public DeleteRequest(ChargeBeeApi api, string url, HttpMethod method) : base(api, url, method) { } public DeleteRequest DeletePaymentMethod(bool deletePaymentMethod) { _params.AddOpt("delete_payment_method", deletePaymentMethod); return this; } } public class MoveRequest : EntityRequest<MoveRequest> { public MoveRequest(ChargeBeeApi api, string url, HttpMethod method) : base(api, url, method) { } public MoveRequest IdAtFromSite(string idAtFromSite) { _params.Add("id_at_from_site", idAtFromSite); return this; } public MoveRequest FromSite(string fromSite) { _params.Add("from_site", fromSite); return this; } } public class ChangeBillingDateRequest : EntityRequest<ChangeBillingDateRequest> { public ChangeBillingDateRequest(ChargeBeeApi api, string url, HttpMethod method) : base(api, url, method) { } public ChangeBillingDateRequest BillingDate(int billingDate) { _params.AddOpt("billing_date", billingDate); return this; } public ChangeBillingDateRequest BillingDateMode(ChargeBee.Models.Enums.BillingDateModeEnum billingDateMode) { _params.AddOpt("billing_date_mode", billingDateMode); return this; } public ChangeBillingDateRequest BillingDayOfWeek(Customer.BillingDayOfWeekEnum billingDayOfWeek) { _params.AddOpt("billing_day_of_week", billingDayOfWeek); return this; } public ChangeBillingDateRequest BillingDayOfWeekMode(ChargeBee.Models.Enums.BillingDayOfWeekModeEnum billingDayOfWeekMode) { _params.AddOpt("billing_day_of_week_mode", billingDayOfWeekMode); return this; } } public enum BillingDayOfWeekEnum { Unknown, [Description("sunday")] Sunday, [Description("monday")] Monday, [Description("tuesday")] Tuesday, [Description("wednesday")] Wednesday, [Description("thursday")] Thursday, [Description("friday")] Friday, [Description("saturday")] Saturday, } public enum FraudFlagEnum { Unknown, [Description("safe")] Safe, [Description("suspicious")] Suspicious, [Description("fraudulent")] Fraudulent, } public class CustomerBillingAddress : Resource { public string FirstName() { return GetValue<string>("first_name", false); } public string LastName() { return GetValue<string>("last_name", false); } public string Email() { return GetValue<string>("email", false); } public string Company() { return GetValue<string>("company", false); } public string Phone() { return GetValue<string>("phone", false); } public string Line1() { return GetValue<string>("line1", false); } public string Line2() { return GetValue<string>("line2", false); } public string Line3() { return GetValue<string>("line3", false); } public string City() { return GetValue<string>("city", false); } public string StateCode() { return GetValue<string>("state_code", false); } public string State() { return GetValue<string>("state", false); } public string Country() { return GetValue<string>("country", false); } public string Zip() { return GetValue<string>("zip", false); } public ValidationStatusEnum? ValidationStatus() { return GetEnum<ValidationStatusEnum>("validation_status", false); } } public class CustomerReferralUrl : Resource { public string ExternalCustomerId() { return GetValue<string>("external_customer_id", false); } public string ReferralSharingUrl() { return GetValue<string>("referral_sharing_url", true); } public DateTime CreatedAt() { return (DateTime)GetDateTime("created_at", true); } public DateTime UpdatedAt() { return (DateTime)GetDateTime("updated_at", true); } public string ReferralCampaignId() { return GetValue<string>("referral_campaign_id", true); } public string ReferralAccountId() { return GetValue<string>("referral_account_id", true); } public string ReferralExternalCampaignId() { return GetValue<string>("referral_external_campaign_id", false); } public ReferralSystemEnum ReferralSystem() { return GetEnum<ReferralSystemEnum>("referral_system", true); } } public class CustomerContact : Resource { public string Id() { return GetValue<string>("id", true); } public string FirstName() { return GetValue<string>("first_name", false); } public string LastName() { return GetValue<string>("last_name", false); } public string Email() { return GetValue<string>("email", true); } public string Phone() { return GetValue<string>("phone", false); } public string Label() { return GetValue<string>("label", false); } public bool Enabled() { return GetValue<bool>("enabled", true); } public bool SendAccountEmail() { return GetValue<bool>("send_account_email", true); } public bool SendBillingEmail() { return GetValue<bool>("send_billing_email", true); } } public class CustomerPaymentMethod : Resource { public enum TypeEnum { Unknown, [Description("card")] Card, [Description("paypal_express_checkout")] PaypalExpressCheckout, [Description("amazon_payments")] AmazonPayments, [Description("direct_debit")] DirectDebit, [Description("generic")] Generic, [Description("alipay")] Alipay, [Description("unionpay")] Unionpay, [Description("apple_pay")] ApplePay, } public enum StatusEnum { Unknown, [Description("valid")] Valid, [Description("expiring")] Expiring, [Description("expired")] Expired, [Description("invalid")] Invalid, [Description("pending_verification")] PendingVerification, } public TypeEnum PaymentMethodType() { return GetEnum<TypeEnum>("type", true); } public GatewayEnum Gateway() { return GetEnum<GatewayEnum>("gateway", true); } public string GatewayAccountId() { return GetValue<string>("gateway_account_id", false); } public StatusEnum Status() { return GetEnum<StatusEnum>("status", true); } public string ReferenceId() { return GetValue<string>("reference_id", true); } } } }
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License 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.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Orleans.Runtime.Scheduler; using Orleans.Runtime.Configuration; namespace Orleans.Runtime.GrainDirectory { /// <summary> /// Most methods of this class are synchronized since they might be called both /// from LocalGrainDirectory on CacheValidator.SchedulingContext and from RemoteGrainDirectory. /// </summary> internal class GrainDirectoryHandoffManager { private const int HANDOFF_CHUNK_SIZE = 500; private readonly LocalGrainDirectory localDirectory; private readonly Dictionary<SiloAddress, GrainDirectoryPartition> directoryPartitionsMap; private readonly List<SiloAddress> silosHoldingMyPartition; private readonly Dictionary<SiloAddress, Task> lastPromise; private readonly TraceLogger logger; internal GrainDirectoryHandoffManager(LocalGrainDirectory localDirectory, GlobalConfiguration config) { logger = TraceLogger.GetLogger(this.GetType().FullName); this.localDirectory = localDirectory; directoryPartitionsMap = new Dictionary<SiloAddress, GrainDirectoryPartition>(); silosHoldingMyPartition = new List<SiloAddress>(); lastPromise = new Dictionary<SiloAddress, Task>(); } [MethodImpl(MethodImplOptions.Synchronized)] internal List<ActivationAddress> GetHandedOffInfo(GrainId grain) { foreach (var partition in directoryPartitionsMap.Values) { var result = partition.LookUpGrain(grain); if (result != null) { // Force the list to be created in order to avoid race conditions return result.Item1.Select(pair => ActivationAddress.GetAddress(pair.Item1, grain, pair.Item2)).ToList(); } } return null; } private async Task HandoffMyPartitionUponStop(Dictionary<GrainId, IGrainInfo> batchUpdate, bool isFullCopy) { if (batchUpdate.Count == 0 || silosHoldingMyPartition.Count == 0) { if (logger.IsVerbose) logger.Verbose((isFullCopy ? "FULL" : "DELTA") + " handoff finished with empty delta (nothing to send)"); return; } if (logger.IsVerbose) logger.Verbose("Sending {0} items to my {1}: (ring status is {2})", batchUpdate.Count, silosHoldingMyPartition.ToStrings(), localDirectory.RingStatusToString()); var tasks = new List<Task>(); var n = 0; var chunk = new Dictionary<GrainId, IGrainInfo>(); // Note that batchUpdate will not change while this method is executing foreach (var pair in batchUpdate) { chunk[pair.Key] = pair.Value; n++; if ((n % HANDOFF_CHUNK_SIZE != 0) && (n != batchUpdate.Count)) { // If we haven't filled in a chunk yet, keep looping. continue; } foreach (SiloAddress silo in silosHoldingMyPartition) { SiloAddress captureSilo = silo; Dictionary<GrainId, IGrainInfo> captureChunk = chunk; bool captureIsFullCopy = isFullCopy; if (logger.IsVerbose) logger.Verbose("Sending handed off partition to " + captureSilo); Task pendingRequest; if (lastPromise.TryGetValue(captureSilo, out pendingRequest)) { try { await pendingRequest; } catch (Exception) { } } Task task = localDirectory.Scheduler.RunOrQueueTask( () => localDirectory.GetDirectoryReference(captureSilo).AcceptHandoffPartition( localDirectory.MyAddress, captureChunk, captureIsFullCopy), localDirectory.RemGrainDirectory.SchedulingContext); lastPromise[captureSilo] = task; tasks.Add(task); } // We need to use a new Dictionary because the call to AcceptHandoffPartition, which reads the current Dictionary, // happens asynchronously (and typically after some delay). chunk = new Dictionary<GrainId, IGrainInfo>(); // This is a quick temporary solution. We send a full copy by sending one chunk as a full copy and follow-on chunks as deltas. // Obviously, this will really mess up if there's a failure after the first chunk but before the others are sent, since on a // full copy receive the follower dumps all old data and replaces it with the new full copy. // On the other hand, over time things should correct themselves, and of course, losing directory data isn't necessarily catastrophic. isFullCopy = false; } await Task.WhenAll(tasks); } [MethodImpl(MethodImplOptions.Synchronized)] internal void ProcessSiloRemoveEvent(SiloAddress removedSilo) { if (logger.IsVerbose) logger.Verbose("Processing silo remove event for " + removedSilo); // Reset our follower list to take the changes into account ResetFollowers(); // check if this is one of our successors (i.e., if I hold this silo's copy) // (if yes, adjust local and/or handoffed directory partitions) if (!directoryPartitionsMap.ContainsKey(removedSilo)) return; // at least one predcessor should exist, which is me SiloAddress predecessor = localDirectory.FindPredecessors(removedSilo, 1)[0]; if (localDirectory.MyAddress.Equals(predecessor)) { if (logger.IsVerbose) logger.Verbose("Merging my partition with the copy of silo " + removedSilo); // now I am responsible for this directory part localDirectory.DirectoryPartition.Merge(directoryPartitionsMap[removedSilo]); // no need to send our new partition to all others, as they // will realize the change and combine their copies without any additional communication (see below) } else { if (logger.IsVerbose) logger.Verbose("Merging partition of " + predecessor + " with the copy of silo " + removedSilo); // adjust copy for the predecessor of the failed silo directoryPartitionsMap[predecessor].Merge(directoryPartitionsMap[removedSilo]); } if (logger.IsVerbose) logger.Verbose("Removed copied partition of silo " + removedSilo); directoryPartitionsMap.Remove(removedSilo); } [MethodImpl(MethodImplOptions.Synchronized)] internal void ProcessSiloStoppingEvent() { ProcessSiloStoppingEvent_Impl(); } private async void ProcessSiloStoppingEvent_Impl() { if (logger.IsVerbose) logger.Verbose("Processing silo stopping event"); // Select our nearest predecessor to receive our hand-off, since that's the silo that will wind up owning our partition (assuming // that it doesn't also fail and that no other silo joins during the transition period). if (silosHoldingMyPartition.Count == 0) { silosHoldingMyPartition.AddRange(localDirectory.FindPredecessors(localDirectory.MyAddress, 1)); } // take a copy of the current directory partition Dictionary<GrainId, IGrainInfo> batchUpdate = localDirectory.DirectoryPartition.GetItems(); try { await HandoffMyPartitionUponStop(batchUpdate, true); localDirectory.MarkStopPreparationCompleted(); } catch (Exception exc) { localDirectory.MarkStopPreparationFailed(exc); } } [MethodImpl(MethodImplOptions.Synchronized)] internal void ProcessSiloAddEvent(SiloAddress addedSilo) { if (logger.IsVerbose) logger.Verbose("Processing silo add event for " + addedSilo); // Reset our follower list to take the changes into account ResetFollowers(); // check if this is one of our successors (i.e., if I should hold this silo's copy) // (if yes, adjust local and/or copied directory partitions by splitting them between old successors and the new one) // NOTE: We need to move part of our local directory to the new silo if it is an immediate successor. List<SiloAddress> successors = localDirectory.FindSuccessors(localDirectory.MyAddress, 1); if (!successors.Contains(addedSilo)) return; // check if this is an immediate successor if (successors[0].Equals(addedSilo)) { // split my local directory and send to my new immediate successor his share if (logger.IsVerbose) logger.Verbose("Splitting my partition between me and " + addedSilo); GrainDirectoryPartition splitPart = localDirectory.DirectoryPartition.Split( grain => { var s = localDirectory.CalculateTargetSilo(grain); return (s != null) && !localDirectory.MyAddress.Equals(s); }, false); List<ActivationAddress> splitPartListSingle = splitPart.ToListOfActivations(true); List<ActivationAddress> splitPartListMulti = splitPart.ToListOfActivations(false); if (splitPartListSingle.Count > 0) { if (logger.IsVerbose) logger.Verbose("Sending " + splitPartListSingle.Count + " single activation entries to " + addedSilo); localDirectory.Scheduler.QueueTask(async () => { await localDirectory.GetDirectoryReference(successors[0]).RegisterManySingleActivation( splitPartListSingle, LocalGrainDirectory.NUM_RETRIES); splitPartListSingle.ForEach( activationAddress => localDirectory.DirectoryPartition.RemoveGrain(activationAddress.Grain)); }, localDirectory.RemGrainDirectory.SchedulingContext).Ignore(); } if (splitPartListMulti.Count > 0) { if (logger.IsVerbose) logger.Verbose("Sending " + splitPartListMulti.Count + " entries to " + addedSilo); localDirectory.Scheduler.QueueTask(async () => { await localDirectory.GetDirectoryReference(successors[0]).RegisterMany(splitPartListMulti); splitPartListMulti.ForEach( activationAddress => localDirectory.DirectoryPartition.RemoveGrain(activationAddress.Grain)); }, localDirectory.RemGrainDirectory.SchedulingContext).Ignore(); } } else { // adjust partitions by splitting them accordingly between new and old silos SiloAddress predecessorOfNewSilo = localDirectory.FindPredecessors(addedSilo, 1)[0]; if (!directoryPartitionsMap.ContainsKey(predecessorOfNewSilo)) { // we should have the partition of the predcessor of our new successor logger.Warn(ErrorCode.DirectoryPartitionPredecessorExpected, "This silo is expected to hold directory partition of " + predecessorOfNewSilo); } else { if (logger.IsVerbose) logger.Verbose("Splitting partition of " + predecessorOfNewSilo + " and creating a copy for " + addedSilo); GrainDirectoryPartition splitPart = directoryPartitionsMap[predecessorOfNewSilo].Split( grain => { // Need to review the 2nd line condition. var s = localDirectory.CalculateTargetSilo(grain); return (s != null) && !predecessorOfNewSilo.Equals(s); }, true); directoryPartitionsMap[addedSilo] = splitPart; } } // remove partition of one of the old successors that we do not need to now SiloAddress oldSuccessor = directoryPartitionsMap.FirstOrDefault(pair => !successors.Contains(pair.Key)).Key; if (oldSuccessor == null) return; if (logger.IsVerbose) logger.Verbose("Removing copy of the directory partition of silo " + oldSuccessor + " (holding copy of " + addedSilo + " instead)"); directoryPartitionsMap.Remove(oldSuccessor); } internal void AcceptHandoffPartition(SiloAddress source, Dictionary<GrainId, IGrainInfo> partition, bool isFullCopy) { if (logger.IsVerbose) logger.Verbose("Got request to register " + (isFullCopy ? "FULL" : "DELTA") + " directory partition with " + partition.Count + " elements from " + source); if (!directoryPartitionsMap.ContainsKey(source)) { if (!isFullCopy) { logger.Warn(ErrorCode.DirectoryUnexpectedDelta, String.Format("Got delta of the directory partition from silo {0} (Membership status {1}) while not holding a full copy. Membership active cluster size is {2}", source, localDirectory.Membership.GetApproximateSiloStatus(source), localDirectory.Membership.GetApproximateSiloStatuses(true).Count)); } directoryPartitionsMap[source] = new GrainDirectoryPartition(); } if (isFullCopy) { directoryPartitionsMap[source].Set(partition); } else { directoryPartitionsMap[source].Update(partition); } } internal void RemoveHandoffPartition(SiloAddress source) { if (logger.IsVerbose) logger.Verbose("Got request to unregister directory partition copy from " + source); directoryPartitionsMap.Remove(source); } private void ResetFollowers() { var copyList = silosHoldingMyPartition.ToList(); foreach (var follower in copyList) { RemoveOldFollower(follower); } } private void RemoveOldFollower(SiloAddress silo) { if (logger.IsVerbose) logger.Verbose("Removing my copy from silo " + silo); // release this old copy, as we have got a new one silosHoldingMyPartition.Remove(silo); localDirectory.Scheduler.QueueTask(() => localDirectory.GetDirectoryReference(silo).RemoveHandoffPartition(localDirectory.MyAddress), localDirectory.RemGrainDirectory.SchedulingContext).Ignore(); } } }
/* * Copyright (c) 2008, openmetaverse.org * 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. * - Neither the name of the openmetaverse.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. */ using System; using System.Runtime.InteropServices; using System.Globalization; namespace OpenMetaverse { /// <summary> /// A three-dimensional vector with floating-point values /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector3 : IComparable<Vector3>, IEquatable<Vector3> { /// <summary>X value</summary> public float X; /// <summary>Y value</summary> public float Y; /// <summary>Z value</summary> public float Z; #region Constructors public Vector3(float x, float y, float z) { X = x; Y = y; Z = z; } public Vector3(float value) { X = value; Y = value; Z = value; } public Vector3(Vector2 value, float z) { X = value.X; Y = value.Y; Z = z; } public Vector3(Vector3d vector) { X = (float)vector.X; Y = (float)vector.Y; Z = (float)vector.Z; } /// <summary> /// Constructor, builds a vector from a byte array /// </summary> /// <param name="byteArray">Byte array containing three four-byte floats</param> /// <param name="pos">Beginning position in the byte array</param> public Vector3(byte[] byteArray, int pos) { X = Y = Z = 0f; FromBytes(byteArray, pos); } public Vector3(Vector3 vector) { X = vector.X; Y = vector.Y; Z = vector.Z; } #endregion Constructors #region Public Methods public float Length() { return (float)Math.Sqrt(DistanceSquared(this, Zero)); } public float LengthSquared() { return DistanceSquared(this, Zero); } public void Normalize() { this = Normalize(this); } /// <summary> /// Test if this vector is equal to another vector, within a given /// tolerance range /// </summary> /// <param name="vec">Vector to test against</param> /// <param name="tolerance">The acceptable magnitude of difference /// between the two vectors</param> /// <returns>True if the magnitude of difference between the two vectors /// is less than the given tolerance, otherwise false</returns> public bool ApproxEquals(Vector3 vec, float tolerance) { Vector3 diff = this - vec; return (diff.LengthSquared() <= tolerance * tolerance); } /// <summary> /// IComparable.CompareTo implementation /// </summary> public int CompareTo(Vector3 vector) { return Length().CompareTo(vector.Length()); } /// <summary> /// Test if this vector is composed of all finite numbers /// </summary> public bool IsFinite() { return (Utils.IsFinite(X) && Utils.IsFinite(Y) && Utils.IsFinite(Z)); } /// <summary> /// Builds a vector from a byte array /// </summary> /// <param name="byteArray">Byte array containing a 12 byte vector</param> /// <param name="pos">Beginning position in the byte array</param> public void FromBytes(byte[] byteArray, int pos) { if (!BitConverter.IsLittleEndian) { // Big endian architecture byte[] conversionBuffer = new byte[12]; Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 12); Array.Reverse(conversionBuffer, 0, 4); Array.Reverse(conversionBuffer, 4, 4); Array.Reverse(conversionBuffer, 8, 4); X = BitConverter.ToSingle(conversionBuffer, 0); Y = BitConverter.ToSingle(conversionBuffer, 4); Z = BitConverter.ToSingle(conversionBuffer, 8); } else { // Little endian architecture X = BitConverter.ToSingle(byteArray, pos); Y = BitConverter.ToSingle(byteArray, pos + 4); Z = BitConverter.ToSingle(byteArray, pos + 8); } } /// <summary> /// Returns the raw bytes for this vector /// </summary> /// <returns>A 12 byte array containing X, Y, and Z</returns> public byte[] GetBytes() { byte[] byteArray = new byte[12]; ToBytes(byteArray, 0); return byteArray; } /// <summary> /// Writes the raw bytes for this vector to a byte array /// </summary> /// <param name="dest">Destination byte array</param> /// <param name="pos">Position in the destination array to start /// writing. Must be at least 12 bytes before the end of the array</param> public void ToBytes(byte[] dest, int pos) { Buffer.BlockCopy(BitConverter.GetBytes(X), 0, dest, pos + 0, 4); Buffer.BlockCopy(BitConverter.GetBytes(Y), 0, dest, pos + 4, 4); Buffer.BlockCopy(BitConverter.GetBytes(Z), 0, dest, pos + 8, 4); if (!BitConverter.IsLittleEndian) { Array.Reverse(dest, pos + 0, 4); Array.Reverse(dest, pos + 4, 4); Array.Reverse(dest, pos + 8, 4); } } #endregion Public Methods #region Static Methods public static Vector3 Add(Vector3 value1, Vector3 value2) { value1.X += value2.X; value1.Y += value2.Y; value1.Z += value2.Z; return value1; } public static Vector3 Clamp(Vector3 value1, Vector3 min, Vector3 max) { return new Vector3( Utils.Clamp(value1.X, min.X, max.X), Utils.Clamp(value1.Y, min.Y, max.Y), Utils.Clamp(value1.Z, min.Z, max.Z)); } public static Vector3 Cross(Vector3 value1, Vector3 value2) { return new Vector3( value1.Y * value2.Z - value2.Y * value1.Z, value1.Z * value2.X - value2.Z * value1.X, value1.X * value2.Y - value2.X * value1.Y); } public static float Distance(Vector3 value1, Vector3 value2) { return (float)Math.Sqrt(DistanceSquared(value1, value2)); } public static float DistanceSquared(Vector3 value1, Vector3 value2) { return (value1.X - value2.X) * (value1.X - value2.X) + (value1.Y - value2.Y) * (value1.Y - value2.Y) + (value1.Z - value2.Z) * (value1.Z - value2.Z); } public static Vector3 Divide(Vector3 value1, Vector3 value2) { value1.X /= value2.X; value1.Y /= value2.Y; value1.Z /= value2.Z; return value1; } public static Vector3 Divide(Vector3 value1, float value2) { float factor = 1f / value2; value1.X *= factor; value1.Y *= factor; value1.Z *= factor; return value1; } public static float Dot(Vector3 value1, Vector3 value2) { return value1.X * value2.X + value1.Y * value2.Y + value1.Z * value2.Z; } public static Vector3 Lerp(Vector3 value1, Vector3 value2, float amount) { return new Vector3( Utils.Lerp(value1.X, value2.X, amount), Utils.Lerp(value1.Y, value2.Y, amount), Utils.Lerp(value1.Z, value2.Z, amount)); } public static float Mag(Vector3 value) { return (float)Math.Sqrt((value.X * value.X) + (value.Y * value.Y) + (value.Z * value.Z)); } public static Vector3 Max(Vector3 value1, Vector3 value2) { return new Vector3( Math.Max(value1.X, value2.X), Math.Max(value1.Y, value2.Y), Math.Max(value1.Z, value2.Z)); } public static Vector3 Min(Vector3 value1, Vector3 value2) { return new Vector3( Math.Min(value1.X, value2.X), Math.Min(value1.Y, value2.Y), Math.Min(value1.Z, value2.Z)); } public static Vector3 Multiply(Vector3 value1, Vector3 value2) { value1.X *= value2.X; value1.Y *= value2.Y; value1.Z *= value2.Z; return value1; } public static Vector3 Multiply(Vector3 value1, float scaleFactor) { value1.X *= scaleFactor; value1.Y *= scaleFactor; value1.Z *= scaleFactor; return value1; } public static Vector3 Negate(Vector3 value) { value.X = -value.X; value.Y = -value.Y; value.Z = -value.Z; return value; } public static Vector3 Normalize(Vector3 value) { const float MAG_THRESHOLD = 0.0000001f; float factor = Distance(value, Zero); if (factor > MAG_THRESHOLD) { factor = 1f / factor; value.X *= factor; value.Y *= factor; value.Z *= factor; } else { value.X = 0f; value.Y = 0f; value.Z = 0f; } return value; } /// <summary> /// Parse a vector from a string /// </summary> /// <param name="val">A string representation of a 3D vector, enclosed /// in arrow brackets and separated by commas</param> public static Vector3 Parse(string val) { char[] splitChar = { ',' }; string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar); return new Vector3( Single.Parse(split[0].Trim(), Utils.EnUsCulture), Single.Parse(split[1].Trim(), Utils.EnUsCulture), Single.Parse(split[2].Trim(), Utils.EnUsCulture)); } public static bool TryParse(string val, out Vector3 result) { try { result = Parse(val); return true; } catch (Exception) { result = Vector3.Zero; return false; } } /// <summary> /// Calculate the rotation between two vectors /// </summary> /// <param name="a">Normalized directional vector (such as 1,0,0 for forward facing)</param> /// <param name="b">Normalized target vector</param> public static Quaternion RotationBetween(Vector3 a, Vector3 b) { float dotProduct = Dot(a, b); Vector3 crossProduct = Cross(a, b); float magProduct = a.Length() * b.Length(); double angle = Math.Acos(dotProduct / magProduct); Vector3 axis = Normalize(crossProduct); float s = (float)Math.Sin(angle / 2d); return new Quaternion( axis.X * s, axis.Y * s, axis.Z * s, (float)Math.Cos(angle / 2d)); } /// <summary> /// Interpolates between two vectors using a cubic equation /// </summary> public static Vector3 SmoothStep(Vector3 value1, Vector3 value2, float amount) { return new Vector3( Utils.SmoothStep(value1.X, value2.X, amount), Utils.SmoothStep(value1.Y, value2.Y, amount), Utils.SmoothStep(value1.Z, value2.Z, amount)); } public static Vector3 Subtract(Vector3 value1, Vector3 value2) { value1.X -= value2.X; value1.Y -= value2.Y; value1.Z -= value2.Z; return value1; } public static Vector3 Transform(Vector3 position, Matrix4 matrix) { return new Vector3( (position.X * matrix.M11) + (position.Y * matrix.M21) + (position.Z * matrix.M31) + matrix.M41, (position.X * matrix.M12) + (position.Y * matrix.M22) + (position.Z * matrix.M32) + matrix.M42, (position.X * matrix.M13) + (position.Y * matrix.M23) + (position.Z * matrix.M33) + matrix.M43); } public static Vector3 TransformNormal(Vector3 position, Matrix4 matrix) { return new Vector3( (position.X * matrix.M11) + (position.Y * matrix.M21) + (position.Z * matrix.M31), (position.X * matrix.M12) + (position.Y * matrix.M22) + (position.Z * matrix.M32), (position.X * matrix.M13) + (position.Y * matrix.M23) + (position.Z * matrix.M33)); } #endregion Static Methods #region Overrides public override bool Equals(object obj) { return (obj is Vector3) ? this == (Vector3)obj : false; } public bool Equals(Vector3 other) { return this == other; } public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode(); } /// <summary> /// Get a formatted string representation of the vector /// </summary> /// <returns>A string representation of the vector</returns> public override string ToString() { return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}>", X, Y, Z); } /// <summary> /// Get a string representation of the vector elements with up to three /// decimal digits and separated by spaces only /// </summary> /// <returns>Raw string representation of the vector</returns> public string ToRawString() { CultureInfo enUs = new CultureInfo("en-us"); enUs.NumberFormat.NumberDecimalDigits = 3; return String.Format(enUs, "{0} {1} {2}", X, Y, Z); } #endregion Overrides #region Operators public static bool operator ==(Vector3 value1, Vector3 value2) { return value1.X == value2.X && value1.Y == value2.Y && value1.Z == value2.Z; } public static bool operator !=(Vector3 value1, Vector3 value2) { return !(value1 == value2); } public static Vector3 operator +(Vector3 value1, Vector3 value2) { value1.X += value2.X; value1.Y += value2.Y; value1.Z += value2.Z; return value1; } public static Vector3 operator -(Vector3 value) { value.X = -value.X; value.Y = -value.Y; value.Z = -value.Z; return value; } public static Vector3 operator -(Vector3 value1, Vector3 value2) { value1.X -= value2.X; value1.Y -= value2.Y; value1.Z -= value2.Z; return value1; } public static Vector3 operator *(Vector3 value1, Vector3 value2) { value1.X *= value2.X; value1.Y *= value2.Y; value1.Z *= value2.Z; return value1; } public static Vector3 operator *(Vector3 value, float scaleFactor) { value.X *= scaleFactor; value.Y *= scaleFactor; value.Z *= scaleFactor; return value; } public static Vector3 operator *(Vector3 vec, Quaternion rot) { Vector3 vec2; vec2.X = rot.W * rot.W * vec.X + 2f * rot.Y * rot.W * vec.Z - 2f * rot.Z * rot.W * vec.Y + rot.X * rot.X * vec.X + 2f * rot.Y * rot.X * vec.Y + 2f * rot.Z * rot.X * vec.Z - rot.Z * rot.Z * vec.X - rot.Y * rot.Y * vec.X; vec2.Y = 2f * rot.X * rot.Y * vec.X + rot.Y * rot.Y * vec.Y + 2f * rot.Z * rot.Y * vec.Z + 2f * rot.W * rot.Z * vec.X - rot.Z * rot.Z * vec.Y + rot.W * rot.W * vec.Y - 2f * rot.X * rot.W * vec.Z - rot.X * rot.X * vec.Y; vec2.Z = 2f * rot.X * rot.Z * vec.X + 2f * rot.Y * rot.Z * vec.Y + rot.Z * rot.Z * vec.Z - 2f * rot.W * rot.Y * vec.X - rot.Y * rot.Y * vec.Z + 2f * rot.W * rot.X * vec.Y - rot.X * rot.X * vec.Z + rot.W * rot.W * vec.Z; return vec2; } public static Vector3 operator *(Vector3 vector, Matrix4 matrix) { return Transform(vector, matrix); } public static Vector3 operator /(Vector3 value1, Vector3 value2) { value1.X /= value2.X; value1.Y /= value2.Y; value1.Z /= value2.Z; return value1; } public static Vector3 operator /(Vector3 value, float divider) { float factor = 1f / divider; value.X *= factor; value.Y *= factor; value.Z *= factor; return value; } /// <summary> /// Cross product between two vectors /// </summary> public static Vector3 operator %(Vector3 value1, Vector3 value2) { return Cross(value1, value2); } #endregion Operators /// <summary>A vector with a value of 0,0,0</summary> public readonly static Vector3 Zero = new Vector3(); /// <summary>A vector with a value of 1,1,1</summary> public readonly static Vector3 One = new Vector3(1f, 1f, 1f); /// <summary>A unit vector facing forward (X axis), value 1,0,0</summary> public readonly static Vector3 UnitX = new Vector3(1f, 0f, 0f); /// <summary>A unit vector facing left (Y axis), value 0,1,0</summary> public readonly static Vector3 UnitY = new Vector3(0f, 1f, 0f); /// <summary>A unit vector facing up (Z axis), value 0,0,1</summary> public readonly static Vector3 UnitZ = new Vector3(0f, 0f, 1f); } }
#region License // Copyright (c) 2018, Fluent Migrator Project // // 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.Data; using System.IO; using System.Collections.Generic; using System.Diagnostics; using FluentMigrator.Expressions; using FluentMigrator.Runner.BatchParser; using FluentMigrator.Runner.BatchParser.Sources; using FluentMigrator.Runner.Generators.SqlServer; using FluentMigrator.Runner.Helpers; using FluentMigrator.Runner.Initialization; using JetBrains.Annotations; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace FluentMigrator.Runner.Processors.SqlServer { public sealed class SqlServerCeProcessor : GenericProcessorBase { [CanBeNull] private readonly IServiceProvider _serviceProvider; public override string DatabaseType => "SqlServerCe"; public override IList<string> DatabaseTypeAliases { get; } = new List<string> { "SqlServer" }; [Obsolete] public SqlServerCeProcessor(IDbConnection connection, IMigrationGenerator generator, IAnnouncer announcer, IMigrationProcessorOptions options, IDbFactory factory) : base(connection, factory, generator, announcer, options) { } public SqlServerCeProcessor( [NotNull] SqlServerCeDbFactory factory, [NotNull] SqlServerCeGenerator generator, [NotNull] ILogger<SqlServerCeProcessor> logger, [NotNull] IOptionsSnapshot<ProcessorOptions> options, [NotNull] IConnectionStringAccessor connectionStringAccessor, [NotNull] IServiceProvider serviceProvider) : base(() => factory.Factory, generator, logger, options.Value, connectionStringAccessor) { _serviceProvider = serviceProvider; } public override bool SchemaExists(string schemaName) { return true; // SqlServerCe has no schemas } public override bool TableExists(string schemaName, string tableName) { return Exists("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{0}'", FormatHelper.FormatSqlEscape(tableName)); } public override bool ColumnExists(string schemaName, string tableName, string columnName) { return Exists("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{0}' AND COLUMN_NAME = '{1}'", FormatHelper.FormatSqlEscape(tableName), FormatHelper.FormatSqlEscape(columnName)); } public override bool ConstraintExists(string schemaName, string tableName, string constraintName) { return Exists("SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = '{0}' AND CONSTRAINT_NAME = '{1}'", FormatHelper.FormatSqlEscape(tableName), FormatHelper.FormatSqlEscape(constraintName)); } public override bool IndexExists(string schemaName, string tableName, string indexName) { return Exists("SELECT NULL FROM INFORMATION_SCHEMA.INDEXES WHERE INDEX_NAME = '{0}'", FormatHelper.FormatSqlEscape(indexName)); } public override bool SequenceExists(string schemaName, string sequenceName) { return false; } public override bool DefaultValueExists(string schemaName, string tableName, string columnName, object defaultValue) { return false; } public override void Execute(string template, params object[] args) { Process(string.Format(template, args)); } public override bool Exists(string template, params object[] args) { EnsureConnectionIsOpen(); using (var command = CreateCommand(string.Format(template, args))) using (var reader = command.ExecuteReader()) { return reader.Read(); } } public override DataSet ReadTableData(string schemaName, string tableName) { return Read("SELECT * FROM [{0}]", tableName); } public override DataSet Read(string template, params object[] args) { EnsureConnectionIsOpen(); using (var command = CreateCommand(string.Format(template, args))) using (var reader = command.ExecuteReader()) { return reader.ReadDataSet(); } } protected override void Process(string sql) { Logger.LogSql(sql); if (Options.PreviewOnly || string.IsNullOrEmpty(sql)) return; EnsureConnectionIsOpen(); using (var command = CreateCommand(string.Empty)) { foreach (string statement in SplitIntoSingleStatements(sql)) { try { command.CommandText = statement; command.ExecuteNonQuery(); } catch (Exception ex) { using (var message = new StringWriter()) { message.WriteLine("An error occurred executing the following sql:"); message.WriteLine(statement); message.WriteLine("The error was {0}", ex.Message); throw new Exception(message.ToString(), ex); } } } } } private IEnumerable<string> SplitIntoSingleStatements(string sql) { var sqlStatements = new List<string>(); var parser = _serviceProvider?.GetService<SqlServerBatchParser>() ?? new SqlServerBatchParser(); parser.SqlText += (sender, args) => { var content = args.SqlText.Trim(); if (!string.IsNullOrEmpty(content)) { sqlStatements.Add(content); } }; using (var source = new TextReaderSource(new StringReader(sql), true)) { parser.Process(source); } return sqlStatements; } public override void Process(PerformDBOperationExpression expression) { Logger.LogSay("Performing DB Operation"); if (Options.PreviewOnly) { return; } EnsureConnectionIsOpen(); expression.Operation?.Invoke(Connection, Transaction); } /// <inheritdoc /> protected override IDbCommand CreateCommand(string commandText, IDbConnection connection, IDbTransaction transaction) { IDbCommand result; if (DbProviderFactory != null) { result = DbProviderFactory.CreateCommand(); Debug.Assert(result != null, nameof(result) + " != null"); result.Connection = connection; if (transaction != null) result.Transaction = transaction; result.CommandText = commandText; } else { #pragma warning disable 612 result = Factory.CreateCommand(commandText, connection, transaction, Options); #pragma warning restore 612 } // SQL Server CE does not support non-zero command timeout values!! :/ return result; } } }
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License 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.Linq; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Orleans.Runtime; using Orleans.Messaging; using Orleans.Providers; using Orleans.CodeGeneration; using Orleans.Serialization; using Orleans.Storage; using Orleans.Runtime.Configuration; using System.Collections.Concurrent; using Orleans.Streams; namespace Orleans { internal class OutsideRuntimeClient : IRuntimeClient, IDisposable { internal static bool TestOnlyThrowExceptionDuringInit { get; set; } private readonly TraceLogger logger; private readonly TraceLogger appLogger; private readonly ClientConfiguration config; private readonly ConcurrentDictionary<CorrelationId, CallbackData> callbacks; private readonly ConcurrentDictionary<GuidId, LocalObjectData> localObjects; private readonly ProxiedMessageCenter transport; private bool listenForMessages; private CancellationTokenSource listeningCts; private readonly ClientProviderRuntime clientProviderRuntime; private readonly StatisticsProviderManager statisticsProviderManager; internal ClientStatisticsManager ClientStatistics; private readonly GrainId clientId; private GrainInterfaceMap grainInterfaceMap; private readonly ThreadTrackingStatistic incomingMessagesThreadTimeTracking; // initTimeout used to be AzureTableDefaultPolicies.TableCreationTimeout, which was 3 min private static readonly TimeSpan initTimeout = TimeSpan.FromMinutes(1); private static readonly TimeSpan resetTimeout = TimeSpan.FromMinutes(1); private const string BARS = "----------"; private readonly GrainFactory grainFactory; public GrainFactory InternalGrainFactory { get { return grainFactory; } } /// <summary> /// Response timeout. /// </summary> private TimeSpan responseTimeout; private static readonly Object staticLock = new Object(); Logger IRuntimeClient.AppLogger { get { return appLogger; } } public ActivationAddress CurrentActivationAddress { get; private set; } public SiloAddress CurrentSilo { get { return CurrentActivationAddress.Silo; } } public string Identity { get { return CurrentActivationAddress.ToString(); } } public IActivationData CurrentActivationData { get { return null; } } public IAddressable CurrentGrain { get { return null; } } public IStorageProvider CurrentStorageProvider { get { throw new InvalidOperationException("Storage provider only available from inside grain"); } } internal List<Uri> Gateways { get { return transport.GatewayManager.ListProvider.GetGateways().ToList(); } } public IStreamProviderManager CurrentStreamProviderManager { get; private set; } public IStreamProviderRuntime CurrentStreamProviderRuntime { get { return clientProviderRuntime; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "MessageCenter is IDisposable but cannot call Dispose yet as it lives past the end of this method call.")] public OutsideRuntimeClient(ClientConfiguration cfg, GrainFactory grainFactory, bool secondary = false) { this.grainFactory = grainFactory; this.clientId = GrainId.NewClientId(); if (cfg == null) { Console.WriteLine("An attempt to create an OutsideRuntimeClient with null ClientConfiguration object."); throw new ArgumentException("OutsideRuntimeClient was attempted to be created with null ClientConfiguration object.", "cfg"); } this.config = cfg; if (!TraceLogger.IsInitialized) TraceLogger.Initialize(config); StatisticsCollector.Initialize(config); SerializationManager.Initialize(config.UseStandardSerializer); logger = TraceLogger.GetLogger("OutsideRuntimeClient", TraceLogger.LoggerType.Runtime); appLogger = TraceLogger.GetLogger("Application", TraceLogger.LoggerType.Application); try { LoadAdditionalAssemblies(); PlacementStrategy.Initialize(); callbacks = new ConcurrentDictionary<CorrelationId, CallbackData>(); localObjects = new ConcurrentDictionary<GuidId, LocalObjectData>(); CallbackData.Config = config; if (!secondary) { UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnhandledException); } // Ensure SerializationManager static constructor is called before AssemblyLoad event is invoked SerializationManager.GetDeserializer(typeof(String)); // Ensure that any assemblies that get loaded in the future get recorded AppDomain.CurrentDomain.AssemblyLoad += NewAssemblyHandler; // Load serialization info for currently-loaded assemblies foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (!assembly.ReflectionOnly) { SerializationManager.FindSerializationInfo(assembly); } } clientProviderRuntime = new ClientProviderRuntime(grainFactory); statisticsProviderManager = new StatisticsProviderManager("Statistics", clientProviderRuntime); var statsProviderName = statisticsProviderManager.LoadProvider(config.ProviderConfigurations) .WaitForResultWithThrow(initTimeout); if (statsProviderName != null) { config.StatisticsProviderName = statsProviderName; } responseTimeout = Debugger.IsAttached ? Constants.DEFAULT_RESPONSE_TIMEOUT : config.ResponseTimeout; BufferPool.InitGlobalBufferPool(config); var localAddress = ClusterConfiguration.GetLocalIPAddress(config.PreferredFamily, config.NetInterface); // Client init / sign-on message logger.Info(ErrorCode.ClientInitializing, string.Format( "{0} Initializing OutsideRuntimeClient on {1} at {2} Client Id = {3} {0}", BARS, config.DNSHostName, localAddress, clientId)); string startMsg = string.Format("{0} Starting OutsideRuntimeClient with runtime Version='{1}'", BARS, RuntimeVersion.Current); startMsg = string.Format("{0} Config= " + Environment.NewLine + " {1}", startMsg, config); logger.Info(ErrorCode.ClientStarting, startMsg); if (TestOnlyThrowExceptionDuringInit) { throw new ApplicationException("TestOnlyThrowExceptionDuringInit"); } config.CheckGatewayProviderSettings(); var generation = -SiloAddress.AllocateNewGeneration(); // Client generations are negative var gatewayListProvider = GatewayProviderFactory.CreateGatewayListProvider(config) .WithTimeout(initTimeout).Result; transport = new ProxiedMessageCenter(config, localAddress, generation, clientId, gatewayListProvider); if (StatisticsCollector.CollectThreadTimeTrackingStats) { incomingMessagesThreadTimeTracking = new ThreadTrackingStatistic("ClientReceiver"); } } catch (Exception exc) { if (logger != null) logger.Error(ErrorCode.Runtime_Error_100319, "OutsideRuntimeClient constructor failed.", exc); ConstructorReset(); throw; } } private void StreamingInitialize() { var implicitSubscriberTable = transport.GetImplicitStreamSubscriberTable(grainFactory).Result; clientProviderRuntime.StreamingInitialize(implicitSubscriberTable); var streamProviderManager = new Streams.StreamProviderManager(); streamProviderManager .LoadStreamProviders( this.config.ProviderConfigurations, clientProviderRuntime) .Wait(); CurrentStreamProviderManager = streamProviderManager; } private static void LoadAdditionalAssemblies() { var logger = TraceLogger.GetLogger("AssemblyLoader.Client", TraceLogger.LoggerType.Runtime); var directories = new Dictionary<string, SearchOption> { { Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), SearchOption.AllDirectories } }; var excludeCriteria = new AssemblyLoaderPathNameCriterion[] { AssemblyLoaderCriteria.ExcludeResourceAssemblies, AssemblyLoaderCriteria.ExcludeSystemBinaries() }; var loadProvidersCriteria = new AssemblyLoaderReflectionCriterion[] { AssemblyLoaderCriteria.LoadTypesAssignableFrom(typeof(IProvider)) }; AssemblyLoader.LoadAssemblies(directories, excludeCriteria, loadProvidersCriteria, logger); } private static void NewAssemblyHandler(object sender, AssemblyLoadEventArgs args) { var assembly = args.LoadedAssembly; if (!assembly.ReflectionOnly) { SerializationManager.FindSerializationInfo(args.LoadedAssembly); } } private void UnhandledException(ISchedulingContext context, Exception exception) { logger.Error(ErrorCode.Runtime_Error_100007, String.Format("OutsideRuntimeClient caught an UnobservedException."), exception); logger.Assert(ErrorCode.Runtime_Error_100008, context == null, "context should be not null only inside OrleansRuntime and not on the client."); } public void Start() { lock (staticLock) { if (RuntimeClient.Current != null) throw new InvalidOperationException("Can only have one RuntimeClient per AppDomain"); RuntimeClient.Current = this; } StartInternal(); logger.Info(ErrorCode.ProxyClient_StartDone, "{0} Started OutsideRuntimeClient with Global Client ID: {1}", BARS, CurrentActivationAddress.ToString() + ", client GUID ID: " + clientId); } // used for testing to (carefully!) allow two clients in the same process internal void StartInternal() { transport.Start(); TraceLogger.MyIPEndPoint = transport.MyAddress.Endpoint; // transport.MyAddress is only set after transport is Started. CurrentActivationAddress = ActivationAddress.NewActivationAddress(transport.MyAddress, clientId); ClientStatistics = new ClientStatisticsManager(config); ClientStatistics.Start(config, statisticsProviderManager, transport, clientId) .WaitWithThrow(initTimeout); listeningCts = new CancellationTokenSource(); var ct = listeningCts.Token; listenForMessages = true; // Keeping this thread handling it very simple for now. Just queue task on thread pool. Task.Factory.StartNew(() => { try { RunClientMessagePump(ct); } catch(Exception exc) { logger.Error(ErrorCode.Runtime_Error_100326, "RunClientMessagePump has thrown exception", exc); } } ); grainInterfaceMap = transport.GetTypeCodeMap(grainFactory).Result; StreamingInitialize(); } private void RunClientMessagePump(CancellationToken ct) { if (StatisticsCollector.CollectThreadTimeTrackingStats) { incomingMessagesThreadTimeTracking.OnStartExecution(); } while (listenForMessages) { var message = transport.WaitMessage(Message.Categories.Application, ct); if (message == null) // if wait was cancelled break; #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectThreadTimeTrackingStats) { incomingMessagesThreadTimeTracking.OnStartProcessing(); } #endif switch (message.Direction) { case Message.Directions.Response: { ReceiveResponse(message); break; } case Message.Directions.OneWay: case Message.Directions.Request: { this.DispatchToLocalObject(message); break; } default: logger.Error(ErrorCode.Runtime_Error_100327, String.Format("Message not supported: {0}.", message)); break; } #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectThreadTimeTrackingStats) { incomingMessagesThreadTimeTracking.OnStopProcessing(); incomingMessagesThreadTimeTracking.IncrementNumberOfProcessed(); } #endif } if (StatisticsCollector.CollectThreadTimeTrackingStats) { incomingMessagesThreadTimeTracking.OnStopExecution(); } } private void DispatchToLocalObject(Message message) { LocalObjectData objectData; GuidId observerId = message.TargetObserverId; if (observerId == null) { logger.Error( ErrorCode.ProxyClient_OGC_TargetNotFound_2, String.Format("Did not find TargetObserverId header in the message = {0}. A request message to a client is expected to have an observerId.", message)); return; } if (localObjects.TryGetValue(observerId, out objectData)) this.InvokeLocalObjectAsync(objectData, message); else { logger.Error( ErrorCode.ProxyClient_OGC_TargetNotFound, String.Format( "Unexpected target grain in request: {0}. Message={1}", message.TargetGrain, message)); } } private void InvokeLocalObjectAsync(LocalObjectData objectData, Message message) { var obj = (IAddressable)objectData.LocalObject.Target; if (obj == null) { //// Remove from the dictionary record for the garbage collected object? But now we won't be able to detect invalid dispatch IDs anymore. logger.Warn(ErrorCode.Runtime_Error_100162, String.Format("Object associated with Observer ID {0} has been garbage collected. Deleting object reference and unregistering it. Message = {1}", objectData.ObserverId, message)); LocalObjectData ignore; // Try to remove. If it's not there, we don't care. localObjects.TryRemove(objectData.ObserverId, out ignore); return; } bool start; lock (objectData.Messages) { objectData.Messages.Enqueue(message); start = !objectData.Running; objectData.Running = true; } if (logger.IsVerbose) logger.Verbose("InvokeLocalObjectAsync {0} start {1}", message, start); if (start) { // we use Task.Run() to ensure that the message pump operates asynchronously // with respect to the current thread. see // http://channel9.msdn.com/Events/TechEd/Europe/2013/DEV-B317#fbid=aIWUq0ssW74 // at position 54:45. // // according to the information posted at: // http://stackoverflow.com/questions/12245935/is-task-factory-startnew-guaranteed-to-use-another-thread-than-the-calling-thr // this idiom is dependent upon the a TaskScheduler not implementing the // override QueueTask as task inlining (as opposed to queueing). this seems // implausible to the author, since none of the .NET schedulers do this and // it is considered bad form (the OrleansTaskScheduler does not do this). // // if, for some reason this doesn't hold true, we can guarantee what we // want by passing a placeholder continuation token into Task.StartNew() // instead. i.e.: // // return Task.StartNew(() => ..., new CancellationToken()); Func<Task> asyncFunc = async () => await this.LocalObjectMessagePumpAsync(objectData); Task.Run(asyncFunc).Ignore(); } } private async Task LocalObjectMessagePumpAsync(LocalObjectData objectData) { while (true) { try { Message message; lock (objectData.Messages) { if (objectData.Messages.Count == 0) { objectData.Running = false; break; } message = objectData.Messages.Dequeue(); } if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Invoke)) continue; RequestContext.ImportFromMessage(message); var request = (InvokeMethodRequest)message.BodyObject; var targetOb = (IAddressable)objectData.LocalObject.Target; object resultObject = null; Exception caught = null; try { // exceptions thrown within this scope are not considered to be thrown from user code // and not from runtime code. var resultPromise = objectData.Invoker.Invoke( targetOb, request.InterfaceId, request.MethodId, request.Arguments); if (resultPromise != null) // it will be null for one way messages { resultObject = await resultPromise; } } catch (Exception exc) { // the exception needs to be reported in the log or propagated back to the caller. caught = exc; } if (caught != null) this.ReportException(message, caught); else if (message.Direction != Message.Directions.OneWay) await this.SendResponseAsync(message, resultObject); }catch(Exception) { // ignore, keep looping. } } } private static bool ExpireMessageIfExpired(Message message, MessagingStatisticsGroup.Phase phase) { if (message.IsExpired) { message.DropExpiredMessage(phase); return true; } return false; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private Task SendResponseAsync( Message message, object resultObject) { if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Respond)) return TaskDone.Done; object deepCopy = null; try { // we're expected to notify the caller if the deep copy failed. deepCopy = SerializationManager.DeepCopy(resultObject); } catch (Exception exc2) { SendResponse(message, Response.ExceptionResponse(exc2)); logger.Warn( ErrorCode.ProxyClient_OGC_SendResponseFailed, "Exception trying to send a response.", exc2); return TaskDone.Done; } // the deep-copy succeeded. SendResponse(message, new Response(deepCopy)); return TaskDone.Done; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void ReportException(Message message, Exception exception) { var request = (InvokeMethodRequest)message.BodyObject; switch (message.Direction) { default: throw new InvalidOperationException(); case Message.Directions.OneWay: { logger.Error( ErrorCode.ProxyClient_OGC_UnhandledExceptionInOneWayInvoke, String.Format( "Exception during invocation of notification method {0}, interface {1}. Ignoring exception because this is a one way request.", request.MethodId, request.InterfaceId), exception); break; } case Message.Directions.Request: { Exception deepCopy = null; try { // we're expected to notify the caller if the deep copy failed. deepCopy = (Exception)SerializationManager.DeepCopy(exception); } catch (Exception ex2) { SendResponse(message, Response.ExceptionResponse(ex2)); logger.Warn( ErrorCode.ProxyClient_OGC_SendExceptionResponseFailed, "Exception trying to send an exception response", ex2); return; } // the deep-copy succeeded. var response = Response.ExceptionResponse(deepCopy); SendResponse(message, response); break; } } } private void SendResponse(Message request, Response response) { var message = request.CreateResponseMessage(); message.BodyObject = response; transport.SendMessage(message); } /// <summary> /// For testing only. /// </summary> public void Disconnect() { transport.Disconnect(); } /// <summary> /// For testing only. /// </summary> public void Reconnect() { transport.Reconnect(); } #region Implementation of IRuntimeClient [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "CallbackData is IDisposable but instances exist beyond lifetime of this method so cannot Dispose yet.")] public void SendRequest(GrainReference target, InvokeMethodRequest request, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null) { var message = RuntimeClient.CreateMessage(request, options); SendRequestMessage(target, message, context, callback, debugContext, options, genericArguments); } private void SendRequestMessage(GrainReference target, Message message, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null) { var targetGrainId = target.GrainId; var oneWay = (options & InvokeMethodOptions.OneWay) != 0; message.SendingGrain = CurrentActivationAddress.Grain; message.SendingActivation = CurrentActivationAddress.Activation; message.TargetGrain = targetGrainId; if (!String.IsNullOrEmpty(genericArguments)) message.GenericGrainType = genericArguments; if (targetGrainId.IsSystemTarget) { // If the silo isn't be supplied, it will be filled in by the sender to be the gateway silo message.TargetSilo = target.SystemTargetSilo; if (target.SystemTargetSilo != null) { message.TargetActivation = ActivationId.GetSystemActivation(targetGrainId, target.SystemTargetSilo); } } // Client sending messages to another client (observer). Yes, we support that. if (target.IsObserverReference) { message.TargetObserverId = target.ObserverId; } if (debugContext != null) { message.DebugContext = debugContext; } if (message.IsExpirableMessage(config)) { // don't set expiration for system target messages. message.Expiration = DateTime.UtcNow + responseTimeout + Constants.MAXIMUM_CLOCK_SKEW; } if (!oneWay) { var callbackData = new CallbackData(callback, TryResendMessage, context, message, () => UnRegisterCallback(message.Id)); callbacks.TryAdd(message.Id, callbackData); callbackData.StartTimer(responseTimeout); } if (logger.IsVerbose2) logger.Verbose2("Send {0}", message); transport.SendMessage(message); } private bool TryResendMessage(Message message) { if (!message.MayResend(config)) { return false; } if (logger.IsVerbose) logger.Verbose("Resend {0}", message); message.ResendCount = message.ResendCount + 1; message.SetMetadata(Message.Metadata.TARGET_HISTORY, message.GetTargetHistory()); if (!message.TargetGrain.IsSystemTarget) { message.RemoveHeader(Message.Header.TARGET_ACTIVATION); message.RemoveHeader(Message.Header.TARGET_SILO); } transport.SendMessage(message); return true; } public void ReceiveResponse(Message response) { if (logger.IsVerbose2) logger.Verbose2("Received {0}", response); // ignore duplicate requests if (response.Result == Message.ResponseTypes.Rejection && response.RejectionType == Message.RejectionTypes.DuplicateRequest) return; CallbackData callbackData; var found = callbacks.TryGetValue(response.Id, out callbackData); if (found) { callbackData.DoCallback(response); } else { logger.Warn(ErrorCode.Runtime_Error_100011, "No callback for response message: " + response); } } private void UnRegisterCallback(CorrelationId id) { CallbackData ignore; callbacks.TryRemove(id, out ignore); } public void Reset() { Utils.SafeExecute(() => { if (logger != null) { logger.Info("OutsideRuntimeClient.Reset(): client Id " + clientId); } }); Utils.SafeExecute(() => { if (clientProviderRuntime != null) { clientProviderRuntime.Reset().WaitWithThrow(resetTimeout); } }, logger, "Client.clientProviderRuntime.Reset"); Utils.SafeExecute(() => { if (StatisticsCollector.CollectThreadTimeTrackingStats) { incomingMessagesThreadTimeTracking.OnStopExecution(); } }, logger, "Client.incomingMessagesThreadTimeTracking.OnStopExecution"); Utils.SafeExecute(() => { if (transport != null) { transport.PrepareToStop(); } }, logger, "Client.PrepareToStop-Transport"); listenForMessages = false; Utils.SafeExecute(() => { if (listeningCts != null) { listeningCts.Cancel(); } }, logger, "Client.Stop-ListeningCTS"); Utils.SafeExecute(() => { if (transport != null) { transport.Stop(); } }, logger, "Client.Stop-Transport"); Utils.SafeExecute(() => { if (ClientStatistics != null) { ClientStatistics.Stop(); } }, logger, "Client.Stop-ClientStatistics"); ConstructorReset(); } private void ConstructorReset() { Utils.SafeExecute(() => { if (logger != null) { logger.Info("OutsideRuntimeClient.ConstructorReset(): client Id " + clientId); } }); try { UnobservedExceptionsHandlerClass.ResetUnobservedExceptionHandler(); } catch (Exception) { } try { if (clientProviderRuntime != null) { clientProviderRuntime.Reset().WaitWithThrow(resetTimeout); } } catch (Exception) { } try { TraceLogger.UnInitialize(); } catch (Exception) { } } public void SetResponseTimeout(TimeSpan timeout) { responseTimeout = timeout; } public TimeSpan GetResponseTimeout() { return responseTimeout; } public Task<IGrainReminder> RegisterOrUpdateReminder(string reminderName, TimeSpan dueTime, TimeSpan period) { throw new InvalidOperationException("RegisterReminder can only be called from inside a grain"); } public Task UnregisterReminder(IGrainReminder reminder) { throw new InvalidOperationException("UnregisterReminder can only be called from inside a grain"); } public Task<IGrainReminder> GetReminder(string reminderName) { throw new InvalidOperationException("GetReminder can only be called from inside a grain"); } public Task<List<IGrainReminder>> GetReminders() { throw new InvalidOperationException("GetReminders can only be called from inside a grain"); } public SiloStatus GetSiloStatus(SiloAddress silo) { throw new InvalidOperationException("GetSiloStatus can only be called on the silo."); } public async Task ExecAsync(Func<Task> asyncFunction, ISchedulingContext context) { await Task.Run(asyncFunction); // No grain context on client - run on .NET thread pool } public GrainReference CreateObjectReference(IAddressable obj, IGrainMethodInvoker invoker) { if (obj is GrainReference) throw new ArgumentException("Argument obj is already a grain reference."); GrainReference gr = GrainReference.NewObserverGrainReference(clientId, GuidId.GetNewGuidId()); if (!localObjects.TryAdd(gr.ObserverId, new LocalObjectData(obj, gr.ObserverId, invoker))) { throw new ArgumentException(String.Format("Failed to add new observer {0} to localObjects collection.", gr), "gr"); } return gr; } public void DeleteObjectReference(IAddressable obj) { if (!(obj is GrainReference)) throw new ArgumentException("Argument reference is not a grain reference."); var reference = (GrainReference) obj; LocalObjectData ignore; if (!localObjects.TryRemove(reference.ObserverId, out ignore)) throw new ArgumentException("Reference is not associated with a local object.", "reference"); } public void DeactivateOnIdle(ActivationId id) { throw new InvalidOperationException(); } #endregion private class LocalObjectData { internal WeakReference LocalObject { get; private set; } internal IGrainMethodInvoker Invoker { get; private set; } internal GuidId ObserverId { get; private set; } internal Queue<Message> Messages { get; private set; } internal bool Running { get; set; } internal LocalObjectData(IAddressable obj, GuidId observerId, IGrainMethodInvoker invoker) { LocalObject = new WeakReference(obj); ObserverId = observerId; Invoker = invoker; Messages = new Queue<Message>(); Running = false; } } public void Dispose() { if (listeningCts != null) { listeningCts.Dispose(); listeningCts = null; } GC.SuppressFinalize(this); } public IGrainTypeResolver GrainTypeResolver { get { return grainInterfaceMap; } } public string CaptureRuntimeEnvironment() { throw new NotImplementedException(); } public IGrainMethodInvoker GetInvoker(int interfaceId, string genericGrainType = null) { throw new NotImplementedException(); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using Avalonia.Controls.Presenters; using Avalonia.Controls.Templates; using Avalonia.Data; namespace Avalonia.Controls.Generators { /// <summary> /// Creates containers for items and maintains a list of created containers. /// </summary> public class ItemContainerGenerator : IItemContainerGenerator { private Dictionary<int, ItemContainerInfo> _containers = new Dictionary<int, ItemContainerInfo>(); /// <summary> /// Initializes a new instance of the <see cref="ItemContainerGenerator"/> class. /// </summary> /// <param name="owner">The owner control.</param> public ItemContainerGenerator(IControl owner) { Contract.Requires<ArgumentNullException>(owner != null); Owner = owner; } /// <inheritdoc/> public IEnumerable<ItemContainerInfo> Containers => _containers.Values; /// <inheritdoc/> public event EventHandler<ItemContainerEventArgs> Materialized; /// <inheritdoc/> public event EventHandler<ItemContainerEventArgs> Dematerialized; /// <inheritdoc/> public event EventHandler<ItemContainerEventArgs> Recycled; /// <summary> /// Gets or sets the data template used to display the items in the control. /// </summary> public IDataTemplate ItemTemplate { get; set; } /// <summary> /// Gets the owner control. /// </summary> public IControl Owner { get; } /// <inheritdoc/> public ItemContainerInfo Materialize( int index, object item, IMemberSelector selector) { var i = selector != null ? selector.Select(item) : item; var container = new ItemContainerInfo(CreateContainer(i), item, index); _containers.Add(container.Index, container); Materialized?.Invoke(this, new ItemContainerEventArgs(container)); return container; } /// <inheritdoc/> public virtual IEnumerable<ItemContainerInfo> Dematerialize(int startingIndex, int count) { var result = new List<ItemContainerInfo>(); for (int i = startingIndex; i < startingIndex + count; ++i) { result.Add(_containers[i]); _containers.Remove(i); } Dematerialized?.Invoke(this, new ItemContainerEventArgs(startingIndex, result)); return result; } /// <inheritdoc/> public virtual void InsertSpace(int index, int count) { if (count > 0) { var toMove = _containers.Where(x => x.Key >= index).ToList(); foreach (var i in toMove) { _containers.Remove(i.Key); i.Value.Index += count; _containers[i.Value.Index] = i.Value; } } } /// <inheritdoc/> public virtual IEnumerable<ItemContainerInfo> RemoveRange(int startingIndex, int count) { var result = new List<ItemContainerInfo>(); if (count > 0) { for (var i = startingIndex; i < startingIndex + count; ++i) { ItemContainerInfo found; if (_containers.TryGetValue(i, out found)) { result.Add(found); } _containers.Remove(i); } var toMove = _containers.Where(x => x.Key >= startingIndex).ToList(); foreach (var i in toMove) { _containers.Remove(i.Key); i.Value.Index -= count; _containers.Add(i.Value.Index, i.Value); } Dematerialized?.Invoke(this, new ItemContainerEventArgs(startingIndex, result)); } return result; } /// <inheritdoc/> public virtual bool TryRecycle( int oldIndex, int newIndex, object item, IMemberSelector selector) { return false; } /// <inheritdoc/> public virtual IEnumerable<ItemContainerInfo> Clear() { var result = Containers.ToList(); _containers.Clear(); if (result.Count > 0) { Dematerialized?.Invoke(this, new ItemContainerEventArgs(0, result)); } return result; } /// <inheritdoc/> public IControl ContainerFromIndex(int index) { ItemContainerInfo result; _containers.TryGetValue(index, out result); return result?.ContainerControl; } /// <inheritdoc/> public int IndexFromContainer(IControl container) { foreach (var i in _containers) { if (i.Value.ContainerControl == container) { return i.Key; } } return -1; } /// <summary> /// Creates the container for an item. /// </summary> /// <param name="item">The item.</param> /// <returns>The created container control.</returns> protected virtual IControl CreateContainer(object item) { var result = item as IControl; if (result == null) { result = new ContentPresenter(); result.SetValue(ContentPresenter.ContentProperty, item, BindingPriority.Style); if (ItemTemplate != null) { result.SetValue( ContentPresenter.ContentTemplateProperty, ItemTemplate, BindingPriority.TemplatedParent); } } return result; } /// <summary> /// Moves a container. /// </summary> /// <param name="oldIndex">The old index.</param> /// <param name="newIndex">The new index.</param> /// <param name="item">The new item.</param> /// <returns>The container info.</returns> protected ItemContainerInfo MoveContainer(int oldIndex, int newIndex, object item) { var container = _containers[oldIndex]; container.Index = newIndex; container.Item = item; _containers.Remove(oldIndex); _containers.Add(newIndex, container); return container; } /// <summary> /// Gets all containers with an index that fall within a range. /// </summary> /// <param name="index">The first index.</param> /// <param name="count">The number of elements in the range.</param> /// <returns>The containers.</returns> protected IEnumerable<ItemContainerInfo> GetContainerRange(int index, int count) { return _containers.Where(x => x.Key >= index && x.Key <= index + count).Select(x => x.Value); } /// <summary> /// Raises the <see cref="Recycled"/> event. /// </summary> /// <param name="e">The event args.</param> protected void RaiseRecycled(ItemContainerEventArgs e) { Recycled?.Invoke(this, e); } } }
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Collections.Generic; using System.Threading.Tasks; using System.IO; using System.Linq; using Newtonsoft.Json; namespace LwInfluxDb { /// <summary> /// The obvious implementation of ISeriesPoint. /// You may wish to write a more constrained version to more conveniently match your requirements. /// </summary> public class SeriesPoint : ISeriesPoint { public string Name { get; set; } public Dictionary<string, string> Tags { get; set; } public List<string> Fields { get; set; } public List<object> Values { get; set; } public DateTime? Timestamp { get; set; } } public interface ISeriesPoint { string Name { get; } Dictionary<string, string> Tags { get; } List<string> Fields { get; } List<object> Values { get; } DateTime? Timestamp { get; } } public class InfluxDb { private string _url; private string _credentials; public InfluxDb(string url, string db) { _url = url; if (!_url.EndsWith("/")) { _url = _url + "/"; } //_credentials = "?db=" + db + "&u=" + user + "&p=" + password; _credentials = "?db=" + db; Timeout = TimeSpan.FromSeconds(15); } public TimeSpan Timeout { get; set; } private static string SerializeWriteData(ISeriesPoint data) { if (data.Fields.Count != data.Values.Count) { throw new Exception("Invalid field series point - number of fields does not match number of values."); } var result = data.Name.Replace(",", "\\,").Replace(" ", "\\ "); if (data.Tags != null && data.Tags.Count > 0) { foreach (var kvp in data.Tags) { result += "," + kvp.Key + "=" + kvp.Value; } } result += " "; var separatorNeeded = false; for (int i = 0; i < data.Fields.Count; ++i) { string strRep; var value = data.Values[i]; if (value == null) { continue; } else if (value is double) { strRep = ((double)value).ToString(".0##############"); } else if (value is float) { strRep = ((float)value).ToString(".0######"); } else if (value is decimal || value is Int16 || value is Int32 || value is Int64 || value is UInt16 || value is UInt32 || value is UInt64) { strRep = string.Format("{0}", value); } else if (value is bool) { strRep = ((bool)value) ? "t" : "f"; } else { strRep = string.Format("\"{0}\"", string.Format("{0}", value).Replace("\"", "\\\"")); } if (separatorNeeded) { result += ","; } else { separatorNeeded = true; } result += data.Fields[i] + "=" + strRep; } if (data.Timestamp.HasValue) { result += string.Format(" {0}", ToUnixTimeNanoseconds(data.Timestamp.Value)); } return result; } public static long ToUnixTimeNanoseconds(DateTime date) { return (date.ToUniversalTime().Ticks - 621355968000000000) * 100; } public async Task WriteAsync(List<ISeriesPoint> data) { string s = ""; foreach (var d in data) { s += SerializeWriteData(d) + "\n"; } Console.WriteLine(s); await WriteAsync(s); } public async Task WriteAsync(ISeriesPoint data) { await WriteAsync(SerializeWriteData(data)); } private async Task WriteAsync(string data) { using (var client = new HttpClient()) { client.Timeout = Timeout; client.BaseAddress = new Uri(_url); client.DefaultRequestHeaders.Accept.Clear(); HttpResponseMessage response = await client.PostAsync("write" + _credentials, new StringContent(data)); if (!response.IsSuccessStatusCode) { throw new Exception( string.Format("Unable to write series point data. status: {0}, reason: {1}, result: {2}", response.StatusCode, response.ReasonPhrase, await response.Content.ReadAsStringAsync())); } } } public class QuerySeries { public string Name; public List<string> Columns; public List<List<object>> Values; } public async Task<List<List<object>>> QuerySingleSeriesAsync(string query) { var queryString = Uri.EscapeDataString(query); using (var client = new HttpClient()) { client.Timeout = Timeout; client.BaseAddress = new Uri(_url); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var url = "query" + _credentials + "&q=" + queryString; HttpResponseMessage response = await client.GetAsync(url); if (!response.IsSuccessStatusCode) { throw new Exception("unable to read series point data."); } using (var stream = await response.Content.ReadAsStreamAsync()) using (var sr = new StreamReader(stream)) { var result = JsonConvert.DeserializeObject<Dictionary<string, List<Dictionary<string, List<QuerySeries>>>>>(sr.ReadToEnd()); if (result.ContainsKey("results")) { if (result["results"].Count == 1) { if (result["results"][0].ContainsKey("series")) { if (result["results"][0]["series"].Count == 1) { return result["results"][0]["series"][0].Values; } } } } return null; } } } public async Task<List<List<List<object>>>> QueryMultipleSeriesAsync(string query) { var queryString = Uri.EscapeDataString(query); using (var client = new HttpClient()) { client.Timeout = Timeout; client.BaseAddress = new Uri(_url); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var url = "query" + _credentials + "&q=" + queryString; HttpResponseMessage response = await client.GetAsync(url); if (!response.IsSuccessStatusCode) { throw new Exception("unable to read series point data."); } using (var stream = await response.Content.ReadAsStreamAsync()) using (var sr = new StreamReader(stream)) { var result = JsonConvert.DeserializeObject<Dictionary<string, List<Dictionary<string, List<QuerySeries>>>>>(sr.ReadToEnd()); return result["results"][0]["series"].Select(a => a.Values).ToList(); } } } } }
/* * Copyright 2002-2015 Drew Noakes * * Modified by Yakov Danilov <yakodani@gmail.com> for Imazen LLC (Ported from Java to C#) * 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. * * More information about this project is available at: * * https://drewnoakes.com/code/exif/ * https://github.com/drewnoakes/metadata-extractor */ using System.IO; using JetBrains.Annotations; using Sharpen; namespace Com.Drew.Lang { /// <author>Drew Noakes https://drewnoakes.com</author> public abstract class SequentialReader { private bool _isMotorolaByteOrder = true; // TODO review whether the masks are needed (in both this and RandomAccessReader) /// <summary>Gets the next byte in the sequence.</summary> /// <returns>The read byte value</returns> /// <exception cref="System.IO.IOException"/> protected internal abstract sbyte GetByte(); /// <summary>Returns the required number of bytes from the sequence.</summary> /// <param name="count">The number of bytes to be returned</param> /// <returns>The requested bytes</returns> /// <exception cref="System.IO.IOException"/> [NotNull] public abstract sbyte[] GetBytes(int count); /// <summary>Skips forward in the sequence.</summary> /// <remarks> /// Skips forward in the sequence. If the sequence ends, an /// <see cref="System.IO.EOFException"/> /// is thrown. /// </remarks> /// <param name="n">the number of byte to skip. Must be zero or greater.</param> /// <exception cref="System.IO.EOFException">the end of the sequence is reached.</exception> /// <exception cref="System.IO.IOException">an error occurred reading from the underlying source.</exception> public abstract void Skip(long n); /// <summary>Skips forward in the sequence, returning a boolean indicating whether the skip succeeded, or whether the sequence ended.</summary> /// <param name="n">the number of byte to skip. Must be zero or greater.</param> /// <returns>a boolean indicating whether the skip succeeded, or whether the sequence ended.</returns> /// <exception cref="System.IO.IOException">an error occurred reading from the underlying source.</exception> public abstract bool TrySkip(long n); /// <summary>Sets the endianness of this reader.</summary> /// <remarks> /// Sets the endianness of this reader. /// <ul> /// <li><code>true</code> for Motorola (or big) endianness (also known as network byte order), with MSB before LSB.</li> /// <li><code>false</code> for Intel (or little) endianness, with LSB before MSB.</li> /// </ul> /// </remarks> /// <param name="motorolaByteOrder"><code>true</code> for Motorola/big endian, <code>false</code> for Intel/little endian</param> public virtual void SetMotorolaByteOrder(bool motorolaByteOrder) { _isMotorolaByteOrder = motorolaByteOrder; } /// <summary>Gets the endianness of this reader.</summary> /// <remarks> /// Gets the endianness of this reader. /// <ul> /// <li><code>true</code> for Motorola (or big) endianness (also known as network byte order), with MSB before LSB.</li> /// <li><code>false</code> for Intel (or little) endianness, with LSB before MSB.</li> /// </ul> /// </remarks> public virtual bool IsMotorolaByteOrder() { return _isMotorolaByteOrder; } /// <summary>Returns an unsigned 8-bit int calculated from the next byte of the sequence.</summary> /// <returns>the 8 bit int value, between 0 and 255</returns> /// <exception cref="System.IO.IOException"/> public virtual short GetUInt8() { return (short)(GetByte() & unchecked((int)(0xFF))); } /// <summary>Returns a signed 8-bit int calculated from the next byte the sequence.</summary> /// <returns>the 8 bit int value, between 0x00 and 0xFF</returns> /// <exception cref="System.IO.IOException"/> public virtual sbyte GetInt8() { return GetByte(); } /// <summary>Returns an unsigned 16-bit int calculated from the next two bytes of the sequence.</summary> /// <returns>the 16 bit int value, between 0x0000 and 0xFFFF</returns> /// <exception cref="System.IO.IOException"/> public virtual int GetUInt16() { if (_isMotorolaByteOrder) { // Motorola - MSB first return (GetByte() << 8 & unchecked((int)(0xFF00))) | (GetByte() & unchecked((int)(0xFF))); } else { // Intel ordering - LSB first return (GetByte() & unchecked((int)(0xFF))) | (GetByte() << 8 & unchecked((int)(0xFF00))); } } /// <summary>Returns a signed 16-bit int calculated from two bytes of data (MSB, LSB).</summary> /// <returns>the 16 bit int value, between 0x0000 and 0xFFFF</returns> /// <exception cref="System.IO.IOException">the buffer does not contain enough bytes to service the request</exception> public virtual short GetInt16() { if (_isMotorolaByteOrder) { // Motorola - MSB first return (short)(((short)GetByte() << 8 & unchecked((short)(0xFF00))) | ((short)GetByte() & (short)0xFF)); } else { // Intel ordering - LSB first return (short)(((short)GetByte() & (short)0xFF) | ((short)GetByte() << 8 & unchecked((short)(0xFF00)))); } } /// <summary>Get a 32-bit unsigned integer from the buffer, returning it as a long.</summary> /// <returns>the unsigned 32-bit int value as a long, between 0x00000000 and 0xFFFFFFFF</returns> /// <exception cref="System.IO.IOException">the buffer does not contain enough bytes to service the request</exception> public virtual long GetUInt32() { if (_isMotorolaByteOrder) { // Motorola - MSB first (big endian) return (((long)GetByte()) << 24 & unchecked((long)(0xFF000000L))) | (((long)GetByte()) << 16 & unchecked((long)(0xFF0000L))) | (((long)GetByte()) << 8 & unchecked((long)(0xFF00L))) | (((long)GetByte()) & unchecked((long)(0xFFL))); } else { // Intel ordering - LSB first (little endian) return (((long)GetByte()) & unchecked((long)(0xFFL))) | (((long)GetByte()) << 8 & unchecked((long)(0xFF00L))) | (((long)GetByte()) << 16 & unchecked((long)(0xFF0000L))) | (((long)GetByte()) << 24 & unchecked((long)(0xFF000000L))); } } /// <summary>Returns a signed 32-bit integer from four bytes of data.</summary> /// <returns>the signed 32 bit int value, between 0x00000000 and 0xFFFFFFFF</returns> /// <exception cref="System.IO.IOException">the buffer does not contain enough bytes to service the request</exception> public virtual int GetInt32() { if (_isMotorolaByteOrder) { // Motorola - MSB first (big endian) return (GetByte() << 24 & unchecked((int)(0xFF000000))) | (GetByte() << 16 & unchecked((int)(0xFF0000))) | (GetByte() << 8 & unchecked((int)(0xFF00))) | (GetByte() & unchecked((int)(0xFF))); } else { // Intel ordering - LSB first (little endian) return (GetByte() & unchecked((int)(0xFF))) | (GetByte() << 8 & unchecked((int)(0xFF00))) | (GetByte() << 16 & unchecked((int)(0xFF0000))) | (GetByte() << 24 & unchecked((int)(0xFF000000))); } } /// <summary>Get a signed 64-bit integer from the buffer.</summary> /// <returns>the 64 bit int value, between 0x0000000000000000 and 0xFFFFFFFFFFFFFFFF</returns> /// <exception cref="System.IO.IOException">the buffer does not contain enough bytes to service the request</exception> public virtual long GetInt64() { if (_isMotorolaByteOrder) { // Motorola - MSB first return ((long)GetByte() << 56 & unchecked((long)(0xFF00000000000000L))) | ((long)GetByte() << 48 & unchecked((long)(0xFF000000000000L))) | ((long)GetByte() << 40 & unchecked((long)(0xFF0000000000L))) | ((long)GetByte() << 32 & unchecked((long )(0xFF00000000L))) | ((long)GetByte() << 24 & unchecked((long)(0xFF000000L))) | ((long)GetByte() << 16 & unchecked((long)(0xFF0000L))) | ((long)GetByte() << 8 & unchecked((long)(0xFF00L))) | ((long)GetByte() & unchecked((long)(0xFFL))); } else { // Intel ordering - LSB first return ((long)GetByte() & unchecked((long)(0xFFL))) | ((long)GetByte() << 8 & unchecked((long)(0xFF00L))) | ((long)GetByte() << 16 & unchecked((long)(0xFF0000L))) | ((long)GetByte() << 24 & unchecked((long)(0xFF000000L))) | ((long)GetByte() << 32 & unchecked((long)(0xFF00000000L))) | ((long)GetByte() << 40 & unchecked((long)(0xFF0000000000L))) | ((long)GetByte() << 48 & unchecked((long)(0xFF000000000000L))) | ((long)GetByte() << 56 & unchecked((long)(0xFF00000000000000L))); } } /// <summary>Gets a s15.16 fixed point float from the buffer.</summary> /// <remarks> /// Gets a s15.16 fixed point float from the buffer. /// <p> /// This particular fixed point encoding has one sign bit, 15 numerator bits and 16 denominator bits. /// </remarks> /// <returns>the floating point value</returns> /// <exception cref="System.IO.IOException">the buffer does not contain enough bytes to service the request</exception> public virtual float GetS15Fixed16() { if (_isMotorolaByteOrder) { float res = (GetByte() & unchecked((int)(0xFF))) << 8 | (GetByte() & unchecked((int)(0xFF))); int d = (GetByte() & unchecked((int)(0xFF))) << 8 | (GetByte() & unchecked((int)(0xFF))); return (float)(res + d / 65536.0); } else { // this particular branch is untested int d = (GetByte() & unchecked((int)(0xFF))) | (GetByte() & unchecked((int)(0xFF))) << 8; float res = (GetByte() & unchecked((int)(0xFF))) | (GetByte() & unchecked((int)(0xFF))) << 8; return (float)(res + d / 65536.0); } } /// <exception cref="System.IO.IOException"/> public virtual float GetFloat32() { return Sharpen.Extensions.IntBitsToFloat(GetInt32()); } /// <exception cref="System.IO.IOException"/> public virtual double GetDouble64() { return Sharpen.Extensions.LongBitsToDouble(GetInt64()); } /// <exception cref="System.IO.IOException"/> [NotNull] public virtual string GetString(int bytesRequested) { return Sharpen.Runtime.GetStringForBytes(GetBytes(bytesRequested)); } /// <exception cref="System.IO.IOException"/> [NotNull] public virtual string GetString(int bytesRequested, string charset) { sbyte[] bytes = GetBytes(bytesRequested); try { return Sharpen.Runtime.GetStringForBytes(bytes, charset); } catch (UnsupportedEncodingException) { return Sharpen.Runtime.GetStringForBytes(bytes); } } /// <summary>Creates a String from the stream, ending where <code>byte=='\0'</code> or where <code>length==maxLength</code>.</summary> /// <param name="maxLengthBytes"> /// The maximum number of bytes to read. If a zero-byte is not reached within this limit, /// reading will stop and the string will be truncated to this length. /// </param> /// <returns>The read string.</returns> /// <exception cref="System.IO.IOException">The buffer does not contain enough bytes to satisfy this request.</exception> [NotNull] public virtual string GetNullTerminatedString(int maxLengthBytes) { // NOTE currently only really suited to single-byte character strings sbyte[] bytes = new sbyte[maxLengthBytes]; // Count the number of non-null bytes int length = 0; while (length < bytes.Length && (bytes[length] = GetByte()) != '\0') { length++; } return Sharpen.Runtime.GetStringForBytes(bytes, 0, length); } } }
/* * TestDelegate.cs - Tests for the "Delegate" class. * * Copyright (C) 2004 Southern Storm Software, Pty Ltd. * * Contributors: Thong Nguyen (tum@veridicus.com) * * 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 */ using CSUnit; using System; using System.Threading; public class TestDelegate : TestCase { // Constructor. public TestDelegate(String name) : base(name) { // Nothing to do here. } // Set up for the tests. protected override void Setup() { // Nothing to do here. } // Clean up after the tests. protected override void Cleanup() { // Nothing to do here. } /* * Test async calls with objects. */ private delegate object ObjectMethod(object x, object y); private object ObjectAdd(object x, object y) { return (int)x + (int)y; } public void TestAsyncCallWithObjects() { int result; IAsyncResult ar; ObjectMethod m = new ObjectMethod(ObjectAdd); ar = m.BeginInvoke(10, 20, null, null); result = (int)m.EndInvoke(ar); AssertEquals("result==30", 30, result); } /* * Test async calls with objects byref. */ private delegate object ObjectByRefMethod(ref object x, ref object y); private object ObjectByRefAdd(ref object x, ref object y) { object tmp; tmp = x; x = y; y = tmp; return (int)x + (int)y; } public void TestAsyncCallWithObjectsByRef() { int result; object x, y, x2, y2; IAsyncResult ar; ObjectByRefMethod m = new ObjectByRefMethod(ObjectByRefAdd); x = 10; y = 20; x2 = x; y2 = y; ar = m.BeginInvoke(ref x, ref y, null, null); result = (int)m.EndInvoke(ref x, ref y, ar); Assert("x==y2", Object.ReferenceEquals(x, y2)); Assert("y==x2", Object.ReferenceEquals(y, x2)); AssertEquals("result==30", 30, result); } /* * Test async calls with ints. */ private delegate int IntMethod(int x, int y); private int IntAdd(int x, int y) { return x + y; } public void TestAsyncCallWithInts() { int result; IAsyncResult ar; IntMethod m = new IntMethod(IntAdd); ar = m.BeginInvoke(10, 20, null, null); result = m.EndInvoke(ar); AssertEquals("result==30", 30, result); } /* * Test async calls with ints byref. */ private delegate int IntByRefMethod(ref int x, ref int y); private int IntByRefAdd(ref int x, ref int y) { int tmp; tmp = x; x = y; y = tmp; return x + y; } public void TestAsyncCallWithIntsByRef() { int x, y, result; IAsyncResult ar; IntByRefMethod m = new IntByRefMethod(IntByRefAdd); x = 10; y = 20; ar = m.BeginInvoke(ref x, ref y, null, null); result = m.EndInvoke(ref x, ref y, ar); AssertEquals("x==20", 20, x); AssertEquals("y==10", 10, y); AssertEquals("result==30", 30, result); } /* * Test async calls with double results. */ private delegate double DoubleMethod(double x, double y); private double DoubleAdd(double x, double y) { return x + y; } public void TestAsyncCallWithDoubles() { double result; IAsyncResult ar; DoubleMethod m = new DoubleMethod(DoubleAdd); ar = m.BeginInvoke(10, 20, null, null); result = m.EndInvoke(ar); AssertEquals("result==30", (double)30, result); } /* * Test async calls with doubles byref. */ private delegate double DoubleByRefMethod(ref double x, ref double y); private double DoubleByRefAdd(ref double x, ref double y) { double tmp; tmp = x; x = y; y = tmp; return x + y; } public void TestAsyncCallWithDoublesByRef() { double x, y, result; IAsyncResult ar; DoubleByRefMethod m = new DoubleByRefMethod(DoubleByRefAdd); x = 10; y = 20; ar = m.BeginInvoke(ref x, ref y, null, null); result = m.EndInvoke(ref x, ref y, ar); AssertEquals("x==20", (double)20, x); AssertEquals("y==10", (double)10, y); AssertEquals("result==30", (double)30, result); } /* * Test async calls with custom valuetype results. */ private delegate Point PointMethod(Point x, Point y); public struct Point { public int X; public int Y; public Point(int x, int y) { this.X = x; this.Y = y; } } private Point PointAdd(Point x, Point y) { return new Point(x.X + y.X, x.Y + y.Y); } public void TestAsyncCallWithValueTypes() { Point result; IAsyncResult ar; PointMethod m = new PointMethod(PointAdd); ar = m.BeginInvoke(new Point(10, 20), new Point(30, 40), null, null); result = m.EndInvoke(ar); AssertEquals("result==Point(40, 60)", new Point(40, 60), result); } /* * Test async calls with custom valuetypes byref. */ private delegate Point PointByRefMethod(ref Point x, ref Point y); private Point PointByRefAdd(ref Point x, ref Point y) { Point tmp; tmp = x; x = y; y = tmp; return new Point(x.X + y.X, x.Y + y.Y); } public void TestAsyncCallWithValueTypesByRef() { Point x, y, result; IAsyncResult ar; PointByRefMethod m = new PointByRefMethod(PointByRefAdd); x = new Point(10, 20); y = new Point(30, 40); ar = m.BeginInvoke(ref x, ref y, null, null); result = m.EndInvoke(ref x, ref y, ar); AssertEquals("x=(30,40)", new Point(30, 40), x); AssertEquals("y=(10,20)", new Point(10, 20), y); AssertEquals("result==Point(40, 60)", new Point(40, 60), result); } }; // class TestArray
/* * Exchange Web Services Managed API * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * 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. */ namespace Microsoft.Exchange.WebServices.Autodiscover { using System; using System.Collections.Generic; using System.Linq; using Microsoft.Exchange.WebServices.Data; /// <summary> /// Represents Outlook configuration settings. /// </summary> internal sealed class OutlookConfigurationSettings : ConfigurationSettingsBase { #region Static fields /// <summary> /// All user settings that are available from the Outlook provider. /// </summary> private static LazyMember<List<UserSettingName>> allOutlookProviderSettings = new LazyMember<List<UserSettingName>>( () => { List<UserSettingName> results = new List<UserSettingName>(); results.AddRange(OutlookUser.AvailableUserSettings); results.AddRange(OutlookProtocol.AvailableUserSettings); results.Add(UserSettingName.AlternateMailboxes); return results; }); #endregion #region Private fields private OutlookUser user; private OutlookAccount account; #endregion /// <summary> /// Initializes a new instance of the <see cref="OutlookConfigurationSettings"/> class. /// </summary> public OutlookConfigurationSettings() { this.user = new OutlookUser(); this.account = new OutlookAccount(); } /// <summary> /// Determines whether user setting is available in the OutlookConfiguration or not. /// </summary> /// <param name="setting">The setting.</param> /// <returns>True if user setting is available, otherwise, false. /// </returns> internal static bool IsAvailableUserSetting(UserSettingName setting) { return allOutlookProviderSettings.Member.Contains(setting); } /// <summary> /// Gets the namespace that defines the settings. /// </summary> /// <returns>The namespace that defines the settings.</returns> internal override string GetNamespace() { return "http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a"; } /// <summary> /// Makes this instance a redirection response. /// </summary> /// <param name="redirectUrl">The redirect URL.</param> internal override void MakeRedirectionResponse(Uri redirectUrl) { this.account = new OutlookAccount() { RedirectTarget = redirectUrl.ToString(), ResponseType = AutodiscoverResponseType.RedirectUrl }; } /// <summary> /// Tries to read the current XML element. /// </summary> /// <param name="reader">The reader.</param> /// <returns>True is the current element was read, false otherwise.</returns> internal override bool TryReadCurrentXmlElement(EwsXmlReader reader) { if (!base.TryReadCurrentXmlElement(reader)) { switch (reader.LocalName) { case XmlElementNames.User: this.user.LoadFromXml(reader); return true; case XmlElementNames.Account: this.account.LoadFromXml(reader); return true; default: reader.SkipCurrentElement(); return false; } } else { return true; } } /// <summary> /// Convert OutlookConfigurationSettings to GetUserSettings response. /// </summary> /// <param name="smtpAddress">SMTP address requested.</param> /// <param name="requestedSettings">The requested settings.</param> /// <returns>GetUserSettingsResponse</returns> internal override GetUserSettingsResponse ConvertSettings(string smtpAddress, List<UserSettingName> requestedSettings) { GetUserSettingsResponse response = new GetUserSettingsResponse(); response.SmtpAddress = smtpAddress; if (this.Error != null) { response.ErrorCode = AutodiscoverErrorCode.InternalServerError; response.ErrorMessage = this.Error.Message; } else { switch (this.ResponseType) { case AutodiscoverResponseType.Success: response.ErrorCode = AutodiscoverErrorCode.NoError; response.ErrorMessage = string.Empty; this.user.ConvertToUserSettings(requestedSettings, response); this.account.ConvertToUserSettings(requestedSettings, response); this.ReportUnsupportedSettings(requestedSettings, response); break; case AutodiscoverResponseType.Error: response.ErrorCode = AutodiscoverErrorCode.InternalServerError; response.ErrorMessage = Strings.InvalidAutodiscoverServiceResponse; break; case AutodiscoverResponseType.RedirectAddress: response.ErrorCode = AutodiscoverErrorCode.RedirectAddress; response.ErrorMessage = string.Empty; response.RedirectTarget = this.RedirectTarget; break; case AutodiscoverResponseType.RedirectUrl: response.ErrorCode = AutodiscoverErrorCode.RedirectUrl; response.ErrorMessage = string.Empty; response.RedirectTarget = this.RedirectTarget; break; default: EwsUtilities.Assert( false, "OutlookConfigurationSettings.ConvertSettings", "An unexpected error has occured. This code path should never be reached."); break; } } return response; } /// <summary> /// Reports any requested user settings that aren't supported by the Outlook provider. /// </summary> /// <param name="requestedSettings">The requested settings.</param> /// <param name="response">The response.</param> private void ReportUnsupportedSettings(List<UserSettingName> requestedSettings, GetUserSettingsResponse response) { // In English: find settings listed in requestedSettings that are not supported by the Legacy provider. IEnumerable<UserSettingName> invalidSettingQuery = from setting in requestedSettings where !OutlookConfigurationSettings.IsAvailableUserSetting(setting) select setting; // Add any unsupported settings to the UserSettingsError collection. foreach (UserSettingName invalidSetting in invalidSettingQuery) { UserSettingError settingError = new UserSettingError() { ErrorCode = AutodiscoverErrorCode.InvalidSetting, SettingName = invalidSetting.ToString(), ErrorMessage = string.Format(Strings.AutodiscoverInvalidSettingForOutlookProvider, invalidSetting.ToString()) }; response.UserSettingErrors.Add(settingError); } } /// <summary> /// Gets the type of the response. /// </summary> /// <value>The type of the response.</value> internal override AutodiscoverResponseType ResponseType { get { if (this.account != null) { return this.account.ResponseType; } else { return AutodiscoverResponseType.Error; } } } /// <summary> /// Gets the redirect target. /// </summary> internal override string RedirectTarget { get { return this.account.RedirectTarget; } } } }
// 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 Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { ///////////////////////////////////////////////////////////////////////////////// // Defines the structure used when binding types // CheckConstraints options. internal enum CheckConstraintsFlags { None = 0x00, Outer = 0x01, NoDupErrors = 0x02, NoErrors = 0x04, } ///////////////////////////////////////////////////////////////////////////////// // TypeBind has static methods to accomplish most tasks. // // For some of these tasks there are also instance methods. The instance // method versions don't report not found errors (they may report others) but // instead record error information in the TypeBind instance. Call the // ReportErrors method to report recorded errors. internal static class TypeBind { // Check the constraints of any type arguments in the given Type. public static bool CheckConstraints(CSemanticChecker checker, ErrorHandling errHandling, CType type, CheckConstraintsFlags flags) { type = type.GetNakedType(false); if (type.IsNullableType()) { CType typeT = type.AsNullableType().GetAts(checker.GetErrorContext()); if (typeT != null) type = typeT; else type = type.GetNakedType(true); } if (!type.IsAggregateType()) return true; AggregateType ats = type.AsAggregateType(); if (ats.GetTypeArgsAll().size == 0) { // Common case: there are no type vars, so there are no constraints. ats.fConstraintsChecked = true; ats.fConstraintError = false; return true; } if (ats.fConstraintsChecked) { // Already checked. if (!ats.fConstraintError || (flags & CheckConstraintsFlags.NoDupErrors) != 0) { // No errors or no need to report errors again. return !ats.fConstraintError; } } TypeArray typeVars = ats.getAggregate().GetTypeVars(); TypeArray typeArgsThis = ats.GetTypeArgsThis(); TypeArray typeArgsAll = ats.GetTypeArgsAll(); Debug.Assert(typeVars.size == typeArgsThis.size); if (!ats.fConstraintsChecked) { ats.fConstraintsChecked = true; ats.fConstraintError = false; } // Check the outer type first. If CheckConstraintsFlags.Outer is not specified and the // outer type has already been checked then don't bother checking it. if (ats.outerType != null && ((flags & CheckConstraintsFlags.Outer) != 0 || !ats.outerType.fConstraintsChecked)) { CheckConstraints(checker, errHandling, ats.outerType, flags); ats.fConstraintError |= ats.outerType.fConstraintError; } if (typeVars.size > 0) ats.fConstraintError |= !CheckConstraintsCore(checker, errHandling, ats.getAggregate(), typeVars, typeArgsThis, typeArgsAll, null, (flags & CheckConstraintsFlags.NoErrors)); // Now check type args themselves. for (int i = 0; i < typeArgsThis.size; i++) { CType arg = typeArgsThis.Item(i).GetNakedType(true); if (arg.IsAggregateType() && !arg.AsAggregateType().fConstraintsChecked) { CheckConstraints(checker, errHandling, arg.AsAggregateType(), flags | CheckConstraintsFlags.Outer); if (arg.AsAggregateType().fConstraintError) ats.fConstraintError = true; } } return !ats.fConstraintError; } //////////////////////////////////////////////////////////////////////////////// // Check the constraints on the method instantiation. public static void CheckMethConstraints(CSemanticChecker checker, ErrorHandling errCtx, MethWithInst mwi) { Debug.Assert(mwi.Meth() != null && mwi.GetType() != null && mwi.TypeArgs != null); Debug.Assert(mwi.Meth().typeVars.size == mwi.TypeArgs.size); Debug.Assert(mwi.GetType().getAggregate() == mwi.Meth().getClass()); if (mwi.TypeArgs.size > 0) { CheckConstraintsCore(checker, errCtx, mwi.Meth(), mwi.Meth().typeVars, mwi.TypeArgs, mwi.GetType().GetTypeArgsAll(), mwi.TypeArgs, CheckConstraintsFlags.None); } } //////////////////////////////////////////////////////////////////////////////// // Check whether typeArgs satisfies the constraints of typeVars. The // typeArgsCls and typeArgsMeth are used for substitution on the bounds. The // tree and symErr are used for error reporting. private static bool CheckConstraintsCore(CSemanticChecker checker, ErrorHandling errHandling, Symbol symErr, TypeArray typeVars, TypeArray typeArgs, TypeArray typeArgsCls, TypeArray typeArgsMeth, CheckConstraintsFlags flags) { Debug.Assert(typeVars.size == typeArgs.size); Debug.Assert(typeVars.size > 0); Debug.Assert(flags == CheckConstraintsFlags.None || flags == CheckConstraintsFlags.NoErrors); bool fError = false; for (int i = 0; i < typeVars.size; i++) { // Empty bounds should be set to object. TypeParameterType var = typeVars.ItemAsTypeParameterType(i); CType arg = typeArgs.Item(i); bool fOK = CheckSingleConstraint(checker, errHandling, symErr, var, arg, typeArgsCls, typeArgsMeth, flags); fError |= !fOK; } return !fError; } private static bool CheckSingleConstraint(CSemanticChecker checker, ErrorHandling errHandling, Symbol symErr, TypeParameterType var, CType arg, TypeArray typeArgsCls, TypeArray typeArgsMeth, CheckConstraintsFlags flags) { bool fReportErrors = 0 == (flags & CheckConstraintsFlags.NoErrors); if (arg.IsOpenTypePlaceholderType()) { return true; } if (arg.IsErrorType()) { // Error should have been reported previously. return false; } if (checker.CheckBogus(arg)) { if (fReportErrors) { errHandling.ErrorRef(ErrorCode.ERR_BogusType, arg); } return false; } if (arg.IsPointerType() || arg.isSpecialByRefType()) { if (fReportErrors) { errHandling.Error(ErrorCode.ERR_BadTypeArgument, arg); } return false; } if (arg.isStaticClass()) { if (fReportErrors) { checker.ReportStaticClassError(null, arg, ErrorCode.ERR_GenericArgIsStaticClass); } return false; } bool fError = false; if (var.HasRefConstraint() && !arg.IsRefType()) { if (fReportErrors) { errHandling.ErrorRef(ErrorCode.ERR_RefConstraintNotSatisfied, symErr, new ErrArgNoRef(var), arg); } fError = true; } TypeArray bnds = checker.GetSymbolLoader().GetTypeManager().SubstTypeArray(var.GetBounds(), typeArgsCls, typeArgsMeth); int itypeMin = 0; if (var.HasValConstraint()) { // If we have a type variable that is constrained to a value type, then we // want to check if its a nullable type, so that we can report the // constraint error below. In order to do this however, we need to check // that either the type arg is not a value type, or it is a nullable type. // // To check whether or not its a nullable type, we need to get the resolved // bound from the type argument and check against that. bool bIsValueType = arg.IsValType(); bool bIsNullable = arg.IsNullableType(); if (bIsValueType && arg.IsTypeParameterType()) { TypeArray pArgBnds = arg.AsTypeParameterType().GetBounds(); if (pArgBnds.size > 0) { bIsNullable = pArgBnds.Item(0).IsNullableType(); } } if (!bIsValueType || bIsNullable) { if (fReportErrors) { errHandling.ErrorRef(ErrorCode.ERR_ValConstraintNotSatisfied, symErr, new ErrArgNoRef(var), arg); } fError = true; } // Since FValCon() is set it is redundant to check System.ValueType as well. if (bnds.size != 0 && bnds.Item(0).isPredefType(PredefinedType.PT_VALUE)) { itypeMin = 1; } } for (int j = itypeMin; j < bnds.size; j++) { CType typeBnd = bnds.Item(j); if (!SatisfiesBound(checker, arg, typeBnd)) { if (fReportErrors) { // The bound isn't satisfied because of a constaint type. Explain to the user why not. // There are 4 main cases, based on the type of the supplied type argument: // - reference type, or type parameter known to be a reference type // - nullable type, from which there is a boxing conversion to the constraint type(see below for details) // - type varaiable // - value type // These cases are broken out because: a) The sets of conversions which can be used // for constraint satisfaction is different based on the type argument supplied, // and b) Nullable is one funky type, and user's can use all the help they can get // when using it. ErrorCode error; if (arg.IsRefType()) { // A reference type can only satisfy bounds to types // to which they have an implicit reference conversion error = ErrorCode.ERR_GenericConstraintNotSatisfiedRefType; } else if (arg.IsNullableType() && checker.GetSymbolLoader().HasBaseConversion(arg.AsNullableType().GetUnderlyingType(), typeBnd)) // This is inlining FBoxingConv { // nullable types do not satisfy bounds to every type that they are boxable to // They only satisfy bounds of object and ValueType if (typeBnd.isPredefType(PredefinedType.PT_ENUM) || arg.AsNullableType().GetUnderlyingType() == typeBnd) { // Nullable types don't satisfy bounds of EnumType, or the underlying type of the enum // even though the conversion from Nullable to these types is a boxing conversion // This is a rare case, because these bounds can never be directly stated ... // These bounds can only occur when one type paramter is constrained to a second type parameter // and the second type parameter is instantiated with Enum or the underlying type of the first type // parameter error = ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum; } else { // Nullable types don't satisfy the bounds of any interface type // even when there is a boxing conversion from the Nullable type to // the interface type. This will be a relatively common scenario // so we cal it out separately from the previous case. Debug.Assert(typeBnd.isInterfaceType()); error = ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface; } } else if (arg.IsTypeParameterType()) { // Type variables can satisfy bounds through boxing and type variable conversions Debug.Assert(!arg.IsRefType()); error = ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar; } else { // Value types can only satisfy bounds through boxing conversions. // Note that the exceptional case of Nullable types and boxing is handled above. error = ErrorCode.ERR_GenericConstraintNotSatisfiedValType; } errHandling.Error(error, new ErrArgRef(symErr), new ErrArg(typeBnd, ErrArgFlags.Unique), var, new ErrArgRef(arg, ErrArgFlags.Unique)); } fError = true; } } // Check the newable constraint. if (!var.HasNewConstraint() || arg.IsValType()) { return !fError; } if (arg.isClassType()) { AggregateSymbol agg = arg.AsAggregateType().getAggregate(); // Due to late binding nature of IDE created symbols, the AggregateSymbol might not // have all the information necessary yet, if it is not fully bound. // by calling LookupAggMember, it will ensure that we will update all the // information necessary at least for the given method. checker.GetSymbolLoader().LookupAggMember(checker.GetNameManager().GetPredefName(PredefinedName.PN_CTOR), agg, symbmask_t.MASK_ALL); if (agg.HasPubNoArgCtor() && !agg.IsAbstract()) { return !fError; } } else if (arg.IsTypeParameterType() && arg.AsTypeParameterType().HasNewConstraint()) { return !fError; } if (fReportErrors) { errHandling.ErrorRef(ErrorCode.ERR_NewConstraintNotSatisfied, symErr, new ErrArgNoRef(var), arg); } return false; } //////////////////////////////////////////////////////////////////////////////// // Determine whether the arg type satisfies the typeBnd constraint. Note that // typeBnd could be just about any type (since we added naked type parameter // constraints). private static bool SatisfiesBound(CSemanticChecker checker, CType arg, CType typeBnd) { if (typeBnd == arg) return true; switch (typeBnd.GetTypeKind()) { default: Debug.Assert(false, "Unexpected type."); return false; case TypeKind.TK_VoidType: case TypeKind.TK_PointerType: case TypeKind.TK_ErrorType: return false; case TypeKind.TK_ArrayType: case TypeKind.TK_TypeParameterType: break; case TypeKind.TK_NullableType: typeBnd = typeBnd.AsNullableType().GetAts(checker.GetErrorContext()); if (null == typeBnd) return true; break; case TypeKind.TK_AggregateType: break; } Debug.Assert(typeBnd.IsAggregateType() || typeBnd.IsTypeParameterType() || typeBnd.IsArrayType()); switch (arg.GetTypeKind()) { default: return false; case TypeKind.TK_ErrorType: case TypeKind.TK_PointerType: return false; case TypeKind.TK_NullableType: arg = arg.AsNullableType().GetAts(checker.GetErrorContext()); if (null == arg) return true; // Fall through. goto case TypeKind.TK_TypeParameterType; case TypeKind.TK_TypeParameterType: case TypeKind.TK_ArrayType: case TypeKind.TK_AggregateType: return checker.GetSymbolLoader().HasBaseConversion(arg, typeBnd); } } } }
using System; using System.Diagnostics; using Lucene.Net.Documents; namespace Lucene.Net.Search { using NUnit.Framework; using AttributeSource = Lucene.Net.Util.AttributeSource; using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using DirectoryReader = Lucene.Net.Index.DirectoryReader; using Document = Documents.Document; using Field = Field; using IndexReader = Lucene.Net.Index.IndexReader; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /* * 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MultiReader = Lucene.Net.Index.MultiReader; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using Term = Lucene.Net.Index.Term; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; [TestFixture] public class TestMultiTermQueryRewrites : LuceneTestCase { internal static Directory Dir, Sdir1, Sdir2; internal static IndexReader Reader, MultiReader, MultiReaderDupls; internal static IndexSearcher Searcher, MultiSearcher, MultiSearcherDupls; [TestFixtureSetUp] public static void BeforeClass() { Dir = NewDirectory(); Sdir1 = NewDirectory(); Sdir2 = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), Dir, new MockAnalyzer(Random())); RandomIndexWriter swriter1 = new RandomIndexWriter(Random(), Sdir1, new MockAnalyzer(Random())); RandomIndexWriter swriter2 = new RandomIndexWriter(Random(), Sdir2, new MockAnalyzer(Random())); for (int i = 0; i < 10; i++) { Document doc = new Document(); doc.Add(NewStringField("data", Convert.ToString(i), Field.Store.NO)); writer.AddDocument(doc); ((i % 2 == 0) ? swriter1 : swriter2).AddDocument(doc); } writer.ForceMerge(1); swriter1.ForceMerge(1); swriter2.ForceMerge(1); writer.Dispose(); swriter1.Dispose(); swriter2.Dispose(); Reader = DirectoryReader.Open(Dir); Searcher = NewSearcher(Reader); MultiReader = new MultiReader(new IndexReader[] { DirectoryReader.Open(Sdir1), DirectoryReader.Open(Sdir2) }, true); MultiSearcher = NewSearcher(MultiReader); MultiReaderDupls = new MultiReader(new IndexReader[] { DirectoryReader.Open(Sdir1), DirectoryReader.Open(Dir) }, true); MultiSearcherDupls = NewSearcher(MultiReaderDupls); } [TestFixtureTearDown] public static void AfterClass() { Reader.Dispose(); MultiReader.Dispose(); MultiReaderDupls.Dispose(); Dir.Dispose(); Sdir1.Dispose(); Sdir2.Dispose(); Reader = MultiReader = MultiReaderDupls = null; Searcher = MultiSearcher = MultiSearcherDupls = null; Dir = Sdir1 = Sdir2 = null; } private Query ExtractInnerQuery(Query q) { if (q is ConstantScoreQuery) { // wrapped as ConstantScoreQuery q = ((ConstantScoreQuery)q).Query; } return q; } private Term ExtractTerm(Query q) { q = ExtractInnerQuery(q); return ((TermQuery)q).Term; } private void CheckBooleanQueryOrder(Query q) { q = ExtractInnerQuery(q); BooleanQuery bq = (BooleanQuery)q; Term last = null, act; foreach (BooleanClause clause in bq.Clauses) { act = ExtractTerm(clause.Query); if (last != null) { Assert.IsTrue(last.CompareTo(act) < 0, "sort order of terms in BQ violated"); } last = act; } } private void CheckDuplicateTerms(MultiTermQuery.RewriteMethod method) { MultiTermQuery mtq = TermRangeQuery.NewStringRange("data", "2", "7", true, true); mtq.SetRewriteMethod(method); Query q1 = Searcher.Rewrite(mtq); Query q2 = MultiSearcher.Rewrite(mtq); Query q3 = MultiSearcherDupls.Rewrite(mtq); if (VERBOSE) { Console.WriteLine(); Console.WriteLine("single segment: " + q1); Console.WriteLine("multi segment: " + q2); Console.WriteLine("multi segment with duplicates: " + q3); } Assert.IsTrue(q1.Equals(q2), "The multi-segment case must produce same rewritten query"); Assert.IsTrue(q1.Equals(q3), "The multi-segment case with duplicates must produce same rewritten query"); CheckBooleanQueryOrder(q1); CheckBooleanQueryOrder(q2); CheckBooleanQueryOrder(q3); } [Test] public virtual void TestRewritesWithDuplicateTerms() { CheckDuplicateTerms(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE); CheckDuplicateTerms(MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE); // use a large PQ here to only test duplicate terms and dont mix up when all scores are equal CheckDuplicateTerms(new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(1024)); CheckDuplicateTerms(new MultiTermQuery.TopTermsBoostOnlyBooleanQueryRewrite(1024)); // Test auto rewrite (but only boolean mode), so we set the limits to large values to always get a BQ MultiTermQuery.ConstantScoreAutoRewrite rewrite = new MultiTermQuery.ConstantScoreAutoRewrite(); rewrite.TermCountCutoff = int.MaxValue; rewrite.DocCountPercent = 100.0; CheckDuplicateTerms(rewrite); } private void CheckBooleanQueryBoosts(BooleanQuery bq) { foreach (BooleanClause clause in bq.Clauses) { TermQuery mtq = (TermQuery)clause.Query; Assert.AreEqual(Convert.ToSingle(mtq.Term.Text()), mtq.Boost, 0, "Parallel sorting of boosts in rewrite mode broken"); } } private void CheckBoosts(MultiTermQuery.RewriteMethod method) { MultiTermQuery mtq = new MultiTermQueryAnonymousInnerClassHelper(this); mtq.SetRewriteMethod(method); Query q1 = Searcher.Rewrite(mtq); Query q2 = MultiSearcher.Rewrite(mtq); Query q3 = MultiSearcherDupls.Rewrite(mtq); if (VERBOSE) { Console.WriteLine(); Console.WriteLine("single segment: " + q1); Console.WriteLine("multi segment: " + q2); Console.WriteLine("multi segment with duplicates: " + q3); } Assert.IsTrue(q1.Equals(q2), "The multi-segment case must produce same rewritten query"); Assert.IsTrue(q1.Equals(q3), "The multi-segment case with duplicates must produce same rewritten query"); CheckBooleanQueryBoosts((BooleanQuery)q1); CheckBooleanQueryBoosts((BooleanQuery)q2); CheckBooleanQueryBoosts((BooleanQuery)q3); } private class MultiTermQueryAnonymousInnerClassHelper : MultiTermQuery { private readonly TestMultiTermQueryRewrites OuterInstance; public MultiTermQueryAnonymousInnerClassHelper(TestMultiTermQueryRewrites outerInstance) : base("data") { this.OuterInstance = outerInstance; } public override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts) { return new TermRangeTermsEnumAnonymousInnerClassHelper(this, terms.Iterator(null), new BytesRef("2"), new BytesRef("7")); } private class TermRangeTermsEnumAnonymousInnerClassHelper : TermRangeTermsEnum { private readonly MultiTermQueryAnonymousInnerClassHelper OuterInstance; public TermRangeTermsEnumAnonymousInnerClassHelper(MultiTermQueryAnonymousInnerClassHelper outerInstance, TermsEnum iterator, BytesRef bref1, BytesRef bref2) : base(iterator, bref1, bref2, true, true) { this.OuterInstance = outerInstance; boostAtt = Attributes().AddAttribute<IBoostAttribute>(); } internal readonly IBoostAttribute boostAtt; protected override AcceptStatus Accept(BytesRef term) { boostAtt.Boost = Convert.ToSingle(term.Utf8ToString()); return base.Accept(term); } } public override string ToString(string field) { return "dummy"; } } [Test] public virtual void TestBoosts() { CheckBoosts(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE); // use a large PQ here to only test boosts and dont mix up when all scores are equal CheckBoosts(new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(1024)); } private void CheckMaxClauseLimitation(MultiTermQuery.RewriteMethod method) { int savedMaxClauseCount = BooleanQuery.MaxClauseCount; BooleanQuery.MaxClauseCount = 3; MultiTermQuery mtq = TermRangeQuery.NewStringRange("data", "2", "7", true, true); mtq.SetRewriteMethod(method); try { MultiSearcherDupls.Rewrite(mtq); Assert.Fail("Should throw BooleanQuery.TooManyClauses"); } catch (BooleanQuery.TooManyClauses e) { // Maybe remove this assert in later versions, when internal API changes: Assert.AreEqual("CheckMaxClauseCount", new StackTrace(e).GetFrames()[0].GetMethod().Name, "Should throw BooleanQuery.TooManyClauses with a stacktrace containing checkMaxClauseCount()"); } finally { BooleanQuery.MaxClauseCount = savedMaxClauseCount; } } private void CheckNoMaxClauseLimitation(MultiTermQuery.RewriteMethod method) { int savedMaxClauseCount = BooleanQuery.MaxClauseCount; BooleanQuery.MaxClauseCount = 3; MultiTermQuery mtq = TermRangeQuery.NewStringRange("data", "2", "7", true, true); mtq.SetRewriteMethod(method); try { MultiSearcherDupls.Rewrite(mtq); } finally { BooleanQuery.MaxClauseCount = savedMaxClauseCount; } } [Test] public virtual void TestMaxClauseLimitations() { CheckMaxClauseLimitation(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE); CheckMaxClauseLimitation(MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE); CheckNoMaxClauseLimitation(MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE); CheckNoMaxClauseLimitation(MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT); CheckNoMaxClauseLimitation(new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(1024)); CheckNoMaxClauseLimitation(new MultiTermQuery.TopTermsBoostOnlyBooleanQueryRewrite(1024)); } } }
/* ==================================================================== 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. ==================================================================== */ namespace NPOI { using System; using System.IO; using System.Collections; using NPOI.Util; using NPOI.POIFS.FileSystem; using NPOI.HPSF; using System.Collections.Generic; /// <summary> /// This holds the common functionality for all POI /// Document classes. /// Currently, this relates to Document Information Properties /// </summary> /// <remarks>@author Nick Burch</remarks> [Serializable] internal abstract class POIDocument { /** Holds metadata on our document */ protected SummaryInformation sInf; /** Holds further metadata on our document */ protected DocumentSummaryInformation dsInf; /** The directory that our document lives in */ protected DirectoryNode directory; /** For our own logging use */ //protected POILogger logger; /* Have the property streams been Read yet? (Only done on-demand) */ protected bool initialized = false; protected POIDocument(DirectoryNode dir) { this.directory = dir; } /// <summary> /// Initializes a new instance of the <see cref="POIDocument"/> class. /// </summary> /// <param name="dir">The dir.</param> /// <param name="fs">The fs.</param> [Obsolete] public POIDocument(DirectoryNode dir, POIFSFileSystem fs) { this.directory = dir; //POILogFactory.GetLogger(this.GetType()); } /// <summary> /// Initializes a new instance of the <see cref="POIDocument"/> class. /// </summary> /// <param name="fs">The fs.</param> public POIDocument(POIFSFileSystem fs) : this(fs.Root) { } /** * Will create whichever of SummaryInformation * and DocumentSummaryInformation (HPSF) properties * are not already part of your document. * This is normally useful when creating a new * document from scratch. * If the information properties are already there, * then nothing will happen. */ public void CreateInformationProperties() { if (!initialized) ReadProperties(); if (sInf == null) { sInf = PropertySetFactory.CreateSummaryInformation(); } if (dsInf == null) { dsInf = PropertySetFactory.CreateDocumentSummaryInformation(); } } // nothing to dispose //public virtual void Dispose() //{ // //} /// <summary> /// Fetch the Document Summary Information of the document /// </summary> /// <value>The document summary information.</value> public DocumentSummaryInformation DocumentSummaryInformation { get { if (!initialized) ReadProperties(); return dsInf; } set { dsInf = value; } } /// <summary> /// Fetch the Summary Information of the document /// </summary> /// <value>The summary information.</value> public SummaryInformation SummaryInformation { get { if (!initialized) ReadProperties(); return sInf; } set { sInf = value; } } /// <summary> /// Find, and Create objects for, the standard /// Documment Information Properties (HPSF). /// If a given property Set is missing or corrupt, /// it will remain null; /// </summary> protected void ReadProperties() { PropertySet ps; // DocumentSummaryInformation ps = GetPropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME); if (ps != null && ps is DocumentSummaryInformation) { dsInf = (DocumentSummaryInformation)ps; } else if (ps != null) { //logger.Log(POILogger.WARN, "DocumentSummaryInformation property Set came back with wrong class - ", ps.GetType()); } // SummaryInformation ps = GetPropertySet(SummaryInformation.DEFAULT_STREAM_NAME); if (ps is SummaryInformation) { sInf = (SummaryInformation)ps; } else if (ps != null) { //logger.Log(POILogger.WARN, "SummaryInformation property Set came back with wrong class - ", ps.GetType()); } // Mark the fact that we've now loaded up the properties initialized = true; } /// <summary> /// For a given named property entry, either return it or null if /// if it wasn't found /// </summary> /// <param name="SetName">Name of the set.</param> /// <returns></returns> protected PropertySet GetPropertySet(String SetName) { //directory can be null when creating new documents if (directory == null) return null; DocumentInputStream dis; try { // Find the entry, and Get an input stream for it dis = directory.CreateDocumentInputStream(SetName); } catch (IOException) { // Oh well, doesn't exist //logger.Log(POILogger.WARN, "Error Getting property Set with name " + SetName + "\n" + ie); return null; } try { // Create the Property Set PropertySet Set = PropertySetFactory.Create(dis); return Set; } catch (IOException) { // Must be corrupt or something like that //logger.Log(POILogger.WARN, "Error creating property Set with name " + SetName + "\n" + ie); } catch (HPSFException) { // Oh well, doesn't exist //logger.Log(POILogger.WARN, "Error creating property Set with name " + SetName + "\n" + he); } return null; } /// <summary> /// Writes out the standard Documment Information Properties (HPSF) /// </summary> /// <param name="outFS">the POIFSFileSystem to Write the properties into</param> protected void WriteProperties(POIFSFileSystem outFS) { WriteProperties(outFS, null); } /// <summary> /// Writes out the standard Documment Information Properties (HPSF) /// </summary> /// <param name="outFS">the POIFSFileSystem to Write the properties into.</param> /// <param name="writtenEntries">a list of POIFS entries to Add the property names too.</param> protected void WriteProperties(POIFSFileSystem outFS, IList writtenEntries) { if (sInf != null) { WritePropertySet(SummaryInformation.DEFAULT_STREAM_NAME, sInf, outFS); if (writtenEntries != null) { writtenEntries.Add(SummaryInformation.DEFAULT_STREAM_NAME); } } if (dsInf != null) { WritePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME, dsInf, outFS); if (writtenEntries != null) { writtenEntries.Add(DocumentSummaryInformation.DEFAULT_STREAM_NAME); } } } /// <summary> /// Writes out a given ProperySet /// </summary> /// <param name="name">the (POIFS Level) name of the property to Write.</param> /// <param name="Set">the PropertySet to Write out.</param> /// <param name="outFS">the POIFSFileSystem to Write the property into.</param> protected void WritePropertySet(String name, PropertySet Set, POIFSFileSystem outFS) { try { MutablePropertySet mSet = new MutablePropertySet(Set); using (MemoryStream bOut = new MemoryStream()) { mSet.Write(bOut); byte[] data = bOut.ToArray(); using (MemoryStream bIn = new MemoryStream(data)) { outFS.CreateDocument(bIn, name); } //logger.Log(POILogger.INFO, "Wrote property Set " + name + " of size " + data.Length); } } catch (WritingNotSupportedException) { Console.Error.WriteLine("Couldn't Write property Set with name " + name + " as not supported by HPSF yet"); } } /// <summary> /// Writes the document out to the specified output stream /// </summary> /// <param name="out1">The out1.</param> public abstract void Write(Stream out1); /// <summary> /// Copies nodes from one POIFS to the other minus the excepts /// </summary> /// <param name="source">the source POIFS to copy from.</param> /// <param name="target">the target POIFS to copy to</param> /// <param name="excepts">a list of Strings specifying what nodes NOT to copy</param> [Obsolete] protected void CopyNodes(POIFSFileSystem source, POIFSFileSystem target, List<String> excepts) { POIUtils.CopyNodes(source, target, excepts); } /// <summary> /// Copies nodes from one POIFS to the other minus the excepts /// </summary> /// <param name="sourceRoot">the source POIFS to copy from.</param> /// <param name="targetRoot">the target POIFS to copy to</param> /// <param name="excepts">a list of Strings specifying what nodes NOT to copy</param> [Obsolete] protected void CopyNodes(DirectoryNode sourceRoot, DirectoryNode targetRoot, List<String> excepts) { POIUtils.CopyNodes(sourceRoot, targetRoot, excepts); } /// <summary> /// Checks to see if the String is in the list, used when copying /// nodes between one POIFS and another /// </summary> /// <param name="entry">The entry.</param> /// <param name="list">The list.</param> /// <returns> /// <c>true</c> if [is in list] [the specified entry]; otherwise, <c>false</c>. /// </returns> private bool isInList(String entry, IList list) { for (int k = 0; k < list.Count; k++) { if (list[k].Equals(entry)) { return true; } } return false; } /// <summary> /// Copies an Entry into a target POIFS directory, recursively /// </summary> /// <param name="entry">The entry.</param> /// <param name="target">The target.</param> [Obsolete] private void CopyNodeRecursively(Entry entry, DirectoryEntry target) { //System.err.println("copyNodeRecursively called with "+entry.Name+ // ","+target.Name); POIUtils.CopyNodeRecursively(entry, target); } } }
// 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.Collections.Immutable; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Provides APIs to enumerate and look up assemblies stored in the Global Assembly Cache. /// </summary> internal sealed class MonoGlobalAssemblyCache : GlobalAssemblyCache { public static readonly ImmutableArray<string> RootLocations; static MonoGlobalAssemblyCache() { RootLocations = ImmutableArray.Create(GetMonoCachePath()); } private static string GetMonoCachePath() { string file = CorLightup.Desktop.GetAssemblyLocation(typeof(Uri).GetTypeInfo().Assembly); return Directory.GetParent(Path.GetDirectoryName(file)).Parent.FullName; } private static IEnumerable<string> GetCorlibPaths(Version version) { string corlibPath = CorLightup.Desktop.GetAssemblyLocation(typeof(object).GetTypeInfo().Assembly); var corlibParentDir = Directory.GetParent(corlibPath).Parent; var corlibPaths = new List<string>(); foreach (var corlibDir in corlibParentDir.GetDirectories()) { var path = Path.Combine(corlibDir.FullName, "mscorlib.dll"); if (!File.Exists(path)) { continue; } var name = new AssemblyName(path); if (version != null && name.Version != version) { continue; } corlibPaths.Add(path); } return corlibPaths; } private static IEnumerable<string> GetGacAssemblyPaths(string gacPath, string name, Version version, string publicKeyToken) { if (version != null && publicKeyToken != null) { yield return Path.Combine(gacPath, name, version + "__" + publicKeyToken, name + ".dll"); yield break; } var gacAssemblyRootDir = new DirectoryInfo(Path.Combine(gacPath, name)); if (!gacAssemblyRootDir.Exists) { yield break; } foreach (var assemblyDir in gacAssemblyRootDir.GetDirectories()) { if (version != null && !assemblyDir.Name.StartsWith(version.ToString(), StringComparison.Ordinal)) { continue; } if (publicKeyToken != null && !assemblyDir.Name.EndsWith(publicKeyToken, StringComparison.Ordinal)) { continue; } var assemblyPath = Path.Combine(assemblyDir.ToString(), name + ".dll"); if (File.Exists(assemblyPath)) { yield return assemblyPath; } } } private static IEnumerable<Tuple<AssemblyIdentity, string>> GetAssemblyIdentitiesAndPaths(AssemblyName name, ImmutableArray<ProcessorArchitecture> architectureFilter) { if (name == null) { return GetAssemblyIdentitiesAndPaths(null, null, null, architectureFilter); } string publicKeyToken = null; if (name.GetPublicKeyToken() != null) { var sb = new StringBuilder(); foreach (var b in name.GetPublicKeyToken()) { sb.AppendFormat("{0:x2}", b); } publicKeyToken = sb.ToString(); } return GetAssemblyIdentitiesAndPaths(name.Name, name.Version, publicKeyToken, architectureFilter); } private static IEnumerable<Tuple<AssemblyIdentity, string>> GetAssemblyIdentitiesAndPaths(string name, Version version, string publicKeyToken, ImmutableArray<ProcessorArchitecture> architectureFilter) { foreach (string gacPath in RootLocations) { var assemblyPaths = (name == "mscorlib") ? GetCorlibPaths(version) : GetGacAssemblyPaths(gacPath, name, version, publicKeyToken); foreach (var assemblyPath in assemblyPaths) { if (!File.Exists(assemblyPath)) { continue; } var gacAssemblyName = new AssemblyName(assemblyPath); if (gacAssemblyName.ProcessorArchitecture != ProcessorArchitecture.None && architectureFilter != default(ImmutableArray<ProcessorArchitecture>) && architectureFilter.Length > 0 && !architectureFilter.Contains(gacAssemblyName.ProcessorArchitecture)) { continue; } var assemblyIdentity = new AssemblyIdentity( gacAssemblyName.Name, gacAssemblyName.Version, gacAssemblyName.CultureName, ImmutableArray.Create(gacAssemblyName.GetPublicKeyToken())); yield return new Tuple<AssemblyIdentity, string>(assemblyIdentity, assemblyPath); } } } public override IEnumerable<AssemblyIdentity> GetAssemblyIdentities(AssemblyName partialName, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { return GetAssemblyIdentitiesAndPaths(partialName, architectureFilter).Select(identityAndPath => identityAndPath.Item1); } public override IEnumerable<AssemblyIdentity> GetAssemblyIdentities(string partialName = null, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { AssemblyName name; try { name = (partialName == null) ? null : new AssemblyName(partialName); } catch { return SpecializedCollections.EmptyEnumerable<AssemblyIdentity>(); } return GetAssemblyIdentities(name, architectureFilter); } public override IEnumerable<string> GetAssemblySimpleNames(ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { return GetAssemblyIdentitiesAndPaths(name: null, version: null, publicKeyToken: null, architectureFilter: architectureFilter). Select(identityAndPath => identityAndPath.Item1.Name).Distinct(); } public override AssemblyIdentity ResolvePartialName( string displayName, out string location, ImmutableArray<ProcessorArchitecture> architectureFilter, CultureInfo preferredCulture) { if (displayName == null) { throw new ArgumentNullException(nameof(displayName)); } string cultureName = (preferredCulture != null && !preferredCulture.IsNeutralCulture) ? preferredCulture.Name : null; var assemblyName = new AssemblyName(displayName); AssemblyIdentity assemblyIdentity = null; location = null; bool isBestMatch = false; foreach (var identityAndPath in GetAssemblyIdentitiesAndPaths(assemblyName, architectureFilter)) { var assemblyPath = identityAndPath.Item2; if (!File.Exists(assemblyPath)) { continue; } var gacAssemblyName = new AssemblyName(assemblyPath); isBestMatch = cultureName == null || gacAssemblyName.CultureName == cultureName; bool isBetterMatch = location == null || isBestMatch; if (isBetterMatch) { location = assemblyPath; assemblyIdentity = identityAndPath.Item1; } if (isBestMatch) { break; } } return assemblyIdentity; } } }
//! \file ImageERI.cs //! \date Tue May 26 12:04:30 2015 //! \brief Entis rasterized image format. // // Copyright (C) 2015 by morkt // // 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.ComponentModel.Composition; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Windows.Media; using GameRes.Utility; namespace GameRes.Formats.Entis { internal class EriMetaData : ImageMetaData { public int StreamPos; public int Version; public CvType Transformation; public EriCode Architecture; public EriType FormatType; public bool VerticalFlip; public int ClippedPixel; public EriSampling SamplingFlags; public ulong QuantumizedBits; public ulong AllottedBits; public int BlockingDegree; public int LappedBlock; public int FrameTransform; public int FrameDegree; public EriFileHeader Header; public string Description; } public enum CvType { Lossless_EMI = 0x03010000, Lossless_ERI = 0x03020000, DCT_ERI = 0x00000001, LOT_ERI = 0x00000005, LOT_ERI_MSS = 0x00000105, } internal class EriFileHeader { public int Version; public int ContainedFlag; public int KeyFrameCount; public int FrameCount; public int AllFrameTime; } public enum EriCode { ArithmeticCode = 32, RunlengthGamma = -1, RunlengthHuffman = -4, Nemesis = -16, } [Flags] public enum EriType { RGB = 0x00000001, Gray = 0x00000002, BGR = 0x00000003, YUV = 0x00000004, HSB = 0x00000006, RGBA = 0x04000001, BGRA = 0x04000003, Mask = 0x0000FFFF, WithPalette = 0x01000000, UseClipping = 0x02000000, WithAlpha = 0x04000000, SideBySide = 0x10000000, } public enum EriSampling { YUV_4_4_4 = 0x00040404, YUV_4_2_2 = 0x00040202, YUV_4_1_1 = 0x00040101, } internal class EriFile : BinaryReader { internal struct Section { public AsciiString Id; public long Length; } public EriFile (Stream stream) : base (stream, Encoding.Unicode, true) { } public Section ReadSection () { var section = new Section(); section.Id = new AsciiString (8); if (8 != this.Read (section.Id.Value, 0, 8)) throw new EndOfStreamException(); section.Length = this.ReadInt64(); return section; } public long FindSection (string name) { var id = new AsciiString (8); for (;;) { if (8 != this.Read (id.Value, 0, 8)) throw new EndOfStreamException(); var length = this.ReadInt64(); if (length < 0) throw new EndOfStreamException(); if (id == name) return length; this.BaseStream.Seek (length, SeekOrigin.Current); } } } [Export(typeof(ImageFormat))] public class EriFormat : ImageFormat { public override string Tag { get { return "ERI"; } } public override string Description { get { return "Entis rasterized image format"; } } public override uint Signature { get { return 0x69746e45u; } } // 'Enti' public EriFormat () { Extensions = new [] { "eri", "emi" }; Signatures = new uint[] { 0x69746E45, 0x54534956 }; } public override ImageMetaData ReadMetaData (IBinaryStream stream) { var header = stream.ReadHeader (0x40); uint id = header.ToUInt32 (8); if (0x03000100 != id && 0x02000100 != id) return null; if (!header.AsciiEqual (0x10, "Entis Rasterized Image") && !header.AsciiEqual (0x10, "Moving Entis Image") && !header.AsciiEqual (0x10, "EMSAC-Image")) return null; using (var reader = new EriFile (stream.AsStream)) { var section = reader.ReadSection(); if (section.Id != "Header " || section.Length <= 0) return null; int header_size = (int)section.Length; int stream_pos = 0x50 + header_size; EriFileHeader file_header = null; EriMetaData info = null; string desc = null; while (header_size > 0x10) { section = reader.ReadSection(); header_size -= 0x10; if (section.Length <= 0 || section.Length > header_size) break; if ("FileHdr " == section.Id) { file_header = new EriFileHeader { Version = reader.ReadInt32() }; if (file_header.Version > 0x00020100) throw new InvalidFormatException ("Invalid ERI file version"); file_header.ContainedFlag = reader.ReadInt32(); file_header.KeyFrameCount = reader.ReadInt32(); file_header.FrameCount = reader.ReadInt32(); file_header.AllFrameTime = reader.ReadInt32(); } else if ("ImageInf" == section.Id) { int version = reader.ReadInt32(); if (version != 0x00020100 && version != 0x00020200) return null; info = new EriMetaData { StreamPos = stream_pos, Version = version }; info.Transformation = (CvType)reader.ReadInt32(); info.Architecture = (EriCode)reader.ReadInt32(); info.FormatType = (EriType)reader.ReadInt32(); int w = reader.ReadInt32(); int h = reader.ReadInt32(); info.Width = (uint)Math.Abs (w); info.Height = (uint)Math.Abs (h); info.VerticalFlip = h < 0; info.BPP = reader.ReadInt32(); info.ClippedPixel = reader.ReadInt32(); info.SamplingFlags = (EriSampling)reader.ReadInt32(); info.QuantumizedBits = reader.ReadUInt64(); info.AllottedBits = reader.ReadUInt64(); info.BlockingDegree = reader.ReadInt32(); info.LappedBlock = reader.ReadInt32(); info.FrameTransform = reader.ReadInt32(); info.FrameDegree = reader.ReadInt32(); } else if ("descript" == section.Id) { if (0xFEFF == reader.PeekChar()) { reader.Read(); var desc_chars = reader.ReadChars ((int)section.Length/2 - 1); desc = new string (desc_chars); } else { var desc_chars = reader.ReadBytes ((int)section.Length); desc = Encoding.UTF8.GetString (desc_chars); } } else { reader.BaseStream.Seek (section.Length, SeekOrigin.Current); } header_size -= (int)section.Length; } if (info != null) { if (file_header != null) info.Header = file_header; if (desc != null) info.Description = desc; } return info; } } public override ImageData Read (IBinaryStream stream, ImageMetaData info) { var reader = ReadImageData (stream, (EriMetaData)info); return ImageData.Create (info, reader.Format, reader.Palette, reader.Data, reader.Stride); } internal static Color[] ReadPalette (Stream input, int palette_length) { int colors = palette_length / 4; if (colors <= 0 || colors > 0x100) throw new InvalidFormatException(); return ImageFormat.ReadColorMap (input, colors); } internal EriReader ReadImageData (IBinaryStream stream, EriMetaData meta) { stream.Position = meta.StreamPos; Color[] palette = null; using (var input = new EriFile (stream.AsStream)) { for (;;) // ReadSection throws an exception in case of EOF { var section = input.ReadSection(); if ("Stream " == section.Id) continue; if ("ImageFrm" == section.Id) break; if ("Palette " == section.Id && meta.BPP <= 8 && section.Length <= 0x400) { palette = ReadPalette (stream.AsStream, (int)section.Length); continue; } input.BaseStream.Seek (section.Length, SeekOrigin.Current); } } var reader = new EriReader (stream.AsStream, meta, palette); reader.DecodeImage(); if (!string.IsNullOrEmpty (meta.Description)) { var tags = ParseTagInfo (meta.Description); string ref_file; if (tags.TryGetValue ("reference-file", out ref_file)) { ref_file = ref_file.TrimEnd (null); if (!string.IsNullOrEmpty (ref_file)) { if ((meta.BPP + 7) / 8 < 3) throw new InvalidFormatException(); ref_file = VFS.CombinePath (VFS.GetDirectoryName (meta.FileName), ref_file); using (var ref_src = VFS.OpenBinaryStream (ref_file)) { var ref_info = ReadMetaData (ref_src) as EriMetaData; if (null == ref_info) throw new FileNotFoundException ("Referenced image not found", ref_file); ref_info.FileName = ref_file; var ref_reader = ReadImageData (ref_src, ref_info); reader.AddImageBuffer (ref_reader); } } } } return reader; } static readonly Regex s_TagRe = new Regex (@"^\s*#\s*(\S+)"); Dictionary<string, string> ParseTagInfo (string desc) { var dict = new Dictionary<string, string>(); if (string.IsNullOrEmpty (desc)) { return dict; } if ('#' != desc[0]) { dict["comment"] = desc; return dict; } var tag_value = new StringBuilder(); using (var reader = new StringReader (desc)) { string line = reader.ReadLine(); while (null != line) { var match = s_TagRe.Match (line); if (!match.Success) break; string tag = match.Groups[1].Value; tag_value.Clear(); for (;;) { line = reader.ReadLine(); if (null == line) break; if (line.StartsWith ("#")) { if (line.Length < 2 || '#' != line[1]) break; line = line.Substring (1); } tag_value.AppendLine (line); } dict[tag] = tag_value.ToString(); } } return dict; } public override void Write (Stream file, ImageData image) { throw new NotImplementedException ("EriFormat.Write not implemented"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading.Tasks; using Heijden.DNS; namespace Heijden.Dns.Portable { public class VerboseEventArgs : EventArgs { public string Message { get; } public VerboseEventArgs(string message) { Message = message; } } /// <summary> /// Resolver is the main class to do DNS query lookups /// </summary> public class Resolver { /// <summary> /// Default DNS port /// </summary> public const int DefaultPort = 53; /// <summary> /// OpenDNS dns servers. /// For information only. /// </summary> public static readonly IPEndPoint[] DefaultDnsServers = { new IPEndPoint(IPAddress.Parse("208.67.222.222"), DefaultPort), new IPEndPoint(IPAddress.Parse("208.67.220.220"), DefaultPort) }; private ushort unique; private bool useCache; private int retries; private readonly List<IPEndPoint> dnsServers; private readonly Dictionary<string, Response> responseCache = new Dictionary<string, Response>(); #region public properties /// <summary> /// Verbose messages from internal operations /// </summary> public event EventHandler<VerboseEventArgs> OnVerbose; public string Version => typeof(Resolver).GetTypeInfo().Assembly.GetName().Version.ToString(); /// <summary> /// Gets first DNS server address or sets single DNS server to use /// </summary> public IPAddress DnsServer => dnsServers.FirstOrDefault()?.Address; public TimeSpan Timeout { get; set; } /// <summary> /// Gets or set recursion for doing queries /// </summary> public bool Recursion { get; set; } /// <summary> /// Gets or sets protocol to use /// </summary> public TransportType TransportType { get; set; } /// <summary> /// Gets or sets number of retries before giving up /// </summary> public int Retries { get { return retries; } set { if (value >= 1) retries = value; } } /// <summary> /// Gets or sets list of DNS servers to use /// </summary> public List<IPEndPoint> DnsServers { get { return dnsServers; } set { dnsServers.Clear(); if (value != null) dnsServers.AddRange(value); } } public bool UseCache { get { return useCache; } set { useCache = value; if (!useCache) ClearCache(); } } #endregion /// <summary> /// Resolver constructor, using DNS servers specified by Windows /// </summary> public Resolver() : this(GetDnsServers()) { } /// <summary> /// Constructor of Resolver using DNS servers specified. /// </summary> /// <param name="dnsServers">Set of DNS servers</param> public Resolver(IPEndPoint[] dnsServers) { this.dnsServers = new List<IPEndPoint>(dnsServers); unique = (ushort) (new Random()).Next(); retries = 3; Timeout = TimeSpan.FromSeconds(1); Recursion = true; useCache = true; TransportType = TransportType.Udp; } /// <summary> /// Constructor of Resolver using DNS server specified. /// </summary> /// <param name="dnsServer">DNS server to use</param> public Resolver(IPEndPoint dnsServer) : this(new[] {dnsServer}) { } /// <summary> /// Constructor of Resolver using DNS server and port specified. /// </summary> /// <param name="serverIpAddress">DNS server to use</param> /// <param name="serverPortNumber">DNS port to use</param> public Resolver(IPAddress serverIpAddress, int serverPortNumber) : this(new IPEndPoint(serverIpAddress, serverPortNumber)) { } /// <summary> /// Constructor of Resolver using DNS address and port specified. /// </summary> /// <param name="serverIpAddress">DNS server address to use</param> /// <param name="serverPortNumber">DNS port to use</param> public Resolver(string serverIpAddress, int serverPortNumber = DefaultPort) : this(IPAddress.Parse(serverIpAddress), serverPortNumber) { } public class VerboseOutputEventArgs : EventArgs { public string Message; public VerboseOutputEventArgs(string message) { Message = message; } } private void FireVerbose(string format, params object[] args) { OnVerbose?.Invoke(this, new VerboseEventArgs(string.Format(format, args))); } public async Task<bool> SetDnsServer(string dnsServer) { dnsServers.Clear(); IPAddress ip; if (IPAddress.TryParse(dnsServer, out ip)) dnsServers.Add(new IPEndPoint(ip, DefaultPort)); var response = await Query(dnsServer, QType.A); if (response.RecordsA.Length > 0) dnsServers.Add(new IPEndPoint(response.RecordsA[0].Address, DefaultPort)); return dnsServers.Count != 0; } /// <summary> /// Clear the resolver cache /// </summary> public void ClearCache() { lock (responseCache) { responseCache.Clear(); } } private Response SearchInCache(Question question) { if (!useCache) return null; var strKey = question.QClass + "-" + question.QType + "-" + question.QName; Response response = null; lock (responseCache) { if (!responseCache.ContainsKey(strKey)) return null; response = responseCache[strKey]; } var timeLived = (int) ((DateTime.Now.Ticks - response.TimeStamp.Ticks) / TimeSpan.TicksPerSecond); foreach (var rr in response.RecordsRR) { rr.TimeLived = timeLived; // The TTL property calculates its actual time to live if (rr.TTL == 0) return null; // out of date } return response; } private void AddToCache(Response response) { if (!useCache) return; // No question, no caching if (response.Questions.Count == 0) return; // Only cached non-error responses if (response.header.RCODE != RCode.NoError) return; var question = response.Questions[0]; var strKey = question.QClass + "-" + question.QType + "-" + question.QName; lock (responseCache) { if (responseCache.ContainsKey(strKey)) responseCache.Remove(strKey); responseCache.Add(strKey, response); } } private Response UdpRequest(Request request) { if (dnsServers.Count == 0) return new Response { Error = "No dns server" }; // RFC1035 max. size of a UDP datagram is 512 bytes var responseMessage = new byte[4096]; for (var intAttempts = 0; intAttempts < retries; intAttempts++) { foreach (var dnsServer in dnsServers) { using (var socket = new Socket(dnsServer.AddressFamily, SocketType.Dgram, ProtocolType.Udp)) { try { socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, (int)(Timeout.TotalMilliseconds+.5)); } catch (Exception e) { FireVerbose($"Can not set ReceiveTimeout: {e.Message}"); //Ignore } try { socket.SendTo(request.Data, dnsServer); var intReceived = socket.Receive(responseMessage); var data = new byte[intReceived]; Array.Copy(responseMessage, data, intReceived); var response = new Response(dnsServer, data); AddToCache(response); return response; } catch (SocketException e) { FireVerbose($"Udp SocketException connecting to {dnsServer.Address}:{dnsServer.Port}: {e.Message}"); } finally { unique++; } } } } return new Response { Error = "Generic Error, see verbose messages" }; } private async Task<Response> TcpRequest(Request request) { if (dnsServers.Count == 0) return new Response { Error = "No dns server" }; //System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); //sw.Start(); for (var attempts = 0; attempts < retries; attempts++) { foreach(var dnsServer in dnsServers) { using (var tcpClient = new TcpClient()) { //tcpClient.ReceiveBufferSize = ... 8Kb by default //tcpClient.SendBufferSize = ... 8Kb by default try { var connectTask = tcpClient.ConnectAsync(dnsServer.Address, dnsServer.Port); var waitTask = Task.Delay((int)(Timeout.TotalMilliseconds + .5)); await Task.WhenAny(waitTask, connectTask); if (!connectTask.IsCompleted) throw new TimeoutException(); if (!tcpClient.Connected) { FireVerbose($"Tcp connection to nameserver {dnsServer.Address}:{dnsServer.Port} failed"); continue; } var bs = tcpClient.GetStream(); var data = request.Data; bs.WriteByte((byte) ((data.Length >> 8) & 0xff)); bs.WriteByte((byte) (data.Length & 0xff)); bs.Write(data, 0, data.Length); bs.Flush(); var transferResponse = new Response(); var intSoa = 0; var intMessageSize = 0; //Debug.WriteLine("Sending "+ (request.Length+2) + " bytes in "+ sw.ElapsedMilliseconds+" mS"); while (true) { var intLength = bs.ReadByte() << 8 | bs.ReadByte(); if (intLength <= 0) { // next try throw new Exception($"Tcp connection to nameserver {dnsServer.Address}:{dnsServer.Port} failed"); } intMessageSize += intLength; data = new byte[intLength]; bs.Read(data, 0, intLength); var response = new Response(dnsServer, data); //Debug.WriteLine("Received "+ (intLength+2)+" bytes in "+sw.ElapsedMilliseconds +" mS"); if (response.header.RCODE != RCode.NoError) return response; if (response.Questions[0].QType != QType.AXFR) { AddToCache(response); return response; } // Zone transfer!! if (transferResponse.Questions.Count == 0) transferResponse.Questions.AddRange(response.Questions); transferResponse.Answers.AddRange(response.Answers); transferResponse.Authorities.AddRange(response.Authorities); transferResponse.Additionals.AddRange(response.Additionals); if (response.Answers[0].Type == DnsEntryType.SOA) intSoa++; if (intSoa == 2) { transferResponse.header.QDCOUNT = (ushort) transferResponse.Questions.Count; transferResponse.header.ANCOUNT = (ushort) transferResponse.Answers.Count; transferResponse.header.NSCOUNT = (ushort) transferResponse.Authorities.Count; transferResponse.header.ARCOUNT = (ushort) transferResponse.Additionals.Count; transferResponse.MessageSize = intMessageSize; return transferResponse; } } } catch (TimeoutException) { FireVerbose($"TcpRequest to {dnsServer.Address}:{dnsServer.Port} timed out"); } catch (Exception e) { FireVerbose($"TcpRequest to {dnsServer.Address}:{dnsServer.Port} failed: {e.Message}"); } finally { unique++; } } } } return new Response { Error = "Generic Error, see verbose messages" }; } /// <summary> /// Do Query on specified DNS servers /// </summary> /// <param name="name">Name to query</param> /// <param name="qtype">Question type</param> /// <param name="qclass">Class type</param> /// <returns>Response of the query</returns> public async Task<Response> Query(string name, QType qtype, QClass qclass = QClass.IN) { Question question = new Question(name, qtype, qclass); Response response = SearchInCache(question); if (response != null) return response; Request request = new Request(); request.AddQuestion(question); return await GetResponse(request); } private async Task<Response> GetResponse(Request request) { request.header.ID = unique; request.header.RD = Recursion; if (TransportType == TransportType.Udp) return UdpRequest(request); if (TransportType == TransportType.Tcp) return await TcpRequest(request); return new Response { Error = "Unknown TransportType" }; } /// <summary> /// Gets a list of default DNS servers used on the Windows machine. /// </summary> /// <returns></returns> public static IPEndPoint[] GetDnsServers() { return (from adapter in NetworkInterface.GetAllNetworkInterfaces() where adapter.OperationalStatus == OperationalStatus.Up let ipProps = adapter.GetIPProperties() from ipAddr in ipProps.DnsAddresses where ipAddr.AddressFamily == AddressFamily.InterNetwork || (ipAddr.AddressFamily == AddressFamily.InterNetworkV6 && (ipAddr.IsIPv4MappedToIPv6 || ipAddr.IsIPv6Multicast || ipAddr.IsIPv6Teredo)) select new IPEndPoint(ipAddr, DefaultPort) ).ToArray(); } private async Task<IPHostEntry> MakeEntry(string hostName) { var entry = new IPHostEntry {HostName = hostName}; var response = await Query(hostName, QType.A); // fill AddressList and aliases var addressList = new List<IPAddress>(); var aliases = new List<string>(); foreach (var answerRr in response.Answers) { if (answerRr.Type == DnsEntryType.A) { // answerRR.RECORD.ToString() == (answerRR.RECORD as RecordA).Address addressList.Add(IPAddress.Parse((answerRr.RECORD.ToString()))); entry.HostName = answerRr.NAME; } else { if (answerRr.Type == DnsEntryType.CNAME) aliases.Add(answerRr.NAME); } } entry.AddressList = addressList.ToArray(); entry.Aliases = aliases.ToArray(); return entry; } /// <summary> /// Translates the IPV4 or IPV6 address into an arpa address /// </summary> /// <param name="ip">IP address to get the arpa address form</param> /// <returns>The 'mirrored' IPV4 or IPV6 arpa address</returns> public static string GetArpaFromIp(IPAddress ip) { if (ip.AddressFamily == AddressFamily.InterNetwork) { StringBuilder sb = new StringBuilder(); sb.Append("in-addr.arpa."); foreach (byte b in ip.GetAddressBytes()) { sb.Insert(0, string.Format("{0}.", b)); } return sb.ToString(); } if (ip.AddressFamily == AddressFamily.InterNetworkV6) { StringBuilder sb = new StringBuilder(); sb.Append("ip6.arpa."); foreach (byte b in ip.GetAddressBytes()) { sb.Insert(0, string.Format("{0:x}.", (b >> 4) & 0xf)); sb.Insert(0, string.Format("{0:x}.", (b >> 0) & 0xf)); } return sb.ToString(); } return "?"; } public static string GetArpaFromEnum(string strEnum) { var number = System.Text.RegularExpressions.Regex.Replace(strEnum, "[^0-9]", ""); var sb = new StringBuilder("e164.arpa."); foreach (char c in number) sb.Insert(0, string.Format("{0}.", c)); return sb.ToString(); } /// <summary> /// Resolves an IP address to an System.Net.IPHostEntry instance. /// </summary> /// <param name="ip">An IP address.</param> /// <returns> /// An System.Net.IPHostEntry instance that contains address information about /// the host specified in address. ///</returns> public async Task<IPHostEntry> GetHostEntry(IPAddress ip) { var response = await Query(GetArpaFromIp(ip), QType.PTR); if (response.RecordsPTR.Length > 0) return await MakeEntry(response.RecordsPTR[0].PTRDNAME); return new IPHostEntry(); } /// <summary> /// Resolves a host name or IP address to an System.Net.IPHostEntry instance. /// </summary> /// <param name="hostNameOrAddress">The host name or IP address to resolve.</param> /// <returns> /// An System.Net.IPHostEntry instance that contains address information about /// the host specified in hostNameOrAddress. ///</returns> public async Task<IPHostEntry> GetHostEntry(string hostNameOrAddress) { IPAddress iPAddress; if (IPAddress.TryParse(hostNameOrAddress, out iPAddress)) return await GetHostEntry(iPAddress); return await MakeEntry(hostNameOrAddress); } } }
using System.Linq; using NUnit.Framework; using StructureMap.Pipeline; using StructureMap.Query; using StructureMap.Testing.Configuration.DSL; using StructureMap.Testing.Graph; using StructureMap.Testing.Widget; using StructureMap.Testing.Widget2; namespace StructureMap.Testing.Query { [TestFixture] public class ClosedTypeConfigurationIntegrationTester { #region Setup/Teardown [SetUp] public void SetUp() { container = new Container(x => { x.For<IWidget>().Singleton().Use<AWidget>(); x.For<Rule>().AddInstances(o => { o.Type<DefaultRule>(); o.Type<ARule>(); o.Type<ColorRule>().Ctor<string>("color").Is("red"); }); x.For<IEngine>().Use<PushrodEngine>(); x.For<IAutomobile>(); }); } #endregion private Container container; [Test] public void build_when_the_cast_does_not_work() { var configuration = container.Model.For<IWidget>(); configuration.Default.Get<Rule>().ShouldBeNull(); } [Test] public void build_when_the_cast_does_work() { container.Model.For<IWidget>().Default.Get<IWidget>().ShouldBeOfType<AWidget>(); } [Test] public void building_respects_the_lifecycle() { var widget1 = container.Model.For<IWidget>().Default.Get<IWidget>(); var widget2 = container.Model.For<IWidget>().Default.Get<IWidget>(); widget1.ShouldBeTheSameAs(widget2); } [Test] public void can_iterate_over_the_children_instances() { container.Model.InstancesOf<Rule>().Count().ShouldEqual(3); } [Test] public void eject_a_singleton() { var widget1 = container.GetInstance<IWidget>(); container.GetInstance<IWidget>().ShouldBeTheSameAs(widget1); container.Model.For<IWidget>().Default.EjectObject(); container.GetInstance<IWidget>().ShouldNotBeTheSameAs(widget1); } [Test] public void eject_a_singleton_that_has_not_been_created_does_no_harm() { container.Model.For<IWidget>().Default.EjectObject(); } [Test] public void eject_a_transient_does_no_harm() { container.Model.For<IEngine>().Default.EjectObject(); } [Test] public void eject_and_remove_an_instance_by_filter_should_remove_it_from_the_model() { InstanceRef iRef = container.Model.For<Rule>().Instances.First(); container.Model.For<Rule>().EjectAndRemove(x => x.Name == iRef.Name); container.Model.For<Rule>().Instances.Select(x => x.ConcreteType) .ShouldHaveTheSameElementsAs(typeof (ARule), typeof (ColorRule)); container.GetAllInstances<Rule>().Select(x => x.GetType()) .ShouldHaveTheSameElementsAs(typeof (ARule), typeof (ColorRule)); } [Test] public void eject_and_remove_an_instance_should_remove_it_from_the_model() { InstanceRef iRef = container.Model.For<Rule>().Instances.First(); container.Model.For<Rule>().EjectAndRemove(iRef); container.Model.For<Rule>().Instances.Select(x => x.ConcreteType) .ShouldHaveTheSameElementsAs(typeof (ARule), typeof (ColorRule)); container.GetAllInstances<Rule>().Select(x => x.GetType()) .ShouldHaveTheSameElementsAs(typeof (ARule), typeof (ColorRule)); } [Test] public void eject_and_remove_an_instance_should_remove_it_from_the_model_by_name() { InstanceRef iRef = container.Model.For<Rule>().Instances.First(); container.Model.For<Rule>().EjectAndRemove(iRef.Name); container.Model.For<Rule>().Instances.Select(x => x.ConcreteType) .ShouldHaveTheSameElementsAs(typeof (ARule), typeof (ColorRule)); container.GetAllInstances<Rule>().Select(x => x.GetType()) .ShouldHaveTheSameElementsAs(typeof (ARule), typeof (ColorRule)); } [Test] public void eject_for_a_transient_type_in_a_container_should_be_tracked() { IContainer nested = container.GetNestedContainer(); var engine1 = nested.GetInstance<IEngine>(); nested.GetInstance<IEngine>().ShouldBeTheSameAs(engine1); nested.GetInstance<IEngine>().ShouldBeTheSameAs(engine1); nested.GetInstance<IEngine>().ShouldBeTheSameAs(engine1); nested.GetInstance<IEngine>().ShouldBeTheSameAs(engine1); nested.GetInstance<IEngine>().ShouldBeTheSameAs(engine1); nested.GetInstance<IEngine>().ShouldBeTheSameAs(engine1); nested.GetInstance<IEngine>().ShouldBeTheSameAs(engine1); nested.Model.For<IEngine>().Default.EjectObject(); nested.GetInstance<IEngine>().ShouldNotBeTheSameAs(engine1); } [Test] public void get_default_should_return_null_when_it_does_not_exist() { container.Model.For<Rule>().Default.ShouldBeNull(); } [Test] public void get_default_when_it_exists() { container.Model.For<IWidget>().Default.ConcreteType.ShouldEqual(typeof (AWidget)); } [Test] public void get_lifecycle() { container.Model.For<IWidget>().Lifecycle.ShouldBeOfType<SingletonLifecycle>(); container.Model.For<Rule>().Lifecycle.ShouldBeOfType<TransientLifecycle>(); } [Test] public void has_been_created_for_a_purely_transient_object_should_always_be_false() { container.Model.For<IEngine>().Default.ObjectHasBeenCreated().ShouldBeFalse(); container.GetInstance<IEngine>(); container.Model.For<IEngine>().Default.ObjectHasBeenCreated().ShouldBeFalse(); } [Test] public void has_been_created_for_a_singleton() { container.Model.For<IWidget>().Default.ObjectHasBeenCreated().ShouldBeFalse(); container.GetInstance<IWidget>(); container.Model.For<IWidget>().Default.ObjectHasBeenCreated().ShouldBeTrue(); } [Test] public void has_been_created_for_a_transient_type_in_a_container_should_be_tracked() { IContainer nested = container.GetNestedContainer(); nested.Model.For<IEngine>().Default.ObjectHasBeenCreated().ShouldBeFalse(); nested.GetInstance<IEngine>(); nested.Model.For<IEngine>().Default.ObjectHasBeenCreated().ShouldBeTrue(); } [Test] public void has_implementations_negative_test() { container.Model.For<IAutomobile>().HasImplementations().ShouldBeFalse(); } [Test] public void has_implementations_positive_test() { container.Model.For<Rule>().HasImplementations().ShouldBeTrue(); container.Model.For<IWidget>().HasImplementations().ShouldBeTrue(); } } }
using System; using System.Collections.Generic; using CoreGraphics; using System.IO; using Mono.Data.Sqlite; using Foundation; using UIKit; namespace MonoCatalog { public partial class MonoDataSqliteController : UITableViewController { // The IntPtr and NSCoder constructors are required for controllers that need // to be able to be created from a xib rather than from managed code public MonoDataSqliteController (IntPtr handle) : base(handle) { Initialize (); } [Export("initWithCoder:")] public MonoDataSqliteController (NSCoder coder) : base(coder) { Initialize (); } public MonoDataSqliteController () : base ("MonoDataSqlite", null) { Initialize (); } void Initialize () { } class ItemsTableDelegate : UITableViewDelegate { // // Override to provide the sizing of the rows in our table // public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath) { if (indexPath.Section == 0) return 70f; return 50f; } } class ItemsDataSource : UITableViewDataSource { static readonly NSString kAdd = new NSString ("Add"); static readonly NSString kKey = new NSString ("Key"); const int kKeyTag = 1; const int kValueTag = 2; const int kAddTag = 3; class SectionInfo { public string Title; public Func<UITableView, NSIndexPath, UITableViewCell> Creator; } SectionInfo [] Sections = new[]{ new SectionInfo { Title = "Add Key/Value Pair", Creator = GetAddKeyValuePairCell }, new SectionInfo { Title = "Key/Value Pairs", Creator = GetKeyValuePairCell }, }; protected override void Dispose (bool disposing) { foreach (var cell in cells) cell.Dispose (); cells = null; base.Dispose (disposing); } public override nint NumberOfSections (UITableView tableView) { return Sections.Length; } public override string TitleForHeader (UITableView tableView, nint section) { return Sections [section].Title; } // keep a managed reference to the `cell` otherwise the GC can collect it and events // like TouchUpInside will crash the application (needs to be static for SectionInfo // initialization) static List<UITableViewCell> cells = new List<UITableViewCell> (); public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { return Sections [indexPath.Section].Creator (tableView, indexPath); } static UITableViewCell GetAddKeyValuePairCell (UITableView tableView, NSIndexPath indexPath) { var cell = tableView.DequeueReusableCell (kAdd); if (cell == null) { cell = new UITableViewCell (UITableViewCellStyle.Default, kAdd); cells.Add (cell); } else { RemoveViewWithTag (cell, kKeyTag << 1); RemoveViewWithTag (cell, kKeyTag); RemoveViewWithTag (cell, kValueTag << 1); RemoveViewWithTag (cell, kValueTag); RemoveViewWithTag (cell, kAddTag); } var lblKey = new UILabel () { BaselineAdjustment = UIBaselineAdjustment.AlignCenters, Frame = new CGRect (10f, 0f, 70f, 31f), Tag = kKeyTag << 1, Text = "Key: ", TextAlignment = UITextAlignment.Right, }; var key = new UITextField () { BorderStyle = UITextBorderStyle.Bezel, ClearButtonMode = UITextFieldViewMode.WhileEditing, Frame = new CGRect (80f, 1f, 170f, 31f), Placeholder = "Key", Tag = kKeyTag, AccessibilityLabel = "Key" }; var lblValue = new UILabel () { BaselineAdjustment = UIBaselineAdjustment.AlignCenters, Frame = new CGRect (10f, 37f, 70f, 31f), Tag = kValueTag << 1, Text = "Value: ", TextAlignment = UITextAlignment.Right, }; var value = new UITextField () { BorderStyle = UITextBorderStyle.Bezel, ClearButtonMode = UITextFieldViewMode.WhileEditing, Frame = new CGRect (80f, 38f, 170f, 31f), Placeholder = "Value", Tag = kValueTag, AccessibilityLabel = "Value" }; var add = UIButton.FromType (UIButtonType.ContactAdd); add.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; add.VerticalAlignment = UIControlContentVerticalAlignment.Center; add.Frame = new CGRect (255, 0, 40f, 70f); add.SetTitle ("Add", UIControlState.Normal); add.TouchUpInside += (o, e) => { WithCommand (c => { c.CommandText = "INSERT INTO [Items] ([Key], [Value]) VALUES (@key, @value)"; c.Parameters.Add (new SqliteParameter ("@key", key.Text)); c.Parameters.Add (new SqliteParameter ("@value", value.Text)); c.ExecuteNonQuery (); key.Text = ""; value.Text = ""; key.ResignFirstResponder (); value.ResignFirstResponder (); var path = NSIndexPath.FromRowSection (GetItemCount () - 1, 1); tableView.InsertRows (new NSIndexPath [] {path}, UITableViewRowAnimation.Bottom); }); }; cell.ContentView.AddSubview (lblKey); cell.ContentView.AddSubview (key); cell.ContentView.AddSubview (lblValue); cell.ContentView.AddSubview (value); cell.ContentView.AddSubview (add); return cell; } static void RemoveViewWithTag (UITableViewCell cell, int tag) { var u = cell.ContentView.ViewWithTag (tag); Console.Error.WriteLine ("# Removing view: {0}", u); if (u != null) u.RemoveFromSuperview (); } static UITableViewCell GetKeyValuePairCell (UITableView tableView, NSIndexPath indexPath) { string query = string.Format ("SELECT [Key], [Value] FROM [Items] LIMIT {0},1", indexPath.Row); string key = null, value = null; WithCommand (c => { c.CommandText = query; var r = c.ExecuteReader (); while (r.Read ()) { key = r ["Key"].ToString (); value = r ["Value"].ToString (); } }); var cell = tableView.DequeueReusableCell (kKey); if (cell == null){ cell = new UITableViewCell (UITableViewCellStyle.Default, kKey); cell.SelectionStyle = UITableViewCellSelectionStyle.None; cells.Add (cell); } else { RemoveViewWithTag (cell, kKeyTag); RemoveViewWithTag (cell, kValueTag); } var width = tableView.Bounds.Width / 2; Func<string, int, bool, UILabel> createLabel = (v, t, left) => { var label = new UILabel (); label.Frame = left ? new CGRect (10f, 1f, width-10, 40) : new CGRect (width, 1f, width-30, 40); label.Text = v; label.TextAlignment = left ? UITextAlignment.Left : UITextAlignment.Right; label.Tag = t; return label; }; var f = cell.TextLabel.Frame; cell.ContentView.AddSubview (createLabel (key, kKeyTag, true)); cell.ContentView.AddSubview (createLabel (value, kValueTag, false)); return cell; } public override nint RowsInSection (UITableView tableview, nint section) { if (section == 0) return 1; return GetItemCount (); } } static int GetItemCount () { int count = 0; WithCommand (c => { c.CommandText = "SELECT COUNT(*) FROM [Items]"; var r = c.ExecuteReader (); while (r.Read ()) { count = (int) (long) r [0]; } }); return count; } public override void ViewDidLoad () { base.ViewDidLoad (); TableView.DataSource = new ItemsDataSource (); TableView.Delegate = new ItemsTableDelegate (); } static SqliteConnection GetConnection () { var documents = Environment.GetFolderPath (Environment.SpecialFolder.Personal); string db = Path.Combine (documents, "items.db3"); bool exists = File.Exists (db); if (!exists) SqliteConnection.CreateFile (db); var conn = new SqliteConnection("Data Source=" + db); if (!exists) { var commands = new[] { "CREATE TABLE Items (Key ntext, Value ntext)", "INSERT INTO [Items] ([Key], [Value]) VALUES ('sample', 'text')", }; foreach (var cmd in commands) WithCommand (c => { c.CommandText = cmd; c.ExecuteNonQuery (); }); } return conn; } static void WithConnection (Action<SqliteConnection> action) { var connection = GetConnection (); try { connection.Open (); action (connection); } finally { connection.Close (); } } static void WithCommand (Action<SqliteCommand> command) { WithConnection (conn => { using (var cmd = conn.CreateCommand ()) command (cmd); }); } } }
namespace Microsoft.Azure.Management.Scheduler { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; public partial class SchedulerManagementClient : ServiceClient<SchedulerManagementClient>, ISchedulerManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Gets Azure subscription credentials. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// The subscription id. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// The API version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IJobCollectionsOperations. /// </summary> public virtual IJobCollectionsOperations JobCollections { get; private set; } /// <summary> /// Gets the IJobsOperations. /// </summary> public virtual IJobsOperations Jobs { get; private set; } /// <summary> /// Initializes a new instance of the SchedulerManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected SchedulerManagementClient(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SchedulerManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected SchedulerManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SchedulerManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected SchedulerManagementClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SchedulerManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected SchedulerManagementClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SchedulerManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SchedulerManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SchedulerManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SchedulerManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SchedulerManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SchedulerManagementClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SchedulerManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SchedulerManagementClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.JobCollections = new JobCollectionsOperations(this); this.Jobs = new JobsOperations(this); this.BaseUri = new Uri("https://management.azure.com"); this.ApiVersion = "2016-03-01"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), //// NOTE (pinwang): Scheduler supports Non ISO format TimeSpan and //// SDK Iso8601TimeSpanConverter will only convert ISO format for TimeSpan. ////Converters = new List<JsonConverter> //// { //// new Iso8601TimeSpanConverter() //// } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), //// NOTE (pinwang): Scheduler supports Non ISO format TimeSpan and //// SDK Iso8601TimeSpanConverter will only convert ISO format for TimeSpan. ////Converters = new List<JsonConverter> //// { //// new Iso8601TimeSpanConverter() //// } }; DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
using System.Runtime.Serialization; namespace VkApi.Wrapper.Objects { public enum GroupsGroupSubject { ///<summary> /// auto ///</summary> [EnumMember(Value = "1")] _1, ///<summary> /// activity holidays ///</summary> [EnumMember(Value = "2")] _2, ///<summary> /// business ///</summary> [EnumMember(Value = "3")] _3, ///<summary> /// pets ///</summary> [EnumMember(Value = "4")] _4, ///<summary> /// health ///</summary> [EnumMember(Value = "5")] _5, ///<summary> /// dating and communication ///</summary> [EnumMember(Value = "6")] _6, ///<summary> /// games ///</summary> [EnumMember(Value = "7")] _7, ///<summary> /// it ///</summary> [EnumMember(Value = "8")] _8, ///<summary> /// cinema ///</summary> [EnumMember(Value = "9")] _9, ///<summary> /// beauty and fashion ///</summary> [EnumMember(Value = "10")] _10, ///<summary> /// cooking ///</summary> [EnumMember(Value = "11")] _11, ///<summary> /// art and culture ///</summary> [EnumMember(Value = "12")] _12, ///<summary> /// literature ///</summary> [EnumMember(Value = "13")] _13, ///<summary> /// mobile services and internet ///</summary> [EnumMember(Value = "14")] _14, ///<summary> /// music ///</summary> [EnumMember(Value = "15")] _15, ///<summary> /// science and technology ///</summary> [EnumMember(Value = "16")] _16, ///<summary> /// real estate ///</summary> [EnumMember(Value = "17")] _17, ///<summary> /// news and media ///</summary> [EnumMember(Value = "18")] _18, ///<summary> /// security ///</summary> [EnumMember(Value = "19")] _19, ///<summary> /// education ///</summary> [EnumMember(Value = "20")] _20, ///<summary> /// home and renovations ///</summary> [EnumMember(Value = "21")] _21, ///<summary> /// politics ///</summary> [EnumMember(Value = "22")] _22, ///<summary> /// food ///</summary> [EnumMember(Value = "23")] _23, ///<summary> /// industry ///</summary> [EnumMember(Value = "24")] _24, ///<summary> /// travel ///</summary> [EnumMember(Value = "25")] _25, ///<summary> /// work ///</summary> [EnumMember(Value = "26")] _26, ///<summary> /// entertainment ///</summary> [EnumMember(Value = "27")] _27, ///<summary> /// religion ///</summary> [EnumMember(Value = "28")] _28, ///<summary> /// family ///</summary> [EnumMember(Value = "29")] _29, ///<summary> /// sports ///</summary> [EnumMember(Value = "30")] _30, ///<summary> /// insurance ///</summary> [EnumMember(Value = "31")] _31, ///<summary> /// television ///</summary> [EnumMember(Value = "32")] _32, ///<summary> /// goods and services ///</summary> [EnumMember(Value = "33")] _33, ///<summary> /// hobbies ///</summary> [EnumMember(Value = "34")] _34, ///<summary> /// finance ///</summary> [EnumMember(Value = "35")] _35, ///<summary> /// photo ///</summary> [EnumMember(Value = "36")] _36, ///<summary> /// esoterics ///</summary> [EnumMember(Value = "37")] _37, ///<summary> /// electronics and appliances ///</summary> [EnumMember(Value = "38")] _38, ///<summary> /// erotic ///</summary> [EnumMember(Value = "39")] _39, ///<summary> /// humor ///</summary> [EnumMember(Value = "40")] _40, ///<summary> /// society_humanities ///</summary> [EnumMember(Value = "41")] _41, ///<summary> /// design and graphics ///</summary> [EnumMember(Value = "42")] _42 } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Globalization; using Avalonia.Animation.Animators; using Avalonia.Utilities; namespace Avalonia { /// <summary> /// Defines a point. /// </summary> public readonly struct Point { static Point() { Animation.Animation.RegisterAnimator<PointAnimator>(prop => typeof(Point).IsAssignableFrom(prop.PropertyType)); } /// <summary> /// The X position. /// </summary> private readonly double _x; /// <summary> /// The Y position. /// </summary> private readonly double _y; /// <summary> /// Initializes a new instance of the <see cref="Point"/> structure. /// </summary> /// <param name="x">The X position.</param> /// <param name="y">The Y position.</param> public Point(double x, double y) { _x = x; _y = y; } /// <summary> /// Gets the X position. /// </summary> public double X => _x; /// <summary> /// Gets the Y position. /// </summary> public double Y => _y; /// <summary> /// Converts the <see cref="Point"/> to a <see cref="Vector"/>. /// </summary> /// <param name="p">The point.</param> public static implicit operator Vector(Point p) { return new Vector(p._x, p._y); } /// <summary> /// Negates a point. /// </summary> /// <param name="a">The point.</param> /// <returns>The negated point.</returns> public static Point operator -(Point a) { return new Point(-a._x, -a._y); } /// <summary> /// Checks for equality between two <see cref="Point"/>s. /// </summary> /// <param name="left">The first point.</param> /// <param name="right">The second point.</param> /// <returns>True if the points are equal; otherwise false.</returns> public static bool operator ==(Point left, Point right) { return left.X == right.X && left.Y == right.Y; } /// <summary> /// Checks for inequality between two <see cref="Point"/>s. /// </summary> /// <param name="left">The first point.</param> /// <param name="right">The second point.</param> /// <returns>True if the points are unequal; otherwise false.</returns> public static bool operator !=(Point left, Point right) { return !(left == right); } /// <summary> /// Adds two points. /// </summary> /// <param name="a">The first point.</param> /// <param name="b">The second point.</param> /// <returns>A point that is the result of the addition.</returns> public static Point operator +(Point a, Point b) { return new Point(a._x + b._x, a._y + b._y); } /// <summary> /// Adds a vector to a point. /// </summary> /// <param name="a">The point.</param> /// <param name="b">The vector.</param> /// <returns>A point that is the result of the addition.</returns> public static Point operator +(Point a, Vector b) { return new Point(a._x + b.X, a._y + b.Y); } /// <summary> /// Subtracts two points. /// </summary> /// <param name="a">The first point.</param> /// <param name="b">The second point.</param> /// <returns>A point that is the result of the subtraction.</returns> public static Point operator -(Point a, Point b) { return new Point(a._x - b._x, a._y - b._y); } /// <summary> /// Subtracts a vector from a point. /// </summary> /// <param name="a">The point.</param> /// <param name="b">The vector.</param> /// <returns>A point that is the result of the subtraction.</returns> public static Point operator -(Point a, Vector b) { return new Point(a._x - b.X, a._y - b.Y); } /// <summary> /// Multiplies a point by a factor coordinate-wise /// </summary> /// <param name="p">Point to multiply</param> /// <param name="k">Factor</param> /// <returns>Points having its coordinates multiplied</returns> public static Point operator *(Point p, double k) => new Point(p.X * k, p.Y * k); /// <summary> /// Multiplies a point by a factor coordinate-wise /// </summary> /// <param name="p">Point to multiply</param> /// <param name="k">Factor</param> /// <returns>Points having its coordinates multiplied</returns> public static Point operator *(double k, Point p) => new Point(p.X * k, p.Y * k); /// <summary> /// Divides a point by a factor coordinate-wise /// </summary> /// <param name="p">Point to divide by</param> /// <param name="k">Factor</param> /// <returns>Points having its coordinates divided</returns> public static Point operator /(Point p, double k) => new Point(p.X / k, p.Y / k); /// <summary> /// Applies a matrix to a point. /// </summary> /// <param name="point">The point.</param> /// <param name="matrix">The matrix.</param> /// <returns>The resulting point.</returns> public static Point operator *(Point point, Matrix matrix) { return new Point( (point.X * matrix.M11) + (point.Y * matrix.M21) + matrix.M31, (point.X * matrix.M12) + (point.Y * matrix.M22) + matrix.M32); } /// <summary> /// Parses a <see cref="Point"/> string. /// </summary> /// <param name="s">The string.</param> /// <returns>The <see cref="Thickness"/>.</returns> public static Point Parse(string s) { using (var tokenizer = new StringTokenizer(s, CultureInfo.InvariantCulture, exceptionMessage: "Invalid Point")) { return new Point( tokenizer.ReadDouble(), tokenizer.ReadDouble() ); } } /// <summary> /// Checks for equality between a point and an object. /// </summary> /// <param name="obj">The object.</param> /// <returns> /// True if <paramref name="obj"/> is a point that equals the current point. /// </returns> public override bool Equals(object obj) { if (obj is Point) { var other = (Point)obj; return X == other.X && Y == other.Y; } return false; } /// <summary> /// Returns a hash code for a <see cref="Point"/>. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { unchecked { int hash = 17; hash = (hash * 23) + _x.GetHashCode(); hash = (hash * 23) + _y.GetHashCode(); return hash; } } /// <summary> /// Returns the string representation of the point. /// </summary> /// <returns>The string representation of the point.</returns> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "{0}, {1}", _x, _y); } /// <summary> /// Transforms the point by a matrix. /// </summary> /// <param name="transform">The transform.</param> /// <returns>The transformed point.</returns> public Point Transform(Matrix transform) { var x = X; var y = Y; var xadd = y * transform.M21 + transform.M31; var yadd = x * transform.M12 + transform.M32; x *= transform.M11; x += xadd; y *= transform.M22; y += yadd; return new Point(x, y); } /// <summary> /// Returns a new point with the specified X coordinate. /// </summary> /// <param name="x">The X coordinate.</param> /// <returns>The new point.</returns> public Point WithX(double x) { return new Point(x, _y); } /// <summary> /// Returns a new point with the specified Y coordinate. /// </summary> /// <param name="y">The Y coordinate.</param> /// <returns>The new point.</returns> public Point WithY(double y) { return new Point(_x, y); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; namespace EventBus { /// <summary> /// The OrderedEventBus class is a simple and fast IEventBus implemention which processes event in the delivery order. /// </summary> /// <remarks>If you do not need the event processed in the delivery order, use SimpleEventBus instead.</remarks> public class OrderedEventBus : IEventBus, IDisposable { private const int DefaultMaxPendingEventNumber = 1024 * 1024; private bool _isDisposed; private static readonly OrderedEventBus DefaultEventBus = new OrderedEventBus(DefaultMaxPendingEventNumber); private List<EventHandlerHolder> _eventHandlerList = new List<EventHandlerHolder>(); private readonly object _eventHandlerLock = new object(); private readonly BlockingCollection<object> _eventQueue; /// <summary> /// The constructor of OrderedEventBus. /// </summary> /// <param name="maxPendingEventNumber">The maximum pending event number which does not yet dispatched</param> public OrderedEventBus(int maxPendingEventNumber) { _eventQueue = new BlockingCollection<object>( maxPendingEventNumber > 0 ? maxPendingEventNumber : DefaultMaxPendingEventNumber); Thread dispatchThread = new Thread(DispatchMessage) {IsBackground = true}; dispatchThread.Name = "OrderedEventBus-Thread-" + dispatchThread.ManagedThreadId; dispatchThread.Start(); } /// <summary> /// The pending event number which does not yet dispatched. /// </summary> public int PendingEventNumber => Math.Max(_eventQueue.Count, 0); /// <summary> /// Post an event to the event bus, dispatched after the specific time. /// </summary> /// <remarks>If you do not need the event processed in the delivery order, use SimpleEventBus instead.</remarks> /// <param name="eventObject">The event object</param> /// <param name="dispatchDelay">The delay time before dispatch this event</param> public void Post(object eventObject, TimeSpan dispatchDelay) { int dispatchDelayMs = (int) dispatchDelay.TotalMilliseconds; if (dispatchDelayMs >= 1) { Task.Delay(dispatchDelayMs).ContinueWith(task => _eventQueue.Add(eventObject)); } else { _eventQueue.Add(eventObject); } } /// <summary> /// Register event handlers in the handler instance. /// One handler instance may have many event handler methods. /// These methods have EventSubscriberAttribute contract and exactly one parameter. /// </summary> /// <remarks>If you do not need the event processed in the delivery order, use SimpleEventBus instead.</remarks> /// <param name="handler">The instance of event handler class</param> public void Register(object handler) { if (handler == null) { return; } MethodInfo[] miList = handler.GetType().GetMethods(); lock (_eventHandlerLock) { // Don't allow register multiple times. if (_eventHandlerList.Any(record => record.Handler == handler)) { return; } List<EventHandlerHolder> newList = null; foreach (MethodInfo mi in miList) { EventSubscriberAttribute attribute = mi.GetCustomAttribute<EventSubscriberAttribute>(); if (attribute != null) { ParameterInfo[] piList = mi.GetParameters(); if (piList.Length == 1) { // OK, we got valid handler, create newList as needed if (newList == null) { newList = new List<EventHandlerHolder>(_eventHandlerList); } newList.Add(new EventHandlerHolder(handler, mi, piList[0].ParameterType)); } } } // OK, we have new handler registered if (newList != null) { _eventHandlerList = newList; } } } /// <summary> /// Deregister event handlers belong to the handler instance. /// One handler instance may have many event handler methods. /// These methods have EventSubscriberAttribute contract and exactly one parameter. /// </summary> /// <param name="handler">The instance of event handler class</param> public void Deregister(object handler) { if (handler == null) { return; } lock (_eventHandlerLock) { bool needAction = _eventHandlerList.Any(record => record.Handler == handler); if (needAction) { List<EventHandlerHolder> newList = _eventHandlerList.Where(record => record.Handler != handler).ToList(); _eventHandlerList = newList; } } } /// <summary> /// Get the global OrderedEventBus instance. /// </summary> /// <returns>The global OrderedEventBus instance</returns> public static OrderedEventBus GetDefaultEventBus() { return DefaultEventBus; } private void DispatchMessage() { while (true) { object eventObject = null; try { eventObject = _eventQueue.Take(); InvokeEventHandler(eventObject); } catch (Exception de) { if (de is ObjectDisposedException) { return; } Trace.TraceError("Dispatch event ({0}) failed: {1}{2}{3}", eventObject, de.Message, Environment.NewLine, de.StackTrace); } } } private void InvokeEventHandler(object eventObject) { List<Task> taskList = null; // ReSharper disable once ForCanBeConvertedToForeach for (int i = 0; i < _eventHandlerList.Count; i++) { // ReSharper disable once InconsistentlySynchronizedField EventHandlerHolder record = _eventHandlerList[i]; if (eventObject == null || record.ParameterType.IsInstanceOfType(eventObject)) { Task task = Task.Run(() => record.MethodInfo.Invoke(record.Handler, new[] { eventObject })); if (taskList == null) taskList = new List<Task>(); taskList.Add(task); //record.MethodInfo.Invoke(record.Handler, new[] { eventObject }); } } if (taskList != null) { Task.WaitAll(taskList.ToArray()); } } /// <summary> /// Releases resources used by the <see cref="EventBus.OrderedEventBus"/> instance. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases resources used by the <see cref="EventBus.OrderedEventBus"/> instance. /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) { _eventQueue.Dispose(); } _isDisposed = true; } } } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * 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 halcyon 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.Collections.Generic; using System.Linq; using System.Text; using OpenMetaverse; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Framework; namespace OpenSim.Region.CoreModules.Agent.BotManager { public abstract class MovementAction { protected readonly NodeGraph m_nodeGraph = new NodeGraph(); protected int m_frame; protected bool m_toAvatar; protected BotMovementController m_controller; protected bool m_paused; private bool m_hasStoppedMoving = false; protected MovementDescription m_baseDescription; protected bool m_hasFiredFinishedMovingEvent = false; protected DateTime m_timeOfLastStep = DateTime.MinValue; private int _amountOfTimesLeftToJump = 0; public MovementAction(MovementDescription desc, BotMovementController controller) { m_baseDescription = desc; m_controller = controller; } public abstract void Start(); public abstract void Stop(); public abstract void UpdateInformation(); public abstract void CheckInformationBeforeMove(); public virtual bool Frame() { ScenePresence botPresence = m_controller.Scene.GetScenePresence(m_controller.Bot.AgentID); if (botPresence == null) return false; m_frame++; GetNextDestination(); SetBeginningOfMovementFrame(); if (m_frame % 10 == 0) //Only every 10 frames { m_frame = 0; UpdateInformation(); } return true; } public void PauseMovement() { m_paused = true; } public void ResumeMovement() { m_paused = false; SetBeginningOfMovementFrame(); } public void SetBeginningOfMovementFrame() { m_timeOfLastStep = DateTime.Now; } private void GetNextDestination() { //Fire the move event CheckInformationBeforeMove(); ScenePresence botPresence = m_controller.Scene.GetScenePresence(m_controller.Bot.AgentID); if (m_controller == null || botPresence.PhysicsActor == null) return; if (m_paused) { StopMoving(botPresence, LastFlying, false); return; } Vector3 pos; TravelMode state; bool teleport; bool changingNodes; float closeToPoint = botPresence.PhysicsActor.Flying ? 1.5f : 1.0f; TimeSpan diffFromLastFrame = (DateTime.Now - m_timeOfLastStep); if (m_nodeGraph.GetNextPosition(botPresence, closeToPoint, diffFromLastFrame, m_baseDescription.TimeBeforeTeleportToNextPositionOccurs, out pos, out state, out teleport, out changingNodes)) { if (changingNodes) _amountOfTimesLeftToJump = 0; m_hasFiredFinishedMovingEvent = false; if (teleport) { //We're forced to teleport to the next location Teleport(botPresence, pos); m_nodeGraph.CurrentPos++; changingNodes = true; //Trigger the update to tell the user that the move failed TriggerFailedToMoveToNextNode(botPresence, m_nodeGraph.CurrentPos == 0 ? m_nodeGraph.NumberOfNodes : m_nodeGraph.CurrentPos); } else { switch (state) { case TravelMode.Fly: FlyTo(botPresence, pos); break; case TravelMode.Run: botPresence.SetAlwaysRun = true; WalkTo(botPresence, pos); break; case TravelMode.Walk: botPresence.SetAlwaysRun = false; WalkTo(botPresence, pos); break; case TravelMode.Teleport: //We have to do this here as if there is a wait before the teleport, we won't get the wait event fired if (changingNodes) TriggerChangingNodes(botPresence, m_nodeGraph.CurrentPos == 0 ? m_nodeGraph.NumberOfNodes : m_nodeGraph.CurrentPos); Teleport(botPresence, pos); m_nodeGraph.CurrentPos++; changingNodes = true; break; case TravelMode.Wait: StopMoving(botPresence, LastFlying, false); break; } } //Tell the user that we've switched nodes if (changingNodes) TriggerChangingNodes(botPresence, m_nodeGraph.CurrentPos == 0 ? m_nodeGraph.NumberOfNodes : m_nodeGraph.CurrentPos); } else { StopMoving(botPresence, LastFlying, true); if (!m_hasFiredFinishedMovingEvent) { m_hasFiredFinishedMovingEvent = true; TriggerFinishedMovement(botPresence); } } } public virtual void TriggerFinishedMovement(ScenePresence botPresence) { List<object> parameters = new List<object>() { botPresence.AbsolutePosition }; const int BOT_MOVE_COMPLETE = 1; TriggerBotUpdate(BOT_MOVE_COMPLETE, parameters); } public virtual void TriggerChangingNodes(ScenePresence botPresence, int nextNode) { List<object> parameters = new List<object>() { nextNode, botPresence.AbsolutePosition }; const int BOT_MOVE_UPDATE = 2; TriggerBotUpdate(BOT_MOVE_UPDATE, parameters); } public virtual void TriggerFailedToMoveToNextNode(ScenePresence botPresence, int nextNode) { List<object> parameters = new List<object>() { nextNode, botPresence.AbsolutePosition }; const int BOT_MOVE_FAILED = 3; TriggerBotUpdate(BOT_MOVE_FAILED, parameters); } public virtual void TriggerAvatarLost(ScenePresence botPresence, ScenePresence followPresence, float distance) { List<object> parameters = new List<object>() { followPresence == null ? Vector3.Zero : followPresence.AbsolutePosition, distance, botPresence.AbsolutePosition }; const int BOT_MOVE_AVATAR_LOST = 4; TriggerBotUpdate(BOT_MOVE_AVATAR_LOST, parameters); } public virtual void TriggerBotUpdate(int flag, List<object> parameters) { lock (m_controller.Bot.RegisteredScriptsForPathUpdateEvents) { foreach (UUID itemID in m_controller.Bot.RegisteredScriptsForPathUpdateEvents) { m_controller.Scene.EventManager.TriggerBotPathUpdateEvent(itemID, m_controller.Bot.AgentID, flag, parameters); } } } public void Teleport(ScenePresence botPresence, Vector3 pos) { botPresence.StandUp(null, false, true); botPresence.Teleport(pos); } public void UpdateMovementAnimations(bool p) { ScenePresence presence = m_controller.Scene.GetScenePresence(m_controller.Bot.AgentID); presence.UpdateMovementAnimations(); } // Makes the bot fly to the specified destination public void StopMoving(ScenePresence botPresence, bool fly, bool clearPath) { if (m_hasStoppedMoving) return; m_hasStoppedMoving = true; State = BotState.Idle; //Clear out any nodes if (clearPath) m_nodeGraph.Clear(); //Send the stop message m_movementFlag = (uint)AgentManager.ControlFlags.NONE; if (fly) m_movementFlag |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY; OnBotAgentUpdate(botPresence, Vector3.Zero, m_movementFlag, m_bodyDirection, false); //botPresence.CollisionPlane = Vector4.UnitW; if (botPresence.PhysicsActor != null) botPresence.PhysicsActor.SetVelocity(Vector3.Zero, false); } #region Move/Rotate the bot private uint m_movementFlag; private Quaternion m_bodyDirection = Quaternion.Identity; public BotState m_currentState = BotState.Idle; public BotState m_previousState = BotState.Idle; public bool LastFlying { get; set; } public BotState State { get { return m_currentState; } set { if (m_currentState != value) { m_previousState = m_currentState; m_currentState = value; } } } // Makes the bot walk to the specified destination public void WalkTo(ScenePresence presence, Vector3 destination) { if (!Util.IsZeroVector(destination - presence.AbsolutePosition)) { walkTo(presence, destination); State = BotState.Walking; LastFlying = false; } } // Makes the bot fly to the specified destination public void FlyTo(ScenePresence presence, Vector3 destination) { if (Util.IsZeroVector(destination - presence.AbsolutePosition) == false) { flyTo(presence, destination); State = BotState.Flying; LastFlying = true; } else { m_movementFlag = (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS; OnBotAgentUpdate(presence, Vector3.Zero, m_movementFlag, m_bodyDirection); m_movementFlag = (uint)AgentManager.ControlFlags.NONE; } } private void RotateTo(ScenePresence presence, Vector3 destination) { Vector3 bot_forward = new Vector3(1, 0, 0); if (destination - presence.AbsolutePosition != Vector3.Zero) { Vector3 bot_toward = Util.GetNormalizedVector(destination - presence.AbsolutePosition); Quaternion rot_result = llRotBetween(bot_forward, bot_toward); m_bodyDirection = rot_result; } m_movementFlag = (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS; OnBotAgentUpdate(presence, Vector3.Zero, m_movementFlag, m_bodyDirection); m_movementFlag = (uint)AgentManager.ControlFlags.NONE; } #region rotation helper functions private Vector3 llRot2Fwd(Quaternion r) { return (new Vector3(1, 0, 0) * r); } private Quaternion llRotBetween(Vector3 a, Vector3 b) { //A and B should both be normalized double dotProduct = Vector3.Dot(a, b); Vector3 crossProduct = Vector3.Cross(a, b); double magProduct = Vector3.Distance(Vector3.Zero, a) * Vector3.Distance(Vector3.Zero, b); double angle = Math.Acos(dotProduct / magProduct); Vector3 axis = Vector3.Normalize(crossProduct); float s = (float)Math.Sin(angle / 2); return new Quaternion(axis.X * s, axis.Y * s, axis.Z * s, (float)Math.Cos(angle / 2)); } #endregion #region Move / fly bot /// <summary> /// Does the actual movement of the bot /// </summary> /// <param name="pos"></param> protected void walkTo(ScenePresence presence, Vector3 pos) { Vector3 bot_forward = new Vector3(2, 0, 0); Vector3 bot_toward = Vector3.Zero; Vector3 dif = pos - presence.AbsolutePosition; bool isJumping = (Math.Abs(dif.X) < 2 && Math.Abs(dif.Y) < 2 && Math.Abs(dif.Z) > 1.5f) || _amountOfTimesLeftToJump > 0; if (dif != Vector3.Zero) { try { bot_toward = Util.GetNormalizedVector(dif); Quaternion rot_result = llRotBetween(bot_forward, bot_toward); m_bodyDirection = rot_result; } catch (ArgumentException) { } } //if the bot is being forced to turn around 180 degrees, it won't be able to and it will get stuck // and eventually teleport (mantis 2898). This detects when the vector is too close to zero and // needs to have help being turned around so that it can then go in the correct direction if(m_bodyDirection.ApproxEquals(new Quaternion(), 0.01f)) { //Turn to the right until we move far enough away from zero that we will turn around on our own bot_toward = new Vector3(0, 1, 0); Quaternion rot_result = llRotBetween(bot_forward, bot_toward); m_bodyDirection = rot_result; } if (isJumping) { //Add UP_POS as well (meaning that we need to be able to move freely up as well as along the ground) m_movementFlag = (uint)(AgentManager.ControlFlags.AGENT_CONTROL_AT_POS | AgentManager.ControlFlags.AGENT_CONTROL_UP_POS); presence.ShouldJump = true; if (_amountOfTimesLeftToJump == 0) _amountOfTimesLeftToJump = 10;//Because we need the bot to apply force over multiple frames (just like agents do) _amountOfTimesLeftToJump--; //Make sure that we aren't jumping too far (apply a constant to make sure of this) const double JUMP_CONST = 0.3; bot_toward = Util.GetNormalizedVector(dif); if (Math.Abs(bot_toward.X) < JUMP_CONST) bot_toward.X = (float)JUMP_CONST * (bot_toward.X < 0 ? -1 : 1); if (Math.Abs(bot_toward.Y) < JUMP_CONST) bot_toward.Y = (float)JUMP_CONST * (bot_toward.Y < 0 ? -1 : 1); if(presence.PhysicsActor.IsColliding)//After they leave the ground, don't use as much force so we don't send the bot flying into the air bot_forward = new Vector3(4, 0, 4); else bot_forward = new Vector3(2, 0, 2); Quaternion rot_result = llRotBetween(bot_forward, bot_toward); m_bodyDirection = rot_result; } else m_movementFlag = (uint)(AgentManager.ControlFlags.AGENT_CONTROL_AT_POS); if (presence.AllowMovement) OnBotAgentUpdate(presence, bot_toward, m_movementFlag, m_bodyDirection); else OnBotAgentUpdate(presence, Vector3.Zero, (uint)AgentManager.ControlFlags.AGENT_CONTROL_STOP, Quaternion.Identity); if (!isJumping) m_movementFlag = (uint)AgentManager.ControlFlags.NONE; } /// <summary> /// Does the actual movement of the bot /// </summary> /// <param name="pos"></param> protected void flyTo(ScenePresence presence, Vector3 pos) { Vector3 bot_forward = new Vector3(1, 0, 0), bot_toward = Vector3.Zero; if (pos - presence.AbsolutePosition != Vector3.Zero) { try { bot_toward = Util.GetNormalizedVector(pos - presence.AbsolutePosition); Quaternion rot_result = llRotBetween(bot_forward, bot_toward); m_bodyDirection = rot_result; } catch (ArgumentException) { } } //if the bot is being forced to turn around 180 degrees, it won't be able to and it will get stuck // and eventually teleport (mantis 2898). This detects when the vector is too close to zero and // needs to have help being turned around so that it can then go in the correct direction if (m_bodyDirection.ApproxEquals(new Quaternion(), 0.01f)) { //Turn to the right until we move far enough away from zero that we will turn around on our own bot_toward = new Vector3(0, 1, 0); Quaternion rot_result = llRotBetween(bot_forward, bot_toward); m_bodyDirection = rot_result; } m_movementFlag = (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY; Vector3 diffPos = pos - presence.AbsolutePosition; if (Math.Abs(diffPos.X) > 1.5 || Math.Abs(diffPos.Y) > 1.5) { m_movementFlag |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS; } if (presence.AbsolutePosition.Z < pos.Z - 1) { m_movementFlag |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_POS; } else if (presence.AbsolutePosition.Z > pos.Z + 1) { m_movementFlag |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG; } if (bot_forward.X > 0) { m_movementFlag |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_TURN_LEFT; m_movementFlag |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS; } if (bot_forward.X < 0) { m_movementFlag |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_TURN_RIGHT; m_movementFlag |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG; } if (presence.AllowMovement) OnBotAgentUpdate(presence, bot_toward, m_movementFlag, m_bodyDirection); m_movementFlag = (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY; } #endregion public void OnBotAgentUpdate(ScenePresence presence, Vector3 toward, uint controlFlag, Quaternion bodyRotation) { OnBotAgentUpdate(presence, toward, controlFlag, bodyRotation, true); } public void OnBotAgentUpdate(ScenePresence presence, Vector3 toward, uint controlFlag, Quaternion bodyRotation, bool isMoving) { if (m_controller.Bot.Frozen && isMoving) { bool fly = presence.PhysicsActor == null ? false : presence.PhysicsActor.Flying; StopMoving(presence, fly, false); return; } if (isMoving) m_hasStoppedMoving = false; AgentUpdateArgs pack = new AgentUpdateArgs { ControlFlags = controlFlag, BodyRotation = bodyRotation }; presence.HandleAgentUpdate(presence.ControllingClient, pack); } #endregion } public class MovementDescription { /// <summary> /// The time (in seconds) before the bot teleports to the next position /// </summary> public float TimeBeforeTeleportToNextPositionOccurs = 60; } }
using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Orleans; using Orleans.Concurrency; using Orleans.Runtime; using UnitTests.GrainInterfaces; using Orleans.Runtime.Configuration; using Microsoft.Extensions.Logging; namespace UnitTests.Grains { internal class StressTestGrain : Grain, IStressTestGrain { private string label; private ILogger logger; public StressTestGrain(ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}"); } public override Task OnActivateAsync() { if (this.GetPrimaryKeyLong() == -2) throw new ArgumentException("Primary key cannot be -2 for this test case"); this.label = this.GetPrimaryKeyLong().ToString(); this.logger.Info("OnActivateAsync"); return Task.CompletedTask; } public Task<string> GetLabel() { return Task.FromResult(this.label); } public Task SetLabel(string label) { this.label = label; //logger.Info("SetLabel {0} received", label); return Task.CompletedTask; } public Task<IStressTestGrain> GetGrainReference() { return Task.FromResult(this.AsReference<IStressTestGrain>()); } public Task PingOthers(long[] others) { List<Task> promises = new List<Task>(); foreach (long key in others) { IStressTestGrain g1 = this.GrainFactory.GetGrain<IStressTestGrain>(key); Task promise = g1.GetLabel(); promises.Add(promise); } return Task.WhenAll(promises); } public Task<List<Tuple<GrainId, int, List<Tuple<SiloAddress, ActivationId>>>>> LookUpMany( SiloAddress destination, List<Tuple<GrainId, int>> grainAndETagList, int retries = 0) { var list = new List<Tuple<GrainId, int, List<Tuple<SiloAddress, ActivationId>>>>(); foreach (Tuple<GrainId, int> tuple in grainAndETagList) { GrainId id = tuple.Item1; var reply = new List<Tuple<SiloAddress, ActivationId>>(); for (int i = 0; i < 10; i++) { var siloAddress = SiloAddress.New(new IPEndPoint(ConfigUtilities.GetLocalIPAddress(),0), 0); reply.Add(new Tuple<SiloAddress, ActivationId>(siloAddress, ActivationId.NewId())); } list.Add(new Tuple<GrainId, int, List<Tuple<SiloAddress, ActivationId>>>(id, 3, reply)); } return Task.FromResult(list); } public Task<byte[]> Echo(byte[] data) { return Task.FromResult(data); } public Task Ping(byte[] data) { return Task.CompletedTask; } public async Task PingWithDelay(byte[] data, TimeSpan delay) { await Task.Delay(delay); } public Task Send(byte[] data) { return Task.CompletedTask; } public Task DeactivateSelf() { DeactivateOnIdle(); return Task.CompletedTask; } } [Reentrant] internal class ReentrantStressTestGrain : Grain, IReentrantStressTestGrain { private string label; private ILogger logger; public ReentrantStressTestGrain(ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}"); } public override Task OnActivateAsync() { this.label = this.GetPrimaryKeyLong().ToString(); this.logger.Info("OnActivateAsync"); return Task.CompletedTask; } public Task<string> GetRuntimeInstanceId() { return Task.FromResult(this.RuntimeIdentity); } public Task<byte[]> Echo(byte[] data) { return Task.FromResult(data); } public Task Ping(byte[] data) { return Task.CompletedTask; } public async Task PingWithDelay(byte[] data, TimeSpan delay) { await Task.Delay(delay); } public Task PingMutableArray(byte[] data, long nextGrain, bool nextGrainIsRemote) { if (nextGrain > 0) { if (nextGrainIsRemote) { return this.GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain).PingMutableArray(data, -1, false); } return this.GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain) .PingMutableArray(data, -1, false); } return Task.CompletedTask; } public Task PingImmutableArray(Immutable<byte[]> data, long nextGrain, bool nextGrainIsRemote) { if (nextGrain > 0) { if (nextGrainIsRemote) { return this.GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain) .PingImmutableArray(data, -1, false); } return this.GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain) .PingImmutableArray(data, -1, false); } return Task.CompletedTask; } public Task PingMutableDictionary(Dictionary<int, string> data, long nextGrain, bool nextGrainIsRemote) { if (nextGrain > 0) { if (nextGrainIsRemote) { return this.GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain) .PingMutableDictionary(data, -1, false); } return this.GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain) .PingMutableDictionary(data, -1, false); } return Task.CompletedTask; } public Task PingImmutableDictionary(Immutable<Dictionary<int, string>> data, long nextGrain, bool nextGrainIsRemote) { if (nextGrain > 0) { if (nextGrainIsRemote) { return this.GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain) .PingImmutableDictionary(data, -1, false); } return this.GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain) .PingImmutableDictionary(data, -1, false); } return Task.CompletedTask; } public async Task InterleavingConsistencyTest(int numItems) { TimeSpan delay = TimeSpan.FromMilliseconds(1); SafeRandom random = new SafeRandom(); List<Task> getFileMetadataPromises = new List<Task>(numItems*2); Dictionary<int, string> fileMetadatas = new Dictionary<int, string>(numItems*2); for (int i = 0; i < numItems; i++) { int capture = i; Func<Task> func = ( async () => { await Task.Delay(random.NextTimeSpan(delay)); int fileMetadata = capture; if ((fileMetadata%2) == 0) { fileMetadatas.Add(fileMetadata, fileMetadata.ToString()); } }); getFileMetadataPromises.Add(func()); } await Task.WhenAll(getFileMetadataPromises.ToArray()); List<Task> tagPromises = new List<Task>(fileMetadatas.Count); foreach (KeyValuePair<int, string> keyValuePair in fileMetadatas) { int fileId = keyValuePair.Key; Func<Task> func = (async () => { await Task.Delay(random.NextTimeSpan(delay)); string fileMetadata = fileMetadatas[fileId]; }); tagPromises.Add(func()); } await Task.WhenAll(tagPromises); // sort the fileMetadatas according to fileIds. List<string> results = new List<string>(fileMetadatas.Count); for (int i = 0; i < numItems; i++) { string metadata; if (fileMetadatas.TryGetValue(i, out metadata)) { results.Add(metadata); } } if (numItems != results.Count) { //throw new OrleansException(String.Format("numItems != results.Count, {0} != {1}", numItems, results.Count)); } } } [Reentrant] [StatelessWorker] public class ReentrantLocalStressTestGrain : Grain, IReentrantLocalStressTestGrain { private string label; private ILogger logger; public ReentrantLocalStressTestGrain(ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}"); } public override Task OnActivateAsync() { this.label = this.GetPrimaryKeyLong().ToString(); this.logger.Info("OnActivateAsync"); return Task.CompletedTask; } public Task<byte[]> Echo(byte[] data) { return Task.FromResult(data); } public Task<string> GetRuntimeInstanceId() { return Task.FromResult(this.RuntimeIdentity); } public Task Ping(byte[] data) { return Task.CompletedTask; } public async Task PingWithDelay(byte[] data, TimeSpan delay) { await Task.Delay(delay); } public Task PingMutableArray(byte[] data, long nextGrain, bool nextGrainIsRemote) { if (nextGrain > 0) { if (nextGrainIsRemote) { return this.GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain).PingMutableArray(data, -1, false); } return this.GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain) .PingMutableArray(data, -1, false); } return Task.CompletedTask; } public Task PingImmutableArray(Immutable<byte[]> data, long nextGrain, bool nextGrainIsRemote) { if (nextGrain > 0) { if (nextGrainIsRemote) { return this.GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain) .PingImmutableArray(data, -1, false); } return this.GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain) .PingImmutableArray(data, -1, false); } return Task.CompletedTask; } public Task PingMutableDictionary(Dictionary<int, string> data, long nextGrain, bool nextGrainIsRemote) { if (nextGrain > 0) { if (nextGrainIsRemote) { return this.GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain) .PingMutableDictionary(data, -1, false); } return this.GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain) .PingMutableDictionary(data, -1, false); } return Task.CompletedTask; } public Task PingImmutableDictionary(Immutable<Dictionary<int, string>> data, long nextGrain, bool nextGrainIsRemote) { if (nextGrain > 0) { if (nextGrainIsRemote) { return this.GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain) .PingImmutableDictionary(data, -1, false); } return this.GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain) .PingImmutableDictionary(data, -1, false); } return Task.CompletedTask; } } }
using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace Lucene.Net.Util.Automaton { /* * 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. */ // TODO // - do we really need the .bits...? if not we can make util in UnicodeUtil to convert 1 char into a BytesRef /// <summary> /// Converts UTF-32 automata to the equivalent UTF-8 representation. /// @lucene.internal /// </summary> public sealed class UTF32ToUTF8 { // Unicode boundaries for UTF8 bytes 1,2,3,4 private static readonly int[] StartCodes = new int[] { 0, 128, 2048, 65536 }; private static readonly int[] EndCodes = new int[] { 127, 2047, 65535, 1114111 }; internal static int[] MASKS = new int[32]; static UTF32ToUTF8() { int v = 2; for (int i = 0; i < 32; i++) { MASKS[i] = v - 1; v *= 2; } } // Represents one of the N utf8 bytes that (in sequence) // define a code point. value is the byte value; bits is // how many bits are "used" by utf8 at that byte private class UTF8Byte { internal int Value; // TODO: change to byte internal sbyte Bits; } // Holds a single code point, as a sequence of 1-4 utf8 bytes: // TODO: maybe move to UnicodeUtil? private class UTF8Sequence { internal readonly UTF8Byte[] Bytes; internal int Len; public UTF8Sequence() { Bytes = new UTF8Byte[4]; for (int i = 0; i < 4; i++) { Bytes[i] = new UTF8Byte(); } } public virtual int ByteAt(int idx) { return Bytes[idx].Value; } public virtual int NumBits(int idx) { return Bytes[idx].Bits; } internal virtual void Set(int code) { if (code < 128) { // 0xxxxxxx Bytes[0].Value = code; Bytes[0].Bits = 7; Len = 1; } else if (code < 2048) { // 110yyyxx 10xxxxxx Bytes[0].Value = (6 << 5) | (code >> 6); Bytes[0].Bits = 5; SetRest(code, 1); Len = 2; } else if (code < 65536) { // 1110yyyy 10yyyyxx 10xxxxxx Bytes[0].Value = (14 << 4) | (code >> 12); Bytes[0].Bits = 4; SetRest(code, 2); Len = 3; } else { // 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx Bytes[0].Value = (30 << 3) | (code >> 18); Bytes[0].Bits = 3; SetRest(code, 3); Len = 4; } } internal virtual void SetRest(int code, int numBytes) { for (int i = 0; i < numBytes; i++) { Bytes[numBytes - i].Value = 128 | (code & MASKS[5]); Bytes[numBytes - i].Bits = 6; code = code >> 6; } } public override string ToString() { StringBuilder b = new StringBuilder(); for (int i = 0; i < Len; i++) { if (i > 0) { b.Append(' '); } b.Append(Number.ToBinaryString(Bytes[i].Value)); } return b.ToString(); } } private readonly UTF8Sequence StartUTF8 = new UTF8Sequence(); private readonly UTF8Sequence EndUTF8 = new UTF8Sequence(); private readonly UTF8Sequence TmpUTF8a = new UTF8Sequence(); private readonly UTF8Sequence TmpUTF8b = new UTF8Sequence(); // Builds necessary utf8 edges between start & end internal void ConvertOneEdge(State start, State end, int startCodePoint, int endCodePoint) { StartUTF8.Set(startCodePoint); EndUTF8.Set(endCodePoint); //System.out.println("start = " + startUTF8); //System.out.println(" end = " + endUTF8); Build(start, end, StartUTF8, EndUTF8, 0); } private void Build(State start, State end, UTF8Sequence startUTF8, UTF8Sequence endUTF8, int upto) { // Break into start, middle, end: if (startUTF8.ByteAt(upto) == endUTF8.ByteAt(upto)) { // Degen case: lead with the same byte: if (upto == startUTF8.Len - 1 && upto == endUTF8.Len - 1) { // Super degen: just single edge, one UTF8 byte: start.AddTransition(new Transition(startUTF8.ByteAt(upto), endUTF8.ByteAt(upto), end)); return; } else { Debug.Assert(startUTF8.Len > upto + 1); Debug.Assert(endUTF8.Len > upto + 1); State n = NewUTF8State(); // Single value leading edge start.AddTransition(new Transition(startUTF8.ByteAt(upto), n)); // type=single // Recurse for the rest Build(n, end, startUTF8, endUTF8, 1 + upto); } } else if (startUTF8.Len == endUTF8.Len) { if (upto == startUTF8.Len - 1) { start.AddTransition(new Transition(startUTF8.ByteAt(upto), endUTF8.ByteAt(upto), end)); // type=startend } else { Start(start, end, startUTF8, upto, false); if (endUTF8.ByteAt(upto) - startUTF8.ByteAt(upto) > 1) { // There is a middle All(start, end, startUTF8.ByteAt(upto) + 1, endUTF8.ByteAt(upto) - 1, startUTF8.Len - upto - 1); } End(start, end, endUTF8, upto, false); } } else { // start Start(start, end, startUTF8, upto, true); // possibly middle, spanning multiple num bytes int byteCount = 1 + startUTF8.Len - upto; int limit = endUTF8.Len - upto; while (byteCount < limit) { // wasteful: we only need first byte, and, we should // statically encode this first byte: TmpUTF8a.Set(StartCodes[byteCount - 1]); TmpUTF8b.Set(EndCodes[byteCount - 1]); All(start, end, TmpUTF8a.ByteAt(0), TmpUTF8b.ByteAt(0), TmpUTF8a.Len - 1); byteCount++; } // end End(start, end, endUTF8, upto, true); } } private void Start(State start, State end, UTF8Sequence utf8, int upto, bool doAll) { if (upto == utf8.Len - 1) { // Done recursing start.AddTransition(new Transition(utf8.ByteAt(upto), utf8.ByteAt(upto) | MASKS[utf8.NumBits(upto) - 1], end)); // type=start } else { State n = NewUTF8State(); start.AddTransition(new Transition(utf8.ByteAt(upto), n)); // type=start Start(n, end, utf8, 1 + upto, true); int endCode = utf8.ByteAt(upto) | MASKS[utf8.NumBits(upto) - 1]; if (doAll && utf8.ByteAt(upto) != endCode) { All(start, end, utf8.ByteAt(upto) + 1, endCode, utf8.Len - upto - 1); } } } private void End(State start, State end, UTF8Sequence utf8, int upto, bool doAll) { if (upto == utf8.Len - 1) { // Done recursing start.AddTransition(new Transition(utf8.ByteAt(upto) & (~MASKS[utf8.NumBits(upto) - 1]), utf8.ByteAt(upto), end)); // type=end } else { int startCode; if (utf8.NumBits(upto) == 5) { // special case -- avoid created unused edges (utf8 // doesn't accept certain byte sequences) -- there // are other cases we could optimize too: startCode = 194; } else { startCode = utf8.ByteAt(upto) & (~MASKS[utf8.NumBits(upto) - 1]); } if (doAll && utf8.ByteAt(upto) != startCode) { All(start, end, startCode, utf8.ByteAt(upto) - 1, utf8.Len - upto - 1); } State n = NewUTF8State(); start.AddTransition(new Transition(utf8.ByteAt(upto), n)); // type=end End(n, end, utf8, 1 + upto, true); } } private void All(State start, State end, int startCode, int endCode, int left) { if (left == 0) { start.AddTransition(new Transition(startCode, endCode, end)); // type=all } else { State lastN = NewUTF8State(); start.AddTransition(new Transition(startCode, endCode, lastN)); // type=all while (left > 1) { State n = NewUTF8State(); lastN.AddTransition(new Transition(128, 191, n)); // type=all* left--; lastN = n; } lastN.AddTransition(new Transition(128, 191, end)); // type = all* } } private State[] Utf8States; private int Utf8StateCount; /// <summary> /// Converts an incoming utf32 automaton to an equivalent /// utf8 one. The incoming automaton need not be /// deterministic. Note that the returned automaton will /// not in general be deterministic, so you must /// determinize it if that's needed. /// </summary> public Automaton Convert(Automaton utf32) { if (utf32.IsSingleton) { utf32 = utf32.CloneExpanded(); } State[] map = new State[utf32.NumberedStates.Length]; List<State> pending = new List<State>(); State utf32State = utf32.InitialState; pending.Add(utf32State); Automaton utf8 = new Automaton(); utf8.Deterministic = false; State utf8State = utf8.InitialState; Utf8States = new State[5]; Utf8StateCount = 0; utf8State.number = Utf8StateCount; Utf8States[Utf8StateCount] = utf8State; Utf8StateCount++; utf8State.Accept = utf32State.Accept; map[utf32State.number] = utf8State; while (pending.Count != 0) { utf32State = pending[pending.Count - 1]; pending.RemoveAt(pending.Count - 1); utf8State = map[utf32State.number]; for (int i = 0; i < utf32State.numTransitions; i++) { Transition t = utf32State.TransitionsArray[i]; State destUTF32 = t.To; State destUTF8 = map[destUTF32.number]; if (destUTF8 == null) { destUTF8 = NewUTF8State(); destUTF8.accept = destUTF32.accept; map[destUTF32.number] = destUTF8; pending.Add(destUTF32); } ConvertOneEdge(utf8State, destUTF8, t.Min_Renamed, t.Max_Renamed); } } utf8.SetNumberedStates(Utf8States, Utf8StateCount); return utf8; } private State NewUTF8State() { State s = new State(); if (Utf8StateCount == Utf8States.Length) { State[] newArray = new State[ArrayUtil.Oversize(1 + Utf8StateCount, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; Array.Copy(Utf8States, 0, newArray, 0, Utf8StateCount); Utf8States = newArray; } Utf8States[Utf8StateCount] = s; s.number = Utf8StateCount; Utf8StateCount++; return s; } } }
namespace android.view.animation { [global::MonoJavaBridge.JavaClass()] public partial class LayoutAnimationController : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected LayoutAnimationController(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public partial class AnimationParameters : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected AnimationParameters(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public AnimationParameters() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.animation.LayoutAnimationController.AnimationParameters._m0.native == global::System.IntPtr.Zero) global::android.view.animation.LayoutAnimationController.AnimationParameters._m0 = @__env.GetMethodIDNoThrow(global::android.view.animation.LayoutAnimationController.AnimationParameters.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.animation.LayoutAnimationController.AnimationParameters.staticClass, global::android.view.animation.LayoutAnimationController.AnimationParameters._m0); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _count5901; public int count { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetIntField(this.JvmHandle, _count5901); } set { } } internal static global::MonoJavaBridge.FieldId _index5902; public int index { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetIntField(this.JvmHandle, _index5902); } set { } } static AnimationParameters() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.animation.LayoutAnimationController.AnimationParameters.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/animation/LayoutAnimationController$AnimationParameters")); global::android.view.animation.LayoutAnimationController.AnimationParameters._count5901 = @__env.GetFieldIDNoThrow(global::android.view.animation.LayoutAnimationController.AnimationParameters.staticClass, "count", "I"); global::android.view.animation.LayoutAnimationController.AnimationParameters._index5902 = @__env.GetFieldIDNoThrow(global::android.view.animation.LayoutAnimationController.AnimationParameters.staticClass, "index", "I"); } } private static global::MonoJavaBridge.MethodId _m0; public virtual void start() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.LayoutAnimationController.staticClass, "start", "()V", ref global::android.view.animation.LayoutAnimationController._m0); } public new global::android.view.animation.Animation Animation { get { return getAnimation(); } set { setAnimation(value); } } private static global::MonoJavaBridge.MethodId _m1; public virtual global::android.view.animation.Animation getAnimation() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.animation.LayoutAnimationController.staticClass, "getAnimation", "()Landroid/view/animation/Animation;", ref global::android.view.animation.LayoutAnimationController._m1) as android.view.animation.Animation; } private static global::MonoJavaBridge.MethodId _m2; public virtual void setAnimation(android.content.Context arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.LayoutAnimationController.staticClass, "setAnimation", "(Landroid/content/Context;I)V", ref global::android.view.animation.LayoutAnimationController._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m3; public virtual void setAnimation(android.view.animation.Animation arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.LayoutAnimationController.staticClass, "setAnimation", "(Landroid/view/animation/Animation;)V", ref global::android.view.animation.LayoutAnimationController._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int Order { get { return getOrder(); } set { setOrder(value); } } private static global::MonoJavaBridge.MethodId _m4; public virtual int getOrder() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.animation.LayoutAnimationController.staticClass, "getOrder", "()I", ref global::android.view.animation.LayoutAnimationController._m4); } private static global::MonoJavaBridge.MethodId _m5; public virtual bool isDone() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.animation.LayoutAnimationController.staticClass, "isDone", "()Z", ref global::android.view.animation.LayoutAnimationController._m5); } private static global::MonoJavaBridge.MethodId _m6; public virtual void setOrder(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.LayoutAnimationController.staticClass, "setOrder", "(I)V", ref global::android.view.animation.LayoutAnimationController._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m7; public virtual void setInterpolator(android.view.animation.Interpolator arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.LayoutAnimationController.staticClass, "setInterpolator", "(Landroid/view/animation/Interpolator;)V", ref global::android.view.animation.LayoutAnimationController._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setInterpolator(global::android.view.animation.InterpolatorDelegate arg0) { setInterpolator((global::android.view.animation.InterpolatorDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m8; public virtual void setInterpolator(android.content.Context arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.LayoutAnimationController.staticClass, "setInterpolator", "(Landroid/content/Context;I)V", ref global::android.view.animation.LayoutAnimationController._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public new global::android.view.animation.InterpolatorDelegate Interpolator { get { return new global::android.view.animation.InterpolatorDelegate(getInterpolator().getInterpolation); } set { setInterpolator(value); } } private static global::MonoJavaBridge.MethodId _m9; public virtual global::android.view.animation.Interpolator getInterpolator() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.view.animation.Interpolator>(this, global::android.view.animation.LayoutAnimationController.staticClass, "getInterpolator", "()Landroid/view/animation/Interpolator;", ref global::android.view.animation.LayoutAnimationController._m9) as android.view.animation.Interpolator; } public new float Delay { get { return getDelay(); } set { setDelay(value); } } private static global::MonoJavaBridge.MethodId _m10; public virtual float getDelay() { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.animation.LayoutAnimationController.staticClass, "getDelay", "()F", ref global::android.view.animation.LayoutAnimationController._m10); } private static global::MonoJavaBridge.MethodId _m11; public virtual void setDelay(float arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.LayoutAnimationController.staticClass, "setDelay", "(F)V", ref global::android.view.animation.LayoutAnimationController._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m12; public virtual bool willOverlap() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.animation.LayoutAnimationController.staticClass, "willOverlap", "()Z", ref global::android.view.animation.LayoutAnimationController._m12); } private static global::MonoJavaBridge.MethodId _m13; public virtual global::android.view.animation.Animation getAnimationForView(android.view.View arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.animation.LayoutAnimationController.staticClass, "getAnimationForView", "(Landroid/view/View;)Landroid/view/animation/Animation;", ref global::android.view.animation.LayoutAnimationController._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.view.animation.Animation; } private static global::MonoJavaBridge.MethodId _m14; protected virtual long getDelayForView(android.view.View arg0) { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.view.animation.LayoutAnimationController.staticClass, "getDelayForView", "(Landroid/view/View;)J", ref global::android.view.animation.LayoutAnimationController._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m15; protected virtual int getTransformedIndex(android.view.animation.LayoutAnimationController.AnimationParameters arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.animation.LayoutAnimationController.staticClass, "getTransformedIndex", "(Landroid/view/animation/LayoutAnimationController$AnimationParameters;)I", ref global::android.view.animation.LayoutAnimationController._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m16; public LayoutAnimationController(android.view.animation.Animation arg0, float arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.animation.LayoutAnimationController._m16.native == global::System.IntPtr.Zero) global::android.view.animation.LayoutAnimationController._m16 = @__env.GetMethodIDNoThrow(global::android.view.animation.LayoutAnimationController.staticClass, "<init>", "(Landroid/view/animation/Animation;F)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.animation.LayoutAnimationController.staticClass, global::android.view.animation.LayoutAnimationController._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m17; public LayoutAnimationController(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.animation.LayoutAnimationController._m17.native == global::System.IntPtr.Zero) global::android.view.animation.LayoutAnimationController._m17 = @__env.GetMethodIDNoThrow(global::android.view.animation.LayoutAnimationController.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.animation.LayoutAnimationController.staticClass, global::android.view.animation.LayoutAnimationController._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m18; public LayoutAnimationController(android.view.animation.Animation arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.animation.LayoutAnimationController._m18.native == global::System.IntPtr.Zero) global::android.view.animation.LayoutAnimationController._m18 = @__env.GetMethodIDNoThrow(global::android.view.animation.LayoutAnimationController.staticClass, "<init>", "(Landroid/view/animation/Animation;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.animation.LayoutAnimationController.staticClass, global::android.view.animation.LayoutAnimationController._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } public static int ORDER_NORMAL { get { return 0; } } public static int ORDER_REVERSE { get { return 1; } } public static int ORDER_RANDOM { get { return 2; } } static LayoutAnimationController() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.animation.LayoutAnimationController.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/animation/LayoutAnimationController")); } } }
/* * 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.Diagnostics; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Text; using System.Threading; using System.Reflection; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Server.Base; using OpenSim.Services.Base; using OpenSim.Services.Interfaces; using Nini.Config; using log4net; using OpenMetaverse; using System.Security.Cryptography; namespace OpenSim.Services.FSAssetService { public class FSAssetConnector : ServiceBase, IAssetService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); static System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); static SHA256CryptoServiceProvider SHA256 = new SHA256CryptoServiceProvider(); static byte[] ToCString(string s) { byte[] ret = enc.GetBytes(s); Array.Resize(ref ret, ret.Length + 1); ret[ret.Length - 1] = 0; return ret; } protected IAssetLoader m_AssetLoader = null; protected IFSAssetDataPlugin m_DataConnector = null; protected IAssetService m_FallbackService; protected Thread m_WriterThread; protected Thread m_StatsThread; protected string m_SpoolDirectory; protected object m_readLock = new object(); protected object m_statsLock = new object(); protected int m_readCount = 0; protected int m_readTicks = 0; protected int m_missingAssets = 0; protected int m_missingAssetsFS = 0; protected string m_FSBase; private static bool m_Initialized; private bool m_MainInstance; public FSAssetConnector(IConfigSource config) : this(config, "AssetService") { } public FSAssetConnector(IConfigSource config, string configName) : base(config) { if (!m_Initialized) { m_Initialized = true; m_MainInstance = true; MainConsole.Instance.Commands.AddCommand("fs", false, "show assets", "show assets", "Show asset stats", HandleShowAssets); MainConsole.Instance.Commands.AddCommand("fs", false, "show digest", "show digest <ID>", "Show asset digest", HandleShowDigest); MainConsole.Instance.Commands.AddCommand("fs", false, "delete asset", "delete asset <ID>", "Delete asset from database", HandleDeleteAsset); MainConsole.Instance.Commands.AddCommand("fs", false, "import", "import <conn> <table> [<start> <count>]", "Import legacy assets", HandleImportAssets); MainConsole.Instance.Commands.AddCommand("fs", false, "force import", "force import <conn> <table> [<start> <count>]", "Import legacy assets, overwriting current content", HandleImportAssets); } IConfig assetConfig = config.Configs[configName]; if (assetConfig == null) throw new Exception("No AssetService configuration"); // Get Database Connector from Asset Config (If present) string dllName = assetConfig.GetString("StorageProvider", string.Empty); string m_ConnectionString = assetConfig.GetString("ConnectionString", string.Empty); string m_Realm = assetConfig.GetString("Realm", "fsassets"); int SkipAccessTimeDays = assetConfig.GetInt("DaysBetweenAccessTimeUpdates", 0); // If not found above, fallback to Database defaults IConfig dbConfig = config.Configs["DatabaseService"]; if (dbConfig != null) { if (dllName == String.Empty) dllName = dbConfig.GetString("StorageProvider", String.Empty); if (m_ConnectionString == String.Empty) m_ConnectionString = dbConfig.GetString("ConnectionString", String.Empty); } // No databse connection found in either config if (dllName.Equals(String.Empty)) throw new Exception("No StorageProvider configured"); if (m_ConnectionString.Equals(String.Empty)) throw new Exception("Missing database connection string"); // Create Storage Provider m_DataConnector = LoadPlugin<IFSAssetDataPlugin>(dllName); if (m_DataConnector == null) throw new Exception(string.Format("Could not find a storage interface in the module {0}", dllName)); // Initialize DB And perform any migrations required m_DataConnector.Initialise(m_ConnectionString, m_Realm, SkipAccessTimeDays); // Setup Fallback Service string str = assetConfig.GetString("FallbackService", string.Empty); if (str != string.Empty) { object[] args = new object[] { config }; m_FallbackService = LoadPlugin<IAssetService>(str, args); if (m_FallbackService != null) { m_log.Info("[FSASSETS]: Fallback service loaded"); } else { m_log.Error("[FSASSETS]: Failed to load fallback service"); } } // Setup directory structure including temp directory m_SpoolDirectory = assetConfig.GetString("SpoolDirectory", "/tmp"); string spoolTmp = Path.Combine(m_SpoolDirectory, "spool"); Directory.CreateDirectory(spoolTmp); m_FSBase = assetConfig.GetString("BaseDirectory", String.Empty); if (m_FSBase == String.Empty) { m_log.ErrorFormat("[FSASSETS]: BaseDirectory not specified"); throw new Exception("Configuration error"); } if (m_MainInstance) { string loader = assetConfig.GetString("DefaultAssetLoader", string.Empty); if (loader != string.Empty) { m_AssetLoader = LoadPlugin<IAssetLoader>(loader); string loaderArgs = assetConfig.GetString("AssetLoaderArgs", string.Empty); m_log.InfoFormat("[FSASSETS]: Loading default asset set from {0}", loaderArgs); m_AssetLoader.ForEachDefaultXmlAsset(loaderArgs, delegate(AssetBase a) { Store(a, false); }); } m_WriterThread = new Thread(Writer); m_WriterThread.Start(); m_StatsThread = new Thread(Stats); m_StatsThread.Start(); } m_log.Info("[FSASSETS]: FS asset service enabled"); } private void Stats() { while (true) { Thread.Sleep(60000); lock (m_statsLock) { if (m_readCount > 0) { double avg = (double)m_readTicks / (double)m_readCount; // if (avg > 10000) // Environment.Exit(0); m_log.InfoFormat("[FSASSETS]: Read stats: {0} files, {1} ticks, avg {2:F2}, missing {3}, FS {4}", m_readCount, m_readTicks, (double)m_readTicks / (double)m_readCount, m_missingAssets, m_missingAssetsFS); } m_readCount = 0; m_readTicks = 0; m_missingAssets = 0; m_missingAssetsFS = 0; } } } private void Writer() { m_log.Info("[FSASSETS]: Writer started"); while (true) { string[] files = Directory.GetFiles(m_SpoolDirectory); if (files.Length > 0) { int tickCount = Environment.TickCount; for (int i = 0 ; i < files.Length ; i++) { string hash = Path.GetFileNameWithoutExtension(files[i]); string s = HashToFile(hash); string diskFile = Path.Combine(m_FSBase, s); Directory.CreateDirectory(Path.GetDirectoryName(diskFile)); try { byte[] data = File.ReadAllBytes(files[i]); using (GZipStream gz = new GZipStream(new FileStream(diskFile + ".gz", FileMode.Create), CompressionMode.Compress)) { gz.Write(data, 0, data.Length); gz.Close(); } File.Delete(files[i]); //File.Move(files[i], diskFile); } catch(System.IO.IOException e) { if (e.Message.StartsWith("Win32 IO returned ERROR_ALREADY_EXISTS")) File.Delete(files[i]); else throw; } } int totalTicks = System.Environment.TickCount - tickCount; if (totalTicks > 0) // Wrap? { m_log.InfoFormat("[FSASSETS]: Write cycle complete, {0} files, {1} ticks, avg {2:F2}", files.Length, totalTicks, (double)totalTicks / (double)files.Length); } } Thread.Sleep(1000); } } string GetSHA256Hash(byte[] data) { byte[] hash = SHA256.ComputeHash(data); return BitConverter.ToString(hash).Replace("-", String.Empty); } public string HashToPath(string hash) { if (hash == null || hash.Length < 10) return "junkyard"; return Path.Combine(hash.Substring(0, 3), Path.Combine(hash.Substring(3, 3))); /* * The below is what core would normally use. * This is modified to work in OSGrid, as seen * above, because the SRAS data is structured * that way. */ /* return Path.Combine(hash.Substring(0, 2), Path.Combine(hash.Substring(2, 2), Path.Combine(hash.Substring(4, 2), hash.Substring(6, 4)))); */ } private bool AssetExists(string hash) { string s = HashToFile(hash); string diskFile = Path.Combine(m_FSBase, s); if (File.Exists(diskFile + ".gz") || File.Exists(diskFile)) return true; return false; } public virtual bool[] AssetsExist(string[] ids) { UUID[] uuid = Array.ConvertAll(ids, id => UUID.Parse(id)); return m_DataConnector.AssetsExist(uuid); } public string HashToFile(string hash) { return Path.Combine(HashToPath(hash), hash); } public AssetBase Get(string id) { string hash; return Get(id, out hash); } private AssetBase Get(string id, out string sha) { string hash = string.Empty; int startTime = System.Environment.TickCount; AssetMetadata metadata; lock (m_readLock) { metadata = m_DataConnector.Get(id, out hash); } sha = hash; if (metadata == null) { AssetBase asset = null; if (m_FallbackService != null) { asset = m_FallbackService.Get(id); if (asset != null) { asset.Metadata.ContentType = SLUtil.SLAssetTypeToContentType((int)asset.Type); sha = GetSHA256Hash(asset.Data); m_log.InfoFormat("[FSASSETS]: Added asset {0} from fallback to local store", id); Store(asset); } } if (asset == null) { // m_log.InfoFormat("[FSASSETS]: Asset {0} not found", id); m_missingAssets++; } return asset; } AssetBase newAsset = new AssetBase(); newAsset.Metadata = metadata; try { newAsset.Data = GetFsData(hash); if (newAsset.Data.Length == 0) { AssetBase asset = null; if (m_FallbackService != null) { asset = m_FallbackService.Get(id); if (asset != null) { asset.Metadata.ContentType = SLUtil.SLAssetTypeToContentType((int)asset.Type); sha = GetSHA256Hash(asset.Data); m_log.InfoFormat("[FSASSETS]: Added asset {0} from fallback to local store", id); Store(asset); } } if (asset == null) m_missingAssetsFS++; // m_log.InfoFormat("[FSASSETS]: Asset {0}, hash {1} not found in FS", id, hash); else return asset; } lock (m_statsLock) { m_readTicks += Environment.TickCount - startTime; m_readCount++; } return newAsset; } catch (Exception exception) { m_log.Error(exception.ToString()); Thread.Sleep(5000); Environment.Exit(1); return null; } } public AssetMetadata GetMetadata(string id) { string hash; return m_DataConnector.Get(id, out hash); } public byte[] GetData(string id) { string hash; if (m_DataConnector.Get(id, out hash) == null) return null; return GetFsData(hash); } public bool Get(string id, Object sender, AssetRetrieved handler) { AssetBase asset = Get(id); handler(id, sender, asset); return true; } public byte[] GetFsData(string hash) { string spoolFile = Path.Combine(m_SpoolDirectory, hash + ".asset"); if (File.Exists(spoolFile)) { try { byte[] content = File.ReadAllBytes(spoolFile); return content; } catch { } } string file = HashToFile(hash); string diskFile = Path.Combine(m_FSBase, file); if (File.Exists(diskFile + ".gz")) { try { using (GZipStream gz = new GZipStream(new FileStream(diskFile + ".gz", FileMode.Open, FileAccess.Read), CompressionMode.Decompress)) { using (MemoryStream ms = new MemoryStream()) { byte[] data = new byte[32768]; int bytesRead; do { bytesRead = gz.Read(data, 0, 32768); if (bytesRead > 0) ms.Write(data, 0, bytesRead); } while (bytesRead > 0); return ms.ToArray(); } } } catch (Exception) { return new Byte[0]; } } else if (File.Exists(diskFile)) { try { byte[] content = File.ReadAllBytes(diskFile); return content; } catch { } } return new Byte[0]; } public string Store(AssetBase asset) { return Store(asset, false); } private string Store(AssetBase asset, bool force) { int tickCount = Environment.TickCount; string hash = GetSHA256Hash(asset.Data); if (!AssetExists(hash)) { string tempFile = Path.Combine(Path.Combine(m_SpoolDirectory, "spool"), hash + ".asset"); string finalFile = Path.Combine(m_SpoolDirectory, hash + ".asset"); if (!File.Exists(finalFile)) { FileStream fs = File.Create(tempFile); fs.Write(asset.Data, 0, asset.Data.Length); fs.Close(); File.Move(tempFile, finalFile); } } if (asset.ID == string.Empty) { if (asset.FullID == UUID.Zero) { asset.FullID = UUID.Random(); } asset.ID = asset.FullID.ToString(); } else if (asset.FullID == UUID.Zero) { UUID uuid = UUID.Zero; if (UUID.TryParse(asset.ID, out uuid)) { asset.FullID = uuid; } else { asset.FullID = UUID.Random(); } } if (!m_DataConnector.Store(asset.Metadata, hash)) { return UUID.Zero.ToString(); } else { return asset.ID; } } public bool UpdateContent(string id, byte[] data) { return false; // string oldhash; // AssetMetadata meta = m_DataConnector.Get(id, out oldhash); // // if (meta == null) // return false; // // AssetBase asset = new AssetBase(); // asset.Metadata = meta; // asset.Data = data; // // Store(asset); // // return true; } public bool Delete(string id) { m_DataConnector.Delete(id); return true; } private void HandleShowAssets(string module, string[] args) { int num = m_DataConnector.Count(); MainConsole.Instance.Output(string.Format("Total asset count: {0}", num)); } private void HandleShowDigest(string module, string[] args) { if (args.Length < 3) { MainConsole.Instance.Output("Syntax: show digest <ID>"); return; } string hash; AssetBase asset = Get(args[2], out hash); if (asset == null || asset.Data.Length == 0) { MainConsole.Instance.Output("Asset not found"); return; } int i; MainConsole.Instance.Output(String.Format("Name: {0}", asset.Name)); MainConsole.Instance.Output(String.Format("Description: {0}", asset.Description)); MainConsole.Instance.Output(String.Format("Type: {0}", asset.Type)); MainConsole.Instance.Output(String.Format("Content-type: {0}", asset.Metadata.ContentType)); MainConsole.Instance.Output(String.Format("Flags: {0}", asset.Metadata.Flags.ToString())); MainConsole.Instance.Output(String.Format("FS file: {0}", HashToFile(hash))); for (i = 0 ; i < 5 ; i++) { int off = i * 16; if (asset.Data.Length <= off) break; int len = 16; if (asset.Data.Length < off + len) len = asset.Data.Length - off; byte[] line = new byte[len]; Array.Copy(asset.Data, off, line, 0, len); string text = BitConverter.ToString(line); MainConsole.Instance.Output(String.Format("{0:x4}: {1}", off, text)); } } private void HandleDeleteAsset(string module, string[] args) { if (args.Length < 3) { MainConsole.Instance.Output("Syntax: delete asset <ID>"); return; } AssetBase asset = Get(args[2]); if (asset == null || asset.Data.Length == 0) { MainConsole.Instance.Output("Asset not found"); return; } m_DataConnector.Delete(args[2]); MainConsole.Instance.Output("Asset deleted"); } private void HandleImportAssets(string module, string[] args) { bool force = false; if (args[0] == "force") { force = true; List<string> list = new List<string>(args); list.RemoveAt(0); args = list.ToArray(); } if (args.Length < 3) { MainConsole.Instance.Output("Syntax: import <conn> <table> [<start> <count>]"); } else { string conn = args[1]; string table = args[2]; int start = 0; int count = -1; if (args.Length > 3) { start = Convert.ToInt32(args[3]); } if (args.Length > 4) { count = Convert.ToInt32(args[4]); } m_DataConnector.Import(conn, table, start, count, force, new FSStoreDelegate(Store)); } } public AssetBase GetCached(string id) { return Get(id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; using System.Threading; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; using Orleans; using Orleans.Messaging; using Orleans.Runtime; using Orleans.TestingHost; using TestExtensions; using UnitTests.GrainInterfaces; using Xunit; using Microsoft.Extensions.DependencyInjection; using Orleans.Configuration; using Orleans.Hosting; using Orleans.Configuration.Internal; using Microsoft.Extensions.Hosting; using Orleans.Runtime.Messaging; namespace Tester { public class TestGatewayManager : IGatewayListProvider { public TimeSpan MaxStaleness => TimeSpan.FromSeconds(1); public bool IsUpdatable => true; public IList<Uri> Gateways { get; } public TestGatewayManager() { Gateways = new List<Uri>(); } public Task InitializeGatewayListProvider() { return Task.CompletedTask; } public Task<IList<Uri>> GetGateways() { return Task.FromResult(Gateways); } } public class GatewayConnectionTests : TestClusterPerTest { private OutsideRuntimeClient runtimeClient; protected override void ConfigureTestCluster(TestClusterBuilder builder) { builder.Options.UseTestClusterMembership = false; builder.Options.InitialSilosCount = 1; builder.AddSiloBuilderConfigurator<SiloBuilderConfigurator>(); builder.AddClientBuilderConfigurator<ClientBuilderConfigurator>(); } public class SiloBuilderConfigurator : IHostConfigurator { public void Configure(IHostBuilder hostBuilder) { hostBuilder.UseOrleans(siloBuilder => { siloBuilder.UseLocalhostClustering(); }); hostBuilder.ConfigureServices((context, services) => { var cfg = context.Configuration; var siloPort = int.Parse(cfg[nameof(TestClusterOptions.BaseSiloPort)]); var gatewayPort = int.Parse(cfg[nameof(TestClusterOptions.BaseGatewayPort)]); services.Configure<EndpointOptions>(options => { options.SiloPort = siloPort; options.GatewayPort = gatewayPort; }); }); } } public class ClientBuilderConfigurator : IClientBuilderConfigurator { public void Configure(IConfiguration configuration, IClientBuilder clientBuilder) { var basePort = int.Parse(configuration[nameof(TestClusterOptions.BaseGatewayPort)]); var primaryGw = new IPEndPoint(IPAddress.Loopback, basePort).ToGatewayUri(); clientBuilder.Configure<GatewayOptions>(options => { options.GatewayListRefreshPeriod = TimeSpan.FromMilliseconds(100); }); clientBuilder.ConfigureServices(services => { services.AddSingleton(sp => { var gateway = new TestGatewayManager(); gateway.Gateways.Add(primaryGw); return gateway; }); services.AddFromExisting<IGatewayListProvider, TestGatewayManager>(); }); } } public override async Task InitializeAsync() { await base.InitializeAsync(); this.runtimeClient = this.Client.ServiceProvider.GetRequiredService<OutsideRuntimeClient>(); } [Fact, TestCategory("Functional")] public async Task NoReconnectionToGatewayNotReturnedByManager() { // Reduce timeout for this test this.runtimeClient.SetResponseTimeout(TimeSpan.FromSeconds(1)); var connectionCount = 0; var timeoutCount = 0; // Fake Gateway var gateways = await this.HostedCluster.Client.ServiceProvider.GetRequiredService<IGatewayListProvider>().GetGateways(); var port = gateways.First().Port + 2; var endpoint = new IPEndPoint(IPAddress.Loopback, port); var evt = new SocketAsyncEventArgs(); var gatewayManager = this.runtimeClient.ServiceProvider.GetService<TestGatewayManager>(); evt.Completed += (sender, args) => { connectionCount++; gatewayManager.Gateways.Remove(endpoint.ToGatewayUri()); }; // Add the fake gateway and wait the refresh from the client gatewayManager.Gateways.Add(endpoint.ToGatewayUri()); await Task.Delay(200); using (var socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { // Start the fake gw socket.Bind(endpoint); socket.Listen(1); socket.AcceptAsync(evt); // Make a bunch of calls for (var i = 0; i < 100; i++) { try { var g = this.Client.GetGrain<ISimpleGrain>(i); await g.SetA(i); } catch (TimeoutException) { timeoutCount++; } } socket.Close(); } // Check that we only connected once to the fake GW Assert.Equal(1, connectionCount); Assert.Equal(1, timeoutCount); } [Fact, TestCategory("Functional")] public async Task ConnectionFromDifferentClusterIsRejected() { // Arange var gateways = await this.HostedCluster.Client.ServiceProvider.GetRequiredService<IGatewayListProvider>().GetGateways(); var gwEndpoint = gateways.First().ToIPEndPoint(); var exceptions = new List<Exception>(); Task<bool> RetryFunc(Exception exception, CancellationToken cancellationToken) { Assert.IsType<ConnectionFailedException>(exception); exceptions.Add(exception); return Task.FromResult(false); } // Close current client connection await this.HostedCluster.StopClusterClientAsync(); var hostBuilder = new HostBuilder().UseOrleansClient( clientBuilder => { clientBuilder.Configure<ClientMessagingOptions>( options => { options.ResponseTimeoutWithDebugger = TimeSpan.FromSeconds(10); }); clientBuilder.Configure<ClusterOptions>( options => { options.ClusterId = "myClusterId"; }) .UseStaticClustering(gwEndpoint) .UseConnectionRetryFilter(RetryFunc); ; }); var host = hostBuilder.Build(); var exception = await Assert.ThrowsAsync<ConnectionFailedException>(async () => await host.StartAsync()); Assert.Contains("Unable to connect to", exception.Message); await host.StopAsync(); } } }
/* * Copyright 2010-2014 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. */ /* * Do not modify this file. This file is generated from the workspaces-2015-04-08.normal.json service model. */ using System; using System.Collections.Generic; using Amazon.WorkSpaces.Model; namespace Amazon.WorkSpaces { /// <summary> /// Interface for accessing WorkSpaces /// /// Amazon WorkSpaces Service /// <para> /// This is the <i>Amazon WorkSpaces API Reference</i>. This guide provides detailed information /// about Amazon WorkSpaces operations, data types, parameters, and errors. /// </para> /// </summary> public partial interface IAmazonWorkSpaces : IDisposable { #region CreateWorkspaces /// <summary> /// Creates one or more WorkSpaces. /// /// <note> /// <para> /// This operation is asynchronous and returns before the WorkSpaces are created. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateWorkspaces service method.</param> /// /// <returns>The response from the CreateWorkspaces service method, as returned by WorkSpaces.</returns> /// <exception cref="Amazon.WorkSpaces.Model.ResourceLimitExceededException"> /// Your resource limits have been exceeded. /// </exception> CreateWorkspacesResponse CreateWorkspaces(CreateWorkspacesRequest request); /// <summary> /// Initiates the asynchronous execution of the CreateWorkspaces operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateWorkspaces operation on AmazonWorkSpacesClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateWorkspaces /// operation.</returns> IAsyncResult BeginCreateWorkspaces(CreateWorkspacesRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the CreateWorkspaces operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateWorkspaces.</param> /// /// <returns>Returns a CreateWorkspacesResult from WorkSpaces.</returns> CreateWorkspacesResponse EndCreateWorkspaces(IAsyncResult asyncResult); #endregion #region DescribeWorkspaceBundles /// <summary> /// Obtains information about the WorkSpace bundles that are available to your account /// in the specified region. /// /// /// <para> /// You can filter the results with either the <code>BundleIds</code> parameter, or the /// <code>Owner</code> parameter, but not both. /// </para> /// /// <para> /// This operation supports pagination with the use of the <code>NextToken</code> request /// and response parameters. If more results are available, the <code>NextToken</code> /// response member contains a token that you pass in the next call to this operation /// to retrieve the next set of items. /// </para> /// </summary> /// /// <returns>The response from the DescribeWorkspaceBundles service method, as returned by WorkSpaces.</returns> /// <exception cref="Amazon.WorkSpaces.Model.InvalidParameterValuesException"> /// One or more parameter values are not valid. /// </exception> DescribeWorkspaceBundlesResponse DescribeWorkspaceBundles(); /// <summary> /// Obtains information about the WorkSpace bundles that are available to your account /// in the specified region. /// /// /// <para> /// You can filter the results with either the <code>BundleIds</code> parameter, or the /// <code>Owner</code> parameter, but not both. /// </para> /// /// <para> /// This operation supports pagination with the use of the <code>NextToken</code> request /// and response parameters. If more results are available, the <code>NextToken</code> /// response member contains a token that you pass in the next call to this operation /// to retrieve the next set of items. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeWorkspaceBundles service method.</param> /// /// <returns>The response from the DescribeWorkspaceBundles service method, as returned by WorkSpaces.</returns> /// <exception cref="Amazon.WorkSpaces.Model.InvalidParameterValuesException"> /// One or more parameter values are not valid. /// </exception> DescribeWorkspaceBundlesResponse DescribeWorkspaceBundles(DescribeWorkspaceBundlesRequest request); /// <summary> /// Initiates the asynchronous execution of the DescribeWorkspaceBundles operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeWorkspaceBundles operation on AmazonWorkSpacesClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeWorkspaceBundles /// operation.</returns> IAsyncResult BeginDescribeWorkspaceBundles(DescribeWorkspaceBundlesRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DescribeWorkspaceBundles operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeWorkspaceBundles.</param> /// /// <returns>Returns a DescribeWorkspaceBundlesResult from WorkSpaces.</returns> DescribeWorkspaceBundlesResponse EndDescribeWorkspaceBundles(IAsyncResult asyncResult); #endregion #region DescribeWorkspaceDirectories /// <summary> /// Retrieves information about the AWS Directory Service directories in the region that /// are registered with Amazon WorkSpaces and are available to your account. /// /// /// <para> /// This operation supports pagination with the use of the <code>NextToken</code> request /// and response parameters. If more results are available, the <code>NextToken</code> /// response member contains a token that you pass in the next call to this operation /// to retrieve the next set of items. /// </para> /// </summary> /// /// <returns>The response from the DescribeWorkspaceDirectories service method, as returned by WorkSpaces.</returns> /// <exception cref="Amazon.WorkSpaces.Model.InvalidParameterValuesException"> /// One or more parameter values are not valid. /// </exception> DescribeWorkspaceDirectoriesResponse DescribeWorkspaceDirectories(); /// <summary> /// Retrieves information about the AWS Directory Service directories in the region that /// are registered with Amazon WorkSpaces and are available to your account. /// /// /// <para> /// This operation supports pagination with the use of the <code>NextToken</code> request /// and response parameters. If more results are available, the <code>NextToken</code> /// response member contains a token that you pass in the next call to this operation /// to retrieve the next set of items. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeWorkspaceDirectories service method.</param> /// /// <returns>The response from the DescribeWorkspaceDirectories service method, as returned by WorkSpaces.</returns> /// <exception cref="Amazon.WorkSpaces.Model.InvalidParameterValuesException"> /// One or more parameter values are not valid. /// </exception> DescribeWorkspaceDirectoriesResponse DescribeWorkspaceDirectories(DescribeWorkspaceDirectoriesRequest request); /// <summary> /// Initiates the asynchronous execution of the DescribeWorkspaceDirectories operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeWorkspaceDirectories operation on AmazonWorkSpacesClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeWorkspaceDirectories /// operation.</returns> IAsyncResult BeginDescribeWorkspaceDirectories(DescribeWorkspaceDirectoriesRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DescribeWorkspaceDirectories operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeWorkspaceDirectories.</param> /// /// <returns>Returns a DescribeWorkspaceDirectoriesResult from WorkSpaces.</returns> DescribeWorkspaceDirectoriesResponse EndDescribeWorkspaceDirectories(IAsyncResult asyncResult); #endregion #region DescribeWorkspaces /// <summary> /// Obtains information about the specified WorkSpaces. /// /// /// <para> /// Only one of the filter parameters, such as <code>BundleId</code>, <code>DirectoryId</code>, /// or <code>WorkspaceIds</code>, can be specified at a time. /// </para> /// /// <para> /// This operation supports pagination with the use of the <code>NextToken</code> request /// and response parameters. If more results are available, the <code>NextToken</code> /// response member contains a token that you pass in the next call to this operation /// to retrieve the next set of items. /// </para> /// </summary> /// /// <returns>The response from the DescribeWorkspaces service method, as returned by WorkSpaces.</returns> /// <exception cref="Amazon.WorkSpaces.Model.InvalidParameterValuesException"> /// One or more parameter values are not valid. /// </exception> /// <exception cref="Amazon.WorkSpaces.Model.ResourceUnavailableException"> /// The specified resource is not available. /// </exception> DescribeWorkspacesResponse DescribeWorkspaces(); /// <summary> /// Obtains information about the specified WorkSpaces. /// /// /// <para> /// Only one of the filter parameters, such as <code>BundleId</code>, <code>DirectoryId</code>, /// or <code>WorkspaceIds</code>, can be specified at a time. /// </para> /// /// <para> /// This operation supports pagination with the use of the <code>NextToken</code> request /// and response parameters. If more results are available, the <code>NextToken</code> /// response member contains a token that you pass in the next call to this operation /// to retrieve the next set of items. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeWorkspaces service method.</param> /// /// <returns>The response from the DescribeWorkspaces service method, as returned by WorkSpaces.</returns> /// <exception cref="Amazon.WorkSpaces.Model.InvalidParameterValuesException"> /// One or more parameter values are not valid. /// </exception> /// <exception cref="Amazon.WorkSpaces.Model.ResourceUnavailableException"> /// The specified resource is not available. /// </exception> DescribeWorkspacesResponse DescribeWorkspaces(DescribeWorkspacesRequest request); /// <summary> /// Initiates the asynchronous execution of the DescribeWorkspaces operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeWorkspaces operation on AmazonWorkSpacesClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeWorkspaces /// operation.</returns> IAsyncResult BeginDescribeWorkspaces(DescribeWorkspacesRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DescribeWorkspaces operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeWorkspaces.</param> /// /// <returns>Returns a DescribeWorkspacesResult from WorkSpaces.</returns> DescribeWorkspacesResponse EndDescribeWorkspaces(IAsyncResult asyncResult); #endregion #region RebootWorkspaces /// <summary> /// Reboots the specified WorkSpaces. /// /// /// <para> /// To be able to reboot a WorkSpace, the WorkSpace must have a <b>State</b> of <code>AVAILABLE</code>, /// <code>IMPAIRED</code>, or <code>INOPERABLE</code>. /// </para> /// <note> /// <para> /// This operation is asynchronous and will return before the WorkSpaces have rebooted. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the RebootWorkspaces service method.</param> /// /// <returns>The response from the RebootWorkspaces service method, as returned by WorkSpaces.</returns> RebootWorkspacesResponse RebootWorkspaces(RebootWorkspacesRequest request); /// <summary> /// Initiates the asynchronous execution of the RebootWorkspaces operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RebootWorkspaces operation on AmazonWorkSpacesClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndRebootWorkspaces /// operation.</returns> IAsyncResult BeginRebootWorkspaces(RebootWorkspacesRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the RebootWorkspaces operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginRebootWorkspaces.</param> /// /// <returns>Returns a RebootWorkspacesResult from WorkSpaces.</returns> RebootWorkspacesResponse EndRebootWorkspaces(IAsyncResult asyncResult); #endregion #region RebuildWorkspaces /// <summary> /// Rebuilds the specified WorkSpaces. /// /// /// <para> /// Rebuilding a WorkSpace is a potentially destructive action that can result in the /// loss of data. Rebuilding a WorkSpace causes the following to occur: /// </para> /// <ul> <li>The system is restored to the image of the bundle that the WorkSpace is /// created from. Any applications that have been installed, or system settings that have /// been made since the WorkSpace was created will be lost.</li> <li>The data drive (D /// drive) is re-created from the last automatic snapshot taken of the data drive. The /// current contents of the data drive are overwritten. Automatic snapshots of the data /// drive are taken every 12 hours, so the snapshot can be as much as 12 hours old.</li> /// </ul> /// <para> /// To be able to rebuild a WorkSpace, the WorkSpace must have a <b>State</b> of <code>AVAILABLE</code> /// or <code>ERROR</code>. /// </para> /// <note> /// <para> /// This operation is asynchronous and will return before the WorkSpaces have been completely /// rebuilt. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the RebuildWorkspaces service method.</param> /// /// <returns>The response from the RebuildWorkspaces service method, as returned by WorkSpaces.</returns> RebuildWorkspacesResponse RebuildWorkspaces(RebuildWorkspacesRequest request); /// <summary> /// Initiates the asynchronous execution of the RebuildWorkspaces operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RebuildWorkspaces operation on AmazonWorkSpacesClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndRebuildWorkspaces /// operation.</returns> IAsyncResult BeginRebuildWorkspaces(RebuildWorkspacesRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the RebuildWorkspaces operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginRebuildWorkspaces.</param> /// /// <returns>Returns a RebuildWorkspacesResult from WorkSpaces.</returns> RebuildWorkspacesResponse EndRebuildWorkspaces(IAsyncResult asyncResult); #endregion #region TerminateWorkspaces /// <summary> /// Terminates the specified WorkSpaces. /// /// /// <para> /// Terminating a WorkSpace is a permanent action and cannot be undone. The user's data /// is not maintained and will be destroyed. If you need to archive any user data, contact /// Amazon Web Services before terminating the WorkSpace. /// </para> /// /// <para> /// You can terminate a WorkSpace that is in any state except <code>SUSPENDED</code>. /// </para> /// <note> /// <para> /// This operation is asynchronous and will return before the WorkSpaces have been completely /// terminated. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the TerminateWorkspaces service method.</param> /// /// <returns>The response from the TerminateWorkspaces service method, as returned by WorkSpaces.</returns> TerminateWorkspacesResponse TerminateWorkspaces(TerminateWorkspacesRequest request); /// <summary> /// Initiates the asynchronous execution of the TerminateWorkspaces operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the TerminateWorkspaces operation on AmazonWorkSpacesClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndTerminateWorkspaces /// operation.</returns> IAsyncResult BeginTerminateWorkspaces(TerminateWorkspacesRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the TerminateWorkspaces operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginTerminateWorkspaces.</param> /// /// <returns>Returns a TerminateWorkspacesResult from WorkSpaces.</returns> TerminateWorkspacesResponse EndTerminateWorkspaces(IAsyncResult asyncResult); #endregion } }