context
stringlengths
2.52k
185k
gt
stringclasses
1 value
#region License // /* // See license included in this library folder. // */ #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using Sqloogle.Libs.NLog.Common; using Sqloogle.Libs.NLog.Config; using Sqloogle.Libs.NLog.Internal; #if !NET_CF && !SILVERLIGHT namespace Sqloogle.Libs.NLog.Targets { /// <summary> /// Increments specified performance counter on each write. /// </summary> /// <seealso href="http://nlog-project.org/wiki/PerformanceCounter_target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/PerfCounter/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/PerfCounter/Simple/Example.cs" /> /// </example> /// <remarks> /// TODO: /// 1. Unable to create a category allowing multiple counter instances (.Net 2.0 API only, probably) /// 2. Is there any way of adding new counters without deleting the whole category? /// 3. There should be some mechanism of resetting the counter (e.g every day starts from 0), or auto-switching to /// another counter instance (with dynamic creation of new instance). This could be done with layouts. /// </remarks> [Target("PerfCounter")] public class PerformanceCounterTarget : Target, IInstallable { private bool created; private bool initialized; private PerformanceCounter perfCounter; /// <summary> /// Initializes a new instance of the <see cref="PerformanceCounterTarget" /> class. /// </summary> public PerformanceCounterTarget() { CounterType = PerformanceCounterType.NumberOfItems32; InstanceName = string.Empty; CounterHelp = string.Empty; } /// <summary> /// Gets or sets a value indicating whether performance counter should be automatically created. /// </summary> /// <docgen category='Performance Counter Options' order='10' /> public bool AutoCreate { get; set; } /// <summary> /// Gets or sets the name of the performance counter category. /// </summary> /// <docgen category='Performance Counter Options' order='10' /> [RequiredParameter] public string CategoryName { get; set; } /// <summary> /// Gets or sets the name of the performance counter. /// </summary> /// <docgen category='Performance Counter Options' order='10' /> [RequiredParameter] public string CounterName { get; set; } /// <summary> /// Gets or sets the performance counter instance name. /// </summary> /// <docgen category='Performance Counter Options' order='10' /> public string InstanceName { get; set; } /// <summary> /// Gets or sets the counter help text. /// </summary> /// <docgen category='Performance Counter Options' order='10' /> public string CounterHelp { get; set; } /// <summary> /// Gets or sets the performance counter type. /// </summary> /// <docgen category='Performance Counter Options' order='10' /> [DefaultValue(PerformanceCounterType.NumberOfItems32)] public PerformanceCounterType CounterType { get; set; } /// <summary> /// Performs installation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Install(InstallationContext installationContext) { // categories must be installed together, so we must find all PerfCounter targets in the configuration file var countersByCategory = LoggingConfiguration.AllTargets.OfType<PerformanceCounterTarget>().BucketSort(c => c.CategoryName); var categoryName = CategoryName; if (countersByCategory[categoryName].Any(c => c.created)) { installationContext.Trace("Category '{0}' has already been installed.", categoryName); return; } try { PerformanceCounterCategoryType categoryType; var ccds = GetCounterCreationDataCollection(countersByCategory[CategoryName], out categoryType); if (PerformanceCounterCategory.Exists(categoryName)) { installationContext.Debug("Deleting category '{0}'", categoryName); PerformanceCounterCategory.Delete(categoryName); } installationContext.Debug("Creating category '{0}' with {1} counter(s) (Type: {2})", categoryName, ccds.Count, categoryType); foreach (CounterCreationData c in ccds) { installationContext.Trace(" Counter: '{0}' Type: ({1}) Help: {2}", c.CounterName, c.CounterType, c.CounterHelp); } PerformanceCounterCategory.Create(categoryName, "Category created by NLog", categoryType, ccds); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } if (installationContext.IgnoreFailures) { installationContext.Warning("Error creating category '{0}': {1}", categoryName, exception.Message); } else { installationContext.Error("Error creating category '{0}': {1}", categoryName, exception.Message); throw; } } finally { foreach (var t in countersByCategory[categoryName]) { t.created = true; } } } /// <summary> /// Performs uninstallation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Uninstall(InstallationContext installationContext) { var categoryName = CategoryName; if (PerformanceCounterCategory.Exists(categoryName)) { installationContext.Debug("Deleting category '{0}'", categoryName); PerformanceCounterCategory.Delete(categoryName); } else { installationContext.Debug("Category '{0}' does not exist.", categoryName); } } /// <summary> /// Determines whether the item is installed. /// </summary> /// <param name="installationContext">The installation context.</param> /// <returns> /// Value indicating whether the item is installed or null if it is not possible to determine. /// </returns> public bool? IsInstalled(InstallationContext installationContext) { if (!PerformanceCounterCategory.Exists(CategoryName)) { return false; } return PerformanceCounterCategory.CounterExists(CounterName, CategoryName); } /// <summary> /// Increments the configured performance counter. /// </summary> /// <param name="logEvent">Log event.</param> protected override void Write(LogEventInfo logEvent) { if (EnsureInitialized()) { perfCounter.Increment(); } } /// <summary> /// Closes the target and releases any unmanaged resources. /// </summary> protected override void CloseTarget() { base.CloseTarget(); if (perfCounter != null) { perfCounter.Close(); perfCounter = null; } initialized = false; } private static CounterCreationDataCollection GetCounterCreationDataCollection(IEnumerable<PerformanceCounterTarget> countersInCategory, out PerformanceCounterCategoryType categoryType) { categoryType = PerformanceCounterCategoryType.SingleInstance; var ccds = new CounterCreationDataCollection(); foreach (var counter in countersInCategory) { if (!string.IsNullOrEmpty(counter.InstanceName)) { categoryType = PerformanceCounterCategoryType.MultiInstance; } ccds.Add(new CounterCreationData(counter.CounterName, counter.CounterHelp, counter.CounterType)); } return ccds; } /// <summary> /// Ensures that the performance counter has been initialized. /// </summary> /// <returns>True if the performance counter is operational, false otherwise.</returns> private bool EnsureInitialized() { if (!initialized) { initialized = true; if (AutoCreate) { using (var context = new InstallationContext()) { Install(context); } } try { perfCounter = new PerformanceCounter(CategoryName, CounterName, InstanceName, false); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Cannot open performance counter {0}/{1}/{2}: {3}", CategoryName, CounterName, InstanceName, exception); } } return perfCounter != null; } } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** Purpose: Capture synchronization semantics for asynchronous callbacks ** ** ===========================================================*/ namespace System.Threading { using Microsoft.Win32.SafeHandles; using System.Security.Permissions; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; #if FEATURE_CORRUPTING_EXCEPTIONS using System.Runtime.ExceptionServices; #endif // FEATURE_CORRUPTING_EXCEPTIONS using System.Runtime; using System.Runtime.Versioning; using System.Runtime.ConstrainedExecution; using System.Reflection; using System.Security; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT [Flags] enum SynchronizationContextProperties { None = 0, RequireWaitNotification = 0x1 }; #endif #if FEATURE_COMINTEROP && FEATURE_APPX // // This is implemented in System.Runtime.WindowsRuntime, allowing us to ask that assembly for a WinRT-specific SyncCtx. // I'd like this to be an interface, or at least an abstract class - but neither seems to play nice with FriendAccessAllowed. // [FriendAccessAllowed] [SecurityCritical] internal class WinRTSynchronizationContextFactoryBase { [SecurityCritical] public virtual SynchronizationContext Create(object coreDispatcher) {return null;} } #endif //FEATURE_COMINTEROP #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags =SecurityPermissionFlag.ControlPolicy|SecurityPermissionFlag.ControlEvidence)] #endif public class SynchronizationContext { #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT SynchronizationContextProperties _props = SynchronizationContextProperties.None; #endif public SynchronizationContext() { } #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT // helper delegate to statically bind to Wait method private delegate int WaitDelegate(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout); static Type s_cachedPreparedType1; static Type s_cachedPreparedType2; static Type s_cachedPreparedType3; static Type s_cachedPreparedType4; static Type s_cachedPreparedType5; // protected so that only the derived sync context class can enable these flags [System.Security.SecuritySafeCritical] // auto-generated [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "We never dereference s_cachedPreparedType*, so ordering is unimportant")] protected void SetWaitNotificationRequired() { // // Prepare the method so that it can be called in a reliable fashion when a wait is needed. // This will obviously only make the Wait reliable if the Wait method is itself reliable. The only thing // preparing the method here does is to ensure there is no failure point before the method execution begins. // // Preparing the method in this way is quite expensive, but only needs to be done once per type, per AppDomain. // So we keep track of a few types we've already prepared in this AD. It is uncommon to have more than // a few SynchronizationContext implementations, so we only cache the first five we encounter; this lets // our cache be much faster than a more general cache might be. This is important, because this // is a *very* hot code path for many WPF and WinForms apps. // Type type = this.GetType(); if (s_cachedPreparedType1 != type && s_cachedPreparedType2 != type && s_cachedPreparedType3 != type && s_cachedPreparedType4 != type && s_cachedPreparedType5 != type) { RuntimeHelpers.PrepareDelegate(new WaitDelegate(this.Wait)); if (s_cachedPreparedType1 == null) s_cachedPreparedType1 = type; else if (s_cachedPreparedType2 == null) s_cachedPreparedType2 = type; else if (s_cachedPreparedType3 == null) s_cachedPreparedType3 = type; else if (s_cachedPreparedType4 == null) s_cachedPreparedType4 = type; else if (s_cachedPreparedType5 == null) s_cachedPreparedType5 = type; } _props |= SynchronizationContextProperties.RequireWaitNotification; } public bool IsWaitNotificationRequired() { return ((_props & SynchronizationContextProperties.RequireWaitNotification) != 0); } #endif public virtual void Send(SendOrPostCallback d, Object state) { d(state); } public virtual void Post(SendOrPostCallback d, Object state) { ThreadPool.QueueUserWorkItem(new WaitCallback(d), state); } /// <summary> /// Optional override for subclasses, for responding to notification that operation is starting. /// </summary> public virtual void OperationStarted() { } /// <summary> /// Optional override for subclasses, for responding to notification that operation has completed. /// </summary> public virtual void OperationCompleted() { } #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT // Method called when the CLR does a wait operation [System.Security.SecurityCritical] // auto-generated_required [CLSCompliant(false)] [PrePrepareMethod] public virtual int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { if (waitHandles == null) { throw new ArgumentNullException("waitHandles"); } Contract.EndContractBlock(); return WaitHelper(waitHandles, waitAll, millisecondsTimeout); } // Static helper to which the above method can delegate to in order to get the default // COM behavior. [System.Security.SecurityCritical] // auto-generated_required [CLSCompliant(false)] [PrePrepareMethod] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] protected static extern int WaitHelper(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout); #endif #if FEATURE_CORECLR [ThreadStatic] private static SynchronizationContext s_threadStaticContext; // // Maintain legacy NetCF Behavior where setting the value for one thread impacts all threads. // private static SynchronizationContext s_appDomainStaticContext; [System.Security.SecurityCritical] public static void SetSynchronizationContext(SynchronizationContext syncContext) { s_threadStaticContext = syncContext; } [System.Security.SecurityCritical] public static void SetThreadStaticContext(SynchronizationContext syncContext) { // // If this is a pre-Mango Windows Phone app, we need to set the SC for *all* threads to match the old NetCF behavior. // if (CompatibilitySwitches.IsAppEarlierThanWindowsPhoneMango) s_appDomainStaticContext = syncContext; else s_threadStaticContext = syncContext; } public static SynchronizationContext Current { get { SynchronizationContext context = null; if (CompatibilitySwitches.IsAppEarlierThanWindowsPhoneMango) context = s_appDomainStaticContext; else context = s_threadStaticContext; #if FEATURE_APPX if (context == null && Environment.IsWinRTSupported) context = GetWinRTContext(); #endif return context; } } // Get the last SynchronizationContext that was set explicitly (not flowed via ExecutionContext.Capture/Run) internal static SynchronizationContext CurrentNoFlow { [FriendAccessAllowed] get { return Current; // SC never flows } } #else //FEATURE_CORECLR // set SynchronizationContext on the current thread [System.Security.SecurityCritical] // auto-generated_required public static void SetSynchronizationContext(SynchronizationContext syncContext) { ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext(); ec.SynchronizationContext = syncContext; ec.SynchronizationContextNoFlow = syncContext; } // Get the current SynchronizationContext on the current thread public static SynchronizationContext Current { get { return Thread.CurrentThread.GetExecutionContextReader().SynchronizationContext ?? GetThreadLocalContext(); } } // Get the last SynchronizationContext that was set explicitly (not flowed via ExecutionContext.Capture/Run) internal static SynchronizationContext CurrentNoFlow { [FriendAccessAllowed] get { return Thread.CurrentThread.GetExecutionContextReader().SynchronizationContextNoFlow ?? GetThreadLocalContext(); } } private static SynchronizationContext GetThreadLocalContext() { SynchronizationContext context = null; #if FEATURE_APPX if (context == null && Environment.IsWinRTSupported) context = GetWinRTContext(); #endif return context; } #endif //FEATURE_CORECLR #if FEATURE_APPX [SecuritySafeCritical] private static SynchronizationContext GetWinRTContext() { Contract.Assert(Environment.IsWinRTSupported); // Temporary workaround to avoid loading a bunch of DLLs in every managed process. // This disables this feature for non-AppX processes that happen to use CoreWindow/CoreDispatcher, // which is not what we want. if (!AppDomain.IsAppXModel()) return null; // // We call into the VM to get the dispatcher. This is because: // // a) We cannot call the WinRT APIs directly from mscorlib, because we don't have the fancy projections here. // b) We cannot call into System.Runtime.WindowsRuntime here, because we don't want to load that assembly // into processes that don't need it (for performance reasons). // // So, we check the VM to see if the current thread has a dispatcher; if it does, we pass that along to // System.Runtime.WindowsRuntime to get a corresponding SynchronizationContext. // object dispatcher = GetWinRTDispatcherForCurrentThread(); if (dispatcher != null) return GetWinRTSynchronizationContextFactory().Create(dispatcher); return null; } [SecurityCritical] static WinRTSynchronizationContextFactoryBase s_winRTContextFactory; [SecurityCritical] private static WinRTSynchronizationContextFactoryBase GetWinRTSynchronizationContextFactory() { // // Since we can't directly reference System.Runtime.WindowsRuntime from mscorlib, we have to get the factory via reflection. // It would be better if we could just implement WinRTSynchronizationContextFactory in mscorlib, but we can't, because // we can do very little with WinRT stuff in mscorlib. // WinRTSynchronizationContextFactoryBase factory = s_winRTContextFactory; if (factory == null) { Type factoryType = Type.GetType("System.Threading.WinRTSynchronizationContextFactory, " + AssemblyRef.SystemRuntimeWindowsRuntime, true); s_winRTContextFactory = factory = (WinRTSynchronizationContextFactoryBase)Activator.CreateInstance(factoryType, true); } return factory; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SecurityCritical] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Interface)] private static extern object GetWinRTDispatcherForCurrentThread(); #endif //FEATURE_APPX // helper to Clone this SynchronizationContext, public virtual SynchronizationContext CreateCopy() { // the CLR dummy has an empty clone function - no member data return new SynchronizationContext(); } #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT [System.Security.SecurityCritical] // auto-generated private static int InvokeWaitMethodHelper(SynchronizationContext syncContext, IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { return syncContext.Wait(waitHandles, waitAll, millisecondsTimeout); } #endif } }
using System; using Eto.Forms; using Eto.Drawing; using JabbR.Client; using JabbR.Client.Models; using System.IO; using Eto; using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using JabbR.Desktop.Model; using System.Diagnostics; using Eto.Threading; namespace JabbR.Desktop.Interface { public abstract class MessageSection : Panel { string existingPrefix; string lastAutoComplete; int? autoCompleteIndex; bool autoCompleting; bool initialized; protected string LastHistoryMessageId { get; private set; } protected WebView History { get; private set; } protected TextBox TextEntry { get; private set; } public abstract string TitleLabel { get; } public virtual bool SupportsAutoComplete { get { return false; } } public virtual bool AllowNotificationCollapsing { get { return false; } } struct DelayedCommand { public string Command { get; set; } public object[] Parameters { get; set; } } List<DelayedCommand> delayedCommands; bool loaded; object sync = new object(); public MessageSection() { History = new WebView(); History.DocumentLoaded += HandleDocumentLoaded; TextEntry = MessageEntry(); } public new void Initialize() { if (initialized) return; initialized = true; Content = CreateLayout(); } protected virtual Control CreateLayout() { var layout = new DynamicLayout(Padding.Empty, Size.Empty); layout.Add(History, yscale: true); layout.Add(new Panel { Content = TextEntry, Padding = new Padding(10) }); return layout; } protected virtual void HandleAction(WebViewLoadingEventArgs e) { FinishLoad(); } void HandleOpenNewWindow(object sender, WebViewNewWindowEventArgs e) { Application.Instance.AsyncInvoke(() => Application.Instance.Open(e.Uri.AbsoluteUri)); e.Cancel = true; } void HandleDocumentLoading(object sender, WebViewLoadingEventArgs e) { if (e.IsMainFrame) { Debug.Print("Loading {0}", e.Uri); if (e.Uri.IsFile || e.Uri.IsLoopback) { Application.Instance.AsyncInvoke(delegate { HandleAction(e); }); e.Cancel = true; } else { Application.Instance.AsyncInvoke(delegate { Application.Instance.Open(e.Uri.AbsoluteUri); }); e.Cancel = true; } } } protected void BeginLoad() { SendCommandDirect("beginLoad"); } protected void FinishLoad() { SendCommandDirect("finishLoad"); } public override void OnLoadComplete(EventArgs e) { base.OnLoadComplete(e); var resourcePath = EtoEnvironment.GetFolderPath(EtoSpecialFolder.ApplicationResources); resourcePath = Path.Combine(resourcePath, "Styles", "default"); resourcePath += Path.DirectorySeparatorChar; //History.LoadHtml (File.OpenRead (Path.Combine (resourcePath, "channel.html")), new Uri(resourcePath)); History.Url = new Uri(Path.Combine(resourcePath, "channel.html")); } protected virtual void HandleDocumentLoaded(object sender, WebViewLoadedEventArgs e) { Application.Instance.AsyncInvoke(delegate { StartLive(); ReplayDelayedCommands(); }); } protected void StartLive() { loaded = true; if (Generator.ID == Generators.Wpf) { SendCommandDirect("settings", new { html5video = false }); } History.DocumentLoading += HandleDocumentLoading; History.OpenNewWindow += HandleOpenNewWindow; } protected void ReplayDelayedCommands() { lock (sync) { if (delayedCommands != null) { foreach (var command in delayedCommands) { SendCommandDirect(command.Command, command.Parameters); } delayedCommands = null; } loaded = true; } } public void AddMessage(ChannelMessage message) { SendCommand("addMessage", message); } public void AddHistory(IEnumerable<ChannelMessage> messages, bool shouldScroll = false) { SendCommand("addHistory", messages, shouldScroll); var last = messages.FirstOrDefault(); if (last != null) LastHistoryMessageId = last.Id; } public void SetTopic(string topic) { SendCommand("setTopic", topic); } public void AddNotification(NotificationMessage notification) { SendCommand("addNotification", notification, AllowNotificationCollapsing); } public void AddMessageContent(MessageContent content) { SendCommand("addMessageContent", content); } public void SetMarker() { SendCommand("setMarker"); } protected void SendCommand(string command, params object[] parameters) { string[] vals = new string[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { vals[i] = JsonConvert.SerializeObject(parameters[i]); } var script = string.Format("JabbR.{0}({1});", command, string.Join(", ", vals)); Application.Instance.AsyncInvoke(delegate { if (!loaded) { lock (sync) { Debug.Print("*** Adding delayed command : {0}", command); if (delayedCommands == null) delayedCommands = new List<DelayedCommand>(); delayedCommands.Add(new DelayedCommand { Command = command, Parameters = parameters }); } return; } History.ExecuteScript(script); }); } protected void SendCommandDirect(string command, params object[] parameters) { string[] vals = new string[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { vals[i] = JsonConvert.SerializeObject(parameters[i]); } var script = string.Format("JabbR.{0}({1});", command, string.Join(", ", vals)); Application.Instance.Invoke(delegate { History.ExecuteScript(script); }); } TextBox MessageEntry() { var control = new TextBox { PlaceholderText = "Send Message..." }; control.KeyDown += (sender, e) => { if (e.KeyData == Keys.Enter) { e.Handled = true; var text = control.Text; control.Text = string.Empty; ProcessCommand(text); } if (SupportsAutoComplete && e.KeyData == Keys.Tab) { e.Handled = true; //Debug.Print("Completing: {0}" , Thread.IsMainThread()); ProcessAutoComplete(control.Text); } }; control.TextChanged += (sender, e) => { UserTyping(); ResetAutoComplete(); }; return control; } public abstract void ProcessCommand(string command); public virtual void UserTyping() { } public override void Focus() { TextEntry.Focus(); } protected virtual Task<IEnumerable<string>> GetAutoCompleteNames(string search) { return null; } protected virtual void ResetAutoComplete() { existingPrefix = null; lastAutoComplete = null; autoCompleteIndex = null; autoCompleting = false; } public virtual async void ProcessAutoComplete(string text) { if (autoCompleting) return; autoCompleting = true; var index = autoCompleteIndex ?? text.LastIndexOf(' '); if (index > text.Length) { ResetAutoComplete(); return; } var prefix = (index >= 0 ? text.Substring(index + 1) : text); if (prefix.Length > 0) { var existingText = index >= 0 ? text.Substring(0, index + 1) : string.Empty; var searchPrefix = existingPrefix ?? prefix; //Debug.Print("Getting auto complete names: {0}" , Thread.IsMainThread()); var results = await GetAutoCompleteNames(searchPrefix); if (results == null) { ResetAutoComplete(); return; } if (!autoCompleting) return; try { var allMatches = results.OrderBy(r => r); IEnumerable<string> matches = allMatches.ToArray(); if (!string.IsNullOrEmpty(lastAutoComplete)) { matches = matches.Where(r => string.Compare(r, lastAutoComplete, StringComparison.CurrentCultureIgnoreCase) > 0); } var user = matches.FirstOrDefault() ?? allMatches.FirstOrDefault(); if (user != null) { //Debug.Print("Setting Text: {0}" , Thread.IsMainThread()); Application.Instance.Invoke(() => { TextEntry.Text = existingText + TranslateAutoCompleteText(user, searchPrefix); lastAutoComplete = user; if (existingPrefix == null) { existingPrefix = prefix; autoCompleteIndex = index; } }); } autoCompleting = false; } catch { ResetAutoComplete(); } } } public virtual string TranslateAutoCompleteText(string selection, string search) { return selection; } } }
/* * Copyright (c) 2006-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.Text; using System.Collections; using System.Collections.Generic; using System.Threading; using OpenMetaverse.StructuredData; using OpenMetaverse.Http; using OpenMetaverse.Packets; namespace OpenMetaverse { #region Enums /// <summary> /// Map layer request type /// </summary> public enum GridLayerType : uint { /// <summary>Objects and terrain are shown</summary> Objects = 0, /// <summary>Only the terrain is shown, no objects</summary> Terrain = 1, /// <summary>Overlay showing land for sale and for auction</summary> LandForSale = 2 } /// <summary> /// Type of grid item, such as telehub, event, populator location, etc. /// </summary> public enum GridItemType : uint { /// <summary>Telehub</summary> Telehub = 1, /// <summary>PG rated event</summary> PgEvent = 2, /// <summary>Mature rated event</summary> MatureEvent = 3, /// <summary>Popular location</summary> Popular = 4, /// <summary>Locations of avatar groups in a region</summary> AgentLocations = 6, /// <summary>Land for sale</summary> LandForSale = 7, /// <summary>Classified ad</summary> Classified = 8, /// <summary>Adult rated event</summary> AdultEvent = 9, /// <summary>Adult land for sale</summary> AdultLandForSale = 10 } #endregion Enums #region Structs /// <summary> /// Information about a region on the grid map /// </summary> public struct GridRegion { /// <summary>Sim X position on World Map</summary> public int X; /// <summary>Sim Y position on World Map</summary> public int Y; /// <summary>Sim Name (NOTE: In lowercase!)</summary> public string Name; /// <summary></summary> public SimAccess Access; /// <summary>Appears to always be zero (None)</summary> public RegionFlags RegionFlags; /// <summary>Sim's defined Water Height</summary> public byte WaterHeight; /// <summary></summary> public byte Agents; /// <summary>UUID of the World Map image</summary> public UUID MapImageID; /// <summary>Unique identifier for this region, a combination of the X /// and Y position</summary> public ulong RegionHandle; /// <summary> /// /// </summary> /// <returns></returns> public override string ToString() { return String.Format("{0} ({1}/{2}), Handle: {3}, MapImage: {4}, Access: {5}, Flags: {6}", Name, X, Y, RegionHandle, MapImageID, Access, RegionFlags); } /// <summary> /// /// </summary> /// <returns></returns> public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { if (obj is GridRegion) return Equals((GridRegion)obj); else return false; } private bool Equals(GridRegion region) { return (this.X == region.X && this.Y == region.Y); } } /// <summary> /// Visual chunk of the grid map /// </summary> public struct GridLayer { public int Bottom; public int Left; public int Top; public int Right; public UUID ImageID; public bool ContainsRegion(int x, int y) { return (x >= Left && x <= Right && y >= Bottom && y <= Top); } } #endregion Structs #region Map Item Classes /// <summary> /// Base class for Map Items /// </summary> public abstract class MapItem { /// <summary>The Global X position of the item</summary> public uint GlobalX; /// <summary>The Global Y position of the item</summary> public uint GlobalY; /// <summary>Get the Local X position of the item</summary> public uint LocalX { get { return GlobalX % 256; } } /// <summary>Get the Local Y position of the item</summary> public uint LocalY { get { return GlobalY % 256; } } /// <summary>Get the Handle of the region</summary> public ulong RegionHandle { get { return Utils.UIntsToLong((uint)(GlobalX - (GlobalX % 256)), (uint)(GlobalY - (GlobalY % 256))); } } } /// <summary> /// Represents an agent or group of agents location /// </summary> public class MapAgentLocation : MapItem { public int AvatarCount; public string Identifier; } /// <summary> /// Represents a Telehub location /// </summary> public class MapTelehub : MapItem { } /// <summary> /// Represents a non-adult parcel of land for sale /// </summary> public class MapLandForSale : MapItem { public int Size; public int Price; public string Name; public UUID ID; } /// <summary> /// Represents an Adult parcel of land for sale /// </summary> public class MapAdultLandForSale : MapItem { public int Size; public int Price; public string Name; public UUID ID; } /// <summary> /// Represents a PG Event /// </summary> public class MapPGEvent : MapItem { public DirectoryManager.EventFlags Flags; // Extra public DirectoryManager.EventCategories Category; // Extra2 public string Description; } /// <summary> /// Represents a Mature event /// </summary> public class MapMatureEvent : MapItem { public DirectoryManager.EventFlags Flags; // Extra public DirectoryManager.EventCategories Category; // Extra2 public string Description; } /// <summary> /// Represents an Adult event /// </summary> public class MapAdultEvent : MapItem { public DirectoryManager.EventFlags Flags; // Extra public DirectoryManager.EventCategories Category; // Extra2 public string Description; } #endregion Grid Item Classes /// <summary> /// Manages grid-wide tasks such as the world map /// </summary> public class GridManager { #region Delegates /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<CoarseLocationUpdateEventArgs> m_CoarseLocationUpdate; /// <summary>Raises the CoarseLocationUpdate event</summary> /// <param name="e">A CoarseLocationUpdateEventArgs object containing the /// data sent by simulator</param> protected virtual void OnCoarseLocationUpdate(CoarseLocationUpdateEventArgs e) { EventHandler<CoarseLocationUpdateEventArgs> handler = m_CoarseLocationUpdate; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_CoarseLocationUpdateLock = new object(); /// <summary>Raised when the simulator sends a <see cref="CoarseLocationUpdatePacket"/> /// containing the location of agents in the simulator</summary> public event EventHandler<CoarseLocationUpdateEventArgs> CoarseLocationUpdate { add { lock (m_CoarseLocationUpdateLock) { m_CoarseLocationUpdate += value; } } remove { lock (m_CoarseLocationUpdateLock) { m_CoarseLocationUpdate -= value; } } } /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<GridRegionEventArgs> m_GridRegion; /// <summary>Raises the GridRegion event</summary> /// <param name="e">A GridRegionEventArgs object containing the /// data sent by simulator</param> protected virtual void OnGridRegion(GridRegionEventArgs e) { EventHandler<GridRegionEventArgs> handler = m_GridRegion; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_GridRegionLock = new object(); /// <summary>Raised when the simulator sends a Region Data in response to /// a Map request</summary> public event EventHandler<GridRegionEventArgs> GridRegion { add { lock (m_GridRegionLock) { m_GridRegion += value; } } remove { lock (m_GridRegionLock) { m_GridRegion -= value; } } } /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<GridLayerEventArgs> m_GridLayer; /// <summary>Raises the GridLayer event</summary> /// <param name="e">A GridLayerEventArgs object containing the /// data sent by simulator</param> protected virtual void OnGridLayer(GridLayerEventArgs e) { EventHandler<GridLayerEventArgs> handler = m_GridLayer; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_GridLayerLock = new object(); /// <summary>Raised when the simulator sends GridLayer object containing /// a map tile coordinates and texture information</summary> public event EventHandler<GridLayerEventArgs> GridLayer { add { lock (m_GridLayerLock) { m_GridLayer += value; } } remove { lock (m_GridLayerLock) { m_GridLayer -= value; } } } /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<GridItemsEventArgs> m_GridItems; /// <summary>Raises the GridItems event</summary> /// <param name="e">A GridItemEventArgs object containing the /// data sent by simulator</param> protected virtual void OnGridItems(GridItemsEventArgs e) { EventHandler<GridItemsEventArgs> handler = m_GridItems; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_GridItemsLock = new object(); /// <summary>Raised when the simulator sends GridItems object containing /// details on events, land sales at a specific location</summary> public event EventHandler<GridItemsEventArgs> GridItems { add { lock (m_GridItemsLock) { m_GridItems += value; } } remove { lock (m_GridItemsLock) { m_GridItems -= value; } } } /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<RegionHandleReplyEventArgs> m_RegionHandleReply; /// <summary>Raises the RegionHandleReply event</summary> /// <param name="e">A RegionHandleReplyEventArgs object containing the /// data sent by simulator</param> protected virtual void OnRegionHandleReply(RegionHandleReplyEventArgs e) { EventHandler<RegionHandleReplyEventArgs> handler = m_RegionHandleReply; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_RegionHandleReplyLock = new object(); /// <summary>Raised in response to a Region lookup</summary> public event EventHandler<RegionHandleReplyEventArgs> RegionHandleReply { add { lock (m_RegionHandleReplyLock) { m_RegionHandleReply += value; } } remove { lock (m_RegionHandleReplyLock) { m_RegionHandleReply -= value; } } } #endregion Delegates /// <summary>Unknown</summary> public float SunPhase { get { return sunPhase; } } /// <summary>Current direction of the sun</summary> public Vector3 SunDirection { get { return sunDirection; } } /// <summary>Current angular velocity of the sun</summary> public Vector3 SunAngVelocity { get { return sunAngVelocity; } } /// <summary>Microseconds since the start of SL 4-hour day</summary> public ulong TimeOfDay { get { return timeOfDay; } } /// <summary>A dictionary of all the regions, indexed by region name</summary> internal Dictionary<string, GridRegion> Regions = new Dictionary<string, GridRegion>(); /// <summary>A dictionary of all the regions, indexed by region handle</summary> internal Dictionary<ulong, GridRegion> RegionsByHandle = new Dictionary<ulong, GridRegion>(); private GridClient Client; private float sunPhase; private Vector3 sunDirection; private Vector3 sunAngVelocity; private ulong timeOfDay; /// <summary> /// Constructor /// </summary> /// <param name="client">Instance of GridClient object to associate with this GridManager instance</param> public GridManager(GridClient client) { Client = client; //Client.Network.RegisterCallback(PacketType.MapLayerReply, MapLayerReplyHandler); Client.Network.RegisterCallback(PacketType.MapBlockReply, MapBlockReplyHandler); Client.Network.RegisterCallback(PacketType.MapItemReply, MapItemReplyHandler); Client.Network.RegisterCallback(PacketType.SimulatorViewerTimeMessage, SimulatorViewerTimeMessageHandler); Client.Network.RegisterCallback(PacketType.CoarseLocationUpdate, CoarseLocationHandler, false); Client.Network.RegisterCallback(PacketType.RegionIDAndHandleReply, RegionHandleReplyHandler); } /// <summary> /// /// </summary> /// <param name="layer"></param> public void RequestMapLayer(GridLayerType layer) { Uri url = Client.Network.CurrentSim.Caps.CapabilityURI("MapLayer"); if (url != null) { OSDMap body = new OSDMap(); body["Flags"] = OSD.FromInteger((int)layer); CapsClient request = new CapsClient(url); request.OnComplete += new CapsClient.CompleteCallback(MapLayerResponseHandler); request.BeginGetResponse(body, OSDFormat.Xml, Client.Settings.CAPS_TIMEOUT); } } /// <summary> /// Request a map layer /// </summary> /// <param name="regionName">The name of the region</param> /// <param name="layer">The type of layer</param> public void RequestMapRegion(string regionName, GridLayerType layer) { MapNameRequestPacket request = new MapNameRequestPacket(); request.AgentData.AgentID = Client.Self.AgentID; request.AgentData.SessionID = Client.Self.SessionID; request.AgentData.Flags = (uint)layer; request.AgentData.EstateID = 0; // Filled in on the sim request.AgentData.Godlike = false; // Filled in on the sim request.NameData.Name = Utils.StringToBytes(regionName); Client.Network.SendPacket(request); } /// <summary> /// /// </summary> /// <param name="layer"></param> /// <param name="minX"></param> /// <param name="minY"></param> /// <param name="maxX"></param> /// <param name="maxY"></param> /// <param name="returnNonExistent"></param> public void RequestMapBlocks(GridLayerType layer, ushort minX, ushort minY, ushort maxX, ushort maxY, bool returnNonExistent) { MapBlockRequestPacket request = new MapBlockRequestPacket(); request.AgentData.AgentID = Client.Self.AgentID; request.AgentData.SessionID = Client.Self.SessionID; request.AgentData.Flags = (uint)layer; request.AgentData.Flags |= (uint)(returnNonExistent ? 0x10000 : 0); request.AgentData.EstateID = 0; // Filled in at the simulator request.AgentData.Godlike = false; // Filled in at the simulator request.PositionData.MinX = minX; request.PositionData.MinY = minY; request.PositionData.MaxX = maxX; request.PositionData.MaxY = maxY; Client.Network.SendPacket(request); } /// <summary> /// /// </summary> /// <param name="regionHandle"></param> /// <param name="item"></param> /// <param name="layer"></param> /// <param name="timeoutMS"></param> /// <returns></returns> public List<MapItem> MapItems(ulong regionHandle, GridItemType item, GridLayerType layer, int timeoutMS) { List<MapItem> itemList = null; AutoResetEvent itemsEvent = new AutoResetEvent(false); EventHandler<GridItemsEventArgs> callback = delegate(object sender, GridItemsEventArgs e) { if (e.Type == GridItemType.AgentLocations) { itemList = e.Items; itemsEvent.Set(); } }; GridItems += callback; RequestMapItems(regionHandle, item, layer); itemsEvent.WaitOne(timeoutMS, false); GridItems -= callback; return itemList; } /// <summary> /// /// </summary> /// <param name="regionHandle"></param> /// <param name="item"></param> /// <param name="layer"></param> public void RequestMapItems(ulong regionHandle, GridItemType item, GridLayerType layer) { MapItemRequestPacket request = new MapItemRequestPacket(); request.AgentData.AgentID = Client.Self.AgentID; request.AgentData.SessionID = Client.Self.SessionID; request.AgentData.Flags = (uint)layer; request.AgentData.Godlike = false; // Filled in on the sim request.AgentData.EstateID = 0; // Filled in on the sim request.RequestData.ItemType = (uint)item; request.RequestData.RegionHandle = regionHandle; Client.Network.SendPacket(request); } /// <summary> /// Request data for all mainland (Linden managed) simulators /// </summary> public void RequestMainlandSims(GridLayerType layer) { RequestMapBlocks(layer, 0, 0, 65535, 65535, false); } /// <summary> /// Request the region handle for the specified region UUID /// </summary> /// <param name="regionID">UUID of the region to look up</param> public void RequestRegionHandle(UUID regionID) { RegionHandleRequestPacket request = new RegionHandleRequestPacket(); request.RequestBlock = new RegionHandleRequestPacket.RequestBlockBlock(); request.RequestBlock.RegionID = regionID; Client.Network.SendPacket(request); } /// <summary> /// Get grid region information using the region name, this function /// will block until it can find the region or gives up /// </summary> /// <param name="name">Name of sim you're looking for</param> /// <param name="layer">Layer that you are requesting</param> /// <param name="region">Will contain a GridRegion for the sim you're /// looking for if successful, otherwise an empty structure</param> /// <returns>True if the GridRegion was successfully fetched, otherwise /// false</returns> public bool GetGridRegion(string name, GridLayerType layer, out GridRegion region) { if (String.IsNullOrEmpty(name)) { Logger.Log("GetGridRegion called with a null or empty region name", Helpers.LogLevel.Error, Client); region = new GridRegion(); return false; } if (Regions.ContainsKey(name)) { // We already have this GridRegion structure region = Regions[name]; return true; } else { AutoResetEvent regionEvent = new AutoResetEvent(false); EventHandler<GridRegionEventArgs> callback = delegate(object sender, GridRegionEventArgs e) { if (e.Region.Name == name) regionEvent.Set(); }; GridRegion += callback; RequestMapRegion(name, layer); regionEvent.WaitOne(Client.Settings.MAP_REQUEST_TIMEOUT, false); GridRegion -= callback; if (Regions.ContainsKey(name)) { // The region was found after our request region = Regions[name]; return true; } else { Logger.Log("Couldn't find region " + name, Helpers.LogLevel.Warning, Client); region = new GridRegion(); return false; } } } protected void MapLayerResponseHandler(CapsClient client, OSD result, Exception error) { if (result == null) { Logger.Log("MapLayerResponseHandler error: " + error.Message + ": " + error.StackTrace, Helpers.LogLevel.Error, Client); return; } OSDMap body = (OSDMap)result; OSDArray layerData = (OSDArray)body["LayerData"]; if (m_GridLayer != null) { for (int i = 0; i < layerData.Count; i++) { OSDMap thisLayerData = (OSDMap)layerData[i]; GridLayer layer; layer.Bottom = thisLayerData["Bottom"].AsInteger(); layer.Left = thisLayerData["Left"].AsInteger(); layer.Top = thisLayerData["Top"].AsInteger(); layer.Right = thisLayerData["Right"].AsInteger(); layer.ImageID = thisLayerData["ImageID"].AsUUID(); OnGridLayer(new GridLayerEventArgs(layer)); } } if (body.ContainsKey("MapBlocks")) { // TODO: At one point this will become activated Logger.Log("Got MapBlocks through CAPS, please finish this function!", Helpers.LogLevel.Error, Client); } } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void MapBlockReplyHandler(object sender, PacketReceivedEventArgs e) { MapBlockReplyPacket map = (MapBlockReplyPacket)e.Packet; foreach (MapBlockReplyPacket.DataBlock block in map.Data) { if (block.X != 0 || block.Y != 0) { GridRegion region; region.X = block.X; region.Y = block.Y; region.Name = Utils.BytesToString(block.Name); // RegionFlags seems to always be zero here? region.RegionFlags = (RegionFlags)block.RegionFlags; region.WaterHeight = block.WaterHeight; region.Agents = block.Agents; region.Access = (SimAccess)block.Access; region.MapImageID = block.MapImageID; region.RegionHandle = Utils.UIntsToLong((uint)(region.X * 256), (uint)(region.Y * 256)); lock (Regions) { Regions[region.Name] = region; RegionsByHandle[region.RegionHandle] = region; } if (m_GridRegion != null) { OnGridRegion(new GridRegionEventArgs(region)); } } } } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void MapItemReplyHandler(object sender, PacketReceivedEventArgs e) { if (m_GridItems != null) { MapItemReplyPacket reply = (MapItemReplyPacket)e.Packet; GridItemType type = (GridItemType)reply.RequestData.ItemType; List<MapItem> items = new List<MapItem>(); for (int i = 0; i < reply.Data.Length; i++) { string name = Utils.BytesToString(reply.Data[i].Name); switch (type) { case GridItemType.AgentLocations: MapAgentLocation location = new MapAgentLocation(); location.GlobalX = reply.Data[i].X; location.GlobalY = reply.Data[i].Y; location.Identifier = name; location.AvatarCount = reply.Data[i].Extra; items.Add(location); break; case GridItemType.Classified: //FIXME: Logger.Log("FIXME", Helpers.LogLevel.Error, Client); break; case GridItemType.LandForSale: MapLandForSale landsale = new MapLandForSale(); landsale.GlobalX = reply.Data[i].X; landsale.GlobalY = reply.Data[i].Y; landsale.ID = reply.Data[i].ID; landsale.Name = name; landsale.Size = reply.Data[i].Extra; landsale.Price = reply.Data[i].Extra2; items.Add(landsale); break; case GridItemType.MatureEvent: MapMatureEvent matureEvent = new MapMatureEvent(); matureEvent.GlobalX = reply.Data[i].X; matureEvent.GlobalY = reply.Data[i].Y; matureEvent.Description = name; matureEvent.Flags = (DirectoryManager.EventFlags)reply.Data[i].Extra2; items.Add(matureEvent); break; case GridItemType.PgEvent: MapPGEvent PGEvent = new MapPGEvent(); PGEvent.GlobalX = reply.Data[i].X; PGEvent.GlobalY = reply.Data[i].Y; PGEvent.Description = name; PGEvent.Flags = (DirectoryManager.EventFlags)reply.Data[i].Extra2; items.Add(PGEvent); break; case GridItemType.Popular: //FIXME: Logger.Log("FIXME", Helpers.LogLevel.Error, Client); break; case GridItemType.Telehub: MapTelehub teleHubItem = new MapTelehub(); teleHubItem.GlobalX = reply.Data[i].X; teleHubItem.GlobalY = reply.Data[i].Y; items.Add(teleHubItem); break; case GridItemType.AdultLandForSale: MapAdultLandForSale adultLandsale = new MapAdultLandForSale(); adultLandsale.GlobalX = reply.Data[i].X; adultLandsale.GlobalY = reply.Data[i].Y; adultLandsale.ID = reply.Data[i].ID; adultLandsale.Name = name; adultLandsale.Size = reply.Data[i].Extra; adultLandsale.Price = reply.Data[i].Extra2; items.Add(adultLandsale); break; case GridItemType.AdultEvent: MapAdultEvent adultEvent = new MapAdultEvent(); adultEvent.GlobalX = reply.Data[i].X; adultEvent.GlobalY = reply.Data[i].Y; adultEvent.Description = Utils.BytesToString(reply.Data[i].Name); adultEvent.Flags = (DirectoryManager.EventFlags)reply.Data[i].Extra2; items.Add(adultEvent); break; default: Logger.Log("Unknown map item type " + type, Helpers.LogLevel.Warning, Client); break; } } OnGridItems(new GridItemsEventArgs(type, items)); } } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void SimulatorViewerTimeMessageHandler(object sender, PacketReceivedEventArgs e) { SimulatorViewerTimeMessagePacket time = (SimulatorViewerTimeMessagePacket)e.Packet; sunPhase = time.TimeInfo.SunPhase; sunDirection = time.TimeInfo.SunDirection; sunAngVelocity = time.TimeInfo.SunAngVelocity; timeOfDay = time.TimeInfo.UsecSinceStart; // TODO: Does anyone have a use for the time stuff? } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void CoarseLocationHandler(object sender, PacketReceivedEventArgs e) { CoarseLocationUpdatePacket coarse = (CoarseLocationUpdatePacket)e.Packet; // populate a dictionary from the packet, for local use Dictionary<UUID, Vector3> coarseEntries = new Dictionary<UUID, Vector3>(); for (int i = 0; i < coarse.AgentData.Length; i++) { if(coarse.Location.Length > 0) coarseEntries[coarse.AgentData[i].AgentID] = new Vector3((int)coarse.Location[i].X, (int)coarse.Location[i].Y, (int)coarse.Location[i].Z * 4); // the friend we are tracking on radar if (i == coarse.Index.Prey) e.Simulator.preyID = coarse.AgentData[i].AgentID; } // find stale entries (people who left the sim) List<UUID> removedEntries = e.Simulator.avatarPositions.FindAll(delegate(UUID findID) { return !coarseEntries.ContainsKey(findID); }); // anyone who was not listed in the previous update List<UUID> newEntries = new List<UUID>(); lock (e.Simulator.avatarPositions.Dictionary) { // remove stale entries foreach(UUID trackedID in removedEntries) e.Simulator.avatarPositions.Dictionary.Remove(trackedID); // add or update tracked info, and record who is new foreach (KeyValuePair<UUID, Vector3> entry in coarseEntries) { if (!e.Simulator.avatarPositions.Dictionary.ContainsKey(entry.Key)) newEntries.Add(entry.Key); e.Simulator.avatarPositions.Dictionary[entry.Key] = entry.Value; } } if (m_CoarseLocationUpdate != null) { ThreadPool.QueueUserWorkItem(delegate(object o) { OnCoarseLocationUpdate(new CoarseLocationUpdateEventArgs(e.Simulator, newEntries, removedEntries)); }); } } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void RegionHandleReplyHandler(object sender, PacketReceivedEventArgs e) { if (m_RegionHandleReply != null) { RegionIDAndHandleReplyPacket reply = (RegionIDAndHandleReplyPacket)e.Packet; OnRegionHandleReply(new RegionHandleReplyEventArgs(reply.ReplyBlock.RegionID, reply.ReplyBlock.RegionHandle)); } } } #region EventArgs classes public class CoarseLocationUpdateEventArgs : EventArgs { private readonly Simulator m_Simulator; private readonly List<UUID> m_NewEntries; private readonly List<UUID> m_RemovedEntries; public Simulator Simulator { get { return m_Simulator; } } public List<UUID> NewEntries { get { return m_NewEntries; } } public List<UUID> RemovedEntries { get { return m_RemovedEntries; } } public CoarseLocationUpdateEventArgs(Simulator simulator, List<UUID> newEntries, List<UUID> removedEntries) { this.m_Simulator = simulator; this.m_NewEntries = newEntries; this.m_RemovedEntries = removedEntries; } } public class GridRegionEventArgs : EventArgs { private readonly GridRegion m_Region; public GridRegion Region { get { return m_Region; } } public GridRegionEventArgs(GridRegion region) { this.m_Region = region; } } public class GridLayerEventArgs : EventArgs { private readonly GridLayer m_Layer; public GridLayer Layer { get { return m_Layer; } } public GridLayerEventArgs(GridLayer layer) { this.m_Layer = layer; } } public class GridItemsEventArgs : EventArgs { private readonly GridItemType m_Type; private readonly List<MapItem> m_Items; public GridItemType Type { get { return m_Type; } } public List<MapItem> Items { get { return m_Items; } } public GridItemsEventArgs(GridItemType type, List<MapItem> items) { this.m_Type = type; this.m_Items = items; } } public class RegionHandleReplyEventArgs : EventArgs { private readonly UUID m_RegionID; private readonly ulong m_RegionHandle; public UUID RegionID { get { return m_RegionID; } } public ulong RegionHandle { get { return m_RegionHandle; } } public RegionHandleReplyEventArgs(UUID regionID, ulong regionHandle) { this.m_RegionID = regionID; this.m_RegionHandle = regionHandle; } } #endregion }
using System; /// <summary> /// Convert.ToUInt32(String,Int32) /// </summary> public class ConvertToUInt3219 { public static int Main() { ConvertToUInt3219 convertToUInt3219 = new ConvertToUInt3219(); TestLibrary.TestFramework.BeginTestCase("ConvertToUInt3219"); if (convertToUInt3219.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; retVal = NegTest5() && retVal; retVal = NegTest6() && retVal; retVal = NegTest7() && retVal; retVal = NegTest8() && retVal; return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Convert to UInt32 from string 1"); try { string strVal = "1111"; uint uintVal1 = Convert.ToUInt32(strVal, 2); uint uintVal2 = Convert.ToUInt32(strVal, 8); uint uintVal3 = Convert.ToUInt32(strVal, 10); uint uintVal4 = Convert.ToUInt32(strVal, 16); if (uintVal1 != (UInt32)(1 * Math.Pow(2, 3) + 1 * Math.Pow(2, 2) + 1 * Math.Pow(2, 1) + 1 * Math.Pow(2, 0)) || uintVal2 != (UInt32)(1 * Math.Pow(8, 3) + 1 * Math.Pow(8, 2) + 1 * Math.Pow(8, 1) + 1 * Math.Pow(8, 0)) || uintVal3 != (UInt32)(1 * Math.Pow(10, 3) + 1 * Math.Pow(10, 2) + 1 * Math.Pow(10, 1) + 1 * Math.Pow(10, 0)) || uintVal4 != (UInt32)(1 * Math.Pow(16, 3) + 1 * Math.Pow(16, 2) + 1 * Math.Pow(16, 1) + 1 * Math.Pow(16, 0)) ) { TestLibrary.TestFramework.LogError("001", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Convert to UInt32 from string 2"); try { uint intVal = (UInt32)this.GetInt32(0, Int32.MaxValue) + (UInt32)this.GetInt32(0, Int32.MaxValue); string strVal = "+" + intVal.ToString(); uint uintVal = Convert.ToUInt32(strVal, 10); if (uintVal != intVal) { TestLibrary.TestFramework.LogError("003", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Convert to UInt32 from string 3"); try { string strVal = null; uint uintVal1 = Convert.ToUInt32(strVal, 2); uint uintVal2 = Convert.ToUInt32(strVal, 8); uint uintVal3 = Convert.ToUInt32(strVal, 10); uint uintVal4 = Convert.ToUInt32(strVal, 16); if (uintVal1 != 0 || uintVal2 != 0 || uintVal3 != 0 || uintVal4 != 0) { TestLibrary.TestFramework.LogError("005", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Convert to UInt32 from string 4"); try { string strVal = "0xff"; uint uintVal = Convert.ToUInt32(strVal, 16); if (uintVal != (UInt32)(15 * Math.Pow(16, 1) + 15 * Math.Pow(16, 0))) { TestLibrary.TestFramework.LogError("007", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region NegativeTest public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: the parameter of fromBase is not 2, 8, 10, or 16"); try { string strVal = "1111"; uint uintVal = Convert.ToUInt32(strVal, 100); TestLibrary.TestFramework.LogError("N001", "the parameter of fromBase is not 2, 8, 10, or 16 but not throw exception"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: the string represents a non-base 10 signed number and is prefixed with a negative sign"); try { string strVal = "-0"; uint uintVal = Convert.ToUInt32(strVal, 2); TestLibrary.TestFramework.LogError("N003", "the string represents a non-base 10 signed number and is prefixed with a negative sign but not throw exception"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N004", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: the string contains a character that is not a valid digit in the base specified by fromBase param 1"); try { string strVal = "1234"; uint uintVal = Convert.ToUInt32(strVal, 2); TestLibrary.TestFramework.LogError("N005", "the string contains a character that is not a valid digit in the base specified by fromBase param but not throw exception"); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N006", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4: the string contains a character that is not a valid digit in the base specified by fromBase param 2"); try { string strVal = "9999"; uint uintVal = Convert.ToUInt32(strVal, 8); TestLibrary.TestFramework.LogError("N007", "the string contains a character that is not a valid digit in the base specified by fromBase param but not throw exception"); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N008", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest5: the string contains a character that is not a valid digit in the base specified by fromBase param 3"); try { string strVal = "abcd"; uint uintVal = Convert.ToUInt32(strVal, 10); TestLibrary.TestFramework.LogError("N009", "the string contains a character that is not a valid digit in the base specified by fromBase param but not throw exception"); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N010", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest6: the string contains a character that is not a valid digit in the base specified by fromBase param 4"); try { string strVal = "gh"; uint uintVal = Convert.ToUInt32(strVal, 16); TestLibrary.TestFramework.LogError("N011", "the string contains a character that is not a valid digit in the base specified by fromBase param but not throw exception"); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N012", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest7: the string represents base 10 number is less than UInt32.minValue"); try { int intVal = this.GetInt32(1, Int32.MaxValue); string strVal = "-" + intVal.ToString(); uint uintVal = Convert.ToUInt32(strVal, 10); TestLibrary.TestFramework.LogError("N013", "the string represent base 10 number is less than UInt32.minValue but not throw exception"); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N014", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest8() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest8: the string represents base 10 number is greater than UInt32.maxValue"); try { UInt64 intVal = (UInt64)UInt32.MaxValue + (UInt64)this.GetInt32(1, Int32.MaxValue); string strVal = intVal.ToString(); uint uintVal = Convert.ToUInt32(strVal, 10); TestLibrary.TestFramework.LogError("N015", "the string represent base 10 number is greater than UInt32.maxValue but not throw exception"); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N016", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region HelpMethod private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
using UnityEngine; using System; using System.Collections.Generic; using Delaunay.Geo; using Delaunay.LR; namespace Delaunay { public sealed class Site: ICoord, IComparable { private static Stack<Site> _pool = new Stack<Site> (); public static Site Create (Vector2 p, uint index, float weight, uint color) { if (_pool.Count > 0) { return _pool.Pop ().Init (p, index, weight, color); } else { return new Site (p, index, weight, color); } } internal static void SortSites (List<Site> sites) { // sites.sort(Site.compare); sites.Sort (); // XXX: Check if this works } /** * sort sites on y, then x, coord * also change each site's _siteIndex to match its new position in the list * so the _siteIndex can be used to identify the site for nearest-neighbor queries * * haha "also" - means more than one responsibility... * */ public int CompareTo (System.Object obj) // XXX: Really, really worried about this because it depends on how sorting works in AS3 impl - Julian { Site s2 = (Site)obj; int returnValue = Voronoi.CompareByYThenX (this, s2); // swap _siteIndex values if necessary to match new ordering: uint tempIndex; if (returnValue == -1) { if (this._siteIndex > s2._siteIndex) { tempIndex = this._siteIndex; this._siteIndex = s2._siteIndex; s2._siteIndex = tempIndex; } } else if (returnValue == 1) { if (s2._siteIndex > this._siteIndex) { tempIndex = s2._siteIndex; s2._siteIndex = this._siteIndex; this._siteIndex = tempIndex; } } return returnValue; } private static readonly float EPSILON = .005f; private static bool CloseEnough (Vector2 p0, Vector2 p1) { return Vector2.Distance (p0, p1) < EPSILON; } private Vector2 _coord; public Vector2 Coord { get { return _coord;} } public uint color; public float weight; private uint _siteIndex; // the edges that define this Site's Voronoi region: private List<Edge> _edges; internal List<Edge> edges { get { return _edges;} } // which end of each edge hooks up with the previous edge in _edges: private List<LR.Side> _edgeOrientations; // ordered list of points that define the region clipped to bounds: private List<Vector2> _region; private Site (Vector2 p, uint index, float weight, uint color) { // if (lock != PrivateConstructorEnforcer) // { // throw new Error("Site constructor is private"); // } Init (p, index, weight, color); } private Site Init (Vector2 p, uint index, float weight, uint color) { _coord = p; _siteIndex = index; this.weight = weight; this.color = color; _edges = new List<Edge> (); _region = null; return this; } public override string ToString () { return "Site " + _siteIndex.ToString () + ": " + Coord.ToString (); } private void Move (Vector2 p) { Clear (); _coord = p; } public void Dispose () { // _coord = null; Clear (); _pool.Push (this); } private void Clear () { if (_edges != null) { _edges.Clear (); _edges = null; } if (_edgeOrientations != null) { _edgeOrientations.Clear (); _edgeOrientations = null; } if (_region != null) { _region.Clear (); _region = null; } } public void AddEdge (Edge edge) { _edges.Add (edge); } public Edge NearestEdge () { _edges.Sort (delegate (Edge a, Edge b) { return Edge.CompareSitesDistances (a, b); }); return _edges [0]; } public List<Site> NeighborSites () { if (_edges == null || _edges.Count == 0) { return new List<Site> (); } if (_edgeOrientations == null) { ReorderEdges (); } List<Site> list = new List<Site> (); Edge edge; for (int i = 0; i < _edges.Count; i++) { edge = _edges [i]; list.Add (NeighborSite (edge)); } return list; } private Site NeighborSite (Edge edge) { if (this == edge.leftSite) { return edge.rightSite; } if (this == edge.rightSite) { return edge.leftSite; } return null; } internal List<Vector2> Region (Rect clippingBounds) { if (_edges == null || _edges.Count == 0) { return new List<Vector2> (); } if (_edgeOrientations == null) { ReorderEdges (); _region = ClipToBounds (clippingBounds); if ((new Polygon (_region)).Winding () == Winding.CLOCKWISE) { _region.Reverse (); } } return _region; } private void ReorderEdges () { //trace("_edges:", _edges); EdgeReorderer reorderer = new EdgeReorderer (_edges, VertexOrSite.VERTEX); _edges = reorderer.edges; //trace("reordered:", _edges); _edgeOrientations = reorderer.edgeOrientations; reorderer.Dispose (); } private List<Vector2> ClipToBounds (Rect bounds) { List<Vector2> points = new List<Vector2> (); int n = _edges.Count; int i = 0; Edge edge; while (i < n && ((_edges[i] as Edge).visible == false)) { ++i; } if (i == n) { // no edges visible return new List<Vector2> (); } edge = _edges [i]; LR.Side orientation = _edgeOrientations [i]; if (edge.clippedEnds [orientation] == null) { Debug.LogError ("XXX: Null detected when there should be a Vector2!"); } if (edge.clippedEnds [SideHelper.Other (orientation)] == null) { Debug.LogError ("XXX: Null detected when there should be a Vector2!"); } points.Add ((Vector2)edge.clippedEnds [orientation]); points.Add ((Vector2)edge.clippedEnds [SideHelper.Other (orientation)]); for (int j = i + 1; j < n; ++j) { edge = _edges [j]; if (edge.visible == false) { continue; } Connect (points, j, bounds); } // close up the polygon by adding another corner point of the bounds if needed: Connect (points, i, bounds, true); return points; } private void Connect (List<Vector2> points, int j, Rect bounds, bool closingUp = false) { Vector2 rightPoint = points [points.Count - 1]; Edge newEdge = _edges [j] as Edge; LR.Side newOrientation = _edgeOrientations [j]; // the point that must be connected to rightPoint: if (newEdge.clippedEnds [newOrientation] == null) { Debug.LogError ("XXX: Null detected when there should be a Vector2!"); } Vector2 newPoint = (Vector2)newEdge.clippedEnds [newOrientation]; if (!CloseEnough (rightPoint, newPoint)) { // The points do not coincide, so they must have been clipped at the bounds; // see if they are on the same border of the bounds: if (rightPoint.x != newPoint.x && rightPoint.y != newPoint.y) { // They are on different borders of the bounds; // insert one or two corners of bounds as needed to hook them up: // (NOTE this will not be correct if the region should take up more than // half of the bounds rect, for then we will have gone the wrong way // around the bounds and included the smaller part rather than the larger) int rightCheck = BoundsCheck.Check (rightPoint, bounds); int newCheck = BoundsCheck.Check (newPoint, bounds); float px, py; if ((rightCheck & BoundsCheck.RIGHT) != 0) { px = bounds.xMax; if ((newCheck & BoundsCheck.BOTTOM) != 0) { py = bounds.yMax; points.Add (new Vector2 (px, py)); } else if ((newCheck & BoundsCheck.TOP) != 0) { py = bounds.yMin; points.Add (new Vector2 (px, py)); } else if ((newCheck & BoundsCheck.LEFT) != 0) { if (rightPoint.y - bounds.y + newPoint.y - bounds.y < bounds.height) { py = bounds.yMin; } else { py = bounds.yMax; } points.Add (new Vector2 (px, py)); points.Add (new Vector2 (bounds.xMin, py)); } } else if ((rightCheck & BoundsCheck.LEFT) != 0) { px = bounds.xMin; if ((newCheck & BoundsCheck.BOTTOM) != 0) { py = bounds.yMax; points.Add (new Vector2 (px, py)); } else if ((newCheck & BoundsCheck.TOP) != 0) { py = bounds.yMin; points.Add (new Vector2 (px, py)); } else if ((newCheck & BoundsCheck.RIGHT) != 0) { if (rightPoint.y - bounds.y + newPoint.y - bounds.y < bounds.height) { py = bounds.yMin; } else { py = bounds.yMax; } points.Add (new Vector2 (px, py)); points.Add (new Vector2 (bounds.xMax, py)); } } else if ((rightCheck & BoundsCheck.TOP) != 0) { py = bounds.yMin; if ((newCheck & BoundsCheck.RIGHT) != 0) { px = bounds.xMax; points.Add (new Vector2 (px, py)); } else if ((newCheck & BoundsCheck.LEFT) != 0) { px = bounds.xMin; points.Add (new Vector2 (px, py)); } else if ((newCheck & BoundsCheck.BOTTOM) != 0) { if (rightPoint.x - bounds.x + newPoint.x - bounds.x < bounds.width) { px = bounds.xMin; } else { px = bounds.xMax; } points.Add (new Vector2 (px, py)); points.Add (new Vector2 (px, bounds.yMax)); } } else if ((rightCheck & BoundsCheck.BOTTOM) != 0) { py = bounds.yMax; if ((newCheck & BoundsCheck.RIGHT) != 0) { px = bounds.xMax; points.Add (new Vector2 (px, py)); } else if ((newCheck & BoundsCheck.LEFT) != 0) { px = bounds.xMin; points.Add (new Vector2 (px, py)); } else if ((newCheck & BoundsCheck.TOP) != 0) { if (rightPoint.x - bounds.x + newPoint.x - bounds.x < bounds.width) { px = bounds.xMin; } else { px = bounds.xMax; } points.Add (new Vector2 (px, py)); points.Add (new Vector2 (px, bounds.yMin)); } } } if (closingUp) { // newEdge's ends have already been added return; } points.Add (newPoint); } if (newEdge.clippedEnds [SideHelper.Other (newOrientation)] == null) { Debug.LogError ("XXX: Null detected when there should be a Vector2!"); } Vector2 newRightPoint = (Vector2)newEdge.clippedEnds [SideHelper.Other (newOrientation)]; if (!CloseEnough (points [0], newRightPoint)) { points.Add (newRightPoint); } } public float x { get { return _coord.x;} } internal float y { get { return _coord.y;} } public float Dist (ICoord p) { return Vector2.Distance (p.Coord, this._coord); } } } // class PrivateConstructorEnforcer {} // import flash.geom.Point; // import flash.geom.Rectangle; static class BoundsCheck { public static readonly int TOP = 1; public static readonly int BOTTOM = 2; public static readonly int LEFT = 4; public static readonly int RIGHT = 8; /** * * @param point * @param bounds * @return an int with the appropriate bits set if the Point lies on the corresponding bounds lines * */ public static int Check (Vector2 point, Rect bounds) { int value = 0; if (point.x == bounds.xMin) { value |= LEFT; } if (point.x == bounds.xMax) { value |= RIGHT; } if (point.y == bounds.yMin) { value |= TOP; } if (point.y == bounds.yMax) { value |= BOTTOM; } return value; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Signum.Utilities; using Signum.Entities.Reflection; using System.Linq.Expressions; using Signum.Utilities.ExpressionTrees; using Signum.Entities; using System.Reflection; using Signum.Utilities.Reflection; namespace Signum.Engine.Maps { public class TableIndex { public ITable Table { get; private set; } public IColumn[] Columns { get; private set; } public IColumn[]? IncludeColumns { get; set; } public string? Where { get; set; } public static IColumn[] GetColumnsFromFields(params Field[] fields) { if (fields == null || fields.IsEmpty()) throw new InvalidOperationException("No fields"); if (fields.Any(f => f is FieldEmbedded || f is FieldMixin)) throw new InvalidOperationException("Embedded fields not supported for indexes"); return fields.SelectMany(f => f.Columns()).ToArray(); } public TableIndex(ITable table, params IColumn[] columns) { if (table == null) throw new ArgumentNullException(nameof(table)); if (columns == null || columns.IsEmpty()) throw new ArgumentNullException(nameof(columns)); this.Table = table; this.Columns = columns; } public virtual string GetIndexName(ObjectName tableName) { int maxLength = MaxNameLength(); return StringHashEncoder.ChopHash("IX_{0}_{1}".FormatWith(tableName.Name, ColumnSignature()), maxLength) + WhereSignature(); } protected static int MaxNameLength() { return Connector.Current.MaxNameLength - StringHashEncoder.HashSize - 2; } public string IndexName => GetIndexName(Table.Name); protected string ColumnSignature() { return Columns.ToString(c => c.Name, "_"); } public string? WhereSignature() { var includeColumns = IncludeColumns.HasItems() ? IncludeColumns.ToString(c => c.Name, "_") : null; if (string.IsNullOrEmpty(Where) && includeColumns == null) return null; return "__" + StringHashEncoder.Codify(Where + includeColumns); } public override string ToString() { return IndexName; } public string HintText() { return $"INDEX([{this.IndexName}])"; } } public class PrimaryKeyIndex : TableIndex { public PrimaryKeyIndex(ITable table) : base(table, new[] { table.PrimaryKey }) { } public override string GetIndexName(ObjectName tableName) => GetPrimaryKeyName(tableName); public static string GetPrimaryKeyName(ObjectName tableName) { return "PK_" + tableName.Schema.Name + "_" + tableName.Name; } } public class UniqueTableIndex : TableIndex { public UniqueTableIndex(ITable table, IColumn[] columns) : base(table, columns) { } public override string GetIndexName(ObjectName tableName) { var maxSize = MaxNameLength(); return StringHashEncoder.ChopHash("UIX_{0}_{1}".FormatWith(tableName.Name, ColumnSignature()), maxSize) + WhereSignature(); } public string? ViewName { get { if (!Where.HasText()) return null; if (Connector.Current.AllowsIndexWithWhere(Where)) return null; var maxSize = MaxNameLength(); return StringHashEncoder.ChopHash("VIX_{0}_{1}".FormatWith(Table.Name.Name, ColumnSignature()), maxSize) + WhereSignature(); } } public bool AvoidAttachToUniqueIndexes { get; set; } } public class IndexKeyColumns { public static IColumn[] Split(IFieldFinder finder, LambdaExpression columns) { if (columns == null) throw new ArgumentNullException(nameof(columns)); if (columns.Body.NodeType == ExpressionType.New) { var resultColumns = (from a in ((NewExpression)columns.Body).Arguments from c in GetColumns(finder, Expression.Lambda(Expression.Convert(a, typeof(object)), columns.Parameters)) select c); return resultColumns.ToArray(); } return GetColumns(finder, columns); } static string[] ignoreMembers = new string[] { "ToLite", "ToLiteFat" }; static IColumn[] GetColumns(IFieldFinder finder, LambdaExpression field) { var body = field.Body; Type? type = RemoveCasting(ref body); body = IndexWhereExpressionVisitor.RemoveLiteEntity(body); var members = Reflector.GetMemberListBase(body); if (members.Any(a => ignoreMembers.Contains(a.Name))) members = members.Where(a => !ignoreMembers.Contains(a.Name)).ToArray(); Field f = Schema.FindField(finder, members); if (type != null) { var ib = f as FieldImplementedBy; if (ib == null) throw new InvalidOperationException("Casting only supported for {0}".FormatWith(typeof(FieldImplementedBy).Name)); return (from ic in ib.ImplementationColumns where type.IsAssignableFrom(ic.Key) select (IColumn)ic.Value).ToArray(); } return TableIndex.GetColumnsFromFields(f); } static Type? RemoveCasting(ref Expression body) { if (body.NodeType == ExpressionType.Convert && body.Type == typeof(object)) body = ((UnaryExpression)body).Operand; Type? type = null; if ((body.NodeType == ExpressionType.Convert || body.NodeType == ExpressionType.TypeAs) && body.Type != typeof(object)) { type = body.Type; body = ((UnaryExpression)body).Operand; } return type; } } public class IndexWhereExpressionVisitor : ExpressionVisitor { StringBuilder sb = new StringBuilder(); IFieldFinder RootFinder; bool isPostgres; public IndexWhereExpressionVisitor(IFieldFinder rootFinder) { RootFinder = rootFinder; this.isPostgres = Schema.Current.Settings.IsPostgres; } public static string GetIndexWhere(LambdaExpression lambda, IFieldFinder rootFiender) { IndexWhereExpressionVisitor visitor = new IndexWhereExpressionVisitor(rootFiender); var newLambda = (LambdaExpression)ExpressionEvaluator.PartialEval(lambda); visitor.Visit(newLambda.Body); return visitor.sb.ToString(); } public Field GetField(Expression exp) { if (exp.NodeType == ExpressionType.Convert) exp = ((UnaryExpression)exp).Operand; return Schema.FindField(RootFinder, Reflector.GetMemberListBase(exp)); } public override Expression Visit(Expression exp) { switch (exp.NodeType) { case ExpressionType.Conditional: case ExpressionType.Constant: case ExpressionType.Parameter: case ExpressionType.Call: case ExpressionType.Lambda: case ExpressionType.New: case ExpressionType.NewArrayInit: case ExpressionType.NewArrayBounds: case ExpressionType.Invoke: case ExpressionType.MemberInit: case ExpressionType.ListInit: throw new NotSupportedException("Expression of type {0} not supported: {1}".FormatWith(exp.NodeType, exp.ToString())); default: return base.Visit(exp); } } protected override Expression VisitTypeBinary(TypeBinaryExpression b) { var exp = RemoveLiteEntity(b.Expression); var f = GetField(exp); if (f is FieldReference fr) { if (b.TypeOperand.IsAssignableFrom(fr.FieldType)) sb.Append(fr.Name.SqlEscape(isPostgres) + " IS NOT NULL"); else throw new InvalidOperationException("A {0} will never be {1}".FormatWith(fr.FieldType.TypeName(), b.TypeOperand.TypeName())); return b; } if (f is FieldImplementedBy fib) { var typeOperant = b.TypeOperand.CleanType(); var imp = fib.ImplementationColumns.Where(kvp => typeOperant.IsAssignableFrom(kvp.Key)); if (imp.Any()) sb.Append(imp.ToString(kvp => kvp.Value.Name.SqlEscape(isPostgres) + " IS NOT NULL", " OR ")); else throw new InvalidOperationException("No implementation ({0}) will never be {1}".FormatWith(fib.ImplementationColumns.Keys.ToString(t => t.TypeName(), ", "), b.TypeOperand.TypeName())); return b; } throw new NotSupportedException("'is' only works with ImplementedBy or Reference fields"); } public static Expression RemoveLiteEntity(Expression exp) { if (exp is MemberExpression m && m.Member is PropertyInfo pi && m.Expression.Type.IsInstantiationOf(typeof(Lite<>)) && (pi.Name == nameof(Lite<Entity>.Entity) || pi.Name == nameof(Lite<Entity>.EntityOrNull))) return m.Expression; return exp; } protected override Expression VisitMember(MemberExpression m) { var field = GetField(m); sb.Append(Equals(field, value: true, equals: true, isPostgres)); return m; } protected override Expression VisitUnary(UnaryExpression u) { switch (u.NodeType) { case ExpressionType.Not: sb.Append(" NOT "); this.Visit(u.Operand); break; case ExpressionType.Negate: sb.Append(" - "); this.Visit(u.Operand); break; case ExpressionType.UnaryPlus: sb.Append(" + "); this.Visit(u.Operand); break; case ExpressionType.Convert: //Las unicas conversiones explicitas son a Binary y desde datetime a numeros this.Visit(u.Operand); break; default: throw new NotSupportedException(string.Format("The unary perator {0} is not supported", u.NodeType)); } return u; } public static string IsNull(Field field, bool equals, bool isPostgres) { string isNull = equals ? "{0} IS NULL" : "{0} IS NOT NULL"; if (field is IColumn col) { string result = isNull.FormatWith(col.Name.SqlEscape(isPostgres)); if (!col.DbType.IsString()) return result; return result + (equals ? " OR " : " AND ") + (col.Name.SqlEscape(isPostgres) + (equals ? " = " : " <> ") + "''"); } else if (field is FieldImplementedBy ib) { return ib.ImplementationColumns.Values.Select(ic => isNull.FormatWith(ic.Name.SqlEscape(isPostgres))).ToString(equals ? " AND " : " OR "); } else if (field is FieldImplementedByAll iba) { return isNull.FormatWith(iba.Column.Name.SqlEscape(isPostgres)) + (equals ? " AND " : " OR ") + isNull.FormatWith(iba.ColumnType.Name.SqlEscape(isPostgres)); } else if (field is FieldEmbedded fe) { if (fe.HasValue == null) throw new NotSupportedException("{0} is not nullable".FormatWith(field)); return fe.HasValue.Name.SqlEscape(isPostgres) + " = 1"; } throw new NotSupportedException(isNull.FormatWith(field.GetType())); } static string Equals(Field field, object value, bool equals, bool isPostgres) { if (value == null) { return IsNull(field, equals, isPostgres); } else { if (field is IColumn) { return ((IColumn)field).Name.SqlEscape(isPostgres) + (equals ? " = " : " <> ") + SqlPreCommandSimple.Encode(value); } throw new NotSupportedException("Impossible to compare {0} to {1}".FormatWith(field, value)); } } protected override Expression VisitBinary(BinaryExpression b) { if (b.NodeType == ExpressionType.Coalesce) { sb.Append("IsNull("); Visit(b.Left); sb.Append(","); Visit(b.Right); sb.Append(")"); } else if (b.NodeType == ExpressionType.Equal || b.NodeType == ExpressionType.NotEqual) { if (b.Left is ConstantExpression) { if (b.Right is ConstantExpression) throw new NotSupportedException("NULL == NULL not supported"); Field field = GetField(b.Right); sb.Append(Equals(field, ((ConstantExpression)b.Left).Value, b.NodeType == ExpressionType.Equal, isPostgres)); } else if (b.Right is ConstantExpression) { Field field = GetField(b.Left); sb.Append(Equals(field, ((ConstantExpression)b.Right).Value, b.NodeType == ExpressionType.Equal, isPostgres)); } else throw new NotSupportedException("Impossible to translate {0}".FormatWith(b.ToString())); } else { sb.Append("("); this.Visit(b.Left); switch (b.NodeType) { case ExpressionType.And: case ExpressionType.AndAlso: sb.Append(b.Type.UnNullify() == typeof(bool) ? " AND " : " & "); break; case ExpressionType.Or: case ExpressionType.OrElse: sb.Append(b.Type.UnNullify() == typeof(bool) ? " OR " : " | "); break; case ExpressionType.ExclusiveOr: sb.Append(" ^ "); break; case ExpressionType.LessThan: sb.Append(" < "); break; case ExpressionType.LessThanOrEqual: sb.Append(" <= "); break; case ExpressionType.GreaterThan: sb.Append(" > "); break; case ExpressionType.GreaterThanOrEqual: sb.Append(" >= "); break; case ExpressionType.Add: case ExpressionType.AddChecked: sb.Append(" + "); break; case ExpressionType.Subtract: case ExpressionType.SubtractChecked: sb.Append(" - "); break; case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: sb.Append(" * "); break; case ExpressionType.Divide: sb.Append(" / "); break; case ExpressionType.Modulo: sb.Append(" % "); break; default: throw new NotSupportedException(string.Format("The binary operator {0} is not supported", b.NodeType)); } this.Visit(b.Right); sb.Append(")"); } return b; } } }
// 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.Diagnostics; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Internal.TypeSystem.Ecma; using ILCompiler; namespace Internal.TypeSystem.TypesDebugInfo { public class UserDefinedTypeDescriptor { object _lock = new object(); bool _is64bit; TargetAbi _abi; public UserDefinedTypeDescriptor(ITypesDebugInfoWriter objectWriter, bool is64Bit, TargetAbi abi) { _objectWriter = objectWriter; _is64bit = is64Bit; _abi = abi; } // Get type index for use as a variable/parameter public uint GetVariableTypeIndex(TypeDesc type) { lock (_lock) { return GetVariableTypeIndex(type, true); } } // Get Type index for this pointer of specified type public uint GetThisTypeIndex(TypeDesc type) { lock (_lock) { uint typeIndex; if (_thisTypes.TryGetValue(type, out typeIndex)) return typeIndex; PointerTypeDescriptor descriptor = new PointerTypeDescriptor(); // Note the use of GetTypeIndex here instead of GetVariableTypeIndex (We need the type exactly, not a reference to the type (as would happen for arrays/classes), and not a primitive value (as would happen for primitives)) descriptor.ElementType = GetTypeIndex(type, true); descriptor.Is64Bit = _is64bit ? 1 : 0; descriptor.IsConst = 1; descriptor.IsReference = 0; typeIndex = _objectWriter.GetPointerTypeIndex(descriptor); _thisTypes.Add(type, typeIndex); return typeIndex; } } // Get type index for method public uint GetMethodTypeIndex(MethodDesc method) { lock (_lock) { uint typeIndex; if (_methodIndices.TryGetValue(method, out typeIndex)) return typeIndex; MemberFunctionTypeDescriptor descriptor = new MemberFunctionTypeDescriptor(); MethodSignature signature = method.Signature; descriptor.ReturnType = GetVariableTypeIndex(DebuggerCanonicalize(signature.ReturnType)); descriptor.ThisAdjust = 0; descriptor.CallingConvention = 0x4; // Near fastcall descriptor.TypeIndexOfThisPointer = signature.IsStatic ? (uint)PrimitiveTypeDescriptor.TYPE_ENUM.T_VOID : GetThisTypeIndex(method.OwningType); descriptor.ContainingClass = GetTypeIndex(method.OwningType, true); try { descriptor.NumberOfArguments = checked((ushort)signature.Length); } catch (OverflowException) { return 0; } uint[] args = new uint[signature.Length]; for (int i = 0; i < args.Length; i++) args[i] = GetVariableTypeIndex(DebuggerCanonicalize(signature[i])); typeIndex = _objectWriter.GetMemberFunctionTypeIndex(descriptor, args); _methodIndices.Add(method, typeIndex); return typeIndex; } } // Get type index for specific method by name public uint GetMethodFunctionIdTypeIndex(MethodDesc method) { lock (_lock) { uint typeIndex; if (_methodIdIndices.TryGetValue(method, out typeIndex)) return typeIndex; MemberFunctionIdTypeDescriptor descriptor = new MemberFunctionIdTypeDescriptor(); descriptor.MemberFunction = GetMethodTypeIndex(method); descriptor.ParentClass = GetTypeIndex(method.OwningType, true); descriptor.Name = method.Name; typeIndex = _objectWriter.GetMemberFunctionId(descriptor); _methodIdIndices.Add(method, typeIndex); return typeIndex; } } private TypeDesc DebuggerCanonicalize(TypeDesc type) { if (type.IsCanonicalSubtype(CanonicalFormKind.Any)) return type.ConvertToCanonForm(CanonicalFormKind.Specific); return type; } private uint GetVariableTypeIndex(TypeDesc type, bool needsCompleteIndex) { uint variableTypeIndex = 0; if (type.IsPrimitive) { variableTypeIndex = PrimitiveTypeDescriptor.GetPrimitiveTypeIndex(type); } else { type = DebuggerCanonicalize(type); if ((type.IsDefType && !type.IsValueType) || type.IsArray) { // The type index of a variable/field of a reference type is wrapped // in a pointer, as these fields are really pointer fields, and the data is on the heap variableTypeIndex = 0; if (_knownReferenceWrappedTypes.TryGetValue(type, out variableTypeIndex)) { return variableTypeIndex; } else { uint typeindex = GetTypeIndex(type, false); PointerTypeDescriptor descriptor = new PointerTypeDescriptor(); descriptor.ElementType = typeindex; descriptor.Is64Bit = _is64bit ? 1 : 0; descriptor.IsConst = 0; descriptor.IsReference = 1; variableTypeIndex = _objectWriter.GetPointerTypeIndex(descriptor); _knownReferenceWrappedTypes[type] = variableTypeIndex; return variableTypeIndex; } } else if (type.IsEnum) { // Enum's use the LF_ENUM record as the variable type index, but it is required to also emit a regular structure record for them. if (_enumTypes.TryGetValue(type, out variableTypeIndex)) return variableTypeIndex; variableTypeIndex = GetEnumTypeIndex(type); GetTypeIndex(type, false); // Ensure regular structure record created } variableTypeIndex = GetTypeIndex(type, needsCompleteIndex); } return variableTypeIndex; } /// <summary> /// Get type index for type without the type being wrapped as a reference (as a variable or field must be) /// </summary> /// <param name="type"></param> /// <param name="needsCompleteType"></param> /// <returns></returns> private uint GetTypeIndex(TypeDesc type, bool needsCompleteType) { uint typeIndex = 0; if (needsCompleteType ? _completeKnownTypes.TryGetValue(type, out typeIndex) : _knownTypes.TryGetValue(type, out typeIndex)) { return typeIndex; } else { return GetNewTypeIndex(type, needsCompleteType); } } private uint GetNewTypeIndex(TypeDesc type, bool needsCompleteType) { if (type.IsArray) { return GetArrayTypeIndex(type); } else if (type.IsDefType) { return GetClassTypeIndex(type, needsCompleteType); } else if (type.IsPointer) { return GetPointerTypeIndex(((ParameterizedType)type).ParameterType); } else if (type.IsByRef) { return GetByRefTypeIndex(((ParameterizedType)type).ParameterType); } return 0; } private uint GetPointerTypeIndex(TypeDesc pointeeType) { uint typeIndex; if (_pointerTypes.TryGetValue(pointeeType, out typeIndex)) return typeIndex; PointerTypeDescriptor descriptor = new PointerTypeDescriptor(); descriptor.ElementType = GetVariableTypeIndex(pointeeType, false); descriptor.Is64Bit = _is64bit ? 1 : 0; descriptor.IsConst = 0; descriptor.IsReference = 0; // Calling GetVariableTypeIndex may have filled in _pointerTypes if (_pointerTypes.TryGetValue(pointeeType, out typeIndex)) return typeIndex; typeIndex = _objectWriter.GetPointerTypeIndex(descriptor); _pointerTypes.Add(pointeeType, typeIndex); return typeIndex; } private uint GetByRefTypeIndex(TypeDesc pointeeType) { uint typeIndex; if (_byRefTypes.TryGetValue(pointeeType, out typeIndex)) return typeIndex; PointerTypeDescriptor descriptor = new PointerTypeDescriptor(); descriptor.ElementType = GetVariableTypeIndex(pointeeType, false); descriptor.Is64Bit = _is64bit ? 1 : 0; descriptor.IsConst = 0; descriptor.IsReference = 1; // Calling GetVariableTypeIndex may have filled in _byRefTypes if (_byRefTypes.TryGetValue(pointeeType, out typeIndex)) return typeIndex; typeIndex = _objectWriter.GetPointerTypeIndex(descriptor); _byRefTypes.Add(pointeeType, typeIndex); return typeIndex; } private uint GetEnumTypeIndex(TypeDesc type) { System.Diagnostics.Debug.Assert(type.IsEnum, "GetEnumTypeIndex was called with wrong type"); DefType defType = type as DefType; System.Diagnostics.Debug.Assert(defType != null, "GetEnumTypeIndex was called with non def type"); List<FieldDesc> fieldsDescriptors = new List<FieldDesc>(); foreach (var field in defType.GetFields()) { if (field.IsLiteral) { fieldsDescriptors.Add(field); } } EnumTypeDescriptor enumTypeDescriptor = new EnumTypeDescriptor { ElementCount = (ulong)fieldsDescriptors.Count, ElementType = PrimitiveTypeDescriptor.GetPrimitiveTypeIndex(defType.UnderlyingType), Name = _objectWriter.GetMangledName(type), }; EnumRecordTypeDescriptor[] typeRecords = new EnumRecordTypeDescriptor[enumTypeDescriptor.ElementCount]; for (int i = 0; i < fieldsDescriptors.Count; ++i) { FieldDesc field = fieldsDescriptors[i]; EnumRecordTypeDescriptor recordTypeDescriptor; recordTypeDescriptor.Value = GetEnumRecordValue(field); recordTypeDescriptor.Name = field.Name; typeRecords[i] = recordTypeDescriptor; } uint typeIndex = _objectWriter.GetEnumTypeIndex(enumTypeDescriptor, typeRecords); return typeIndex; } private uint GetArrayTypeIndex(TypeDesc type) { System.Diagnostics.Debug.Assert(type.IsArray, "GetArrayTypeIndex was called with wrong type"); ArrayType arrayType = (ArrayType)type; uint elementSize = (uint)type.Context.Target.PointerSize; LayoutInt layoutElementSize = arrayType.GetElementSize(); if (!layoutElementSize.IsIndeterminate) elementSize = (uint)layoutElementSize.AsInt; ArrayTypeDescriptor arrayTypeDescriptor = new ArrayTypeDescriptor { Rank = (uint)arrayType.Rank, ElementType = GetVariableTypeIndex(arrayType.ElementType, false), Size = elementSize, IsMultiDimensional = arrayType.IsMdArray ? 1 : 0 }; ClassTypeDescriptor classDescriptor = new ClassTypeDescriptor { IsStruct = 0, Name = _objectWriter.GetMangledName(type), BaseClassId = GetTypeIndex(arrayType.BaseType, false) }; uint typeIndex = _objectWriter.GetArrayTypeIndex(classDescriptor, arrayTypeDescriptor); _knownTypes[type] = typeIndex; _completeKnownTypes[type] = typeIndex; return typeIndex; } private ulong GetEnumRecordValue(FieldDesc field) { var ecmaField = field as EcmaField; if (ecmaField != null) { MetadataReader reader = ecmaField.MetadataReader; FieldDefinition fieldDef = reader.GetFieldDefinition(ecmaField.Handle); ConstantHandle defaultValueHandle = fieldDef.GetDefaultValue(); if (!defaultValueHandle.IsNil) { return HandleConstant(ecmaField.Module, defaultValueHandle); } } return 0; } private ulong HandleConstant(EcmaModule module, ConstantHandle constantHandle) { MetadataReader reader = module.MetadataReader; Constant constant = reader.GetConstant(constantHandle); BlobReader blob = reader.GetBlobReader(constant.Value); switch (constant.TypeCode) { case ConstantTypeCode.Byte: return (ulong)blob.ReadByte(); case ConstantTypeCode.Int16: return (ulong)blob.ReadInt16(); case ConstantTypeCode.Int32: return (ulong)blob.ReadInt32(); case ConstantTypeCode.Int64: return (ulong)blob.ReadInt64(); case ConstantTypeCode.SByte: return (ulong)blob.ReadSByte(); case ConstantTypeCode.UInt16: return (ulong)blob.ReadUInt16(); case ConstantTypeCode.UInt32: return (ulong)blob.ReadUInt32(); case ConstantTypeCode.UInt64: return (ulong)blob.ReadUInt64(); } System.Diagnostics.Debug.Assert(false); return 0; } private uint GetClassTypeIndex(TypeDesc type, bool needsCompleteType) { DefType defType = type as DefType; System.Diagnostics.Debug.Assert(defType != null, "GetClassTypeIndex was called with non def type"); ClassTypeDescriptor classTypeDescriptor = new ClassTypeDescriptor { IsStruct = type.IsValueType ? 1 : 0, Name = _objectWriter.GetMangledName(type), BaseClassId = 0 }; uint typeIndex = _objectWriter.GetClassTypeIndex(classTypeDescriptor); _knownTypes[type] = typeIndex; if (type.HasBaseType && !type.IsValueType) { classTypeDescriptor.BaseClassId = GetTypeIndex(defType.BaseType, true); } List<DataFieldDescriptor> fieldsDescs = new List<DataFieldDescriptor>(); List<DataFieldDescriptor> nonGcStaticFields = new List<DataFieldDescriptor>(); List<DataFieldDescriptor> gcStaticFields = new List<DataFieldDescriptor>(); List<DataFieldDescriptor> threadStaticFields = new List<DataFieldDescriptor>(); bool isCanonical = defType.IsCanonicalSubtype(CanonicalFormKind.Any); foreach (var fieldDesc in defType.GetFields()) { if (fieldDesc.HasRva || fieldDesc.IsLiteral) continue; if (isCanonical && fieldDesc.IsStatic) continue; LayoutInt fieldOffset = fieldDesc.Offset; int fieldOffsetEmit = fieldOffset.IsIndeterminate ? 0xBAAD : fieldOffset.AsInt; DataFieldDescriptor field = new DataFieldDescriptor { FieldTypeIndex = GetVariableTypeIndex(fieldDesc.FieldType, false), Offset = (ulong)fieldOffsetEmit, Name = fieldDesc.Name }; if (fieldDesc.IsStatic) { if (fieldDesc.IsThreadStatic) threadStaticFields.Add(field); else if (fieldDesc.HasGCStaticBase) gcStaticFields.Add(field); else nonGcStaticFields.Add(field); } else { fieldsDescs.Add(field); } } InsertStaticFieldRegionMember(fieldsDescs, defType, nonGcStaticFields, WindowsNodeMangler.NonGCStaticMemberName, "__type_" + WindowsNodeMangler.NonGCStaticMemberName, false); InsertStaticFieldRegionMember(fieldsDescs, defType, gcStaticFields, WindowsNodeMangler.GCStaticMemberName, "__type_" + WindowsNodeMangler.GCStaticMemberName, _abi == TargetAbi.CoreRT); InsertStaticFieldRegionMember(fieldsDescs, defType, threadStaticFields, WindowsNodeMangler.ThreadStaticMemberName, "__type_" + WindowsNodeMangler.ThreadStaticMemberName, _abi == TargetAbi.CoreRT); DataFieldDescriptor[] fields = new DataFieldDescriptor[fieldsDescs.Count]; for (int i = 0; i < fieldsDescs.Count; ++i) { fields[i] = fieldsDescs[i]; } LayoutInt elementSize = defType.GetElementSize(); int elementSizeEmit = elementSize.IsIndeterminate ? 0xBAAD : elementSize.AsInt; ClassFieldsTypeDescriptor fieldsDescriptor = new ClassFieldsTypeDescriptor { Size = (ulong)elementSizeEmit, FieldsCount = fieldsDescs.Count }; uint completeTypeIndex = _objectWriter.GetCompleteClassTypeIndex(classTypeDescriptor, fieldsDescriptor, fields); _completeKnownTypes[type] = completeTypeIndex; if (needsCompleteType) return completeTypeIndex; else return typeIndex; } private void InsertStaticFieldRegionMember(List<DataFieldDescriptor> fieldDescs, DefType defType, List<DataFieldDescriptor> staticFields, string staticFieldForm, string staticFieldFormTypePrefix, bool staticDataInObject) { if (staticFields != null && (staticFields.Count > 0)) { // Generate struct symbol for type describing individual fields of the statics region ClassFieldsTypeDescriptor fieldsDescriptor = new ClassFieldsTypeDescriptor { Size = (ulong)0, FieldsCount = staticFields.Count }; ClassTypeDescriptor classTypeDescriptor = new ClassTypeDescriptor { IsStruct = !staticDataInObject ? 1 : 0, Name = staticFieldFormTypePrefix + _objectWriter.GetMangledName(defType), BaseClassId = 0 }; if (staticDataInObject) { classTypeDescriptor.BaseClassId = GetTypeIndex(defType.Context.GetWellKnownType(WellKnownType.Object), true); } uint staticFieldRegionTypeIndex = _objectWriter.GetCompleteClassTypeIndex(classTypeDescriptor, fieldsDescriptor, staticFields.ToArray()); uint staticFieldRegionSymbolTypeIndex = staticFieldRegionTypeIndex; // This means that access to this static region is done via a double indirection if (staticDataInObject) { PointerTypeDescriptor pointerTypeDescriptor = new PointerTypeDescriptor(); pointerTypeDescriptor.Is64Bit = _is64bit ? 1 : 0; pointerTypeDescriptor.IsConst = 0; pointerTypeDescriptor.IsReference = 0; pointerTypeDescriptor.ElementType = staticFieldRegionTypeIndex; uint intermediatePointerDescriptor = _objectWriter.GetPointerTypeIndex(pointerTypeDescriptor); pointerTypeDescriptor.ElementType = intermediatePointerDescriptor; staticFieldRegionSymbolTypeIndex = _objectWriter.GetPointerTypeIndex(pointerTypeDescriptor); } DataFieldDescriptor staticRegionField = new DataFieldDescriptor { FieldTypeIndex = staticFieldRegionSymbolTypeIndex, Offset = 0xFFFFFFFF, Name = staticFieldForm }; fieldDescs.Add(staticRegionField); } } private ITypesDebugInfoWriter _objectWriter; private Dictionary<TypeDesc, uint> _knownTypes = new Dictionary<TypeDesc, uint>(); private Dictionary<TypeDesc, uint> _completeKnownTypes = new Dictionary<TypeDesc, uint>(); private Dictionary<TypeDesc, uint> _knownReferenceWrappedTypes = new Dictionary<TypeDesc, uint>(); private Dictionary<TypeDesc, uint> _pointerTypes = new Dictionary<TypeDesc, uint>(); private Dictionary<TypeDesc, uint> _enumTypes = new Dictionary<TypeDesc, uint>(); private Dictionary<TypeDesc, uint> _byRefTypes = new Dictionary<TypeDesc, uint>(); private Dictionary<TypeDesc, uint> _thisTypes = new Dictionary<TypeDesc, uint>(); private Dictionary<MethodDesc, uint> _methodIndices = new Dictionary<MethodDesc, uint>(); private Dictionary<MethodDesc, uint> _methodIdIndices = new Dictionary<MethodDesc, uint>(); public ICollection<KeyValuePair<TypeDesc, uint>> CompleteKnownTypes => _completeKnownTypes; } }
//Uncomment this compiler directive to easily remove GEAREST for testing purposes //#undef USE_GEARSET using System; using System.Collections.Generic; using System.Threading; using Gearset; using Gearset.Components.Profiler; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using SampleGame.Gearset; namespace SampleGame { /// <summary> /// This is the main type for your game /// </summary> public class MySampleGame : Game { public GraphicsDeviceManager Graphics { get; private set; } //Game Components FpsCounter _fpsCounter; KeyboardState _keyboardState; KeyboardState _previousKeyboardState; Matrix _worldMatrix; Matrix _viewMatrix; Matrix _projectionMatrix; //Finder test! A custom 'scene graph' used by finder readonly List<GameObject> _gameObjects = new List<GameObject>(); public MySampleGame() { Graphics = new GraphicsDeviceManager(this); Graphics.PreferredBackBufferWidth = 1280; Graphics.PreferredBackBufferHeight = 720; Graphics.IsFullScreen = false; Graphics.ApplyChanges (); Content.RootDirectory = "Content"; } protected override void Initialize() { //Initialise Gearset with the full UI experience. //GS.Initialize(this); //GS.Initialize(this, createUI: true); //Initialise Gearset in 'headless' mode with no 'external' UI - (overlays are still available). //We want to monitor managed memory allocations from our app and the UIs generate a fair amount of garbage which would distort the profiling. GS.Initialize(this, createUI: true); _fpsCounter = new FpsCounter(this); Components.Add(_fpsCounter); IsMouseVisible = true; base.Initialize(); #if USE_GEARSET GearsetSettings.Instance.MemoryMonitorConfig.Visible = true; GearsetSettings.Instance.MemoryMonitorConfig.MemoryGraphConfig.Visible = true; GearsetSettings.Instance.MemoryMonitorConfig.MemoryGraphConfig.Position = new Vector2(100, 50); GearsetSettings.Instance.MemoryMonitorConfig.MemoryGraphConfig.Size = new Vector2(400, 75); #endif GS.Action(()=>GS.GearsetComponent.Console.Inspect("Profiler", new ProfilerInpectorSettings(GS.GearsetComponent.Console.Profiler))); GS.Log("I am a log message - tra la la"); //Finder! //You can double click finder result items to add them to the Inspector window! //Comment this to use the default search query for finder (by default it's GameComponent based). GS.Action(ConfigureFinder); //Quick Actions GS.AddQuickAction("QuickAction1", () => { /* Pass in a delegate here to do something */ }); GS.AddQuickAction("QuickAction2", () => { /* Pass in a delegate here to do something */ }); //Command Console //Comes with 3 built in commands (help, cls, echo). //Some examples of things you can do... GS.RegisterCommand("helloworld", "runs a test command", (host, command, args) => { host.EchoWarning("Hello World"); }); GS.RegisterCommand("echotest", "echotest message [warning|error]", (host, command, args) => { if (args.Count < 1) host.EchoError("You must specify a message"); else if (args.Count == 1) host.Echo(args[0]); else if (args.Count == 2) { if (args[1] == "warning") host.EchoWarning(args[0]); else if (args[1] == "error") host.EchoError(args[0]); else host.Echo(args[0]); } else if (args.Count > 2) { host.Echo("Too many arguments specified"); } }); GS.RegisterCommand("fixedstep", "toggles Game.IsFixedStep", (host, command, args) => { IsFixedTimeStep = !IsFixedTimeStep; host.Echo($"IsFixedStep: {IsFixedTimeStep}"); }); //Let's list all those registered commands now... GS.ExecuteCommand("help"); //Call one of our custom commands... GS.ExecuteCommand("helloworld"); //Set Gerset Matrices if you want to show ovelaid geometry (boxes, spheres, etc). var prj = Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, 1); var halfPixelOffset = Matrix.CreateTranslation(-0.5f, -0.5f, 0); _worldMatrix = Matrix.Identity; _viewMatrix = Matrix.Identity; _projectionMatrix = halfPixelOffset * prj; } void ConfigureFinder() { //This is an example of a 'scene graph' query you can use in finder //Add some objects to the scene graph... _gameObjects.Add(new PlayerGameObject { Name = "Player 1", Health = 100 }); for (var i = 1; i <= 5; i++) _gameObjects.Add(new EnemyGameObject { Name = "Enemy " + i, Damage = i * 10}); //Set the Finder function to query the _gameObjects collection GS.GearsetComponent.Console.SetFinderSearchFunction(queryString => { var result = new FinderResult(); var searchParams = queryString.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // Split the query if (searchParams.Length == 0) { searchParams = new[] { String.Empty }; } else { // Ignore case. for (var i = 0; i < searchParams.Length; i++) searchParams[i] = searchParams[i].ToUpper(); } foreach (var component in _gameObjects) { var matches = true; var type = component.GetType().ToString(); // Check if it matches all search params. foreach (var t in searchParams) { if (component.ToString().ToUpper().Contains(t) || type.ToUpper().Contains(t)) continue; matches = false; break; } if (matches) result.Add(new ObjectDescription(component, type)); } return result; }); } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { const string mark = "Update"; try { base.Update(gameTime); //We must call StartFrame at the top of Update to indicate to the Profiler that a new frame has started. GS.StartFrame(); GS.BeginMark(mark, FlatTheme.PeterRiver); _previousKeyboardState = _keyboardState; _keyboardState = Keyboard.GetState(); // Allows the game to exit #if WINDOWS if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { Exit(); return; } #endif if (_keyboardState.IsKeyUp(Keys.Escape) && _previousKeyboardState.IsKeyDown(Keys.Escape)) { Exit(); return; } #if USE_GEARSET //Test for CPU / GPU bound if (GS.GearsetComponent.Console.Profiler.DoUpdate() == false) { return; } #endif //PLOT test GS.Plot("FPS", _fpsCounter.Fps); // GS.Plot("Tick Memory K", _memoryMonitor.TickMemoryK); var mouseState = Mouse.GetState(); var mousePos2 = new Vector2(mouseState.X, mouseState.Y); var mousePos3 = new Vector3(mousePos2, 0); //Label test GS.ShowLabel("I follow the mouse pointer!", mousePos2); //Line Test //Draw a line but then use the same key to reference it a second time and alter the postion / color // GS.ShowLine("TestLine", new Vector2(mouseState.X, mouseState.Y + 20), new Vector2(mouseState.X + 200, mouseState.Y + 20), Color.Green); // GS.ShowLine("TestLine", new Vector2(mouseState.X, mouseState.Y - 20), new Vector2(mouseState.X + 200, mouseState.Y - 20), Color.Violet); //Other lines... GS.ShowLineOnce(new Vector2(mouseState.X, mouseState.Y + 25), new Vector2(mouseState.X + 200, mouseState.Y + 25), Color.Pink); GS.ShowLineOnce(new Vector2(mouseState.X, mouseState.Y + 35), new Vector2(mouseState.X + 200, mouseState.Y + 35), Color.Red); //ALERT test - press SPACE for an alert message! if (_keyboardState.IsKeyUp(Keys.Space) && _previousKeyboardState.IsKeyDown(Keys.Space)) GS.Alert("I am an alert message"); Thread.Sleep(1);//Let's trick the update into taking some time so that we can see some profile info //Update Gearset matrixes for 3d geometry GS.SetMatrices(ref _worldMatrix, ref _viewMatrix, ref _projectionMatrix); //Geometry tests... // GS.ShowSphere("TestSphere", mousePos3, 50, Color.Azure); GS.ShowSphereOnce(mousePos3, 50, Color.Azure); // GS.ShowBox("TestBox", new Vector3(mouseState.X + 50, mouseState.Y + 50, 0), new Vector3(mouseState.X + 100, mouseState.Y + 100, 0), Color.Blue); GS.ShowBoxOnce(new Vector3(mouseState.X + 100, mouseState.Y + 100, 0), new Vector3(mouseState.X + 150, mouseState.Y + 150, 0), Color.Red); } finally { //Must call EndMark GS.EndMark(mark); } } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(new Color(48,48,48,255)); GS.BeginMark("Draw", FlatTheme.Pomegrantate); GS.BeginMark("Draw Background", FlatTheme.Pumpkin); Thread.Sleep(2); //Let's trick the update into taking some time so that we can see some profile info GS.EndMark("Draw Background"); //Test nesting GS.BeginMark("Draw Sprites", FlatTheme.Sunflower); Thread.Sleep(1); //Let's trick the update into taking some time so that we can see some profile info GS.BeginMark("Draw Sprites", FlatTheme.Sunflower); Thread.Sleep(1); //Let's trick the update into taking some time so that we can see some profile info GS.EndMark("Draw Sprites"); GS.EndMark("Draw Sprites"); GS.BeginMark("Draw Particles", FlatTheme.Amethyst); Thread.Sleep(2); //Let's trick the update into taking some time so that we can see some profile info GS.EndMark("Draw Particles"); GS.BeginMark("base.Draw", FlatTheme.Nephritis); base.Draw(gameTime); GS.EndMark("base.Draw"); GS.EndMark("Draw"); } protected override void OnExiting(object sender, EventArgs args) { base.OnExiting(sender, args); GS.Shutdown(this); } } }
//--------------------------------------------------------------------------- // // <copyright file="RayHitTestParameters.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // History: // 03/16/2004 : [....] - Created // //--------------------------------------------------------------------------- using System; using System.IO; using System.Diagnostics; using System.Collections.Generic; using MS.Internal.Media3D; using CultureInfo = System.Globalization.CultureInfo; namespace System.Windows.Media.Media3D { /// <summary> /// Encapsulates a set parameters for performing a 3D hit test agaist /// a ray. /// </summary> public sealed class RayHitTestParameters : HitTestParameters3D { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors /// <summary> /// Creates a RayHitTestParameters where the ray is described /// by an origin and a direction. /// </summary> public RayHitTestParameters(Point3D origin, Vector3D direction) { _origin = origin; _direction = direction; _isRay = true; } #endregion Constructors //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties /// <summary> /// The origin of the ray to be used for hit testing. /// </summary> public Point3D Origin { get { return _origin; } } /// <summary> /// The direction of the ray to be used for hit testing. /// </summary> public Vector3D Direction { get { return _direction; } } #endregion Public Properties //------------------------------------------------------ // // Public Events // //------------------------------------------------------ //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods internal void ReportResult( MeshGeometry3D meshHit, Point3D pointHit, double distanceToRayOrigin, int vertexIndex1, int vertexIndex2, int vertexIndex3, Point barycentric) { results.Add(new RayMeshGeometry3DHitTestResult( CurrentVisual, CurrentModel, meshHit, pointHit, distanceToRayOrigin, vertexIndex1, vertexIndex2, vertexIndex3, barycentric)); } internal HitTestResultBehavior RaiseCallback(HitTestResultCallback resultCallback, HitTestFilterCallback filterCallback, HitTestResultBehavior lastResult) { return RaiseCallback(resultCallback, filterCallback, lastResult, 0.0 /* distance adjustment */); } internal HitTestResultBehavior RaiseCallback(HitTestResultCallback resultCallback, HitTestFilterCallback filterCallback, HitTestResultBehavior lastResult, double distanceAdjustment) { results.Sort(RayHitTestResult.CompareByDistanceToRayOrigin); for(int i = 0, count = results.Count; i < count; i++) { RayHitTestResult result = results[i]; result.SetDistanceToRayOrigin(result.DistanceToRayOrigin + distanceAdjustment); Viewport2DVisual3D viewport2DVisual3D = result.VisualHit as Viewport2DVisual3D; if (viewport2DVisual3D != null) { Point intersectionPoint; Visual viewport2DVisual3DChild = viewport2DVisual3D.Visual; if (viewport2DVisual3DChild != null) { if (Viewport2DVisual3D.GetIntersectionInfo(result, out intersectionPoint)) { // convert the resulting point to visual coordinates Point visualPoint = Viewport2DVisual3D.TextureCoordsToVisualCoords(intersectionPoint, viewport2DVisual3DChild); GeneralTransform gt = viewport2DVisual3DChild.TransformToOuterSpace().Inverse; Point pointOnChild; if (gt != null && gt.TryTransform(visualPoint, out pointOnChild)) { HitTestResultBehavior behavior2D = viewport2DVisual3DChild.HitTestPoint(filterCallback, resultCallback, new PointHitTestParameters(pointOnChild)); if (behavior2D == HitTestResultBehavior.Stop) { return HitTestResultBehavior.Stop; } } } } } HitTestResultBehavior behavior = resultCallback(results[i]); if (behavior == HitTestResultBehavior.Stop) { return HitTestResultBehavior.Stop; } } return lastResult; } // Gets the hit testing line/ray specified as an origin and direction in // the current local space. internal void GetLocalLine(out Point3D origin, out Vector3D direction) { origin = _origin; direction = _direction; bool isRay = true; if (HasWorldTransformMatrix) { LineUtil.Transform(WorldTransformMatrix, ref origin, ref direction, out isRay); } // At any point along the tree walk we may encounter a transform that turns the ray into // a line and if so we must stay a line _isRay &= isRay; } internal void ClearResults() { if (results != null) { results.Clear(); } } #endregion Internal Methods internal bool IsRay { get { return _isRay; } } //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields private readonly Point3D _origin; private readonly Vector3D _direction; private readonly List<RayHitTestResult> results = new List<RayHitTestResult>(); // 'true' if this is a ray hit test, 'false' if the ray has become a line private bool _isRay; #endregion Private Fields } }
using UnityEngine; using System.IO; #if UNITY_EDITOR using UnityEditor; [InitializeOnLoad] #endif public class FBSettings : ScriptableObject { const string facebookSettingsAssetName = "FacebookSettings"; const string facebookSettingsPath = "3rd-tools/Facebook/Resources"; const string facebookSettingsAssetExtension = ".asset"; private static FBSettings instance; static FBSettings Instance { get { if (instance == null) { instance = Resources.Load(facebookSettingsAssetName) as FBSettings; if (instance == null) { // If not found, autocreate the asset object. instance = CreateInstance<FBSettings>(); #if UNITY_EDITOR string properPath = Path.Combine(Application.dataPath, facebookSettingsPath); if (!Directory.Exists(properPath)) { AssetDatabase.CreateFolder("Assets/3rd-tools/Facebook", "Resources"); } string fullPath = Path.Combine(Path.Combine("Assets", facebookSettingsPath), facebookSettingsAssetName + facebookSettingsAssetExtension ); AssetDatabase.CreateAsset(instance, fullPath); #endif } } return instance; } } #if UNITY_EDITOR [MenuItem("Facebook/Edit Settings")] public static void Edit() { Selection.activeObject = Instance; } [MenuItem("Facebook/Developers Page")] public static void OpenAppPage() { string url = "https://developers.facebook.com/apps/"; if (Instance.AppIds[Instance.SelectedAppIndex] != "0") url += Instance.AppIds[Instance.SelectedAppIndex]; Application.OpenURL(url); } [MenuItem("Facebook/SDK Documentation")] public static void OpenDocumentation() { string url = "https://developers.facebook.com/games/unity/"; Application.OpenURL(url); } [MenuItem("Facebook/SDK Facebook Group")] public static void OpenFacebookGroup() { string url = "https://www.facebook.com/groups/491736600899443/"; Application.OpenURL(url); } [MenuItem("Facebook/Report a SDK Bug")] public static void ReportABug() { string url = "https://developers.facebook.com/bugs/create"; Application.OpenURL(url); } #endif #region App Settings [SerializeField] private int selectedAppIndex = 0; [SerializeField] private string[] appIds = new[] { "0" }; [SerializeField] private string[] appLabels = new[] { "App Name" }; [SerializeField] private bool cookie = true; [SerializeField] private bool logging = true; [SerializeField] private bool status = true; [SerializeField] private bool xfbml = false; [SerializeField] private bool frictionlessRequests = true; [SerializeField] private string iosURLSuffix = ""; public void SetAppIndex(int index) { if (selectedAppIndex != index) { selectedAppIndex = index; DirtyEditor(); } } public int SelectedAppIndex { get { return selectedAppIndex; } } public void SetAppId(int index, string value) { if (appIds[index] != value) { appIds[index] = value; DirtyEditor(); } } public string[] AppIds { get { return appIds; } set { if (appIds != value) { appIds = value; DirtyEditor(); } } } public void SetAppLabel(int index, string value) { if (appLabels[index] != value) { AppLabels[index] = value; DirtyEditor(); } } public string[] AppLabels { get { return appLabels; } set { if (appLabels != value) { appLabels = value; DirtyEditor(); } } } public static string[] AllAppIds { get { return Instance.AppIds; } } public static string AppId { get { return Instance.AppIds[Instance.SelectedAppIndex]; } } public static bool IsValidAppId { get { return FBSettings.AppId != null && FBSettings.AppId.Length > 0 && !FBSettings.AppId.Equals("0"); } } public static bool Cookie { get { return Instance.cookie; } set { if (Instance.cookie != value) { Instance.cookie = value; DirtyEditor(); } } } public static bool Logging { get { return Instance.logging; } set { if (Instance.logging != value) { Instance.logging = value; DirtyEditor(); } } } public static bool Status { get { return Instance.status; } set { if (Instance.status != value) { Instance.status = value; DirtyEditor(); } } } public static bool Xfbml { get { return Instance.xfbml; } set { if (Instance.xfbml != value) { Instance.xfbml = value; DirtyEditor(); } } } public static string IosURLSuffix { get { return Instance.iosURLSuffix; } set { if (Instance.iosURLSuffix != value) { Instance.iosURLSuffix = value; DirtyEditor (); } } } public static string ChannelUrl { get { return "/channel.html"; } } public static bool FrictionlessRequests { get { return Instance.frictionlessRequests; } set { if (Instance.frictionlessRequests != value) { Instance.frictionlessRequests = value; DirtyEditor(); } } } #if UNITY_EDITOR private string testFacebookId = ""; private string testAccessToken = ""; public static string TestFacebookId { get { return Instance.testFacebookId; } set { if (Instance.testFacebookId != value) { Instance.testFacebookId = value; DirtyEditor(); } } } public static string TestAccessToken { get { return Instance.testAccessToken; } set { if (Instance.testAccessToken != value) { Instance.testAccessToken = value; DirtyEditor(); } } } #endif private static void DirtyEditor() { #if UNITY_EDITOR EditorUtility.SetDirty(Instance); #endif } #endregion }
using UnityEngine; using UnityEngine.Serialization; using UnityWeld.Binding.Internal; namespace UnityWeld.Binding { /// <summary> /// Bind a property in the view model to one the UI, subscribing to OnPropertyChanged /// and updating the UI accordingly. Also bind to a UnityEvent in the UI and update the /// view model when the event is triggered. /// </summary> [HelpURL("https://github.com/Real-Serious-Games/Unity-Weld")] public class TwoWayPropertyBinding : AbstractMemberBinding { /// <summary> /// Name of the property in the view model to bind. /// </summary> public string ViewModelPropertyName { get { return viewModelPropertyName; } set { viewModelPropertyName = value; } } [SerializeField] private string viewModelPropertyName; /// <summary> /// Event in the view to bind to. /// </summary> public string ViewEventName { get { return viewEventName; } set { viewEventName = value; } } [SerializeField, FormerlySerializedAs("uiEventName")] private string viewEventName; /// <summary> /// Property on the view to update when value changes. /// </summary> public string ViewPropertName { get { return viewPropertyName; } set { viewPropertyName = value; } } [SerializeField, FormerlySerializedAs("uiPropertyName")] private string viewPropertyName; /// <summary> /// Name of the type of the adapter we're using to convert values from the /// view model to the view. Can be empty for no adapter. /// </summary> public string ViewAdapterTypeName { get { return viewAdapterTypeName; } set { viewAdapterTypeName = value; } } [SerializeField] private string viewAdapterTypeName; /// <summary> /// Options for the adapter from the view model to the view. /// </summary> public AdapterOptions ViewAdapterOptions { get { return viewAdapterOptions; } set { viewAdapterOptions = value; } } [SerializeField] private AdapterOptions viewAdapterOptions; /// <summary> /// Name of the type of the adapter we're using to conver values from the /// view back to the view model. Can be empty for no adapter. /// </summary> public string ViewModelAdapterTypeName { get { return viewModelAdapterTypeName; } set { viewModelAdapterTypeName = value; } } [SerializeField] private string viewModelAdapterTypeName; /// <summary> /// Options for the adapter from the view to the view model. /// </summary> public AdapterOptions ViewModelAdapterOptions { get { return viewModelAdapterOptions; } set { viewModelAdapterOptions = value; } } [SerializeField] private AdapterOptions viewModelAdapterOptions; /// <summary> /// The name of the property to assign an exception to when adapter/validation fails. /// </summary> public string ExceptionPropertyName { get { return exceptionPropertyName; } set { exceptionPropertyName = value; } } [SerializeField] private string exceptionPropertyName; /// <summary> /// Adapter to apply to any adapter/validation exception that is assigned to the view model. /// </summary> public string ExceptionAdapterTypeName { get { return exceptionAdapterTypeName; } set { exceptionAdapterTypeName = value; } } [SerializeField] private string exceptionAdapterTypeName; /// <summary> /// Adapter options for an exception. /// </summary> public AdapterOptions ExceptionAdapterOptions { get { return exceptionAdapterOptions; } set { exceptionAdapterOptions = value; } } [SerializeField] private AdapterOptions exceptionAdapterOptions; /// <summary> /// Watches the view-model for changes that must be propagated to the view. /// </summary> private PropertyWatcher viewModelWatcher; /// <summary> /// Watches the view for changes that must be propagated to the view-model. /// </summary> private UnityEventWatcher unityEventWatcher; public override void Connect() { string propertyName; Component view; ParseViewEndPointReference(viewPropertyName, out propertyName, out view); var viewModelEndPoint = MakeViewModelEndPoint( viewModelPropertyName, viewModelAdapterTypeName, viewModelAdapterOptions ); var propertySync = new PropertySync( // Source viewModelEndPoint, // Dest new PropertyEndPoint( view, propertyName, CreateAdapter(viewAdapterTypeName), viewAdapterOptions, "view", this ), // Errors, exceptions and validation. !string.IsNullOrEmpty(exceptionPropertyName) ? MakeViewModelEndPoint( exceptionPropertyName, exceptionAdapterTypeName, exceptionAdapterOptions ) : null , this ); viewModelWatcher = viewModelEndPoint.Watch( () => propertySync.SyncFromSource() ); string eventName; string eventComponentType; ParseEndPointReference(viewEventName, out eventName, out eventComponentType); var eventView = GetComponent(eventComponentType); unityEventWatcher = new UnityEventWatcher( eventView, eventName, () => propertySync.SyncFromDest() ); // Copy the initial value over from the view-model. propertySync.SyncFromSource(); } public override void Disconnect() { if (viewModelWatcher != null) { viewModelWatcher.Dispose(); viewModelWatcher = null; } if (unityEventWatcher != null) { unityEventWatcher.Dispose(); unityEventWatcher = null; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace MoraleOMeter.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using Newtonsoft.Json.Linq; using POESKillTree.SkillTreeFiles; using POESKillTree.Utils; namespace POESKillTree.Model.Builds { /// <summary> /// <see cref="IBuild"/> implementation that represents a single build, a leaf in the build tree. /// Has a dirty flag that is set with every property change and can be reset. Can be reverted to the state of the /// last dirty flag reset. /// </summary> public class PoEBuild : AbstractBuild<PoEBuild> { private string _note; private string _characterName; private string _accountName; private string _league; private int _level = 1; private string _treeUrl = Constants.DefaultTree; private string _itemData; private DateTime _lastUpdated = DateTime.Now; private ObservableCollection<string[]> _customGroups; private BanditSettings _bandits; private ObservableSet<ushort> _checkedNodeIds; private ObservableSet<ushort> _crossedNodeIds; private JObject _additionalData; private bool _isDirty; private IMemento<PoEBuild> _memento; /// <summary> /// Gets or sets a arbitrary note. /// </summary> public string Note { get { return _note; } set { SetProperty(ref _note, value); } } /// <summary> /// Gets or sets the character name this builds represents. /// </summary> public string CharacterName { get { return _characterName; } set { SetProperty(ref _characterName, value); } } /// <summary> /// Gets or sets the account name that owns the represented character. /// </summary> public string AccountName { get { return _accountName; } set { SetProperty(ref _accountName, value); } } /// <summary> /// Gets or sets the league of the represented character. /// </summary> public string League { get { return _league; } set { SetProperty(ref _league, value); } } /// <summary> /// Gets or sets the level of the represented character. /// </summary> public int Level { get { return _level; } set { SetProperty(ref _level, value); } } /// <summary> /// Gets or sets the build defining skill tree URL. /// </summary> public string TreeUrl { get { return _treeUrl; } set { SetProperty(ref _treeUrl, value); } } /// <summary> /// Gets or sets the item data of this build as serialized JSON. /// </summary> public string ItemData { get { return _itemData; } set { SetProperty(ref _itemData, value); } } /// <summary> /// Gets or sets the last time this build was updated and saved. /// </summary> public DateTime LastUpdated { get { return _lastUpdated; } set { SetProperty(ref _lastUpdated, value); } } /// <summary> /// Gets the custom attribute grouping of this build. /// </summary> public ObservableCollection<string[]> CustomGroups { get { return _customGroups; } private set { SetProperty(ref _customGroups, value); } } /// <summary> /// Gets the bandit settings of this build. /// </summary> public BanditSettings Bandits { get { return _bandits; } private set { SetProperty(ref _bandits, value); } } /// <summary> /// Gets a set containing the ids of the nodes check tagged in this build. /// </summary> public ObservableSet<ushort> CheckedNodeIds { get { return _checkedNodeIds; } private set { SetProperty(ref _checkedNodeIds, value); } } /// <summary> /// Gets a set containing the ids of the nodes cross tagged in this build. /// </summary> public ObservableSet<ushort> CrossedNodeIds { get { return _crossedNodeIds; } private set { SetProperty(ref _crossedNodeIds, value); } } /// <summary> /// Gets a JSON object containing arbitrary additional data. /// Changes to the object will not flag this build dirty, <see cref="FlagDirty"/> needs to be called /// explicitly. /// </summary> public JObject AdditionalData { get { return _additionalData; } private set { SetProperty(ref _additionalData, value); } } /// <summary> /// Gets whether this build was changed since the last <see cref="KeepChanges"/> call. /// </summary> public bool IsDirty { get { return _isDirty; } private set { SetProperty(ref _isDirty, value); } } /// <summary> /// Gets whether this build can be reverted to an old state. It can be reverted if /// <see cref="KeepChanges"/> was called at least once. /// </summary> public bool CanRevert { get { return _memento != null; } } public PoEBuild() { PropertyChanged += PropertyChangedHandler; Bandits = new BanditSettings(); CustomGroups = new ObservableCollection<string[]>(); CheckedNodeIds = new ObservableSet<ushort>(); CrossedNodeIds = new ObservableSet<ushort>(); AdditionalData = new JObject(); PropertyChanging += PropertyChangingHandler; } public PoEBuild(BanditSettings bandits, IEnumerable<string[]> customGroups, IEnumerable<ushort> checkedNodeIds, IEnumerable<ushort> crossedNodeIds, string additionalData) { PropertyChanged += PropertyChangedHandler; Bandits = bandits ?? new BanditSettings(); CustomGroups = new ObservableCollection<string[]>(customGroups); CheckedNodeIds = new ObservableSet<ushort>(checkedNodeIds); CrossedNodeIds = new ObservableSet<ushort>(crossedNodeIds); AdditionalData = additionalData == null ? new JObject() : JObject.Parse(additionalData); PropertyChanging += PropertyChangingHandler; } private void PropertyChangingHandler(object sender, PropertyChangingEventArgs args) { switch (args.PropertyName) { case nameof(CustomGroups): CustomGroups.CollectionChanged -= ChangedHandler; break; case nameof(Bandits): Bandits.PropertyChanged -= ChangedHandler; break; case nameof(CheckedNodeIds): CheckedNodeIds.CollectionChanged -= ChangedHandler; break; case nameof(CrossedNodeIds): CrossedNodeIds.CollectionChanged -= ChangedHandler; break; } } private void PropertyChangedHandler(object sender, PropertyChangedEventArgs args) { switch (args.PropertyName) { case nameof(CustomGroups): CustomGroups.CollectionChanged += ChangedHandler; break; case nameof(Bandits): Bandits.PropertyChanged += ChangedHandler; break; case nameof(CheckedNodeIds): CheckedNodeIds.CollectionChanged += ChangedHandler; break; case nameof(CrossedNodeIds): CrossedNodeIds.CollectionChanged += ChangedHandler; break; } if (args.PropertyName != nameof(IsDirty)) IsDirty = true; } private void ChangedHandler(object sender, EventArgs args) { IsDirty = true; } /// <summary> /// Explicitly flags this instance as having unsaved changes. /// </summary> public void FlagDirty() { IsDirty = true; } /// <summary> /// Reverts changes made to this instance since the last <see cref="KeepChanges"/>. /// </summary> /// <exception cref="NullReferenceException">When <see cref="KeepChanges"/> was never called.</exception> public void RevertChanges() { _memento.Restore(this); IsDirty = false; } /// <summary> /// Removes the dirty flag and stores the current change so they can be reverted to. /// </summary> public void KeepChanges() { _memento = new Memento(this); IsDirty = false; } protected override Notifier SafeMemberwiseClone() { var o = (PoEBuild) base.SafeMemberwiseClone(); o.PropertyChanged += o.PropertyChangedHandler; o.PropertyChanging += o.PropertyChangingHandler; return o; } public override PoEBuild DeepClone() { var o = (PoEBuild) SafeMemberwiseClone(); o.CustomGroups = new ObservableCollection<string[]>(CustomGroups.Select(a => (string[])a.Clone())); o.CheckedNodeIds = new ObservableSet<ushort>(CheckedNodeIds); o.CrossedNodeIds = new ObservableSet<ushort>(CrossedNodeIds); o.AdditionalData = new JObject(AdditionalData); o.Bandits = Bandits.DeepClone(); return o; } private class Memento : IMemento<PoEBuild> { private readonly PoEBuild _build; public Memento(PoEBuild build) { _build = build.DeepClone(); } public void Restore(PoEBuild target) { target.Name = _build.Name; target.Note = _build.Note; target.CharacterName = _build.CharacterName; target.AccountName = _build.AccountName; target.League = _build.League; target.Level = _build.Level; target.TreeUrl = _build.TreeUrl; target.ItemData = _build.ItemData; target.LastUpdated = _build.LastUpdated; target.CustomGroups = new ObservableCollection<string[]>(_build.CustomGroups.Select(a => (string[]) a.Clone())); target.CheckedNodeIds = new ObservableSet<ushort>(_build.CheckedNodeIds); target.CrossedNodeIds = new ObservableSet<ushort>(_build.CrossedNodeIds); target.AdditionalData = new JObject(_build.AdditionalData); target.Bandits = _build.Bandits.DeepClone(); } } } }
using UnityEngine; using UnityEditor; using System; using System.Linq; using System.Collections; using System.Collections.Generic; using UMA; [CustomEditor(typeof(OverlayLibrary))] [CanEditMultipleObjects] public class OverlayLibraryEditor : Editor { private SerializedObject m_Object; private OverlayLibrary overlayLibrary; private SerializedProperty m_OverlayDataCount; private const string kArraySizePath = "overlayElementList.Array.size"; private const string kArrayData = "overlayElementList.Array.data[{0}]"; private bool canUpdate; private bool isDirty; public SerializedProperty scaleAdjust; public SerializedProperty readWrite; public SerializedProperty compress; public void OnEnable(){ m_Object = new SerializedObject(target); overlayLibrary = m_Object.targetObject as OverlayLibrary; m_OverlayDataCount = m_Object.FindProperty(kArraySizePath); scaleAdjust = serializedObject.FindProperty ("scaleAdjust"); readWrite = serializedObject.FindProperty ("readWrite"); compress = serializedObject.FindProperty ("compress"); } private OverlayData[] GetOverlayDataArray(){ int arrayCount = m_OverlayDataCount.intValue; OverlayData[] OverlayDataArray = new OverlayData[arrayCount]; for(int i = 0; i < arrayCount; i++){ OverlayDataArray[i] = m_Object.FindProperty(string.Format(kArrayData,i)).objectReferenceValue as OverlayData ; } return OverlayDataArray; } private void SetOverlayData (int index,OverlayData overlayElement){ m_Object.FindProperty(string.Format(kArrayData,index)).objectReferenceValue = overlayElement; isDirty = true; } private OverlayData GetOverlayDataAtIndex(int index){ return m_Object.FindProperty(string.Format(kArrayData,index)).objectReferenceValue as OverlayData ; } private void AddOverlayData(OverlayData overlayElement){ m_OverlayDataCount.intValue ++; SetOverlayData(m_OverlayDataCount.intValue - 1, overlayElement); } private void RemoveOverlayDataAtIndex(int index){ for(int i = index; i < m_OverlayDataCount.intValue - 1; i++){ SetOverlayData(i, GetOverlayDataAtIndex(i + 1)); } m_OverlayDataCount.intValue --; } private void ScaleDownTextures(){ OverlayData[] overlayElementList = GetOverlayDataArray(); string path; for(int i = 0; i < overlayElementList.Length; i++){ if(overlayElementList[i] != null){ Rect tempRect = overlayElementList[i].rect; overlayElementList[i].rect = new Rect(tempRect.x*0.5f,tempRect.y*0.5f,tempRect.width*0.5f,tempRect.height*0.5f); EditorUtility.SetDirty(overlayElementList[i]); for(int textureID = 0; textureID < overlayElementList[i].textureList.Length; textureID++){ if(overlayElementList[i].textureList[textureID]){ path = AssetDatabase.GetAssetPath(overlayElementList[i].textureList[textureID]); TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter; textureImporter.maxTextureSize = (int)(textureImporter.maxTextureSize*0.5f); AssetDatabase.WriteImportSettingsIfDirty (path); AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate); } } } } AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } private void ScaleUpTextures(){ OverlayData[] overlayElementList = GetOverlayDataArray(); string path; for(int i = 0; i < overlayElementList.Length; i++){ if(overlayElementList[i] != null){ Rect tempRect = overlayElementList[i].rect; overlayElementList[i].rect = new Rect(tempRect.x*2,tempRect.y*2,tempRect.width*2,tempRect.height*2); EditorUtility.SetDirty(overlayElementList[i]); for(int textureID = 0; textureID < overlayElementList[i].textureList.Length; textureID++){ if(overlayElementList[i].textureList[textureID]){ path = AssetDatabase.GetAssetPath(overlayElementList[i].textureList[textureID]); TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter; textureImporter.maxTextureSize = (int)(textureImporter.maxTextureSize*2); AssetDatabase.WriteImportSettingsIfDirty (path); AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate); } } } } AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } private void ConfigureTextures(){ OverlayData[] overlayElementList = GetOverlayDataArray(); string path; for(int i = 0; i < overlayElementList.Length; i++){ if(overlayElementList[i] != null){ for(int textureID = 0; textureID < overlayElementList[i].textureList.Length; textureID++){ if(overlayElementList[i].textureList[textureID]){ path = AssetDatabase.GetAssetPath(overlayElementList[i].textureList[textureID]); TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter; textureImporter.isReadable = readWrite.boolValue; if(compress.boolValue){ textureImporter.textureFormat = TextureImporterFormat.AutomaticCompressed; textureImporter.compressionQuality = (int)TextureCompressionQuality.Best; }else{ textureImporter.textureFormat = TextureImporterFormat.AutomaticTruecolor; textureImporter.compressionQuality = (int)TextureCompressionQuality.Best; } AssetDatabase.WriteImportSettingsIfDirty (path); AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate); Debug.Log(overlayElementList[i].textureList[textureID].name + " isReadable set to " + readWrite.boolValue + " and compression set to " + compress.boolValue); } } } } AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } private void DropAreaGUI(Rect dropArea){ var evt = Event.current; if(evt.type == EventType.DragUpdated){ if(dropArea.Contains(evt.mousePosition)){ DragAndDrop.visualMode = DragAndDropVisualMode.Copy; } } if(evt.type == EventType.DragPerform){ if(dropArea.Contains(evt.mousePosition)){ DragAndDrop.AcceptDrag(); UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences; for(int i = 0; i < draggedObjects.Length; i++){ if (draggedObjects[i]) { OverlayData tempOverlayData = draggedObjects[i] as OverlayData; if (tempOverlayData) { AddOverlayData(tempOverlayData); continue; } var path = AssetDatabase.GetAssetPath(draggedObjects[i]); if (System.IO.Directory.Exists(path)) { var assetFiles = System.IO.Directory.GetFiles(path, "*.asset"); foreach (var assetFile in assetFiles) { tempOverlayData = AssetDatabase.LoadAssetAtPath(assetFile, typeof(OverlayData)) as OverlayData; if (tempOverlayData) { AddOverlayData(tempOverlayData); } } } } } } } } public override void OnInspectorGUI(){ m_Object.Update(); serializedObject.Update(); GUILayout.Label ("overlayList", EditorStyles.boldLabel); OverlayData[] overlayElementList = GetOverlayDataArray(); GUILayout.Space(30); GUILayout.Label ("Overlays reduced " + scaleAdjust.intValue +" time(s)"); GUILayout.BeginHorizontal(); if(scaleAdjust.intValue > 0){ if(GUILayout.Button("Resolution +")){ ScaleUpTextures(); isDirty = true; canUpdate = false; scaleAdjust.intValue --; } } if(GUILayout.Button("Resolution -")){ ScaleDownTextures(); isDirty = true; canUpdate = false; scaleAdjust.intValue ++; } GUILayout.EndHorizontal(); GUILayout.Space(20); GUILayout.BeginHorizontal(); compress.boolValue = GUILayout.Toggle (compress.boolValue ? true : false," Compress Textures"); readWrite.boolValue = GUILayout.Toggle (readWrite.boolValue ? true : false," Read/Write"); if(GUILayout.Button(" Apply")){ ConfigureTextures(); isDirty = true; canUpdate = false; } GUILayout.EndHorizontal(); GUILayout.Space(20); GUILayout.BeginHorizontal(); if(GUILayout.Button("Order by Name")){ canUpdate = false; List<OverlayData> OverlayDataTemp = overlayElementList.ToList(); //Make sure there's no invalid data for(int i = 0; i < OverlayDataTemp.Count; i++){ if(OverlayDataTemp[i] == null){ OverlayDataTemp.RemoveAt(i); i--; } } OverlayDataTemp.Sort((x,y) => x.name.CompareTo(y.name)); for(int i = 0; i < OverlayDataTemp.Count; i++){ SetOverlayData(i,OverlayDataTemp[i]); } } if(GUILayout.Button("Update List")){ isDirty = true; canUpdate = false; } GUILayout.EndHorizontal(); GUILayout.Space(20); Rect dropArea = GUILayoutUtility.GetRect(0.0f,50.0f, GUILayout.ExpandWidth(true)); GUI.Box(dropArea,"Drag Overlays here"); GUILayout.Space(20); for(int i = 0; i < m_OverlayDataCount.intValue; i ++){ GUILayout.BeginHorizontal(); OverlayData result = EditorGUILayout.ObjectField (overlayElementList[i], typeof(OverlayData), true) as OverlayData ; if(GUI.changed && canUpdate){ SetOverlayData(i,result); } if(GUILayout.Button("-", GUILayout.Width(20.0f))){ canUpdate = false; RemoveOverlayDataAtIndex(i); } GUILayout.EndHorizontal(); if(i == m_OverlayDataCount.intValue -1){ canUpdate = true; if(isDirty){ overlayLibrary.UpdateDictionary(); isDirty = false; } } } DropAreaGUI(dropArea); if(GUILayout.Button("Add OverlayData")){ AddOverlayData(null); } if(GUILayout.Button("Clear List")){ m_OverlayDataCount.intValue = 0; } m_Object.ApplyModifiedProperties(); serializedObject.ApplyModifiedProperties(); } }
// 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.Immutable; using System.Linq; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Resources = Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests.Resources; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class WinMdTests : ExpressionCompilerTestBase { /// <summary> /// Handle runtime assemblies rather than Windows.winmd /// (compile-time assembly) since those are the assemblies /// loaded in the debuggee. /// </summary> [WorkItem(981104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981104")] [ConditionalFact(typeof(OSVersionWin8))] public void Win8RuntimeAssemblies() { var source = @"class C { static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p) { } }"; var compilation0 = CreateStandardCompilation( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: WinRtRefs); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections"); Assert.True(runtimeAssemblies.Length >= 2); // no reference to Windows.winmd WithRuntimeInstance(compilation0, new[] { MscorlibRef }.Concat(runtimeAssemblies), runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("(p == null) ? f : null", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: brfalse.s IL_0005 IL_0003: ldnull IL_0004: ret IL_0005: ldarg.0 IL_0006: ret }"); }); } [ConditionalFact(typeof(OSVersionWin8))] public void Win8RuntimeAssemblies_ExternAlias() { var source = @"extern alias X; class C { static void M(X::Windows.Storage.StorageFolder f) { } }"; var compilation0 = CreateStandardCompilation( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: WinRtRefs.Select(r => r.Display == "Windows" ? r.WithAliases(new[] { "X" }) : r)); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage"); Assert.True(runtimeAssemblies.Length >= 1); // no reference to Windows.winmd WithRuntimeInstance(compilation0, new[] { MscorlibRef }.Concat(runtimeAssemblies), runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("X::Windows.Storage.FileProperties.PhotoOrientation.Unspecified", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); }); } [Fact] public void Win8OnWin8() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows.Storage"); } [Fact] public void Win8OnWin10() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows.Storage"); } [WorkItem(1108135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108135")] [Fact] public void Win10OnWin10() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows"); } private void CompileTimeAndRuntimeAssemblies( ImmutableArray<MetadataReference> compileReferences, ImmutableArray<MetadataReference> runtimeReferences, string storageAssemblyName) { var source = @"class C { static void M(LibraryA.A a, LibraryB.B b, Windows.Data.Text.TextSegment t, Windows.Storage.StorageFolder f) { } }"; var compilation0 = CreateStandardCompilation(source, compileReferences, TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtimeReferences, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("(object)a ?? (object)b ?? (object)t ?? f", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_0010 IL_0004: pop IL_0005: ldarg.1 IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.2 IL_000b: dup IL_000c: brtrue.s IL_0010 IL_000e: pop IL_000f: ldarg.3 IL_0010: ret }"); testData = new CompilationTestData(); var result = context.CompileExpression("default(Windows.Storage.StorageFolder)", out error, testData); Assert.Null(error); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); // Check return type is from runtime assembly. var assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference(); var compilation = CSharpCompilation.Create( assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: runtimeReferences.Concat(ImmutableArray.Create<MetadataReference>(assemblyReference))); var assembly = ImmutableArray.CreateRange(result.Assembly); using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly))) { var reader = metadata.MetadataReader; var typeDef = reader.GetTypeDef("<>x"); var methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0"); var module = (PEModuleSymbol)compilation.GetMember("<>x").ContainingModule; var metadataDecoder = new MetadataDecoder(module); SignatureHeader signatureHeader; BadImageFormatException metadataException; var parameters = metadataDecoder.GetSignatureForMethod(methodHandle, out signatureHeader, out metadataException); Assert.Equal(parameters.Length, 5); var actualReturnType = parameters[0].Type; Assert.Equal(actualReturnType.TypeKind, TypeKind.Class); // not error var expectedReturnType = compilation.GetMember("Windows.Storage.StorageFolder"); Assert.Equal(expectedReturnType, actualReturnType); Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name); } }); } /// <summary> /// Assembly-qualified name containing "ContentType=WindowsRuntime", /// and referencing runtime assembly. /// </summary> [WorkItem(1116143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116143")] [ConditionalFact(typeof(OSVersionWin8))] public void AssemblyQualifiedName() { var source = @"class C { static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p) { } }"; var compilation = CreateStandardCompilation(source, WinRtRefs, TestOptions.DebugDll); WithRuntimeInstance(compilation, new[] { MscorlibRef }.Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections")), runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"), VariableAlias("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime")); string error; var testData = new CompilationTestData(); context.CompileExpression( "(object)s.Attributes ?? d.UniversalTime", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldstr ""s"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""Windows.Storage.StorageFolder"" IL_000f: callvirt ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get"" IL_0014: box ""Windows.Storage.FileAttributes"" IL_0019: dup IL_001a: brtrue.s IL_0036 IL_001c: pop IL_001d: ldstr ""d"" IL_0022: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0027: unbox.any ""Windows.Foundation.DateTime"" IL_002c: ldfld ""long Windows.Foundation.DateTime.UniversalTime"" IL_0031: box ""long"" IL_0036: ret }"); }); } <<<<<<< HEAD <<<<<<< HEAD [WorkItem(1117084)] [ConditionalFact(typeof(OSVersionWin8))] ======= ======= >>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00 [WorkItem(1117084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1117084")] [Fact] >>>>>>> roslynOrigin/master public void OtherFrameworkAssembly() { var source = @"class C { static void M(Windows.UI.Xaml.FrameworkElement f) { } }"; var compilation = CreateStandardCompilation(source, WinRtRefs, TestOptions.DebugDll); WithRuntimeInstance(compilation, new[] { MscorlibRef }.Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Foundation", "Windows.UI", "Windows.UI.Xaml")), runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var testData = new CompilationTestData(); var result = context.CompileExpression( "f.RenderSize", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); var expectedAssemblyIdentity = WinRtRefs.Single(r => r.Display == "System.Runtime.WindowsRuntime.dll").GetAssemblyIdentity(); Assert.Equal(expectedAssemblyIdentity, missingAssemblyIdentities.Single()); }); } [WorkItem(1154988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1154988")] [ConditionalFact(typeof(OSVersionWin8))] public void WinMdAssemblyReferenceRequiresRedirect() { var source = @"class C : Windows.UI.Xaml.Controls.UserControl { static void M(C c) { } }"; var compilation = CreateStandardCompilation(source, WinRtRefs, TestOptions.DebugDll); WithRuntimeInstance(compilation, new[] { MscorlibRef }.Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.UI", "Windows.UI.Xaml")), runtime => { string errorMessage; var testData = new CompilationTestData(); ExpressionCompilerTestHelpers.CompileExpressionWithRetry( runtime.Modules.SelectAsArray(m => m.MetadataBlock), "c.Dispatcher", ImmutableArray<Alias>.Empty, (metadataBlocks, _) => { return CreateMethodContext(runtime, "C.M"); }, (AssemblyIdentity assembly, out uint size) => { // Compilation should succeed without retry if we redirect assembly refs correctly. // Throwing so that we don't loop forever (as we did before fix)... throw ExceptionUtilities.Unreachable; }, out errorMessage, out testData); Assert.Null(errorMessage); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: callvirt ""Windows.UI.Core.CoreDispatcher Windows.UI.Xaml.DependencyObject.Dispatcher.get"" IL_0006: ret }"); }); } private static byte[] ToVersion1_3(byte[] bytes) { return ExpressionCompilerTestHelpers.ToVersion1_3(bytes); } private static byte[] ToVersion1_4(byte[] bytes) { return ExpressionCompilerTestHelpers.ToVersion1_4(bytes); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Text; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using Internal.Cryptography; using Internal.Cryptography.Pal; namespace System.Security.Cryptography.X509Certificates { public class X509Certificate : IDisposable { public X509Certificate() { } public X509Certificate(byte[] data) { if (data != null && data.Length != 0) // For compat reasons, this constructor treats passing a null or empty data set as the same as calling the nullary constructor. Pal = CertificatePal.FromBlob(data, null, X509KeyStorageFlags.DefaultKeySet); } public X509Certificate(byte[] rawData, string password) : this(rawData, password, X509KeyStorageFlags.DefaultKeySet) { } public X509Certificate(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { if (rawData == null || rawData.Length == 0) throw new ArgumentException(SR.Arg_EmptyOrNullArray, "rawData"); if ((keyStorageFlags & ~KeyStorageFlagsAll) != 0) throw new ArgumentException(SR.Argument_InvalidFlag, "keyStorageFlags"); Pal = CertificatePal.FromBlob(rawData, password, keyStorageFlags); } public X509Certificate(IntPtr handle) { Pal = CertificatePal.FromHandle(handle); } internal X509Certificate(ICertificatePal pal) { Debug.Assert(pal != null); Pal = pal; } public X509Certificate(string fileName) : this(fileName, null, X509KeyStorageFlags.DefaultKeySet) { } public X509Certificate(string fileName, string password) : this(fileName, password, X509KeyStorageFlags.DefaultKeySet) { } public X509Certificate(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { if (fileName == null) throw new ArgumentNullException("fileName"); if ((keyStorageFlags & ~KeyStorageFlagsAll) != 0) throw new ArgumentException(SR.Argument_InvalidFlag, "keyStorageFlags"); Pal = CertificatePal.FromFile(fileName, password, keyStorageFlags); } public IntPtr Handle { get { if (Pal == null) return IntPtr.Zero; else return Pal.Handle; } } public string Issuer { get { ThrowIfInvalid(); string issuer = _lazyIssuer; if (issuer == null) issuer = _lazyIssuer = Pal.Issuer; return issuer; } } public string Subject { get { ThrowIfInvalid(); string subject = _lazySubject; if (subject == null) subject = _lazySubject = Pal.Subject; return subject; } } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { ICertificatePal pal = Pal; Pal = null; if (pal != null) pal.Dispose(); } } public override bool Equals(object obj) { X509Certificate other = obj as X509Certificate; if (other == null) return false; return Equals(other); } public virtual bool Equals(X509Certificate other) { if (other == null) return false; if (Pal == null) return other.Pal == null; if (!Issuer.Equals(other.Issuer)) return false; byte[] thisSerialNumber = GetRawSerialNumber(); byte[] otherSerialNumber = other.GetRawSerialNumber(); if (thisSerialNumber.Length != otherSerialNumber.Length) return false; for (int i = 0; i < thisSerialNumber.Length; i++) { if (thisSerialNumber[i] != otherSerialNumber[i]) return false; } return true; } public virtual byte[] Export(X509ContentType contentType) { return Export(contentType, null); } public virtual byte[] Export(X509ContentType contentType, string password) { if (!(contentType == X509ContentType.Cert || contentType == X509ContentType.SerializedCert || contentType == X509ContentType.Pkcs12)) throw new CryptographicException(SR.Cryptography_X509_InvalidContentType); if (Pal == null) throw new CryptographicException(ErrorCode.E_POINTER); // Not the greatest error, but needed for backward compat. using (IStorePal storePal = StorePal.FromCertificate(Pal)) { return storePal.Export(contentType, password); } } public virtual byte[] GetCertHash() { ThrowIfInvalid(); return GetRawCertHash().CloneByteArray(); } // Only use for internal purposes when the returned byte[] will not be mutated private byte[] GetRawCertHash() { return _lazyCertHash ?? (_lazyCertHash = Pal.Thumbprint); } public virtual string GetFormat() { return "X509"; } public override int GetHashCode() { if (Pal == null) return 0; byte[] thumbPrint = GetRawCertHash(); int value = 0; for (int i = 0; i < thumbPrint.Length && i < 4; ++i) { value = value << 8 | thumbPrint[i]; } return value; } public virtual string GetKeyAlgorithm() { ThrowIfInvalid(); string keyAlgorithm = _lazyKeyAlgorithm; if (keyAlgorithm == null) keyAlgorithm = _lazyKeyAlgorithm = Pal.KeyAlgorithm; return keyAlgorithm; } public virtual byte[] GetKeyAlgorithmParameters() { ThrowIfInvalid(); byte[] keyAlgorithmParameters = _lazyKeyAlgorithmParameters; if (keyAlgorithmParameters == null) keyAlgorithmParameters = _lazyKeyAlgorithmParameters = Pal.KeyAlgorithmParameters; return keyAlgorithmParameters.CloneByteArray(); } public virtual string GetKeyAlgorithmParametersString() { ThrowIfInvalid(); byte[] keyAlgorithmParameters = GetKeyAlgorithmParameters(); return keyAlgorithmParameters.ToHexStringUpper(); } public virtual byte[] GetPublicKey() { ThrowIfInvalid(); byte[] publicKey = _lazyPublicKey; if (publicKey == null) publicKey = _lazyPublicKey = Pal.PublicKeyValue; return publicKey.CloneByteArray(); } public virtual byte[] GetSerialNumber() { ThrowIfInvalid(); return GetRawSerialNumber().CloneByteArray(); } // Only use for internal purposes when the returned byte[] will not be mutated private byte[] GetRawSerialNumber() { return _lazySerialNumber ?? (_lazySerialNumber = Pal.SerialNumber); } public override string ToString() { return ToString(fVerbose: false); } public virtual string ToString(bool fVerbose) { if (fVerbose == false || Pal == null) return GetType().ToString(); StringBuilder sb = new StringBuilder(); // Subject sb.AppendLine("[Subject]"); sb.Append(" "); sb.AppendLine(Subject); // Issuer sb.AppendLine(); sb.AppendLine("[Issuer]"); sb.Append(" "); sb.AppendLine(Issuer); // Serial Number sb.AppendLine(); sb.AppendLine("[Serial Number]"); sb.Append(" "); byte[] serialNumber = GetSerialNumber(); Array.Reverse(serialNumber); sb.Append(serialNumber.ToHexArrayUpper()); sb.AppendLine(); // NotBefore sb.AppendLine(); sb.AppendLine("[Not Before]"); sb.Append(" "); sb.AppendLine(FormatDate(GetNotBefore())); // NotAfter sb.AppendLine(); sb.AppendLine("[Not After]"); sb.Append(" "); sb.AppendLine(FormatDate(GetNotAfter())); // Thumbprint sb.AppendLine(); sb.AppendLine("[Thumbprint]"); sb.Append(" "); sb.Append(GetRawCertHash().ToHexArrayUpper()); sb.AppendLine(); return sb.ToString(); } internal ICertificatePal Pal { get; private set; } internal DateTime GetNotAfter() { ThrowIfInvalid(); DateTime notAfter = _lazyNotAfter; if (notAfter == DateTime.MinValue) notAfter = _lazyNotAfter = Pal.NotAfter; return notAfter; } internal DateTime GetNotBefore() { ThrowIfInvalid(); DateTime notBefore = _lazyNotBefore; if (notBefore == DateTime.MinValue) notBefore = _lazyNotBefore = Pal.NotBefore; return notBefore; } internal void ThrowIfInvalid() { if (Pal == null) throw new CryptographicException(SR.Format(SR.Cryptography_InvalidHandle, "m_safeCertContext")); // Keeping "m_safeCertContext" string for backward compat sake. } /// <summary> /// Convert a date to a string. /// /// Some cultures, specifically using the Um-AlQura calendar cannot convert dates far into /// the future into strings. If the expiration date of an X.509 certificate is beyond the range /// of one of these these cases, we need to fall back to a calendar which can express the dates /// </summary> internal static string FormatDate(DateTime date) { CultureInfo culture = CultureInfo.CurrentCulture; if (!culture.DateTimeFormat.Calendar.IsValidDay(date.Year, date.Month, date.Day, 0)) { // The most common case of culture failing to work is in the Um-AlQuara calendar. In this case, // we can fall back to the Hijri calendar, otherwise fall back to the invariant culture. if (culture.DateTimeFormat.Calendar is UmAlQuraCalendar) { culture = culture.Clone() as CultureInfo; culture.DateTimeFormat.Calendar = new HijriCalendar(); } else { culture = CultureInfo.InvariantCulture; } } return date.ToString(culture); } private volatile byte[] _lazyCertHash; private volatile string _lazyIssuer; private volatile string _lazySubject; private volatile byte[] _lazySerialNumber; private volatile string _lazyKeyAlgorithm; private volatile byte[] _lazyKeyAlgorithmParameters; private volatile byte[] _lazyPublicKey; private DateTime _lazyNotBefore = DateTime.MinValue; private DateTime _lazyNotAfter = DateTime.MinValue; private const X509KeyStorageFlags KeyStorageFlagsAll = (X509KeyStorageFlags)0x1f; } }
#region Header /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Copyright (c) 2007-2008 James Nies and NArrange contributors. * All rights reserved. * * This program and the accompanying materials are made available under * the terms of the Common Public License v1.0 which accompanies this * distribution. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *<author>James Nies</author> *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #endregion Header namespace NArrange.Core.CodeElements { using System.Collections.Generic; using System.Collections.ObjectModel; /// <summary> /// Code element base class. /// </summary> public abstract class CodeElement : ICodeElement { #region Fields /// <summary> /// Children synch lock. /// </summary> private readonly object _childrenLock = new object(); /// <summary> /// Extened property dictionary. /// </summary> private readonly Dictionary<string, object> _extendedProperties; /// <summary> /// Collection of chile code elements. /// </summary> private List<ICodeElement> _children; /// <summary> /// Element name. /// </summary> private string _name; /// <summary> /// Parent code element. /// </summary> private ICodeElement _parent; #endregion Fields #region Constructors /// <summary> /// Default constructor. /// </summary> protected CodeElement() { // Default property values _name = string.Empty; _extendedProperties = new Dictionary<string, object>(5); } #endregion Constructors #region Properties /// <summary> /// Gets the collection of children for this element. /// </summary> public ReadOnlyCollection<ICodeElement> Children { get { return BaseChildren.AsReadOnly(); } } /// <summary> /// Gets the element type. /// </summary> public abstract ElementType ElementType { get; } /// <summary> /// Gets or sets the code element name. /// </summary> public virtual string Name { get { return _name; } set { _name = value; } } /// <summary> /// Gets or sets the parent element. /// </summary> public virtual ICodeElement Parent { get { return _parent; } set { if (value != _parent) { if (_parent != null) { _parent.RemoveChild(this); } _parent = value; if (_parent != null && !_parent.Children.Contains(this)) { _parent.AddChild(this); } } } } /// <summary> /// Gets the base child collection. /// </summary> protected List<ICodeElement> BaseChildren { get { if (_children == null) { lock (_childrenLock) { if (_children == null) { _children = new List<ICodeElement>(); } } } return _children; } } #endregion Properties #region Indexers /// <summary> /// Gets or sets an extended property. /// </summary> /// <param name="key">Extended property name/key.</param> /// <returns></returns> public virtual object this[string key] { get { object value = null; _extendedProperties.TryGetValue(key, out value); return value; } set { if (value == null) { _extendedProperties.Remove(key); } else { _extendedProperties[key] = value; } } } #endregion Indexers #region Methods /// <summary> /// Allows an ICodeElementVisitor to process (or visit) this element. /// </summary> /// <remarks>See the Gang of Four Visitor design pattern.</remarks> /// <param name="visitor">Visitor to accept the code element.</param> public abstract void Accept(ICodeElementVisitor visitor); /// <summary> /// Adds a child to this element. /// </summary> /// <param name="childElement">Child to add.</param> public virtual void AddChild(ICodeElement childElement) { if (childElement != null) { lock (_childrenLock) { if (childElement != null && !BaseChildren.Contains(childElement)) { BaseChildren.Add(childElement); childElement.Parent = this; } } } } /// <summary> /// Removes all child elements. /// </summary> public virtual void ClearChildren() { lock (_childrenLock) { for (int childIndex = 0; childIndex < BaseChildren.Count; childIndex++) { ICodeElement child = BaseChildren[childIndex]; if (child != null && child.Parent != null) { child.Parent = null; childIndex--; } } BaseChildren.Clear(); } } /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns> /// A new object that is a copy of this instance. /// </returns> public virtual object Clone() { CodeElement clone = DoClone(); // Copy base state clone._name = _name; lock (_childrenLock) { for (int childIndex = 0; childIndex < BaseChildren.Count; childIndex++) { ICodeElement child = BaseChildren[childIndex]; ICodeElement childClone = child.Clone() as ICodeElement; childClone.Parent = clone; } } foreach (string key in _extendedProperties.Keys) { clone[key] = _extendedProperties[key]; } return clone; } /// <summary> /// Inserts a child element at the specified index. /// </summary> /// <param name="index">Index to insert at.</param> /// <param name="childElement">Element to insert.</param> public virtual void InsertChild(int index, ICodeElement childElement) { if (childElement != null) { lock (_childrenLock) { if (BaseChildren.Contains(childElement)) { BaseChildren.Remove(childElement); } BaseChildren.Insert(index, childElement); childElement.Parent = this; } } } /// <summary> /// Removes a child from this element. /// </summary> /// <param name="childElement">Child element to remove.</param> public virtual void RemoveChild(ICodeElement childElement) { if (childElement != null && BaseChildren.Contains(childElement)) { lock (_childrenLock) { if (childElement != null && BaseChildren.Contains(childElement)) { BaseChildren.Remove(childElement); childElement.Parent = null; } } } } /// <summary> /// Gets the string representation of this object. /// </summary> /// <returns>String representation.</returns> public override string ToString() { return _name; } /// <summary> /// Gets a string representation of this object using the specified format string. /// </summary> /// <param name="format">Code element format string.</param> /// <returns>String representation.</returns> public virtual string ToString(string format) { return ElementUtilities.Format(format, this); } /// <summary> /// Creates a clone of the instance and assigns any state. /// </summary> /// <returns>Clone of the code element.</returns> protected abstract CodeElement DoClone(); #endregion Methods } }
namespace Sitecore.Feature.Demo.Tests.Services { using System; using System.Linq; using FluentAssertions; using NSubstitute; using Sitecore.Analytics; using Sitecore.Analytics.Data.Items; using Sitecore.Analytics.Tracking; using Sitecore.Collections; using Sitecore.Data; using Sitecore.Data.Items; using Sitecore.FakeDb; using Sitecore.FakeDb.AutoFixture; using Sitecore.FakeDb.Sites; using Sitecore.Feature.Demo.Services; using Sitecore.Foundation.Testing.Attributes; using Sitecore.Sites; using Xunit; public class ProfileProviderTests { [Theory] [AutoProfileDbData] public void LoadProfiles_SettingWithProfiles_ShouldReturnExistentProfilesEnumerable([Content] Item item, CurrentInteraction currentInteraction, ITracker tracker, Profile profile) { var profileSettingItem = item.Add("profileSetting", new TemplateID(Templates.ProfilingSettings.ID)); var profileItem = item.Add("profile", new TemplateID(ProfileItem.TemplateID)); using (new EditContext(profileSettingItem)) { profileSettingItem.Fields[Templates.ProfilingSettings.Fields.SiteProfiles].Value = profileItem.ID.ToString(); } var provider = new ProfileProvider(); var fakeSiteContext = new FakeSiteContext(new StringDictionary { { "rootPath", "/sitecore" }, { "startItem", profileSettingItem.Paths.FullPath.Remove(0, "/sitecore".Length) } }); fakeSiteContext.Database = item.Database; using (new SiteContextSwitcher(fakeSiteContext)) { var siteProfiles = provider.GetSiteProfiles(); siteProfiles.Count().Should().Be(1); } } [Theory] [AutoProfileDbData] public void LoadProfiles_SettingsIsEmpty_ShouldReturnExistentProfilesEnumerable([Content] Item item, CurrentInteraction currentInteraction, ITracker tracker, Profile profile) { var profileSettingItem = item.Add("profileSetting", new TemplateID(Templates.ProfilingSettings.ID)); var profileItem = item.Add("profile", new TemplateID(ProfileItem.TemplateID)); var provider = new ProfileProvider(); var fakeSiteContext = new FakeSiteContext(new StringDictionary { { "rootPath", "/sitecore" }, { "startItem", profileSettingItem.Paths.FullPath.Remove(0, "/sitecore".Length) } }); fakeSiteContext.Database = item.Database; using (new SiteContextSwitcher(fakeSiteContext)) { provider.GetSiteProfiles().Count().Should().Be(0); } } [Theory] [AutoProfileDbData] public void LoadProfiles_SettingsNotExists_ShouldReturnExistentProfilesEnumerable([Content] Item item) { var fakeSiteContext = new FakeSiteContext(new StringDictionary { { "rootPath", "/sitecore" }, { "startItem", item.Paths.FullPath.Remove(0, "/sitecore".Length) } }); fakeSiteContext.Database = item.Database; using (new SiteContextSwitcher(fakeSiteContext)) { var provider = new ProfileProvider(); provider.GetSiteProfiles().Count().Should().Be(0); } } [Theory] [AutoProfileDbData] public void HasMatchingPattern_ItemNotExists_ShouldReturnFalse([Content] Item profileItem, CurrentInteraction currentInteraction, ITracker tracker, Profile profile) { tracker.Interaction.Returns(currentInteraction); currentInteraction.Profiles[null].ReturnsForAnyArgs(profile); profile.PatternId = Guid.NewGuid(); var fakeSiteContext = new FakeSiteContext("fake") { Database = Database.GetDatabase("master") }; using (new TrackerSwitcher(tracker)) { using (new SiteContextSwitcher(fakeSiteContext)) { var provider = new ProfileProvider(); provider.HasMatchingPattern(new ProfileItem(profileItem), ProfilingTypes.Active).Should().BeFalse(); } } } [Theory] [AutoProfileDbData] public void HasMatchingPattern_ItemExists_ShouldReturnTrue([Content] Item profileItem, CurrentInteraction currentInteraction, ITracker tracker, Profile profile) { tracker.Interaction.Returns(currentInteraction); currentInteraction.Profiles[null].ReturnsForAnyArgs(profile); var pattern = profileItem.Add("fakePattern", new TemplateID(PatternCardItem.TemplateID)); profile.PatternId = pattern.ID.Guid; var fakeSiteContext = new FakeSiteContext("fake") { Database = Database.GetDatabase("master") }; using (new TrackerSwitcher(tracker)) { using (new SiteContextSwitcher(fakeSiteContext)) { var provider = new ProfileProvider(); provider.HasMatchingPattern(new ProfileItem(profileItem), ProfilingTypes.Active).Should().BeTrue(); } } } [Theory] [AutoProfileDbData] public void HasMatchingPattern_TrackerReturnsNull_ShouldReturnFalse([Content] Item profileItem, CurrentInteraction currentInteraction, ITracker tracker, Profile profile) { tracker.Interaction.Returns(currentInteraction); currentInteraction.Profiles[null].ReturnsForAnyArgs((Profile)null); var fakeSiteContext = new FakeSiteContext("fake") { Database = Database.GetDatabase("master") }; using (new TrackerSwitcher(tracker)) { using (new SiteContextSwitcher(fakeSiteContext)) { var provider = new ProfileProvider(); provider.HasMatchingPattern(new ProfileItem(profileItem), ProfilingTypes.Active).Should().BeFalse(); } } } [Theory] [AutoProfileDbData] public void HasMatchingPattern_TrackerReturnsProfileWithoutID_ShouldReturnFalse([Content] Item profileItem, CurrentInteraction currentInteraction, ITracker tracker, Profile profile) { tracker.Interaction.Returns(currentInteraction); currentInteraction.Profiles[null].ReturnsForAnyArgs(profile); profile.PatternId = null; var fakeSiteContext = new FakeSiteContext("fake") { Database = Database.GetDatabase("master") }; using (new TrackerSwitcher(tracker)) { using (new SiteContextSwitcher(fakeSiteContext)) { var provider = new ProfileProvider(); provider.HasMatchingPattern(new ProfileItem(profileItem), ProfilingTypes.Active).Should().BeFalse(); } } } [Theory] [AutoProfileDbData] public void HasMatchingPattern_HistoricProfileProfileNotExitsts_ReturnFalse([Content] Item profileItem, Contact contact, ITracker tracker, Profile profile) { //Arrange tracker.Contact.Returns(contact); contact.BehaviorProfiles[Arg.Is(profileItem.ID)].Returns(x => null); var fakeSiteContext = new FakeSiteContext("fake") { Database = Database.GetDatabase("master") }; //Act using (new TrackerSwitcher(tracker)) { using (new SiteContextSwitcher(fakeSiteContext)) { var provider = new ProfileProvider(); var result = provider.HasMatchingPattern(new ProfileItem(profileItem), ProfilingTypes.Historic); //Assert result.Should().BeFalse(); } } } [Theory] [AutoProfileDbData] public void HasMatchingPattern_HistoricProfileAndItemExists_ShouldReturnTrue([Content] Item profileItem, Contact contact, ITracker tracker, Profile profile) { //Arrange tracker.Contact.Returns(contact); var behaviorPattern = Substitute.For<IBehaviorProfileContext>(); behaviorPattern.PatternId.Returns(profileItem.ID); contact.BehaviorProfiles[Arg.Is(profileItem.ID)].Returns(behaviorPattern); var pattern = profileItem.Add("fakePattern", new TemplateID(PatternCardItem.TemplateID)); profile.PatternId = pattern.ID.Guid; var fakeSiteContext = new FakeSiteContext("fake") { Database = Database.GetDatabase("master") }; using (new TrackerSwitcher(tracker)) { using (new SiteContextSwitcher(fakeSiteContext)) { var provider = new ProfileProvider(); provider.HasMatchingPattern(new ProfileItem(profileItem), ProfilingTypes.Historic).Should().BeTrue(); } } } [Theory] [AutoDbData] public void GetPatternsWithGravityShare_NullProfile_ThrowArgumentNullException(ProfilingTypes profilingTypes, ProfileProvider profileProvider) { //Act profileProvider.Invoking(x => x.GetPatternsWithGravityShare(null, profilingTypes)).ShouldThrow<ArgumentNullException>(); } } }
// 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.Reflection; using System.CommandLine; using System.Runtime.InteropServices; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; using Internal.CommandLine; namespace ILCompiler { internal class Program { private Dictionary<string, string> _inputFilePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private Dictionary<string, string> _referenceFilePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private string _outputFilePath; private bool _isCppCodegen; private bool _isVerbose; private string _dgmlLogFileName; private bool _generateFullDgmlLog; private string _scanDgmlLogFileName; private bool _generateFullScanDgmlLog; private TargetArchitecture _targetArchitecture; private string _targetArchitectureStr; private TargetOS _targetOS; private string _targetOSStr; private OptimizationMode _optimizationMode; private bool _enableDebugInfo; private string _systemModuleName = "System.Private.CoreLib"; private bool _multiFile; private bool _useSharedGenerics; private bool _useScanner; private string _mapFileName; private string _metadataLogFileName; private string _singleMethodTypeName; private string _singleMethodName; private IReadOnlyList<string> _singleMethodGenericArgs; private IReadOnlyList<string> _codegenOptions = Array.Empty<string>(); private IReadOnlyList<string> _rdXmlFilePaths = Array.Empty<string>(); private bool _help; private Program() { } private void Help(string helpText) { Console.WriteLine(); Console.Write("Microsoft (R) .NET Native IL Compiler"); Console.Write(" "); Console.Write(typeof(Program).GetTypeInfo().Assembly.GetName().Version); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(helpText); } private void InitializeDefaultOptions() { // We could offer this as a command line option, but then we also need to // load a different RyuJIT, so this is a future nice to have... if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) _targetOS = TargetOS.Windows; else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) _targetOS = TargetOS.Linux; else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) _targetOS = TargetOS.OSX; else throw new NotImplementedException(); switch (RuntimeInformation.ProcessArchitecture) { case Architecture.X86: _targetArchitecture = TargetArchitecture.X86; break; case Architecture.X64: _targetArchitecture = TargetArchitecture.X64; break; case Architecture.Arm: _targetArchitecture = TargetArchitecture.ARM; break; case Architecture.Arm64: _targetArchitecture = TargetArchitecture.ARM64; break; default: throw new NotImplementedException(); } } private ArgumentSyntax ParseCommandLine(string[] args) { IReadOnlyList<string> inputFiles = Array.Empty<string>(); IReadOnlyList<string> referenceFiles = Array.Empty<string>(); bool optimize = false; bool waitForDebugger = false; AssemblyName name = typeof(Program).GetTypeInfo().Assembly.GetName(); ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax => { syntax.ApplicationName = name.Name.ToString(); // HandleHelp writes to error, fails fast with crash dialog and lacks custom formatting. syntax.HandleHelp = false; syntax.HandleErrors = true; syntax.DefineOption("h|help", ref _help, "Help message for ILC"); syntax.DefineOptionList("r|reference", ref referenceFiles, "Reference file(s) for compilation"); syntax.DefineOption("o|out", ref _outputFilePath, "Output file path"); syntax.DefineOption("O", ref optimize, "Enable optimizations"); syntax.DefineOption("g", ref _enableDebugInfo, "Emit debugging information"); syntax.DefineOption("cpp", ref _isCppCodegen, "Compile for C++ code-generation"); syntax.DefineOption("dgmllog", ref _dgmlLogFileName, "Save result of dependency analysis as DGML"); syntax.DefineOption("fulllog", ref _generateFullDgmlLog, "Save detailed log of dependency analysis"); syntax.DefineOption("scandgmllog", ref _scanDgmlLogFileName, "Save result of scanner dependency analysis as DGML"); syntax.DefineOption("scanfulllog", ref _generateFullScanDgmlLog, "Save detailed log of scanner dependency analysis"); syntax.DefineOption("verbose", ref _isVerbose, "Enable verbose logging"); syntax.DefineOption("systemmodule", ref _systemModuleName, "System module name (default: System.Private.CoreLib)"); syntax.DefineOption("multifile", ref _multiFile, "Compile only input files (do not compile referenced assemblies)"); syntax.DefineOption("waitfordebugger", ref waitForDebugger, "Pause to give opportunity to attach debugger"); syntax.DefineOption("usesharedgenerics", ref _useSharedGenerics, "Enable shared generics"); syntax.DefineOptionList("codegenopt", ref _codegenOptions, "Define a codegen option"); syntax.DefineOptionList("rdxml", ref _rdXmlFilePaths, "RD.XML file(s) for compilation"); syntax.DefineOption("map", ref _mapFileName, "Generate a map file"); syntax.DefineOption("metadatalog", ref _metadataLogFileName, "Generate a metadata log file"); syntax.DefineOption("scan", ref _useScanner, "Use IL scanner to generate optimized code"); syntax.DefineOption("targetarch", ref _targetArchitectureStr, "Target architecture for cross compilation"); syntax.DefineOption("targetos", ref _targetOSStr, "Target OS for cross compilation"); syntax.DefineOption("singlemethodtypename", ref _singleMethodTypeName, "Single method compilation: name of the owning type"); syntax.DefineOption("singlemethodname", ref _singleMethodName, "Single method compilation: name of the method"); syntax.DefineOptionList("singlemethodgenericarg", ref _singleMethodGenericArgs, "Single method compilation: generic arguments to the method"); syntax.DefineParameterList("in", ref inputFiles, "Input file(s) to compile"); }); if (waitForDebugger) { Console.WriteLine("Waiting for debugger to attach. Press ENTER to continue"); Console.ReadLine(); } _optimizationMode = optimize ? OptimizationMode.Blended : OptimizationMode.None; foreach (var input in inputFiles) Helpers.AppendExpandedPaths(_inputFilePaths, input, true); foreach (var reference in referenceFiles) Helpers.AppendExpandedPaths(_referenceFilePaths, reference, false); return argSyntax; } private int Run(string[] args) { InitializeDefaultOptions(); ArgumentSyntax syntax = ParseCommandLine(args); if (_help) { Help(syntax.GetHelpText()); return 1; } if (_outputFilePath == null) throw new CommandLineException("Output filename must be specified (/out <file>)"); // // Set target Architecture and OS // if (_targetArchitectureStr != null) { if (_targetArchitectureStr.Equals("x86", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.X86; else if (_targetArchitectureStr.Equals("x64", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.X64; else if (_targetArchitectureStr.Equals("arm", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.ARM; else if (_targetArchitectureStr.Equals("armel", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.ARMEL; else if (_targetArchitectureStr.Equals("arm64", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.ARM64; else throw new CommandLineException("Target architecture is not supported"); } if (_targetOSStr != null) { if (_targetOSStr.Equals("windows", StringComparison.OrdinalIgnoreCase)) _targetOS = TargetOS.Windows; else if (_targetOSStr.Equals("linux", StringComparison.OrdinalIgnoreCase)) _targetOS = TargetOS.Linux; else if (_targetOSStr.Equals("osx", StringComparison.OrdinalIgnoreCase)) _targetOS = TargetOS.OSX; else throw new CommandLineException("Target OS is not supported"); } // // Initialize type system context // SharedGenericsMode genericsMode = _useSharedGenerics || !_isCppCodegen ? SharedGenericsMode.CanonicalReferenceTypes : SharedGenericsMode.Disabled; // TODO: compiler switch for SIMD support? var simdVectorLength = _isCppCodegen ? SimdVectorLength.None : SimdVectorLength.Vector128Bit; var targetDetails = new TargetDetails(_targetArchitecture, _targetOS, TargetAbi.CoreRT, simdVectorLength); var typeSystemContext = new CompilerTypeSystemContext(targetDetails, genericsMode); // // TODO: To support our pre-compiled test tree, allow input files that aren't managed assemblies since // some tests contain a mixture of both managed and native binaries. // // See: https://github.com/dotnet/corert/issues/2785 // // When we undo this this hack, replace this foreach with // typeSystemContext.InputFilePaths = _inputFilePaths; // Dictionary<string, string> inputFilePaths = new Dictionary<string, string>(); foreach (var inputFile in _inputFilePaths) { try { var module = typeSystemContext.GetModuleFromPath(inputFile.Value); inputFilePaths.Add(inputFile.Key, inputFile.Value); } catch (TypeSystemException.BadImageFormatException) { // Keep calm and carry on. } } typeSystemContext.InputFilePaths = inputFilePaths; typeSystemContext.ReferenceFilePaths = _referenceFilePaths; typeSystemContext.SetSystemModule(typeSystemContext.GetModuleForSimpleName(_systemModuleName)); if (typeSystemContext.InputFilePaths.Count == 0) throw new CommandLineException("No input files specified"); // // Initialize compilation group and compilation roots // // Single method mode? MethodDesc singleMethod = CheckAndParseSingleMethodModeArguments(typeSystemContext); CompilationModuleGroup compilationGroup; List<ICompilationRootProvider> compilationRoots = new List<ICompilationRootProvider>(); if (singleMethod != null) { // Compiling just a single method compilationGroup = new SingleMethodCompilationModuleGroup(singleMethod); compilationRoots.Add(new SingleMethodRootProvider(singleMethod)); } else { // Either single file, or multifile library, or multifile consumption. EcmaModule entrypointModule = null; foreach (var inputFile in typeSystemContext.InputFilePaths) { EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); if (module.PEReader.PEHeaders.IsExe) { if (entrypointModule != null) throw new Exception("Multiple EXE modules"); entrypointModule = module; } compilationRoots.Add(new ExportedMethodsRootProvider(module)); } if (entrypointModule != null) { LibraryInitializers libraryInitializers = new LibraryInitializers(typeSystemContext, _isCppCodegen); compilationRoots.Add(new MainMethodRootProvider(entrypointModule, libraryInitializers.LibraryInitializerMethods)); } if (_multiFile) { List<EcmaModule> inputModules = new List<EcmaModule>(); foreach (var inputFile in typeSystemContext.InputFilePaths) { EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); if (entrypointModule == null) { // This is a multifile production build - we need to root all methods compilationRoots.Add(new LibraryRootProvider(module)); } inputModules.Add(module); } compilationGroup = new MultiFileSharedCompilationModuleGroup(typeSystemContext, inputModules); } else { if (entrypointModule == null) throw new Exception("No entrypoint module"); compilationRoots.Add(new ExportedMethodsRootProvider((EcmaModule)typeSystemContext.SystemModule)); compilationGroup = new SingleFileCompilationModuleGroup(typeSystemContext); } foreach (var rdXmlFilePath in _rdXmlFilePaths) { compilationRoots.Add(new RdXmlRootProvider(typeSystemContext, rdXmlFilePath)); } } // // Compile // CompilationBuilder builder; if (_isCppCodegen) builder = new CppCodegenCompilationBuilder(typeSystemContext, compilationGroup); else builder = new RyuJitCompilationBuilder(typeSystemContext, compilationGroup); ILScanResults scanResults = null; if (_useScanner && !_isCppCodegen) { ILScannerBuilder scannerBuilder = builder.GetILScannerBuilder() .UseCompilationRoots(compilationRoots); if (_scanDgmlLogFileName != null) scannerBuilder.UseDependencyTracking(_generateFullScanDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First); IILScanner scanner = scannerBuilder.ToILScanner(); scanResults = scanner.Scan(); } var logger = _isVerbose ? new Logger(Console.Out, true) : Logger.Null; DependencyTrackingLevel trackingLevel = _dgmlLogFileName == null ? DependencyTrackingLevel.None : (_generateFullDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First); CompilerGeneratedMetadataManager metadataManager = new CompilerGeneratedMetadataManager(compilationGroup, typeSystemContext, _metadataLogFileName); builder .UseBackendOptions(_codegenOptions) .UseMetadataManager(metadataManager) .UseLogger(logger) .UseDependencyTracking(trackingLevel) .UseCompilationRoots(compilationRoots) .UseOptimizationMode(_optimizationMode) .UseDebugInfo(_enableDebugInfo); if (scanResults != null) { // If we have a scanner, feed the vtable analysis results to the compilation. // This could be a command line switch if we really wanted to. builder.UseVTableSliceProvider(scanResults.GetVTableLayoutInfo()); // If we have a scanner, feed the generic dictionary results to the compilation. // This could be a command line switch if we really wanted to. builder.UseGenericDictionaryLayoutProvider(scanResults.GetDictionaryLayoutInfo()); } ICompilation compilation = builder.ToCompilation(); ObjectDumper dumper = _mapFileName != null ? new ObjectDumper(_mapFileName) : null; CompilationResults compilationResults = compilation.Compile(_outputFilePath, dumper); if (_dgmlLogFileName != null) compilationResults.WriteDependencyLog(_dgmlLogFileName); if (scanResults != null) { SimdHelper simdHelper = new SimdHelper(); if (_scanDgmlLogFileName != null) scanResults.WriteDependencyLog(_scanDgmlLogFileName); // If the scanner and compiler don't agree on what to compile, the outputs of the scanner might not actually be usable. // We are going to check this two ways: // 1. The methods and types generated during compilation are a subset of method and types scanned // 2. The methods and types scanned are a subset of methods and types compiled (this has a chance to hold for unoptimized builds only). // Check that methods and types generated during compilation are a subset of method and types scanned bool scanningFail = false; DiffCompilationResults(ref scanningFail, compilationResults.CompiledMethodBodies, scanResults.CompiledMethodBodies, "Methods", "compiled", "scanned", method => !(method.GetTypicalMethodDefinition() is EcmaMethod)); DiffCompilationResults(ref scanningFail, compilationResults.ConstructedEETypes, scanResults.ConstructedEETypes, "EETypes", "compiled", "scanned", type => !(type.GetTypeDefinition() is EcmaType)); // If optimizations are enabled, the results will for sure not match in the other direction due to inlining, etc. // But there's at least some value in checking the scanner doesn't expand the universe too much in debug. if (_optimizationMode == OptimizationMode.None) { // Check that methods and types scanned are a subset of methods and types compiled // If we find diffs here, they're not critical, but still might be causing a Size on Disk regression. bool dummy = false; // We additionally skip methods in SIMD module because there's just too many intrisics to handle and IL scanner // doesn't expand them. They would show up as noisy diffs. DiffCompilationResults(ref dummy, scanResults.CompiledMethodBodies, compilationResults.CompiledMethodBodies, "Methods", "scanned", "compiled", method => !(method.GetTypicalMethodDefinition() is EcmaMethod) || simdHelper.IsInSimdModule(method.OwningType)); DiffCompilationResults(ref dummy, scanResults.ConstructedEETypes, compilationResults.ConstructedEETypes, "EETypes", "scanned", "compiled", type => !(type.GetTypeDefinition() is EcmaType)); } if (scanningFail) throw new Exception("Scanning failure"); } return 0; } [System.Diagnostics.Conditional("DEBUG")] private void DiffCompilationResults<T>(ref bool result, IEnumerable<T> set1, IEnumerable<T> set2, string prefix, string set1name, string set2name, Predicate<T> filter) { HashSet<T> diff = new HashSet<T>(set1); diff.ExceptWith(set2); // TODO: move ownership of compiler-generated entities to CompilerTypeSystemContext. // https://github.com/dotnet/corert/issues/3873 diff.RemoveWhere(filter); if (diff.Count > 0) { result = true; Console.WriteLine($"*** {prefix} {set1name} but not {set2name}:"); foreach (var d in diff) { Console.WriteLine(d.ToString()); } } } private TypeDesc FindType(CompilerTypeSystemContext context, string typeName) { ModuleDesc systemModule = context.SystemModule; TypeDesc foundType = systemModule.GetTypeByCustomAttributeTypeName(typeName); if (foundType == null) throw new CommandLineException($"Type '{typeName}' not found"); TypeDesc classLibCanon = systemModule.GetType("System", "__Canon", false); TypeDesc classLibUniCanon = systemModule.GetType("System", "__UniversalCanon", false); return foundType.ReplaceTypesInConstructionOfType( new TypeDesc[] { classLibCanon, classLibUniCanon }, new TypeDesc[] { context.CanonType, context.UniversalCanonType }); } private MethodDesc CheckAndParseSingleMethodModeArguments(CompilerTypeSystemContext context) { if (_singleMethodName == null && _singleMethodTypeName == null && _singleMethodGenericArgs == null) return null; if (_singleMethodName == null || _singleMethodTypeName == null) throw new CommandLineException("Both method name and type name are required parameters for single method mode"); TypeDesc owningType = FindType(context, _singleMethodTypeName); // TODO: allow specifying signature to distinguish overloads MethodDesc method = owningType.GetMethod(_singleMethodName, null); if (method == null) throw new CommandLineException($"Method '{_singleMethodName}' not found in '{_singleMethodTypeName}'"); if (method.HasInstantiation != (_singleMethodGenericArgs != null) || (method.HasInstantiation && (method.Instantiation.Length != _singleMethodGenericArgs.Count))) { throw new CommandLineException( $"Expected {method.Instantiation.Length} generic arguments for method '{_singleMethodName}' on type '{_singleMethodTypeName}'"); } if (method.HasInstantiation) { List<TypeDesc> genericArguments = new List<TypeDesc>(); foreach (var argString in _singleMethodGenericArgs) genericArguments.Add(FindType(context, argString)); method = method.MakeInstantiatedMethod(genericArguments.ToArray()); } return method; } private static int Main(string[] args) { #if DEBUG return new Program().Run(args); #else try { return new Program().Run(args); } catch (Exception e) { Console.Error.WriteLine("Error: " + e.Message); Console.Error.WriteLine(e.ToString()); return 1; } #endif } } }
// // Layout.cs // // Author: // Stephane Delcroix <stephane@delcroix.org> // // Copyright (C) 2009 Novell, Inc. // Copyright (C) 2009 Stephane Delcroix // // 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 Hyena; namespace FSpot.Widgets { public class Layout : Gtk.Container { public Layout () : this (null, null) { } public Layout (Gtk.Adjustment hadjustment, Gtk.Adjustment vadjustment) : base () { OnSetScrollAdjustments (hadjustment, vadjustment); children = new List<LayoutChild> (); } Gdk.Window bin_window = null; public Gdk.Window BinWindow { get { return bin_window; } } Gtk.Adjustment hadjustment; public Gtk.Adjustment Hadjustment { get { return hadjustment; } set { OnSetScrollAdjustments (hadjustment, Vadjustment); } } Gtk.Adjustment vadjustment; public Gtk.Adjustment Vadjustment { get { return vadjustment; } set { OnSetScrollAdjustments (Hadjustment, vadjustment); } } uint width = 100; public uint Width { get { return width; } } uint height = 100; public uint Height { get { return height; } } class LayoutChild { public Gtk.Widget Widget { get; private set; } public int X { get; set; } public int Y { get; set; } public LayoutChild (Gtk.Widget widget, int x, int y) { Widget = widget; X = x; Y = y; } } List<LayoutChild> children; public void Put (Gtk.Widget widget, int x, int y) { children.Add (new LayoutChild (widget, x, y)); if (IsRealized) widget.ParentWindow = bin_window; widget.Parent = this; } public void Move (Gtk.Widget widget, int x, int y) { LayoutChild child = GetChild (widget); if (child == null) return; child.X = x; child.Y = y; if (Visible && widget.Visible) QueueResize (); } public void SetSize (uint width, uint height) { Hadjustment.Upper = this.width = width; Vadjustment.Upper = this.height = height; if (IsRealized) { bin_window.Resize ((int)Math.Max (width, Allocation.Width), (int)Math.Max (height, Allocation.Height)); } } LayoutChild GetChild (Gtk.Widget widget) { foreach (var child in children) if (child.Widget == widget) return child; return null; } #region widgetry protected override void OnRealized () { SetFlag (Gtk.WidgetFlags.Realized); Gdk.WindowAttr attributes = new Gdk.WindowAttr { WindowType = Gdk.WindowType.Child, X = Allocation.X, Y = Allocation.Y, Width = Allocation.Width, Height = Allocation.Height, Wclass = Gdk.WindowClass.InputOutput, Visual = this.Visual, Colormap = this.Colormap, Mask = Gdk.EventMask.VisibilityNotifyMask }; GdkWindow = new Gdk.Window (ParentWindow, attributes, Gdk.WindowAttributesType.X | Gdk.WindowAttributesType.Y | Gdk.WindowAttributesType.Visual | Gdk.WindowAttributesType.Colormap); GdkWindow.SetBackPixmap (null, false); GdkWindow.UserData = Handle; attributes = new Gdk.WindowAttr { WindowType = Gdk.WindowType.Child, X = (int)-Hadjustment.Value, Y = (int)-Vadjustment.Value, Width = (int)Math.Max (width, Allocation.Width), Height = (int)Math.Max (height, Allocation.Height), Wclass = Gdk.WindowClass.InputOutput, Visual = this.Visual, Colormap = this.Colormap, Mask = Gdk.EventMask.ExposureMask | Gdk.EventMask.ScrollMask | this.Events }; bin_window = new Gdk.Window (GdkWindow, attributes, Gdk.WindowAttributesType.X | Gdk.WindowAttributesType.Y | Gdk.WindowAttributesType.Visual | Gdk.WindowAttributesType.Colormap); bin_window.UserData = Handle; Style.Attach (GdkWindow); Style.SetBackground (bin_window, Gtk.StateType.Normal); foreach (var child in children) { child.Widget.ParentWindow = bin_window; } } protected override void OnUnrealized () { bin_window.Destroy (); bin_window = null; base.OnUnrealized (); } protected override void OnStyleSet (Gtk.Style old_style) { base.OnStyleSet (old_style); if (IsRealized) Style.SetBackground (bin_window, Gtk.StateType.Normal); } protected override void OnMapped () { SetFlag (Gtk.WidgetFlags.Mapped); foreach (var child in children) { if (child.Widget.Visible && !child.Widget.IsMapped) child.Widget.Map (); } bin_window.Show (); GdkWindow.Show (); } protected override void OnSizeRequested (ref Gtk.Requisition requisition) { requisition.Width = requisition.Height = 0; foreach (var child in children) { child.Widget.SizeRequest (); } } protected override void OnSizeAllocated (Gdk.Rectangle allocation) { foreach (var child in children) { Gtk.Requisition req = child.Widget.ChildRequisition; child.Widget.SizeAllocate (new Gdk.Rectangle (child.X, child.Y, req.Width, req.Height)); } if (IsRealized) { GdkWindow.MoveResize (allocation.X, allocation.Y, allocation.Width, allocation.Height); bin_window.Resize ((int)Math.Max (width, allocation.Width), (int)Math.Max (height, allocation.Height)); } Hadjustment.PageSize = allocation.Width; Hadjustment.PageIncrement = Width * .9; Hadjustment.Lower = 0; Hadjustment.Upper = Math.Max (width, allocation.Width); Vadjustment.PageSize = allocation.Height; Vadjustment.PageIncrement = Height * .9; Vadjustment.Lower = 0; Vadjustment.Upper = Math.Max (height, allocation.Height); base.OnSizeAllocated (allocation); } protected override bool OnExposeEvent (Gdk.EventExpose evnt) { if (evnt.Window != bin_window) return false; return base.OnExposeEvent (evnt); } protected override void OnSetScrollAdjustments (Gtk.Adjustment hadjustment, Gtk.Adjustment vadjustment) { Log.Debug ("\n\nLayout.OnSetScrollAdjustments"); if (hadjustment == null) hadjustment = new Gtk.Adjustment (0, 0, 0, 0, 0, 0); if (vadjustment == null) vadjustment = new Gtk.Adjustment (0, 0, 0, 0, 0, 0); bool need_change = false; if (Hadjustment != hadjustment) { this.hadjustment = hadjustment; this.hadjustment.Upper = Width; this.hadjustment.ValueChanged += HandleAdjustmentsValueChanged; need_change = true; } if (Vadjustment != vadjustment) { this.vadjustment = vadjustment; this.vadjustment.Upper = Width; this.vadjustment.ValueChanged += HandleAdjustmentsValueChanged; need_change = true; } if (need_change) HandleAdjustmentsValueChanged (this, EventArgs.Empty); } void HandleAdjustmentsValueChanged (object sender, EventArgs e) { if (IsRealized) bin_window.Move (-(int)Hadjustment.Value, -(int)Vadjustment.Value); } #endregion widgetry #region container stuffs protected override void OnAdded (Gtk.Widget widget) { Put (widget, 0, 0); } protected override void OnRemoved (Gtk.Widget widget) { LayoutChild child = null; foreach (var c in children) { if (child.Widget == widget) { child = c; break; } } if (child != null) { widget.Unparent (); children.Remove (child); } } protected override void ForAll (bool include_internals, Gtk.Callback callback) { foreach (var child in children) { callback (child.Widget); } } #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. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.IO { internal class MultiplexingWin32WinRTFileSystem : FileSystem { private readonly FileSystem _win32FileSystem = new Win32FileSystem(); private readonly FileSystem _winRTFileSystem = new WinRTFileSystem(); internal static IFileSystemObject GetFileSystemObject(FileSystemInfo caller, string fullPath) { return ShouldUseWinRT(fullPath, isCreate: false) ? (IFileSystemObject)new WinRTFileSystem.WinRTFileSystemObject(fullPath, asDirectory: caller is DirectoryInfo) : (IFileSystemObject)caller; } public override int MaxPath { get { return Interop.mincore.MAX_PATH; } } public override int MaxDirectoryPath { get { return Interop.mincore.MAX_DIRECTORY_PATH; } } public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite) { Select(sourceFullPath, destFullPath).CopyFile(sourceFullPath, destFullPath, overwrite); } public override void ReplaceFile(string sourceFullPath, string destFullPath, string destBackupFullPath, bool ignoreMetadataErrors) { Select(sourceFullPath, destFullPath, destBackupFullPath).ReplaceFile(sourceFullPath, destFullPath, destBackupFullPath, ignoreMetadataErrors); } public override void CreateDirectory(string fullPath) { Select(fullPath, isCreate: true).CreateDirectory(fullPath); } public override void DeleteFile(string fullPath) { Select(fullPath).DeleteFile(fullPath); } public override bool DirectoryExists(string fullPath) { return Select(fullPath).DirectoryExists(fullPath); } public override Collections.Generic.IEnumerable<string> EnumeratePaths(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { return Select(fullPath).EnumeratePaths(fullPath, searchPattern, searchOption, searchTarget); } public override Collections.Generic.IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { return Select(fullPath).EnumerateFileSystemInfos(fullPath, searchPattern, searchOption, searchTarget); } public override bool FileExists(string fullPath) { return Select(fullPath).FileExists(fullPath); } public override FileAttributes GetAttributes(string fullPath) { return Select(fullPath).GetAttributes(fullPath); } public override DateTimeOffset GetCreationTime(string fullPath) { return Select(fullPath).GetCreationTime(fullPath); } public override string GetCurrentDirectory() { // WinRT honors the Win32 current directory, but does not expose it, // so we use the Win32 implementation always. return _win32FileSystem.GetCurrentDirectory(); } public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory) { return Select(fullPath).GetFileSystemInfo(fullPath, asDirectory); } public override DateTimeOffset GetLastAccessTime(string fullPath) { return Select(fullPath).GetLastAccessTime(fullPath); } public override DateTimeOffset GetLastWriteTime(string fullPath) { return Select(fullPath).GetLastWriteTime(fullPath); } public override void MoveDirectory(string sourceFullPath, string destFullPath) { Select(sourceFullPath, destFullPath).MoveDirectory(sourceFullPath, destFullPath); } public override void MoveFile(string sourceFullPath, string destFullPath) { Select(sourceFullPath, destFullPath).MoveFile(sourceFullPath, destFullPath); } public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent) { bool isCreate = mode != FileMode.Open && mode != FileMode.Truncate; return Select(fullPath, isCreate).Open(fullPath, mode, access, share, bufferSize, options, parent); } public override void RemoveDirectory(string fullPath, bool recursive) { Select(fullPath).RemoveDirectory(fullPath, recursive); } public override void SetAttributes(string fullPath, FileAttributes attributes) { Select(fullPath).SetAttributes(fullPath, attributes); } public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory) { Select(fullPath).SetCreationTime(fullPath, time, asDirectory); } public override void SetCurrentDirectory(string fullPath) { // WinRT honors the Win32 current directory, but does not expose it, // so we use the Win32 implementation always. // This will throw UnauthorizedAccess on brokered paths. _win32FileSystem.SetCurrentDirectory(fullPath); } public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory) { Select(fullPath).SetLastAccessTime(fullPath, time, asDirectory); } public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory) { Select(fullPath).SetLastWriteTime(fullPath, time, asDirectory); } private FileSystem Select(string fullPath, bool isCreate = false) { return ShouldUseWinRT(fullPath, isCreate) ? _winRTFileSystem : _win32FileSystem; } private FileSystem Select(string sourceFullPath, string destFullPath) { return (ShouldUseWinRT(sourceFullPath, isCreate: false) || ShouldUseWinRT(destFullPath, isCreate: true)) ? _winRTFileSystem : _win32FileSystem; } private FileSystem Select(string sourceFullPath, string destFullPath, string destFullBackupPath) { return (ShouldUseWinRT(sourceFullPath, isCreate: false) || ShouldUseWinRT(destFullPath, isCreate: true) || ShouldUseWinRT(destFullBackupPath, isCreate: true)) ? _winRTFileSystem : _win32FileSystem; } public override string[] GetLogicalDrives() { // This API is always blocked on WinRT, don't use Win32 return _winRTFileSystem.GetLogicalDrives(); } private static bool ShouldUseWinRT(string fullPath, bool isCreate) { // The purpose of this method is to determine if we can access a path // via Win32 or if we need to fallback to WinRT. // We prefer Win32 since it is faster, WinRT's APIs eventually just // call into Win32 after all, but it doesn't provide access to, // brokered paths (like Pictures or Documents) nor does it handle // placeholder files. So we'd like to fall back to WinRT whenever // we can't access a path, or if it known to be a placeholder file. bool useWinRt = false; do { // first use GetFileAttributesEx as it is faster than FindFirstFile and requires minimum permissions Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA(); if (Interop.mincore.GetFileAttributesEx(fullPath, Interop.mincore.GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, ref data)) { // got the attributes if ((data.fileAttributes & Interop.mincore.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) != 0 || (data.fileAttributes & Interop.mincore.FileAttributes.FILE_ATTRIBUTE_REPARSE_POINT) == 0) { // we have a directory or a file that is not a reparse point // useWinRt = false; break; } else { // we need to get the find data to determine if it is a placeholder file Interop.mincore.WIN32_FIND_DATA findData = new Interop.mincore.WIN32_FIND_DATA(); using (SafeFindHandle handle = Interop.mincore.FindFirstFile(fullPath, ref findData)) { if (!handle.IsInvalid) { // got the find data, use WinRT for placeholder files Debug.Assert((findData.dwFileAttributes & Interop.mincore.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) == 0); Debug.Assert((findData.dwFileAttributes & Interop.mincore.FileAttributes.FILE_ATTRIBUTE_REPARSE_POINT) != 0); useWinRt = findData.dwReserved0 == Interop.mincore.IOReparseOptions.IO_REPARSE_TAG_FILE_PLACEHOLDER; break; } } } } int error = Marshal.GetLastWin32Error(); Debug.Assert(error != Interop.mincore.Errors.ERROR_SUCCESS); if (error == Interop.mincore.Errors.ERROR_ACCESS_DENIED) { // The path was not accessible with Win32, so try WinRT useWinRt = true; break; } else if (error != Interop.mincore.Errors.ERROR_PATH_NOT_FOUND && error != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND) { // We hit some error other than ACCESS_DENIED or NOT_FOUND, // Default to Win32 to provide most accurate error behavior break; } // error was ERROR_PATH_NOT_FOUND or ERROR_FILE_NOT_FOUND // if we are creating a file/directory we cannot assume that Win32 will have access to // the parent directory, so we walk up the path. fullPath = PathHelpers.GetDirectoryNameInternal(fullPath); // only walk up the path if we are creating a file/directory and not at the root } while (isCreate && !String.IsNullOrEmpty(fullPath)); return useWinRt; } } }
/* * Copyright 2007-2015 JetBrains * * 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.Collections.Generic; using System.Linq; using JetBrains.Application.Settings; using JetBrains.DocumentModel; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.ControlFlow; using JetBrains.ReSharper.Psi.CSharp.Tree; using JetBrains.ReSharper.Psi.JavaScript.Tree; using JetBrains.ReSharper.Psi.Tree; using JetBrains.UI.RichText; using JetBrains.Util; #if RIDER using JetBrains.Rider.Backend.Platform.Icons; #endif namespace JetBrains.ReSharper.Plugins.CyclomaticComplexity { [ElementProblemAnalyzer(typeof(ITreeNode))] public class ComplexityAnalysisElementProblemAnalyzer : ElementProblemAnalyzer<ITreeNode> { private readonly Key<State> key = new Key<State>("ComplexityAnalyzerState"); #if RIDER private readonly ComplexityCodeInsightsProvider _provider; private readonly IconHost _iconHost; public ComplexityAnalysisElementProblemAnalyzer(ComplexityCodeInsightsProvider provider, IconHost iconHost) { _provider = provider; _iconHost = iconHost; } #endif protected override void Run(ITreeNode element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer) { // We get a fresh data for each file, so we can cache some state to make // things a bit more efficient var state = data.GetOrCreateDataUnderLock(key, () => new State { ControlFlowBuilder = LanguageManager.Instance.TryGetService<IControlFlowBuilder>(element.Language), Threshold = GetThreshold(data, element.Language) }); if (state.ControlFlowBuilder == null || !state.ControlFlowBuilder.CanBuildFrom(element)) return; // We can build control flow information for a JS file section (e.g. inline event handlers, or <src> // elements in html) and it would be nice to flag these up as being too complex, but there's nowhere // to put the warning - it highlights the whole section. Maybe that's ok for when we're over the threshold, // but it's definitely not ok for the info tooltip. if (element is IJavaScriptFileSection) return; var graph = data.GetOrBuildControlFlowGraph(element); if (graph == null) return; var complexity = CalculateCyclomaticComplexity(graph); var documentRange = GetDocumentRange(element); if (complexity > state.Threshold) { consumer.AddHighlighting( new ComplexityWarningHighlight( GetMessage(element, complexity, state.Threshold), documentRange)); } #if !RIDER else consumer.AddHighlighting(new ComplexityInfoHighlight(GetMessage(element, complexity, state.Threshold), documentRange)); #else if (element is ITypeMemberDeclaration memberDeclaration && memberDeclaration.DeclaredElement != null) { var percentage = GetPercentage(complexity, state.Threshold); consumer.AddHighlighting(new ComplexityCodeInsightsHighlight( memberDeclaration, complexity, percentage, _provider, _iconHost)); } #endif } private static int GetThreshold(ElementProblemAnalyzerData data, PsiLanguageType language) { var threshold = data.SettingsStore.GetIndexedValue((CyclomaticComplexityAnalysisSettings s) => s.Thresholds, language.Name); return threshold < 1 ? CyclomaticComplexityAnalysisSettings.DefaultThreshold : threshold; } private static int CalculateCyclomaticComplexity(IControlFlowGraph graph) { var edges = GetEdges(graph); var nodeCount = GetNodeCount(edges); // Standard CC formula (edges - nodes + 2) return edges.Count - nodeCount + 2; } // ReSharper's C# graph treats boolean values as conditions, meaning we // get two (duplicate) edges from one node to the next. This comparer // will remove the duplicates. I.e. any edges that have the same source // and target are considered equal private class EdgeEqualityComparer : EqualityComparer<IControlFlowEdge> { public override bool Equals(IControlFlowEdge x, IControlFlowEdge y) { if (x == y) return true; if (x == null || y == null) return false; return x.Source == y.Source && x.Target == y.Target; } public override int GetHashCode(IControlFlowEdge obj) { var hashCode = 0; if (obj != null) { if (obj.Source != null) hashCode ^= obj.Source.GetHashCode(); if (obj.Target != null) hashCode ^= obj.Target.GetHashCode(); } return hashCode; } } private static HashSet<IControlFlowEdge> GetEdges(IControlFlowGraph graph) { var edges = new HashSet<IControlFlowEdge>(new EdgeEqualityComparer()); foreach (var element in graph.AllElements) { foreach (var edge in element.Exits) edges.Add(edge); foreach (var edge in element.Entries) edges.Add(edge); } return FudgeGraph(graph, edges); } private static HashSet<IControlFlowEdge> FudgeGraph(IControlFlowGraph graph, HashSet<IControlFlowEdge> edges) { // The C# graph treats the unary negation operator `!` as a conditional. It's not, // but having it so means that the CC can be way higher than it should be. var dodgyEdges = new HashSet<IControlFlowEdge>(new EdgeEqualityComparer()); // Look at all of the non-leaf elements (the graph is a tree as well as a graph. // The tree represents the structure of the code, with the control flow graph // running through it) foreach (var element in graph.AllElements.Where(e => e.Children.Count != 0)) { var unaryOperatorExpression = element.SourceElement as IUnaryOperatorExpression; if (unaryOperatorExpression != null && unaryOperatorExpression.UnaryOperatorType == UnaryOperatorType.EXCL) { // The unary operator shouldn't have 2 exits. It's not a conditional. If it does, // remove one of the edges, and it's path, from the collected edges. if (element.Exits.Count == 2) { var edge = element.Exits.FirstOrDefault(); do { dodgyEdges.Add(edge); // Get the source of the exit edge. This is the node in the control flow graph, // not the element in the program structure tree. var source = edge.Source; edge = null; // Walk back to the control flow graph node that represents the exit of the // dodgy condition, so keep going until we have an element with 2 exits. if (source.Entries.Count == 1 && source.Exits.Count == 1) edge = source.Entries.FirstOrDefault(); } while (edge != null); } } } edges.ExceptWith(dodgyEdges); return edges; } private static int GetNodeCount(IEnumerable<IControlFlowEdge> edges) { var hasNullDestination = false; var nodes = new HashSet<IControlFlowElement>(); foreach (var edge in edges) { nodes.Add(edge.Source); if (edge.Target != null) nodes.Add(edge.Target); else hasNullDestination = true; } return nodes.Count + (hasNullDestination ? 1 : 0); } private static string GetMessage(ITreeNode element, int complexity, int threshold) { var type = "Element"; IDeclaration declaration; GetBestTreeNode(element, out declaration); if (declaration?.DeclaredElement != null) { var declaredElement = declaration.DeclaredElement; var declarationType = DeclaredElementPresenter.Format(declaration.Language, DeclaredElementPresenter.KIND_PRESENTER, declaredElement); var declaredElementName = DeclaredElementPresenter.Format(declaration.Language, DeclaredElementPresenter.NAME_PRESENTER, declaredElement); type = $"{declarationType.Capitalize()} '{declaredElementName}'"; } return $"{type} has cyclomatic complexity of {complexity} ({GetPercentage(complexity, threshold)}% of threshold)"; } private static int GetPercentage(int complexity, int threshold) { return (int) (complexity*100.0/threshold); } private DocumentRange GetDocumentRange(ITreeNode element) { IDeclaration declaration; var node = GetBestTreeNode(element, out declaration); return declaration?.DeclaredElement != null ? declaration.GetNameDocumentRange() : node.GetDocumentRange(); } private static ITreeNode GetBestTreeNode(ITreeNode element, out IDeclaration declaration) { declaration = element as IDeclaration; if (declaration?.DeclaredElement != null) return element; // Don't have a declared element to highlight. Going to have to guess. Try the // first meaningful child return element.GetNextMeaningfulChild(null); } private class State { public IControlFlowBuilder ControlFlowBuilder; public int Threshold; } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation 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.Drawing; using System.IO; using System.Runtime.InteropServices; using System.Windows.Forms; using Microsoft.Build.BuildEngine; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Designer.Interfaces; using Microsoft.VisualStudio.Package; using Microsoft.VisualStudio.Package.Automation; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.Win32; using Microsoft.MultiverseInterfaceStudio.Services; using Utilities = Microsoft.VisualStudio.Package.Utilities; namespace Microsoft.MultiverseInterfaceStudio { /// <summary> /// Represents a project node in the Solution Explorer and controls its behavior. /// </summary> [Guid(GuidStrings.MultiverseInterfaceProjectNode)] public class MultiverseInterfaceProjectNode : ProjectNode { private const string MultiverseInterfacePathSubKey = @"SOFTWARE\MultiverseClient\Interface"; private const string MultiverseInterfacePathName = "InstallPath"; private const string MultiverseInterfacePathToken = "$multiversepath$"; private static ImageList multiverseImageList; private static int multiverseImageOffset; private MultiverseInterfaceProjectPackage package; static MultiverseInterfaceProjectNode() { // Get the image list from the embedded resource used by the Multiverse Interface project multiverseImageList = Utilities.GetImageList(typeof(MultiverseInterfaceProjectNode).Assembly.GetManifestResourceStream("Resources.multiverseImageList.bmp")); } /// <summary> /// Initializes a new instance of the <see cref="MultiverseInterfaceProjectNode"/> class. /// </summary> /// <param name="package">The package the project type resides in.</param> public MultiverseInterfaceProjectNode(MultiverseInterfaceProjectPackage package) { if (package == null) throw new ArgumentNullException("package"); this.package = package; // File nodes can have children (!) (think Frame XML has a Lua codebehind file) this.CanFileNodesHaveChilds = true; // Support the Project Designer Editor this.SupportsProjectDesigner = true; // Allow deleting items this.CanProjectDeleteItems = true; // Store the number of images before we add our own so we know the offset where we start multiverseImageOffset = base.ImageHandler.ImageList.Images.Count; // Add all images foreach (Image image in multiverseImageList.Images) { base.ImageHandler.AddImage(image); } } /// <summary> /// Gets the image list that contains the WoW icons for the nodes. /// </summary> public static ImageList MultiverseImageList { get { return multiverseImageList; } } /// <summary> /// Gets the index of the image to show for the project node. /// </summary> public override int ImageIndex { get { // We need to add the offset as we appended our own images to an existing image list. return multiverseImageOffset + (int)MultiverseInterfaceImage.MultiverseInterfaceProject; } } /// <summary> /// Gets the Guid of the project factory. /// </summary> public override Guid ProjectGuid { get { return typeof(MultiverseInterfaceProjectFactory).GUID; } } /// <summary> /// Gets the type of the project. /// </summary> public override string ProjectType { get { return this.GetType().Name; } } /// <summary> /// Loads a project file. Called from the factory CreateProject to load the project. /// </summary> /// <param name="fileName">File name of the project that will be created. </param> /// <param name="location">Location where the project will be created.</param> /// <param name="name">If applicable, the name of the template to use when cloning a new project.</param> /// <param name="flags">Set of flag values taken from the VSCREATEPROJFLAGS enumeration.</param> /// <param name="iidProject">Identifier of the interface that the caller wants returned. </param> /// <param name="canceled">An out parameter specifying if the project creation was canceled</param> public override void Load(string fileName, string location, string name, uint flags, ref Guid iidProject, out int canceled) { // Let MPF first deal with the tasks at hand base.Load(fileName, location, name, flags, ref iidProject, out canceled); // If this project was just created, set WoW path based on the registry if ((flags & (uint)__VSCREATEPROJFLAGS.CPF_CLONEFILE) == (uint)__VSCREATEPROJFLAGS.CPF_CLONEFILE) { this.SetProjectProperty(GeneralPropertyPageTag.MultiversePath.ToString(), this.GetMultiversePath()); } } /// <summary> /// Creates a file node for a project element. /// </summary> /// <param name="element">The project element.</param> /// <returns>An instance of the <see cref="FileNode"/> class.</returns> public override FileNode CreateFileNode(ProjectElement element) { if (element == null) throw new ArgumentNullException("element"); MultiverseInterfaceFileNode node = null; // Get the SubType for the project element. string subType = element.GetMetadata(ProjectFileConstants.SubType); switch (subType) { case MultiverseInterfaceSubType.Code: node = new MultiverseInterfacePythonFileNode(this, element); break; case MultiverseInterfaceSubType.Frame: node = new MultiverseInterfaceXmlFileNode(this, element); break; case MultiverseInterfaceSubType.TableOfContents: node = new MultiverseInterfaceTocFileNode(this, element); break; default: // We could not recognize the file subtype, just create a WowFileNode node = new MultiverseInterfaceFileNode(this, element); break; } // Check whether this file should be added to the language service if (subType == MultiverseInterfaceSubType.Frame || subType == MultiverseInterfaceSubType.Code) { IPythonLanguageService languageService = (IPythonLanguageService)this.GetService(typeof(IPythonLanguageService)); // Make sure the language service is available if (languageService != null) { switch (subType) { case MultiverseInterfaceSubType.Frame: languageService.AddFrameXmlFile(node.GetMkDocument()); break; case MultiverseInterfaceSubType.Code: languageService.AddPythonFile(node.GetMkDocument()); break; } } } return node; } /// <summary> /// Creates a file node for a project element. /// </summary> /// <param name="element">The project element.</param> /// <returns>An instance of the <see cref="DependentFileNode"/> class.</returns> public override DependentFileNode CreateDependentFileNode(ProjectElement element) { if (element == null) throw new ArgumentNullException("element"); string subType = element.GetMetadata(ProjectFileConstants.SubType); if (subType == MultiverseInterfaceSubType.Code) { DependentFileNode node = new MultiverseInterfaceIronPythonDependentFileNode(this, element); IPythonLanguageService languageService = (IPythonLanguageService)this.GetService(typeof(IPythonLanguageService)); // Make sure the language service is available if (languageService != null) languageService.AddPythonFile(node.GetMkDocument()); return node; } return base.CreateDependentFileNode(element); } /// <summary> /// Creates the reference container node. /// </summary> /// <returns></returns> protected override ReferenceContainerNode CreateReferenceContainerNode() { // Return null as we do not support references return null; } /// <summary> /// Removes a node from the hierarchy. /// </summary> /// <param name="node">The node to remove.</param> public override void RemoveChild(HierarchyNode node) { if (node is MultiverseInterfaceXmlFileNode || node is MultiverseInterfacePythonFileNode) { IPythonLanguageService languageService = (IPythonLanguageService)this.GetService(typeof(IPythonLanguageService)); if (languageService != null) { if (node is MultiverseInterfaceXmlFileNode) languageService.RemoveFrameXmlFile(node.GetMkDocument()); if (node is MultiverseInterfacePythonFileNode) languageService.RemovePythonFile(node.GetMkDocument()); } } base.RemoveChild(node); } /// <summary> /// Adds the new file node to hierarchy. /// </summary> /// <param name="parentNode">The parent node.</param> /// <param name="fileName">Name of the file.</param> protected override void AddNewFileNodeToHierarchy(HierarchyNode parentNode, string path) { // If a lua file is being added, try to find a related FrameXML node if (MultiverseInterfaceProjectNode.IsPythonFile(path)) { // Try to find a FrameXML node with a matching relational name string fileName = Path.GetFileNameWithoutExtension(path); HierarchyNode childNode = this.FirstChild; // Iterate through the children while (childNode != null) { // If this child is an XML node and its relational name matches, break out of the loop if (childNode is MultiverseInterfaceXmlFileNode && String.Compare(childNode.GetRelationalName(), fileName, StringComparison.OrdinalIgnoreCase) == 0) { parentNode = childNode; break; } // Move over to the next sibling childNode = childNode.NextSibling; } } HierarchyNode child; if (this.CanFileNodesHaveChilds && (parentNode is FileNode || parentNode is DependentFileNode)) { child = this.CreateDependentFileNode(path); child.ItemNode.SetMetadata(ProjectFileConstants.DependentUpon, parentNode.ItemNode.GetMetadata(ProjectFileConstants.Include)); // Make sure to set the HasNameRelation flag on the dependent node if it is related to the parent by name if (String.Compare(child.GetRelationalName(), parentNode.GetRelationalName(), StringComparison.OrdinalIgnoreCase) == 0) { child.HasParentNodeNameRelation = true; } } else { //Create and add new filenode to the project child = this.CreateFileNode(path); } parentNode.AddChild(child); this.Tracker.OnItemAdded(path, VSADDFILEFLAGS.VSADDFILEFLAGS_NoFlags); } /// <summary> /// Adds the file from template. /// </summary> /// <param name="source">The source.</param> /// <param name="target">The target.</param> public override void AddFileFromTemplate(string source, string target) { if (source == null) throw new ArgumentNullException("source"); if (target == null) throw new ArgumentNullException("target"); if (!File.Exists(source)) throw new FileNotFoundException(Resources.GetString(Resources.FailedToLoadTemplateFileMessage, source)); // We assume that there is no token inside the file because the only // way to add a new element should be through the template wizard that // take care of expanding and replacing the tokens. // The only task to perform is to copy the source file in the // target location. string targetFolder = Path.GetDirectoryName(target); if (!Directory.Exists(targetFolder)) Directory.CreateDirectory(targetFolder); if (File.Exists(target)) File.Delete(target); File.Copy(source, target); } /// <summary> /// Creates an MSBuild ProjectElement for a file. /// </summary> /// <param name="file">The path to the file.</param> /// <returns>An instance of the <see cref="ProjectElement"/> class.</returns> protected override ProjectElement AddFileToMsBuild(string file) { if (file == null) throw new ArgumentNullException("file"); string itemPath = PackageUtilities.MakeRelativeIfRooted(file, this.BaseURI); if (Path.IsPathRooted(itemPath)) throw new ArgumentException("Cannot add item with full path.", "file"); ProjectElement newItem = this.CreateMsBuildFileItem(itemPath, ProjectFileConstants.Content); if (MultiverseInterfaceProjectNode.IsPythonFile(itemPath)) { newItem.SetMetadata(ProjectFileConstants.SubType, MultiverseInterfaceSubType.Code); } else if (MultiverseInterfaceProjectNode.IsFrameXmlFile(itemPath)) { newItem.SetMetadata(ProjectFileConstants.SubType, MultiverseInterfaceSubType.Frame); } else if (MultiverseInterfaceProjectNode.IsTableOfContentsFile(itemPath)) { newItem.SetMetadata(ProjectFileConstants.SubType, MultiverseInterfaceSubType.TableOfContents); } return newItem; } /// <summary> /// Gets the configuration independent property pages. /// </summary> /// <returns></returns> protected override Guid[] GetConfigurationIndependentPropertyPages() { Guid[] result = new Guid[1]; result[0] = typeof(GeneralPropertyPage).GUID; return result; } public override int GetFormatList(out string formatList) { formatList = Resources.GetString(Resources.FormatList, "\0"); return VSConstants.S_OK; } /// <summary> /// Called when a Add References.. is pressed. /// </summary> /// <returns>Returns a value of the <see cref="VSConstants"/> enumeration.</returns> public override int AddProjectReference() { return VSConstants.S_OK; } private static bool IsPythonFile(string fileName) { if (String.IsNullOrEmpty(fileName)) return false; return (String.Compare(Path.GetExtension(fileName), ".py", StringComparison.OrdinalIgnoreCase) == 0); } private static bool IsFrameXmlFile(string fileName) { if (String.IsNullOrEmpty(fileName)) return false; // TODO: Also look into the file, might be a normal XML file return (String.Compare(Path.GetExtension(fileName), ".xml", StringComparison.OrdinalIgnoreCase) == 0); } private static bool IsTableOfContentsFile(string fileName) { if (String.IsNullOrEmpty(fileName)) return false; return (String.Compare(Path.GetExtension(fileName), ".toc", StringComparison.OrdinalIgnoreCase) == 0); } private string GetMultiversePath() { using (RegistryKey key = Registry.LocalMachine.OpenSubKey(MultiverseInterfacePathSubKey)) { if (key != null) { return (string)key.GetValue(MultiverseInterfacePathName, String.Empty); } } return String.Empty; } #region Folder node protected internal override FolderNode CreateFolderNode(string path, ProjectElement element) { FolderNode folderNode = new MultiverseInterfaceFolderNode(this, path, element); return folderNode; } #endregion } }
using System; using System.Collections; using System.IO; using UnityEngine; using UnityEngine.EventSystems; using System.Collections.Generic; namespace UnityStandardAssets.Vehicles.Car { internal enum CarDriveType { FrontWheelDrive, RearWheelDrive, FourWheelDrive } internal enum SpeedType { MPH, KPH } public class CarController : MonoBehaviour { [SerializeField] private CarDriveType m_CarDriveType = CarDriveType.FourWheelDrive; [SerializeField] private WheelCollider[] m_WheelColliders = new WheelCollider[4]; [SerializeField] private GameObject[] m_WheelMeshes = new GameObject[4]; [SerializeField] private WheelEffects[] m_WheelEffects = new WheelEffects[4]; [SerializeField] private Vector3 m_CentreOfMassOffset; [SerializeField] private float m_MaximumSteerAngle; [Range (0, 1)] [SerializeField] private float m_SteerHelper; // 0 is raw physics , 1 the car will grip in the direction it is facing [Range (0, 1)] [SerializeField] private float m_TractionControl; // 0 is no traction control, 1 is full interference [SerializeField] private float m_FullTorqueOverAllWheels; [SerializeField] private float m_ReverseTorque; [SerializeField] private float m_MaxHandbrakeTorque; [SerializeField] private float m_Downforce = 100f; [SerializeField] private SpeedType m_SpeedType; [SerializeField] private float m_Topspeed = 200; [SerializeField] private static int NoOfGears = 5; [SerializeField] private float m_RevRangeBoundary = 1f; [SerializeField] private float m_SlipLimit; [SerializeField] private float m_BrakeTorque; public const string CSVFileName = "driving_log.csv"; public const string DirFrames = "IMG"; [SerializeField] private Camera CenterCamera; [SerializeField] private Camera LeftCamera; [SerializeField] private Camera RightCamera; /* * Custom */ [SerializeField] public bool touchesTrack; public bool resetCar = true; public int secondsOfFreedom = 3; private Vector3 startPos; private Quaternion startRotation; private float startTime = 0; [SerializeField] public int timeAlive = 0; [SerializeField] public float score = 0; /* * End Custom */ private Quaternion[] m_WheelMeshLocalRotations; private Vector3 m_Prevpos, m_Pos; private float m_SteerAngle; private int m_GearNum; private float m_GearFactor; private float m_OldRotation; private float m_CurrentTorque; private Rigidbody m_Rigidbody; private const float k_ReversingThreshold = 0.01f; private string m_saveLocation = ""; private Queue<CarSample> carSamples; private int TotalSamples; private bool isSaving; private Vector3 saved_position; private Quaternion saved_rotation; public bool Skidding { get; private set; } public float BrakeInput { get; private set; } private bool m_isRecording = false; public bool IsRecording { get { return m_isRecording; } set { m_isRecording = value; if(value == true) { Debug.Log("Starting to record"); carSamples = new Queue<CarSample>(); StartCoroutine(Sample()); } else { Debug.Log("Stopping record"); StopCoroutine(Sample()); Debug.Log("Writing to disk"); //save the cars coordinate parameters so we can reset it to this properly after capturing data saved_position = transform.position; saved_rotation = transform.rotation; //see how many samples we captured use this to show save percentage in UISystem script TotalSamples = carSamples.Count; isSaving = true; StartCoroutine(WriteSamplesToDisk()); }; } } public bool checkSaveLocation() { if (m_saveLocation != "") { return true; } else { SimpleFileBrowser.ShowSaveDialog (OpenFolder, null, true, null, "Select Output Folder", "Select"); } return false; } public float CurrentSteerAngle { get { return m_SteerAngle; } set { m_SteerAngle = value; } } public float CurrentSpeed{ get { return m_Rigidbody.velocity.magnitude * 2.23693629f; } } public float MaxSpeed{ get { return m_Topspeed; } } public float Revs { get; private set; } public float AccelInput { get; set; } // Use this for initialization private void Start () { m_WheelMeshLocalRotations = new Quaternion[4]; for (int i = 0; i < 4; i++) { m_WheelMeshLocalRotations [i] = m_WheelMeshes [i].transform.localRotation; } m_WheelColliders [0].attachedRigidbody.centerOfMass = m_CentreOfMassOffset; m_MaxHandbrakeTorque = float.MaxValue; m_Rigidbody = GetComponent<Rigidbody> (); m_CurrentTorque = m_FullTorqueOverAllWheels - (m_TractionControl * m_FullTorqueOverAllWheels); /* * Custom */ this.startPos = transform.position; this.startRotation = transform.rotation; } public bool IsGrounded() { RaycastHit hit; if (Physics.Raycast (transform.position, -Vector3.up, out hit, 5)) { if (hit.collider != null && hit.collider.tag == "Track") return true; } return false; } private void GearChanging () { float f = Mathf.Abs (CurrentSpeed / MaxSpeed); float upgearlimit = (1 / (float)NoOfGears) * (m_GearNum + 1); float downgearlimit = (1 / (float)NoOfGears) * m_GearNum; if (m_GearNum > 0 && f < downgearlimit) { m_GearNum--; } if (f > upgearlimit && (m_GearNum < (NoOfGears - 1))) { m_GearNum++; } } // simple function to add a curved bias towards 1 for a value in the 0-1 range private static float CurveFactor (float factor) { return 1 - (1 - factor) * (1 - factor); } // unclamped version of Lerp, to allow value to exceed the from-to range private static float ULerp (float from, float to, float value) { return (1.0f - value) * from + value * to; } private void CalculateGearFactor () { float f = (1 / (float)NoOfGears); // gear factor is a normalised representation of the current speed within the current gear's range of speeds. // We smooth towards the 'target' gear factor, so that revs don't instantly snap up or down when changing gear. var targetGearFactor = Mathf.InverseLerp (f * m_GearNum, f * (m_GearNum + 1), Mathf.Abs (CurrentSpeed / MaxSpeed)); m_GearFactor = Mathf.Lerp (m_GearFactor, targetGearFactor, Time.deltaTime * 5f); } private void CalculateRevs () { // calculate engine revs (for display / sound) // (this is done in retrospect - revs are not used in force/power calculations) CalculateGearFactor (); var gearNumFactor = m_GearNum / (float)NoOfGears; var revsRangeMin = ULerp (0f, m_RevRangeBoundary, CurveFactor (gearNumFactor)); var revsRangeMax = ULerp (m_RevRangeBoundary, 1f, gearNumFactor); Revs = ULerp (revsRangeMin, revsRangeMax, m_GearFactor); } public void ResetCar(){ this.startTime = 0; transform.position = this.startPos; transform.rotation = this.startRotation; Rigidbody rb = GetComponent<Rigidbody> (); rb.velocity = new Vector3 (0, 0, 0); this.timeAlive = 0; } public void Update() { if (IsRecording) { //Dump(); } /* * Custom */ touchesTrack = IsGrounded(); if (!touchesTrack && this.resetCar) { if (this.startTime == 0) { this.startTime = Time.time; } } if (this.startTime != 0 && (Time.time - this.startTime >= this.secondsOfFreedom) ) { // Reset! ResetCar(); } //var heading = GameObject.Find("GroundTrackVerges").transform.position - transform.position; //var distance = heading.magnitude; //Debug.Log ("distance "+ distance); //Debug.Log ("direction "+ direction); this.timeAlive += 1; /* * End Custom */ } public void Move (float steering, float accel, float footbrake, float handbrake) { for (int i = 0; i < 4; i++) { Quaternion quat; Vector3 position; m_WheelColliders [i].GetWorldPose (out position, out quat); m_WheelMeshes [i].transform.position = position; m_WheelMeshes [i].transform.rotation = quat; } //clamp input values steering = Mathf.Clamp (steering, -1, 1); AccelInput = accel = Mathf.Clamp (accel, 0, 1); BrakeInput = footbrake = -1 * Mathf.Clamp (footbrake, -1, 0); handbrake = Mathf.Clamp (handbrake, 0, 1); //Set the steer on the front wheels. //Assuming that wheels 0 and 1 are the front wheels. m_SteerAngle = steering * m_MaximumSteerAngle; m_WheelColliders [0].steerAngle = m_SteerAngle; m_WheelColliders [1].steerAngle = m_SteerAngle; SteerHelper (); ApplyDrive (accel, footbrake); CapSpeed (); //Set the handbrake. //Assuming that wheels 2 and 3 are the rear wheels. if (handbrake > 0f) { var hbTorque = handbrake * m_MaxHandbrakeTorque; m_WheelColliders [2].brakeTorque = hbTorque; m_WheelColliders [3].brakeTorque = hbTorque; } CalculateRevs (); GearChanging (); AddDownForce (); CheckForWheelSpin (); TractionControl (); } private void CapSpeed () { float speed = m_Rigidbody.velocity.magnitude; switch (m_SpeedType) { case SpeedType.MPH: speed *= 2.23693629f; if (speed > m_Topspeed) m_Rigidbody.velocity = (m_Topspeed / 2.23693629f) * m_Rigidbody.velocity.normalized; break; case SpeedType.KPH: speed *= 3.6f; if (speed > m_Topspeed) m_Rigidbody.velocity = (m_Topspeed / 3.6f) * m_Rigidbody.velocity.normalized; break; } } private void ApplyDrive (float accel, float footbrake) { float thrustTorque; switch (m_CarDriveType) { case CarDriveType.FourWheelDrive: thrustTorque = accel * (m_CurrentTorque / 4f); for (int i = 0; i < 4; i++) { m_WheelColliders [i].motorTorque = thrustTorque; } break; case CarDriveType.FrontWheelDrive: thrustTorque = accel * (m_CurrentTorque / 2f); m_WheelColliders [0].motorTorque = m_WheelColliders [1].motorTorque = thrustTorque; break; case CarDriveType.RearWheelDrive: thrustTorque = accel * (m_CurrentTorque / 2f); m_WheelColliders [2].motorTorque = m_WheelColliders [3].motorTorque = thrustTorque; break; } for (int i = 0; i < 4; i++) { if (CurrentSpeed > 5 && Vector3.Angle (transform.forward, m_Rigidbody.velocity) < 50f) { m_WheelColliders [i].brakeTorque = m_BrakeTorque * footbrake; } else if (footbrake > 0) { m_WheelColliders [i].brakeTorque = 0f; m_WheelColliders [i].motorTorque = -m_ReverseTorque * footbrake; } } } private void SteerHelper () { for (int i = 0; i < 4; i++) { WheelHit wheelhit; m_WheelColliders [i].GetGroundHit (out wheelhit); if (wheelhit.normal == Vector3.zero) return; // wheels arent on the ground so dont realign the rigidbody velocity } // this if is needed to avoid gimbal lock problems that will make the car suddenly shift direction if (Mathf.Abs (m_OldRotation - transform.eulerAngles.y) < 10f) { var turnadjust = (transform.eulerAngles.y - m_OldRotation) * m_SteerHelper; Quaternion velRotation = Quaternion.AngleAxis (turnadjust, Vector3.up); m_Rigidbody.velocity = velRotation * m_Rigidbody.velocity; } m_OldRotation = transform.eulerAngles.y; } // this is used to add more grip in relation to speed private void AddDownForce () { m_WheelColliders [0].attachedRigidbody.AddForce (-transform.up * m_Downforce * m_WheelColliders [0].attachedRigidbody.velocity.magnitude); } // checks if the wheels are spinning and is so does three things // 1) emits particles // 2) plays tiure skidding sounds // 3) leaves skidmarks on the ground // these effects are controlled through the WheelEffects class private void CheckForWheelSpin () { // loop through all wheels for (int i = 0; i < 4; i++) { WheelHit wheelHit; m_WheelColliders [i].GetGroundHit (out wheelHit); // is the tire slipping above the given threshhold if (Mathf.Abs (wheelHit.forwardSlip) >= m_SlipLimit || Mathf.Abs (wheelHit.sidewaysSlip) >= m_SlipLimit) { m_WheelEffects [i].EmitTyreSmoke (); continue; } // if it wasnt slipping stop all the audio if (m_WheelEffects [i].PlayingAudio) { m_WheelEffects [i].StopAudio (); } // end the trail generation m_WheelEffects [i].EndSkidTrail (); } } // crude traction control that reduces the power to wheel if the car is wheel spinning too much private void TractionControl () { WheelHit wheelHit; switch (m_CarDriveType) { case CarDriveType.FourWheelDrive: // loop through all wheels for (int i = 0; i < 4; i++) { m_WheelColliders [i].GetGroundHit (out wheelHit); AdjustTorque (wheelHit.forwardSlip); } break; case CarDriveType.RearWheelDrive: m_WheelColliders [2].GetGroundHit (out wheelHit); AdjustTorque (wheelHit.forwardSlip); m_WheelColliders [3].GetGroundHit (out wheelHit); AdjustTorque (wheelHit.forwardSlip); break; case CarDriveType.FrontWheelDrive: m_WheelColliders [0].GetGroundHit (out wheelHit); AdjustTorque (wheelHit.forwardSlip); m_WheelColliders [1].GetGroundHit (out wheelHit); AdjustTorque (wheelHit.forwardSlip); break; } } private void AdjustTorque (float forwardSlip) { if (forwardSlip >= m_SlipLimit && m_CurrentTorque >= 0) { m_CurrentTorque -= 10 * m_TractionControl; } else { m_CurrentTorque += 10 * m_TractionControl; if (m_CurrentTorque > m_FullTorqueOverAllWheels) { m_CurrentTorque = m_FullTorqueOverAllWheels; } } } //Changed the WriteSamplesToDisk to a IEnumerator method that plays back recording along with percent status from UISystem script //instead of showing frozen screen until all data is recorded public IEnumerator WriteSamplesToDisk() { yield return new WaitForSeconds(0.000f); //retrieve as fast as we can but still allow communication of main thread to screen and UISystem if (carSamples.Count > 0) { //pull off a sample from the que CarSample sample = carSamples.Dequeue(); //pysically moving the car to get the right camera position transform.position = sample.position; transform.rotation = sample.rotation; // Capture and Persist Image string centerPath = WriteImage (CenterCamera, "center", sample.timeStamp); string leftPath = WriteImage (LeftCamera, "left", sample.timeStamp); string rightPath = WriteImage (RightCamera, "right", sample.timeStamp); string row = string.Format ("{0},{1},{2},{3},{4},{5},{6}\n", centerPath, leftPath, rightPath, sample.steeringAngle, sample.throttle, sample.brake, sample.speed); File.AppendAllText (Path.Combine (m_saveLocation, CSVFileName), row); } if (carSamples.Count > 0) { //request if there are more samples to pull StartCoroutine(WriteSamplesToDisk()); } else { //all samples have been pulled StopCoroutine(WriteSamplesToDisk()); isSaving = false; //need to reset the car back to its position before ending recording, otherwise sometimes the car ended up in strange areas transform.position = saved_position; transform.rotation = saved_rotation; m_Rigidbody.velocity = new Vector3(0f,-10f,0f); Move(0f, 0f, 0f, 0f); } } public float getSavePercent() { return (float)(TotalSamples-carSamples.Count)/TotalSamples; } public bool getSaveStatus() { return isSaving; } public IEnumerator Sample() { // Start the Coroutine to Capture Data Every Second. // Persist that Information to a CSV and Perist the Camera Frame yield return new WaitForSeconds(0.0666666666666667f); if (m_saveLocation != "") { CarSample sample = new CarSample(); sample.timeStamp = System.DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_fff"); sample.steeringAngle = m_SteerAngle / m_MaximumSteerAngle; sample.throttle = AccelInput; sample.brake = BrakeInput; sample.speed = CurrentSpeed; sample.position = transform.position; sample.rotation = transform.rotation; carSamples.Enqueue(sample); sample = null; //may or may not be needed } // Only reschedule if the button hasn't toggled if (IsRecording) { StartCoroutine(Sample()); } } private void OpenFolder(string location) { m_saveLocation = location; Directory.CreateDirectory (Path.Combine(m_saveLocation, DirFrames)); } private string WriteImage (Camera camera, string prepend, string timestamp) { //needed to force camera update camera.Render(); RenderTexture targetTexture = camera.targetTexture; RenderTexture.active = targetTexture; Texture2D texture2D = new Texture2D (targetTexture.width, targetTexture.height, TextureFormat.RGB24, false); texture2D.ReadPixels (new Rect (0, 0, targetTexture.width, targetTexture.height), 0, 0); texture2D.Apply (); byte[] image = texture2D.EncodeToJPG (); UnityEngine.Object.DestroyImmediate (texture2D); string directory = Path.Combine(m_saveLocation, DirFrames); string path = Path.Combine(directory, prepend + "_" + timestamp + ".jpg"); File.WriteAllBytes (path, image); image = null; return path; } } internal class CarSample { public Quaternion rotation; public Vector3 position; public float steeringAngle; public float throttle; public float brake; public float speed; public string timeStamp; } }
// // System.Web.UI.TemplateParser // // Authors: // Duncan Mak (duncan@ximian.com) // Gonzalo Paniagua Javier (gonzalo@ximian.com) // // (C) 2002,2003 Ximian, Inc. (http://www.ximian.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. // using System; using System.CodeDom.Compiler; using System.Collections; using System.IO; using System.Reflection; using System.Web; using System.Web.Compilation; using System.Web.Configuration; using System.Web.Util; namespace System.Web.UI { public abstract class TemplateParser : BaseParser { string inputFile; string text; string privateBinPath; Hashtable mainAttributes; ArrayList dependencies; ArrayList assemblies; Hashtable anames; ArrayList imports; ArrayList interfaces; ArrayList scripts; Type baseType; string className; RootBuilder rootBuilder; bool debug; string compilerOptions; string language; bool strictOn = false; bool explicitOn = false; bool output_cache; int oc_duration; string oc_header, oc_custom, oc_param, oc_controls; bool oc_shared; OutputCacheLocation oc_location; Assembly srcAssembly; int appAssemblyIndex = -1; internal TemplateParser () { imports = new ArrayList (); imports.Add ("System"); imports.Add ("System.Collections"); imports.Add ("System.Collections.Specialized"); imports.Add ("System.Configuration"); imports.Add ("System.Text"); imports.Add ("System.Text.RegularExpressions"); imports.Add ("System.Web"); imports.Add ("System.Web.Caching"); imports.Add ("System.Web.Security"); imports.Add ("System.Web.SessionState"); imports.Add ("System.Web.UI"); imports.Add ("System.Web.UI.WebControls"); imports.Add ("System.Web.UI.HtmlControls"); assemblies = new ArrayList (); foreach (string a in CompilationConfig.Assemblies) AddAssemblyByName (a); if (CompilationConfig.AssembliesInBin) AddAssembliesInBin (); language = CompilationConfig.DefaultLanguage; } internal void AddApplicationAssembly () { string location = Context.ApplicationInstance.AssemblyLocation; if (location != typeof (TemplateParser).Assembly.Location) { appAssemblyIndex = assemblies.Add (location); } } protected abstract Type CompileIntoType (); internal virtual void HandleOptions (object obj) { } internal static string GetOneKey (Hashtable tbl) { foreach (object key in tbl.Keys) return key.ToString (); return null; } internal virtual void AddDirective (string directive, Hashtable atts) { if (String.Compare (directive, DefaultDirectiveName, true) == 0) { if (mainAttributes != null) ThrowParseException ("Only 1 " + DefaultDirectiveName + " is allowed"); mainAttributes = atts; ProcessMainAttributes (mainAttributes); return; } int cmp = String.Compare ("Assembly", directive, true); if (cmp == 0) { string name = GetString (atts, "Name", null); string src = GetString (atts, "Src", null); if (atts.Count > 0) ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown."); if (name == null && src == null) ThrowParseException ("You gotta specify Src or Name"); if (name != null && src != null) ThrowParseException ("Src and Name cannot be used together"); if (name != null) { AddAssemblyByName (name); } else { GetAssemblyFromSource (src); } return; } cmp = String.Compare ("Import", directive, true); if (cmp == 0) { string namesp = GetString (atts, "Namespace", null); if (atts.Count > 0) ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown."); if (namesp != null && namesp != "") AddImport (namesp); return; } cmp = String.Compare ("Implements", directive, true); if (cmp == 0) { string ifacename = GetString (atts, "Interface", ""); if (atts.Count > 0) ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown."); Type iface = LoadType (ifacename); if (iface == null) ThrowParseException ("Cannot find type " + ifacename); if (!iface.IsInterface) ThrowParseException (iface + " is not an interface"); AddInterface (iface.FullName); return; } cmp = String.Compare ("OutputCache", directive, true); if (cmp == 0) { output_cache = true; if (atts ["Duration"] == null) ThrowParseException ("The directive is missing a 'duration' attribute."); if (atts ["VaryByParam"] == null) ThrowParseException ("This directive is missing a 'VaryByParam' " + "attribute, which should be set to \"none\", \"*\", " + "or a list of name/value pairs."); foreach (DictionaryEntry entry in atts) { string key = (string) entry.Key; switch (key.ToLower ()) { case "duration": oc_duration = Int32.Parse ((string) entry.Value); if (oc_duration < 1) ThrowParseException ("The 'duration' attribute must be set " + "to a positive integer value"); break; case "varybyparam": oc_param = (string) entry.Value; if (String.Compare (oc_param, "none") == 0) oc_param = null; break; case "varybyheader": oc_header = (string) entry.Value; break; case "varybycustom": oc_custom = (string) entry.Value; break; case "location": if (!(this is PageParser)) goto default; try { oc_location = (OutputCacheLocation) Enum.Parse ( typeof (OutputCacheLocation), (string) entry.Value, true); } catch { ThrowParseException ("The 'location' attribute is case sensitive and " + "must be one of the following values: Any, Client, " + "Downstream, Server, None, ServerAndClient."); } break; case "varybycontrol": if (this is PageParser) goto default; oc_controls = (string) entry.Value; break; case "shared": if (this is PageParser) goto default; try { oc_shared = Boolean.Parse ((string) entry.Value); } catch { ThrowParseException ("The 'shared' attribute is case sensitive" + " and must be set to 'true' or 'false'."); } break; default: ThrowParseException ("The '" + key + "' attribute is not " + "supported by the 'Outputcache' directive."); break; } } return; } ThrowParseException ("Unknown directive: " + directive); } internal Type LoadType (string typeName) { // First try loaded assemblies, then try assemblies in Bin directory. Type type = null; bool seenBin = false; Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies (); foreach (Assembly ass in assemblies) { type = ass.GetType (typeName); if (type == null) continue; if (Path.GetDirectoryName (ass.Location) != PrivateBinPath) { AddAssembly (ass, true); } else { seenBin = true; } AddDependency (ass.Location); return type; } if (seenBin) return null; // Load from bin if (!Directory.Exists (PrivateBinPath)) return null; string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll"); foreach (string s in binDlls) { Assembly binA = Assembly.LoadFrom (s); type = binA.GetType (typeName); if (type == null) continue; AddDependency (binA.Location); return type; } return null; } void AddAssembliesInBin () { if (!Directory.Exists (PrivateBinPath)) return; string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll"); foreach (string s in binDlls) { assemblies.Add (s); } } internal virtual void AddInterface (string iface) { if (interfaces == null) interfaces = new ArrayList (); if (!interfaces.Contains (iface)) interfaces.Add (iface); } internal virtual void AddImport (string namesp) { if (imports == null) imports = new ArrayList (); if (!imports.Contains (namesp)) imports.Add (namesp); } internal virtual void AddSourceDependency (string filename) { if (dependencies != null && dependencies.Contains (filename)) { ThrowParseException ("Circular file references are not allowed. File: " + filename); } AddDependency (filename); } internal virtual void AddDependency (string filename) { if (filename == "") return; if (dependencies == null) dependencies = new ArrayList (); if (!dependencies.Contains (filename)) dependencies.Add (filename); } internal virtual void AddAssembly (Assembly assembly, bool fullPath) { if (assembly.Location == "") return; if (anames == null) anames = new Hashtable (); string name = assembly.GetName ().Name; string loc = assembly.Location; if (fullPath) { if (!assemblies.Contains (loc)) { assemblies.Add (loc); } anames [name] = loc; anames [loc] = assembly; } else { if (!assemblies.Contains (name)) { assemblies.Add (name); } anames [name] = assembly; } } internal virtual Assembly AddAssemblyByName (string name) { if (anames == null) anames = new Hashtable (); if (anames.Contains (name)) { object o = anames [name]; if (o is string) o = anames [o]; return (Assembly) o; } Assembly assembly = null; try { assembly = Assembly.Load (name); } catch (Exception) { try { assembly = Assembly.LoadWithPartialName (name); } catch (Exception e) { ThrowParseException ("Assembly " + name + " not found", e); } if (assembly == null) ThrowParseException ("Assembly " + name + " not found", null); } AddAssembly (assembly, true); return assembly; } internal virtual void ProcessMainAttributes (Hashtable atts) { atts.Remove ("Description"); // ignored atts.Remove ("CodeBehind"); // ignored atts.Remove ("AspCompat"); // ignored #if NET_2_0 atts.Remove ("CodeFile"); // ignored #endif debug = GetBool (atts, "Debug", true); compilerOptions = GetString (atts, "CompilerOptions", ""); language = GetString (atts, "Language", CompilationConfig.DefaultLanguage); strictOn = GetBool (atts, "Strict", CompilationConfig.Strict); explicitOn = GetBool (atts, "Explicit", CompilationConfig.Explicit); string src = GetString (atts, "Src", null); if (src != null) srcAssembly = GetAssemblyFromSource (src); string inherits = GetString (atts, "Inherits", null); if (inherits != null) SetBaseType (inherits); className = GetString (atts, "ClassName", null); if (className != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (className)) ThrowParseException (String.Format ("'{0}' is not valid for 'className'", className)); if (atts.Count > 0) ThrowParseException ("Unknown attribute: " + GetOneKey (atts)); } internal void SetBaseType (string type) { if (type == DefaultBaseTypeName) return; Type parent = null; if (srcAssembly != null) parent = srcAssembly.GetType (type); if (parent == null) parent = LoadType (type); if (parent == null) ThrowParseException ("Cannot find type " + type); if (!DefaultBaseType.IsAssignableFrom (parent)) ThrowParseException ("The parent type does not derive from " + DefaultBaseType); baseType = parent; } Assembly GetAssemblyFromSource (string vpath) { vpath = UrlUtils.Combine (BaseVirtualDir, vpath); string realPath = MapPath (vpath, false); if (!File.Exists (realPath)) ThrowParseException ("File " + vpath + " not found"); AddSourceDependency (realPath); CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies); if (result.NativeCompilerReturnValue != 0) { StreamReader reader = new StreamReader (realPath); throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ()); } AddAssembly (result.CompiledAssembly, true); return result.CompiledAssembly; } internal abstract Type DefaultBaseType { get; } internal abstract string DefaultBaseTypeName { get; } internal abstract string DefaultDirectiveName { get; } internal string InputFile { get { return inputFile; } set { inputFile = value; } } internal string Text { get { return text; } set { text = value; } } internal Type BaseType { get { if (baseType == null) baseType = DefaultBaseType; return baseType; } } internal string ClassName { get { if (className != null) return className; className = Path.GetFileName (inputFile).Replace ('.', '_'); className = className.Replace ('-', '_'); className = className.Replace (' ', '_'); if (Char.IsDigit(className[0])) { className = "_" + className; } return className; } } internal string PrivateBinPath { get { if (privateBinPath != null) return privateBinPath; AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation; privateBinPath = Path.Combine (setup.ApplicationBase, setup.PrivateBinPath); return privateBinPath; } } internal ArrayList Scripts { get { if (scripts == null) scripts = new ArrayList (); return scripts; } } internal ArrayList Imports { get { return imports; } } internal ArrayList Assemblies { get { if (appAssemblyIndex != -1) { object o = assemblies [appAssemblyIndex]; assemblies.RemoveAt (appAssemblyIndex); assemblies.Add (o); appAssemblyIndex = -1; } return assemblies; } } internal ArrayList Interfaces { get { return interfaces; } } internal RootBuilder RootBuilder { get { return rootBuilder; } set { rootBuilder = value; } } internal ArrayList Dependencies { get { return dependencies; } set { dependencies = value; } } internal string CompilerOptions { get { return compilerOptions; } } internal string Language { get { return language; } } internal bool StrictOn { get { return strictOn; } } internal bool ExplicitOn { get { return explicitOn; } } internal bool Debug { get { return debug; } } internal bool OutputCache { get { return output_cache; } } internal int OutputCacheDuration { get { return oc_duration; } } internal string OutputCacheVaryByHeader { get { return oc_header; } } internal string OutputCacheVaryByCustom { get { return oc_custom; } } internal string OutputCacheVaryByControls { get { return oc_controls; } } internal bool OutputCacheShared { get { return oc_shared; } } internal OutputCacheLocation OutputCacheLocation { get { return oc_location; } } internal string OutputCacheVaryByParam { get { return oc_param; } } internal PagesConfiguration PagesConfig { get { return PagesConfiguration.GetInstance (Context); } } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // Copyright (c) 2007 Novell, 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.IO; using System.Xml; using System.Xml.Serialization; using Xunit; namespace System.Data.Tests { public class DataTableTest5 : IDisposable { private string _tempFile; private DataSet _dataSet; private DataTable _dummyTable; private DataTable _parentTable1; private DataTable _childTable; private DataTable _secondChildTable; public DataTableTest5() { _tempFile = Path.GetTempFileName(); } public void Dispose() { if (_tempFile != null) File.Delete(_tempFile); } private void WriteXmlSerializable(Stream s, DataTable dt) { XmlWriterSettings ws = new XmlWriterSettings(); using (XmlWriter xw = XmlWriter.Create(s, ws)) { IXmlSerializable idt = dt; xw.WriteStartElement("start"); idt.WriteXml(xw); xw.WriteEndElement(); xw.Close(); } } private void ReadXmlSerializable(Stream s, DataTable dt) { using (XmlReader xr = XmlReader.Create(s)) { ReadXmlSerializable(dt, xr); } } private static void ReadXmlSerializable(DataTable dt, XmlReader xr) { XmlSerializer serializer = new XmlSerializer(dt.GetType()); IXmlSerializable idt = dt; idt.ReadXml(xr); xr.Close(); } private void ReadXmlSerializable(string fileName, DataTable dt) { using (XmlReader xr = XmlReader.Create(fileName)) { ReadXmlSerializable(dt, xr); } } private void MakeParentTable1() { // Create a new Table _parentTable1 = new DataTable("ParentTable"); _dataSet = new DataSet("XmlDataSet"); DataColumn column; DataRow row; // Create new DataColumn, set DataType, // ColumnName and add to Table. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "id"; column.Unique = true; // Add the Column to the DataColumnCollection. _parentTable1.Columns.Add(column); // Create second column column = new DataColumn(); column.DataType = typeof(string); column.ColumnName = "ParentItem"; column.AutoIncrement = false; column.Caption = "ParentItem"; column.Unique = false; // Add the column to the table _parentTable1.Columns.Add(column); // Create third column. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "DepartmentID"; column.Caption = "DepartmentID"; // Add the column to the table. _parentTable1.Columns.Add(column); // Make the ID column the primary key column. DataColumn[] PrimaryKeyColumns = new DataColumn[2]; PrimaryKeyColumns[0] = _parentTable1.Columns["id"]; PrimaryKeyColumns[1] = _parentTable1.Columns["DepartmentID"]; _parentTable1.PrimaryKey = PrimaryKeyColumns; _dataSet.Tables.Add(_parentTable1); // Create three new DataRow objects and add // them to the DataTable for (int i = 0; i <= 2; i++) { row = _parentTable1.NewRow(); row["id"] = i + 1; row["ParentItem"] = "ParentItem " + (i + 1); row["DepartmentID"] = i + 1; _parentTable1.Rows.Add(row); } } private void MakeDummyTable() { // Create a new Table _dataSet = new DataSet(); _dummyTable = new DataTable("DummyTable"); DataColumn column; DataRow row; // Create new DataColumn, set DataType, // ColumnName and add to Table. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "id"; column.Unique = true; // Add the Column to the DataColumnCollection. _dummyTable.Columns.Add(column); // Create second column column = new DataColumn(); column.DataType = typeof(string); column.ColumnName = "DummyItem"; column.AutoIncrement = false; column.Caption = "DummyItem"; column.Unique = false; // Add the column to the table _dummyTable.Columns.Add(column); _dataSet.Tables.Add(_dummyTable); // Create three new DataRow objects and add // them to the DataTable for (int i = 0; i <= 2; i++) { row = _dummyTable.NewRow(); row["id"] = i + 1; row["DummyItem"] = "DummyItem " + (i + 1); _dummyTable.Rows.Add(row); } DataRow row1 = _dummyTable.Rows[1]; _dummyTable.AcceptChanges(); row1.BeginEdit(); row1[1] = "Changed_DummyItem " + 2; row1.EndEdit(); } private void MakeChildTable() { // Create a new Table _childTable = new DataTable("ChildTable"); DataColumn column; DataRow row; // Create first column and add to the DataTable. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "ChildID"; column.AutoIncrement = true; column.Caption = "ID"; column.Unique = true; // Add the column to the DataColumnCollection _childTable.Columns.Add(column); // Create second column column = new DataColumn(); column.DataType = typeof(string); column.ColumnName = "ChildItem"; column.AutoIncrement = false; column.Caption = "ChildItem"; column.Unique = false; _childTable.Columns.Add(column); //Create third column column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "ParentID"; column.AutoIncrement = false; column.Caption = "ParentID"; column.Unique = false; _childTable.Columns.Add(column); _dataSet.Tables.Add(_childTable); // Create three sets of DataRow objects, // five rows each, and add to DataTable. for (int i = 0; i <= 1; i++) { row = _childTable.NewRow(); row["childID"] = i + 1; row["ChildItem"] = "ChildItem " + (i + 1); row["ParentID"] = 1; _childTable.Rows.Add(row); } for (int i = 0; i <= 1; i++) { row = _childTable.NewRow(); row["childID"] = i + 5; row["ChildItem"] = "ChildItem " + (i + 1); row["ParentID"] = 2; _childTable.Rows.Add(row); } for (int i = 0; i <= 1; i++) { row = _childTable.NewRow(); row["childID"] = i + 10; row["ChildItem"] = "ChildItem " + (i + 1); row["ParentID"] = 3; _childTable.Rows.Add(row); } } private void MakeSecondChildTable() { // Create a new Table _secondChildTable = new DataTable("SecondChildTable"); DataColumn column; DataRow row; // Create first column and add to the DataTable. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "ChildID"; column.AutoIncrement = true; column.Caption = "ID"; column.ReadOnly = true; column.Unique = true; // Add the column to the DataColumnCollection. _secondChildTable.Columns.Add(column); // Create second column. column = new DataColumn(); column.DataType = typeof(string); column.ColumnName = "ChildItem"; column.AutoIncrement = false; column.Caption = "ChildItem"; column.ReadOnly = false; column.Unique = false; _secondChildTable.Columns.Add(column); //Create third column. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "ParentID"; column.AutoIncrement = false; column.Caption = "ParentID"; column.ReadOnly = false; column.Unique = false; _secondChildTable.Columns.Add(column); //Create fourth column. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "DepartmentID"; column.Caption = "DepartmentID"; column.Unique = false; _secondChildTable.Columns.Add(column); _dataSet.Tables.Add(_secondChildTable); // Create three sets of DataRow objects, // five rows each, and add to DataTable. for (int i = 0; i <= 1; i++) { row = _secondChildTable.NewRow(); row["childID"] = i + 1; row["ChildItem"] = "SecondChildItem " + (i + 1); row["ParentID"] = 1; row["DepartmentID"] = 1; _secondChildTable.Rows.Add(row); } for (int i = 0; i <= 1; i++) { row = _secondChildTable.NewRow(); row["childID"] = i + 5; row["ChildItem"] = "SecondChildItem " + (i + 1); row["ParentID"] = 2; row["DepartmentID"] = 2; _secondChildTable.Rows.Add(row); } for (int i = 0; i <= 1; i++) { row = _secondChildTable.NewRow(); row["childID"] = i + 10; row["ChildItem"] = "SecondChildItem " + (i + 1); row["ParentID"] = 3; row["DepartmentID"] = 3; _secondChildTable.Rows.Add(row); } } private void MakeDataRelation() { DataColumn parentColumn = _dataSet.Tables["ParentTable"].Columns["id"]; DataColumn childColumn = _dataSet.Tables["ChildTable"].Columns["ParentID"]; DataRelation relation = new DataRelation("ParentChild_Relation1", parentColumn, childColumn); _dataSet.Tables["ChildTable"].ParentRelations.Add(relation); DataColumn[] parentColumn1 = new DataColumn[2]; DataColumn[] childColumn1 = new DataColumn[2]; parentColumn1[0] = _dataSet.Tables["ParentTable"].Columns["id"]; parentColumn1[1] = _dataSet.Tables["ParentTable"].Columns["DepartmentID"]; childColumn1[0] = _dataSet.Tables["SecondChildTable"].Columns["ParentID"]; childColumn1[1] = _dataSet.Tables["SecondChildTable"].Columns["DepartmentID"]; DataRelation secondRelation = new DataRelation("ParentChild_Relation2", parentColumn1, childColumn1); _dataSet.Tables["SecondChildTable"].ParentRelations.Add(secondRelation); } private void MakeDataRelation(DataTable dt) { DataColumn parentColumn = dt.Columns["id"]; DataColumn childColumn = _dataSet.Tables["ChildTable"].Columns["ParentID"]; DataRelation relation = new DataRelation("ParentChild_Relation1", parentColumn, childColumn); _dataSet.Tables["ChildTable"].ParentRelations.Add(relation); DataColumn[] parentColumn1 = new DataColumn[2]; DataColumn[] childColumn1 = new DataColumn[2]; parentColumn1[0] = dt.Columns["id"]; parentColumn1[1] = dt.Columns["DepartmentID"]; childColumn1[0] = _dataSet.Tables["SecondChildTable"].Columns["ParentID"]; childColumn1[1] = _dataSet.Tables["SecondChildTable"].Columns["DepartmentID"]; DataRelation secondRelation = new DataRelation("ParentChild_Relation2", parentColumn1, childColumn1); _dataSet.Tables["SecondChildTable"].ParentRelations.Add(secondRelation); } //Test properties of a table which does not belongs to a DataSet private void VerifyTableSchema(DataTable table, string tableName, DataSet ds) { //Test Schema //Check Properties of Table Assert.Equal(string.Empty, table.Namespace); Assert.Equal(ds, table.DataSet); Assert.Equal(3, table.Columns.Count); Assert.False(table.CaseSensitive); Assert.Equal(tableName, table.TableName); Assert.Equal(2, table.Constraints.Count); Assert.Equal(string.Empty, table.Prefix); Assert.Equal(2, table.Constraints.Count); Assert.Equal(typeof(UniqueConstraint), table.Constraints[0].GetType()); Assert.Equal(typeof(UniqueConstraint), table.Constraints[1].GetType()); Assert.Equal(2, table.PrimaryKey.Length); Assert.Equal("id", table.PrimaryKey[0].ToString()); Assert.Equal("DepartmentID", table.PrimaryKey[1].ToString()); Assert.Equal(0, table.ParentRelations.Count); Assert.Equal(0, table.ChildRelations.Count); //Check properties of each column //First Column DataColumn col = table.Columns[0]; Assert.False(col.AllowDBNull); Assert.False(col.AutoIncrement); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("id", col.Caption); Assert.Equal("id", col.ColumnName); Assert.Equal(typeof(int), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.False(col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(0, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ParentTable", col.Table.ToString()); Assert.True(col.Unique); //Second Column col = table.Columns[1]; Assert.True(col.AllowDBNull); Assert.False(col.AutoIncrement); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("ParentItem", col.Caption); Assert.Equal("ParentItem", col.ColumnName); Assert.Equal(typeof(string), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.False(col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(1, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ParentTable", col.Table.ToString()); Assert.False(col.Unique); //Third Column col = table.Columns[2]; Assert.False(col.AllowDBNull); Assert.False(col.AutoIncrement); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("DepartmentID", col.Caption); Assert.Equal("DepartmentID", col.ColumnName); Assert.Equal(typeof(int), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.False(col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(2, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ParentTable", col.Table.ToString()); Assert.False(col.Unique); //Test the Xml Assert.Equal(3, table.Rows.Count); //Test values of each row DataRow row = table.Rows[0]; Assert.Equal(1, row["id"]); Assert.Equal("ParentItem 1", row["ParentItem"]); Assert.Equal(1, row["DepartmentID"]); row = table.Rows[1]; Assert.Equal(2, row["id"]); Assert.Equal("ParentItem 2", row["ParentItem"]); Assert.Equal(2, row["DepartmentID"]); row = table.Rows[2]; Assert.Equal(3, row["id"]); Assert.Equal("ParentItem 3", row["ParentItem"]); Assert.Equal(3, row["DepartmentID"]); } [Fact] public void XmlTest1() { //Make a table without any relations MakeParentTable1(); _dataSet.Tables.Remove(_parentTable1); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table = new DataTable("ParentTable"); //Read the Xml and the Schema into a table which does not belongs to any DataSet ReadXmlSerializable(_tempFile, table); VerifyTableSchema(table, _parentTable1.TableName, null);//parentTable1.DataSet); } [Fact] public void XmlTest2() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table = new DataTable("ParentTable"); DataSet ds = new DataSet("XmlDataSet"); ds.Tables.Add(table); //Read the Xml and the Schema into a table which already belongs to a DataSet //and the table name matches with the table in the source XML ReadXmlSerializable(_tempFile, table); VerifyTableSchema(table, _parentTable1.TableName, ds); } [Fact] public void XmlTest3() { //Create a parent table and create child tables MakeParentTable1(); MakeChildTable(); MakeSecondChildTable(); //Relate the parent and the children MakeDataRelation(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table = new DataTable(); ReadXmlSerializable(_tempFile, table); VerifyTableSchema(table, _parentTable1.TableName, null); } [Fact] public void XmlTest4() { //Create a parent table and create child tables MakeParentTable1(); MakeChildTable(); MakeSecondChildTable(); //Relate the parent and the children MakeDataRelation(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { //WriteXml on any of the children WriteXmlSerializable(stream, _childTable); } DataTable table = new DataTable(); ReadXmlSerializable(_tempFile, table); //Test Schema //Check Properties of Table Assert.Equal(string.Empty, table.Namespace); Assert.Null(table.DataSet); Assert.Equal(3, table.Columns.Count); Assert.False(table.CaseSensitive); Assert.Equal("ChildTable", table.TableName); Assert.Equal(string.Empty, table.Prefix); Assert.Equal(1, table.Constraints.Count); Assert.Equal("Constraint1", table.Constraints[0].ToString()); Assert.Equal(typeof(UniqueConstraint), table.Constraints[0].GetType()); Assert.Equal(0, table.PrimaryKey.Length); Assert.Equal(0, table.ParentRelations.Count); Assert.Equal(0, table.ChildRelations.Count); //Check properties of each column //First Column DataColumn col = table.Columns[0]; Assert.True(col.AllowDBNull); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("ChildID", col.ColumnName); Assert.Equal(typeof(int), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.False(col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(0, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ChildTable", col.Table.ToString()); Assert.True(col.Unique); //Second Column col = table.Columns[1]; Assert.True(col.AllowDBNull); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("ChildItem", col.Caption); Assert.Equal("ChildItem", col.ColumnName); Assert.Equal(typeof(string), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.False(col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(1, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ChildTable", col.Table.ToString()); Assert.False(col.Unique); //Third Column col = table.Columns[2]; Assert.True(col.AllowDBNull); Assert.False(col.AutoIncrement); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("ParentID", col.Caption); Assert.Equal("ParentID", col.ColumnName); Assert.Equal(typeof(int), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.False(col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(2, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ChildTable", col.Table.ToString()); Assert.False(col.Unique); //Test the Xml Assert.Equal(6, table.Rows.Count); //Test values of each row DataRow row = table.Rows[0]; Assert.Equal(1, row["ChildID"]); Assert.Equal("ChildItem 1", row["ChildItem"]); Assert.Equal(1, row["ParentID"]); row = table.Rows[1]; Assert.Equal(2, row["ChildID"]); Assert.Equal("ChildItem 2", row["ChildItem"]); Assert.Equal(1, row["ParentID"]); row = table.Rows[2]; Assert.Equal(5, row["ChildID"]); Assert.Equal("ChildItem 1", row["ChildItem"]); Assert.Equal(2, row["ParentID"]); row = table.Rows[3]; Assert.Equal(6, row["ChildID"]); Assert.Equal("ChildItem 2", row["ChildItem"]); Assert.Equal(2, row["ParentID"]); row = table.Rows[4]; Assert.Equal(10, row["ChildID"]); Assert.Equal("ChildItem 1", row["ChildItem"]); Assert.Equal(3, row["ParentID"]); row = table.Rows[5]; Assert.Equal(11, row["ChildID"]); Assert.Equal("ChildItem 2", row["ChildItem"]); Assert.Equal(3, row["ParentID"]); } [Fact] public void XmlTest5() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); stream.Close(); } DataTable table = new DataTable("ParentTable"); DataSet dataSet = new DataSet("XmlDataSet"); dataSet.Tables.Add(table); table.Columns.Add(new DataColumn("id", typeof(string))); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(1, table.Columns.Count); Assert.Equal(typeof(string), table.Columns[0].DataType); Assert.NotNull(table.DataSet); //Check Rows DataRow row = table.Rows[0]; Assert.Equal("1", row[0]); row = table.Rows[1]; Assert.Equal("2", row[0]); row = table.Rows[2]; Assert.Equal("3", row[0]); } [Fact] public void XmlTest6() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); stream.Close(); } //Create a target table which has nomatching column(s) names DataTable table = new DataTable("ParentTable"); DataSet dataSet = new DataSet("XmlDataSet"); dataSet.Tables.Add(table); table.Columns.Add(new DataColumn("sid", typeof(string))); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { // ReadXml does not read anything as the column // names are not matching ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(1, table.Columns.Count); Assert.Equal("sid", table.Columns[0].ColumnName); Assert.Equal(typeof(string), table.Columns[0].DataType); Assert.NotNull(table.DataSet); } [Fact] public void XmlTest7() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); stream.Close(); } //Create a target table which has matching // column(s) name and an extra column DataTable table = new DataTable("ParentTable"); table.Columns.Add(new DataColumn("id", typeof(int))); table.Columns.Add(new DataColumn("ParentItem", typeof(string))); table.Columns.Add(new DataColumn("DepartmentID", typeof(int))); table.Columns.Add(new DataColumn("DummyColumn", typeof(string))); DataSet dataSet = new DataSet("XmlDataSet"); dataSet.Tables.Add(table); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(4, table.Columns.Count); Assert.NotNull(table.DataSet); //Check the Columns Assert.Equal("id", table.Columns[0].ColumnName); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal("ParentItem", table.Columns[1].ColumnName); Assert.Equal(typeof(string), table.Columns[1].DataType); Assert.Equal("DepartmentID", table.Columns[2].ColumnName); Assert.Equal(typeof(int), table.Columns[2].DataType); Assert.Equal("DummyColumn", table.Columns[3].ColumnName); Assert.Equal(typeof(string), table.Columns[3].DataType); //Check the rows DataRow row = table.Rows[0]; Assert.Equal(1, row["id"]); Assert.Equal("ParentItem 1", row["ParentItem"]); Assert.Equal(1, row["DepartmentID"]); row = table.Rows[1]; Assert.Equal(2, row["id"]); Assert.Equal("ParentItem 2", row["ParentItem"]); Assert.Equal(2, row["DepartmentID"]); row = table.Rows[2]; Assert.Equal(3, row["id"]); Assert.Equal("ParentItem 3", row["ParentItem"]); Assert.Equal(3, row["DepartmentID"]); } [Fact] public void XmlTest8() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table = new DataTable("ParentTable"); DataSet dataSet = new DataSet("XmlDataSet"); dataSet.Tables.Add(table); table.Columns.Add(new DataColumn("id", typeof(int))); table.Columns.Add(new DataColumn("DepartmentID", typeof(int))); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(2, table.Columns.Count); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal(typeof(int), table.Columns[1].DataType); Assert.NotNull(table.DataSet); //Check rows DataRow row = table.Rows[0]; Assert.Equal(1, row[0]); Assert.Equal(1, row[1]); row = table.Rows[1]; Assert.Equal(2, row[0]); Assert.Equal(2, row[1]); row = table.Rows[2]; Assert.Equal(3, row[0]); Assert.Equal(3, row[1]); } [Fact] public void XmlTest9() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataSet ds = new DataSet(); DataTable table = new DataTable("ParentTable"); table.Columns.Add(new DataColumn("id", typeof(int))); ds.Tables.Add(table); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(1, table.Columns.Count); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal("System.Data.DataSet", table.DataSet.ToString()); Assert.Equal("NewDataSet", table.DataSet.DataSetName); //Check the rows DataRow row = table.Rows[0]; Assert.Equal(1, row[0]); row = table.Rows[1]; Assert.Equal(2, row[0]); row = table.Rows[2]; Assert.Equal(3, row[0]); } [Fact] public void XmlTest10() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataSet ds = new DataSet(); DataTable table = new DataTable("ParentTable"); table.Columns.Add(new DataColumn("id", typeof(int))); table.Columns.Add(new DataColumn("DepartmentID", typeof(string))); ds.Tables.Add(table); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal("NewDataSet", table.DataSet.DataSetName); Assert.Equal(3, table.Rows.Count); Assert.Equal(2, table.Columns.Count); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal(typeof(string), table.Columns[1].DataType); //Check rows DataRow row = table.Rows[0]; Assert.Equal(1, row[0]); Assert.Equal("1", row[1]); row = table.Rows[1]; Assert.Equal(2, row[0]); Assert.Equal("2", row[1]); row = table.Rows[2]; Assert.Equal(3, row[0]); Assert.Equal("3", row[1]); } [Fact] public void XmlTest11() { MakeDummyTable(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _dummyTable); } //Create a table and set the table name DataTable table = new DataTable("DummyTable"); //define the table schame partially table.Columns.Add(new DataColumn("DummyItem", typeof(string))); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Null(table.DataSet); Assert.Equal(1, table.Columns.Count); Assert.Equal(typeof(string), table.Columns[0].DataType); Assert.Equal(3, table.Rows.Count); //Check Rows DataRow row = table.Rows[0]; Assert.Equal("DummyItem 1", row[0]); Assert.Equal(DataRowState.Unchanged, row.RowState); row = table.Rows[1]; Assert.Equal("Changed_DummyItem 2", row[0]); Assert.Equal(DataRowState.Modified, row.RowState); row = table.Rows[2]; Assert.Equal("DummyItem 3", row[0]); Assert.Equal(DataRowState.Unchanged, row.RowState); } [Fact] public void XmlTest14() { MakeParentTable1(); MakeChildTable(); MakeSecondChildTable(); MakeDataRelation(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table1 = new DataTable("ParentTable"); table1.Columns.Add(new DataColumn(_parentTable1.Columns[0].ColumnName, typeof(int))); table1.Columns.Add(new DataColumn(_parentTable1.Columns[1].ColumnName, typeof(string))); table1.Columns.Add(new DataColumn(_parentTable1.Columns[2].ColumnName, typeof(int))); ReadXmlSerializable(_tempFile, table1); Assert.Null(table1.DataSet); Assert.Equal("ParentTable", table1.TableName); Assert.Equal(3, table1.Columns.Count); Assert.Equal(typeof(int), table1.Columns[0].DataType); Assert.Equal(typeof(string), table1.Columns[1].DataType); Assert.Equal(typeof(int), table1.Columns[2].DataType); Assert.Equal(0, table1.ChildRelations.Count); Assert.Equal(3, table1.Rows.Count); //Check the row DataRow row = table1.Rows[0]; Assert.Equal(1, row[0]); Assert.Equal("ParentItem 1", row[1]); Assert.Equal(1, row[2]); row = table1.Rows[1]; Assert.Equal(2, row[0]); Assert.Equal("ParentItem 2", row[1]); Assert.Equal(2, row[2]); row = table1.Rows[2]; Assert.Equal(3, row[0]); Assert.Equal("ParentItem 3", row[1]); Assert.Equal(3, row[2]); } [Fact] public void XmlTest15() { MakeDummyTable(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _dummyTable); } Assert.Equal(3, _dummyTable.Rows.Count); DataSet dataSet = new DataSet("HelloWorldDataSet"); DataTable table = new DataTable("DummyTable"); table.Columns.Add(new DataColumn("DummyItem", typeof(string))); dataSet.Tables.Add(table); //Call ReadXml on a table which belong to a DataSet ReadXmlSerializable(_tempFile, table); Assert.Equal("HelloWorldDataSet", table.DataSet.DataSetName); Assert.Equal(1, table.Columns.Count); Assert.Equal(typeof(string), table.Columns[0].DataType); Assert.Equal(3, table.Rows.Count); //Check Rows DataRow row = table.Rows[0]; Assert.Equal("DummyItem 1", row[0]); Assert.Equal(DataRowState.Unchanged, row.RowState); row = table.Rows[1]; Assert.Equal("Changed_DummyItem 2", row[0]); Assert.Equal(DataRowState.Modified, row.RowState); row = table.Rows[2]; Assert.Equal("DummyItem 3", row[0]); Assert.Equal(DataRowState.Unchanged, row.RowState); } [Fact] public void XmlTest16() { DataSet ds = new DataSet(); DataTable parent = new DataTable("Parent"); parent.Columns.Add(new DataColumn("col1", typeof(int))); parent.Columns.Add(new DataColumn("col2", typeof(string))); parent.Columns[0].Unique = true; DataTable child1 = new DataTable("Child1"); child1.Columns.Add(new DataColumn("col3", typeof(int))); child1.Columns.Add(new DataColumn("col4", typeof(string))); child1.Columns.Add(new DataColumn("col5", typeof(int))); child1.Columns[2].Unique = true; DataTable child2 = new DataTable("Child2"); child2.Columns.Add(new DataColumn("col6", typeof(int))); child2.Columns.Add(new DataColumn("col7")); parent.Rows.Add(new object[] { 1, "P_" }); parent.Rows.Add(new object[] { 2, "P_" }); child1.Rows.Add(new object[] { 1, "C1_", 3 }); child1.Rows.Add(new object[] { 1, "C1_", 4 }); child1.Rows.Add(new object[] { 2, "C1_", 5 }); child1.Rows.Add(new object[] { 2, "C1_", 6 }); child2.Rows.Add(new object[] { 3, "C2_" }); child2.Rows.Add(new object[] { 3, "C2_" }); child2.Rows.Add(new object[] { 4, "C2_" }); child2.Rows.Add(new object[] { 4, "C2_" }); child2.Rows.Add(new object[] { 5, "C2_" }); child2.Rows.Add(new object[] { 5, "C2_" }); child2.Rows.Add(new object[] { 6, "C2_" }); child2.Rows.Add(new object[] { 6, "C2_" }); ds.Tables.Add(parent); ds.Tables.Add(child1); ds.Tables.Add(child2); DataRelation relation = new DataRelation("Relation1", parent.Columns[0], child1.Columns[0]); parent.ChildRelations.Add(relation); relation = new DataRelation("Relation2", child1.Columns[2], child2.Columns[0]); child1.ChildRelations.Add(relation); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, parent); } DataTable table = new DataTable(); ReadXmlSerializable(_tempFile, table); Assert.Equal("Parent", table.TableName); Assert.Equal(2, table.Columns.Count); Assert.Equal(2, table.Rows.Count); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal(typeof(string), table.Columns[1].DataType); Assert.Equal(1, table.Constraints.Count); Assert.Equal(typeof(UniqueConstraint), table.Constraints[0].GetType()); } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.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. *******************************************************************************/ // // Novell.Directory.Ldap.Utilclass.SchemaTokenCreator.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; namespace Novell.Directory.Ldap.Utilclass { public class SchemaTokenCreator { private string basestring; private bool cppcomments=false; // C++ style comments enabled private bool ccomments=false; // C style comments enabled private bool iseolsig=false; private bool cidtolower; private bool pushedback; private int peekchar; private sbyte[] ctype; private int linenumber=1; private int ichar=1; private char[] buf; private System.IO.StreamReader reader = null; private System.IO.StringReader sreader = null; private System.IO.Stream input = null; public System.String StringValue; public double NumberValue; public int lastttype; private void Initialise() { ctype = new sbyte[256]; buf = new char[20]; peekchar=System.Int32.MaxValue; WordCharacters('a', 'z'); WordCharacters('A', 'Z'); WordCharacters(128 + 32, 255); WhitespaceCharacters(0, ' '); CommentCharacter('/'); QuoteCharacter('"'); QuoteCharacter('\''); parseNumbers(); } public SchemaTokenCreator(System.IO.Stream instream) { Initialise(); if (instream == null) { throw new System.NullReferenceException(); } input = instream; } public SchemaTokenCreator(System.IO.StreamReader r) { Initialise(); if (r == null) { throw new System.NullReferenceException(); } reader = r; } public SchemaTokenCreator(System.IO.StringReader r) { Initialise(); if (r == null) { throw new System.NullReferenceException(); } sreader = r; } public void pushBack() { pushedback = true; } public int CurrentLine { get { return linenumber; } } public System.String ToStringValue() { System.String strval; switch (lastttype) { case (int)TokenTypes.EOF: strval = "EOF"; break; case (int) TokenTypes.EOL: strval = "EOL"; break; case (int) TokenTypes.WORD: strval = StringValue; break; case (int) TokenTypes.STRING: strval = StringValue; break; case (int) TokenTypes.NUMBER: case (int) TokenTypes.REAL: strval = "n=" + NumberValue; break; default: { if (lastttype < 256 && ((ctype[lastttype] & (sbyte)CharacterTypes.STRINGQUOTE) != 0)) { strval = StringValue; break; } char[] s = new char[3]; s[0] = s[2] = '\''; s[1] = (char) lastttype; strval = new System.String(s); break; } } return strval; } public void WordCharacters(int min, int max) { if (min < 0) min = 0; if (max >= ctype.Length) max = ctype.Length - 1; while (min <= max) ctype[min++] |= (sbyte)CharacterTypes.ALPHABETIC; } public void WhitespaceCharacters(int min, int max) { if (min < 0) min = 0; if (max >= ctype.Length) max = ctype.Length - 1; while (min <= max) ctype[min++] = (sbyte)CharacterTypes.WHITESPACE; } public void OrdinaryCharacters(int min, int max) { if (min < 0) min = 0; if (max >= ctype.Length) max = ctype.Length - 1; while (min <= max) ctype[min++] = 0; } public void OrdinaryCharacter(int ch) { if (ch >= 0 && ch < ctype.Length) ctype[ch] = 0; } public void CommentCharacter(int ch) { if (ch >= 0 && ch < ctype.Length) ctype[ch] = (sbyte)CharacterTypes.COMMENTCHAR; } public void InitTable() { for (int i = ctype.Length; --i >= 0; ) ctype[i] = 0; } public void QuoteCharacter(int ch) { if (ch >= 0 && ch < ctype.Length) ctype[ch] = (sbyte)CharacterTypes.STRINGQUOTE; } public void parseNumbers() { for (int i = '0'; i <= '9'; i++) ctype[i] |= (sbyte)CharacterTypes.NUMERIC; ctype['.'] |= (sbyte)CharacterTypes.NUMERIC; ctype['-'] |= (sbyte)CharacterTypes.NUMERIC; } private int read() { if (sreader !=null ) { return sreader.Read(); } else if (reader != null) { return reader.Read(); } else if (input != null) return input.ReadByte(); else throw new System.SystemException(); } public int nextToken() { if (pushedback) { pushedback = false; return lastttype; } StringValue = null; int curc = peekchar; if (curc < 0) curc = System.Int32.MaxValue; if (curc == (System.Int32.MaxValue - 1)) { curc = read(); if (curc < 0) return lastttype = (int) TokenTypes.EOF; if (curc == '\n') curc = System.Int32.MaxValue; } if (curc == System.Int32.MaxValue) { curc = read(); if (curc < 0) return lastttype = (int) TokenTypes.EOF; } lastttype = curc; peekchar = System.Int32.MaxValue; int ctype = curc < 256?this.ctype[curc]:(sbyte)CharacterTypes.ALPHABETIC; while ((ctype & (sbyte)CharacterTypes.WHITESPACE) != 0) { if (curc == '\r') { linenumber++; if (iseolsig) { peekchar = (System.Int32.MaxValue - 1); return lastttype = (int) TokenTypes.EOL; } curc = read(); if (curc == '\n') curc = read(); } else { if (curc == '\n') { linenumber++; if (iseolsig) { return lastttype = (int) TokenTypes.EOL; } } curc = read(); } if (curc < 0) return lastttype = (int) TokenTypes.EOF; ctype = curc < 256?this.ctype[curc]:(sbyte)CharacterTypes.ALPHABETIC; } if ((ctype & (sbyte)CharacterTypes.NUMERIC) != 0) { bool checkb = false; if (curc == '-') { curc = read(); if (curc != '.' && (curc < '0' || curc > '9')) { peekchar = curc; return lastttype = '-'; } checkb = true; } double dvar = 0; int tempvar = 0; int checkdec = 0; while (true) { if (curc == '.' && checkdec == 0) checkdec = 1; else if ('0' <= curc && curc <= '9') { dvar = dvar * 10 + (curc - '0'); tempvar += checkdec; } else break; curc = read(); } peekchar = curc; if (tempvar != 0) { double divby = 10; tempvar--; while (tempvar > 0) { divby *= 10; tempvar--; } dvar = dvar / divby; } NumberValue = checkb?- dvar:dvar; return lastttype = (int) TokenTypes.NUMBER; } if ((ctype & (sbyte)CharacterTypes.ALPHABETIC) != 0) { int i = 0; do { if (i >= buf.Length) { char[] nb = new char[buf.Length * 2]; Array.Copy((System.Array) buf, 0, (System.Array) nb, 0, buf.Length); buf = nb; } buf[i++] = (char) curc; curc = read(); ctype = curc < 0?(sbyte)CharacterTypes.WHITESPACE:curc < 256?this.ctype[curc]:(sbyte)CharacterTypes.ALPHABETIC; } while ((ctype & ((sbyte)CharacterTypes.ALPHABETIC | (sbyte)CharacterTypes.NUMERIC)) != 0); peekchar = curc; StringValue = new String(buf, 0, i); if (cidtolower) StringValue = StringValue.ToLower(); return lastttype = (int) TokenTypes.WORD; } if ((ctype & (sbyte)CharacterTypes.STRINGQUOTE) != 0) { lastttype = curc; int i = 0; int rc = read(); while (rc >= 0 && rc != lastttype && rc != '\n' && rc != '\r') { if (rc == '\\') { curc = read(); int first = curc; if (curc >= '0' && curc <= '7') { curc = curc - '0'; int loopchar = read(); if ('0' <= loopchar && loopchar <= '7') { curc = (curc << 3) + (loopchar - '0'); loopchar = read(); if ('0' <= loopchar && loopchar <= '7' && first <= '3') { curc = (curc << 3) + (loopchar - '0'); rc = read(); } else rc = loopchar; } else rc = loopchar; } else { switch (curc) { case 'f': curc = 0xC; break; case 'a': curc = 0x7; break; case 'b': curc = '\b'; break; case 'v': curc = 0xB; break; case 'n': curc = '\n'; break; case 'r': curc = '\r'; break; case 't': curc = '\t'; break; default: break; } rc = read(); } } else { curc = rc; rc = read(); } if (i >= buf.Length) { char[] nb = new char[buf.Length * 2]; Array.Copy((System.Array) buf, 0, (System.Array) nb, 0, buf.Length); buf = nb; } buf[i++] = (char) curc; } peekchar = (rc == lastttype)?System.Int32.MaxValue:rc; StringValue = new String(buf, 0, i); return lastttype; } if (curc == '/' && (cppcomments || ccomments)) { curc = read(); if (curc == '*' && ccomments) { int prevc = 0; while ((curc = read()) != '/' || prevc != '*') { if (curc == '\r') { linenumber++; curc = read(); if (curc == '\n') { curc = read(); } } else { if (curc == '\n') { linenumber++; curc = read(); } } if (curc < 0) return lastttype = (int) TokenTypes.EOF; prevc = curc; } return nextToken(); } else if (curc == '/' && cppcomments) { while ((curc = read()) != '\n' && curc != '\r' && curc >= 0) ; peekchar = curc; return nextToken(); } else { if ((this.ctype['/'] & (sbyte)CharacterTypes.COMMENTCHAR) != 0) { while ((curc = read()) != '\n' && curc != '\r' && curc >= 0) ; peekchar = curc; return nextToken(); } else { peekchar = curc; return lastttype = '/'; } } } if ((ctype & (sbyte)CharacterTypes.COMMENTCHAR) != 0) { while ((curc = read()) != '\n' && curc != '\r' && curc >= 0) ; peekchar = curc; return nextToken(); } return lastttype = curc; } } }
#region File Description //----------------------------------------------------------------------------- // NetworkPredictionGame.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.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Net; #endregion namespace NetworkPrediction { /// <summary> /// Sample showing how to use prediction and smoothing to compensate /// for the effects of network latency, and for the low packet send /// rates needed to conserve network bandwidth. /// </summary> public class NetworkPredictionGame : Microsoft.Xna.Framework.Game { #region Constants const int screenWidth = 1067; const int screenHeight = 600; const int maxGamers = 16; const int maxLocalGamers = 4; #endregion #region Fields // Graphics objects. GraphicsDeviceManager graphics; SpriteBatch spriteBatch; SpriteFont font; // Current and previous input states. KeyboardState currentKeyboardState; GamePadState currentGamePadState; KeyboardState previousKeyboardState; GamePadState previousGamePadState; // Network objects. NetworkSession networkSession; PacketWriter packetWriter = new PacketWriter(); PacketReader packetReader = new PacketReader(); string errorMessage; // What kind of network latency and packet loss are we simulating? enum NetworkQuality { Typical, // 100 ms latency, 10% packet loss Poor, // 200 ms latency, 20% packet loss Perfect, // 0 latency, 0% packet loss } NetworkQuality networkQuality; // How often should we send network packets? int framesBetweenPackets = 6; // How recently did we send the last network packet? int framesSinceLastSend; // Is prediction and/or smoothing enabled? bool enablePrediction = true; bool enableSmoothing = true; #endregion #region Initialization public NetworkPredictionGame() { graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = screenWidth; graphics.PreferredBackBufferHeight = screenHeight; Content.RootDirectory = "Content"; Components.Add(new GamerServicesComponent(this)); } /// <summary> /// Load your content. /// </summary> protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); font = Content.Load<SpriteFont>("Font"); } #endregion #region Update /// <summary> /// Allows the game to run logic. /// </summary> protected override void Update(GameTime gameTime) { HandleInput(); if (networkSession == null) { // If we are not in a network session, update the // menu screen that will let us create or join one. UpdateMenuScreen(); } else { // If we are in a network session, update it. UpdateNetworkSession(gameTime); } base.Update(gameTime); } /// <summary> /// Menu screen provides options to create or join network sessions. /// </summary> void UpdateMenuScreen() { if (IsActive) { if (Gamer.SignedInGamers.Count == 0) { // If there are no profiles signed in, we cannot proceed. // Show the Guide so the user can sign in. Guide.ShowSignIn(maxLocalGamers, false); } else if (IsPressed(Keys.A, Buttons.A)) { // Create a new session? CreateSession(); } else if (IsPressed(Keys.B, Buttons.B)) { // Join an existing session? JoinSession(); } } } /// <summary> /// Starts hosting a new network session. /// </summary> void CreateSession() { DrawMessage("Creating session..."); try { networkSession = NetworkSession.Create(NetworkSessionType.SystemLink, maxLocalGamers, maxGamers); HookSessionEvents(); } catch (Exception e) { errorMessage = e.Message; } } /// <summary> /// Joins an existing network session. /// </summary> void JoinSession() { DrawMessage("Joining session..."); try { // Search for sessions. using (AvailableNetworkSessionCollection availableSessions = NetworkSession.Find(NetworkSessionType.SystemLink, maxLocalGamers, null)) { if (availableSessions.Count == 0) { errorMessage = "No network sessions found."; return; } // Join the first session we found. networkSession = NetworkSession.Join(availableSessions[0]); HookSessionEvents(); } } catch (Exception e) { errorMessage = e.Message; } } /// <summary> /// After creating or joining a network session, we must subscribe to /// some events so we will be notified when the session changes state. /// </summary> void HookSessionEvents() { networkSession.GamerJoined += GamerJoinedEventHandler; networkSession.SessionEnded += SessionEndedEventHandler; } /// <summary> /// This event handler will be called whenever a new gamer joins the session. /// We use it to allocate a Tank object, and associate it with the new gamer. /// </summary> void GamerJoinedEventHandler(object sender, GamerJoinedEventArgs e) { int gamerIndex = networkSession.AllGamers.IndexOf(e.Gamer); e.Gamer.Tag = new Tank(gamerIndex, Content, screenWidth, screenHeight); } /// <summary> /// Event handler notifies us when the network session has ended. /// </summary> void SessionEndedEventHandler(object sender, NetworkSessionEndedEventArgs e) { errorMessage = e.EndReason.ToString(); networkSession.Dispose(); networkSession = null; } /// <summary> /// Updates the state of the network session, moving the tanks /// around and synchronizing their state over the network. /// </summary> void UpdateNetworkSession(GameTime gameTime) { // Is it time to send outgoing network packets? bool sendPacketThisFrame = false; framesSinceLastSend++; if (framesSinceLastSend >= framesBetweenPackets) { sendPacketThisFrame = true; framesSinceLastSend = 0; } // Update our locally controlled tanks, sending // their latest state at periodic intervals. foreach (LocalNetworkGamer gamer in networkSession.LocalGamers) { UpdateLocalGamer(gamer, gameTime, sendPacketThisFrame); } // Pump the underlying session object. try { networkSession.Update(); } catch (Exception e) { errorMessage = e.Message; networkSession.Dispose(); networkSession = null; } // Make sure the session has not ended. if (networkSession == null) return; // Read any packets telling us the state of remotely controlled tanks. foreach (LocalNetworkGamer gamer in networkSession.LocalGamers) { ReadIncomingPackets(gamer, gameTime); } // Apply prediction and smoothing to the remotely controlled tanks. foreach (NetworkGamer gamer in networkSession.RemoteGamers) { Tank tank = gamer.Tag as Tank; tank.UpdateRemote(framesBetweenPackets, enablePrediction); } // Update the latency and packet loss simulation options. UpdateOptions(); } /// <summary> /// Helper for updating a locally controlled gamer. /// </summary> void UpdateLocalGamer(LocalNetworkGamer gamer, GameTime gameTime, bool sendPacketThisFrame) { // Look up what tank is associated with this local player. Tank tank = gamer.Tag as Tank; // Read the inputs controlling this tank. PlayerIndex playerIndex = gamer.SignedInGamer.PlayerIndex; Vector2 tankInput; Vector2 turretInput; ReadTankInputs(playerIndex, out tankInput, out turretInput); // Update the tank. tank.UpdateLocal(tankInput, turretInput); // Periodically send our state to everyone in the session. if (sendPacketThisFrame) { tank.WriteNetworkPacket(packetWriter, gameTime); gamer.SendData(packetWriter, SendDataOptions.InOrder); } } /// <summary> /// Helper for reading incoming network packets. /// </summary> void ReadIncomingPackets(LocalNetworkGamer gamer, GameTime gameTime) { // Keep reading as long as incoming packets are available. while (gamer.IsDataAvailable) { NetworkGamer sender; // Read a single packet from the network. gamer.ReceiveData(packetReader, out sender); // Discard packets sent by local gamers: we already know their state! if (sender.IsLocal) continue; // Look up the tank associated with whoever sent this packet. Tank tank = sender.Tag as Tank; // Estimate how long this packet took to arrive. TimeSpan latency = networkSession.SimulatedLatency + TimeSpan.FromTicks(sender.RoundtripTime.Ticks / 2); // Read the state of this tank from the network packet. tank.ReadNetworkPacket(packetReader, gameTime, latency, enablePrediction, enableSmoothing); } } /// <summary> /// Updates the latency and packet loss simulation options. Only the /// host can alter these values, which are then synchronized over the /// network by storing them into NetworkSession.SessionProperties. Any /// changes to the SessionProperties data are automatically replicated /// on all the client machines, so there is no need to manually send /// network packets to transmit this data. /// </summary> void UpdateOptions() { if (networkSession.IsHost) { // Change the network quality simultation? if (IsPressed(Keys.A, Buttons.A)) { networkQuality++; if (networkQuality > NetworkQuality.Perfect) networkQuality = 0; } // Change the packet send rate? if (IsPressed(Keys.B, Buttons.B)) { if (framesBetweenPackets == 6) framesBetweenPackets = 3; else if (framesBetweenPackets == 3) framesBetweenPackets = 1; else framesBetweenPackets = 6; } // Toggle prediction on or off? if (IsPressed(Keys.X, Buttons.X)) enablePrediction = !enablePrediction; // Toggle smoothing on or off? if (IsPressed(Keys.Y, Buttons.Y)) enableSmoothing = !enableSmoothing; // Stores the latest settings into NetworkSession.SessionProperties. networkSession.SessionProperties[0] = (int)networkQuality; networkSession.SessionProperties[1] = framesBetweenPackets; networkSession.SessionProperties[2] = enablePrediction ? 1 : 0; networkSession.SessionProperties[3] = enableSmoothing ? 1 : 0; } else { // Client machines read the latest settings from the session properties. networkQuality = (NetworkQuality)networkSession.SessionProperties[0]; framesBetweenPackets = networkSession.SessionProperties[1].Value; enablePrediction = networkSession.SessionProperties[2] != 0; enableSmoothing = networkSession.SessionProperties[3] != 0; } // Update the SimulatedLatency and SimulatedPacketLoss properties. switch (networkQuality) { case NetworkQuality.Typical: networkSession.SimulatedLatency = TimeSpan.FromMilliseconds(100); networkSession.SimulatedPacketLoss = 0.1f; break; case NetworkQuality.Poor: networkSession.SimulatedLatency = TimeSpan.FromMilliseconds(200); networkSession.SimulatedPacketLoss = 0.2f; break; case NetworkQuality.Perfect: networkSession.SimulatedLatency = TimeSpan.Zero; networkSession.SimulatedPacketLoss = 0; break; } } #endregion #region Draw /// <summary> /// This is called when the game should draw itself. /// </summary> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); if (networkSession == null) { // If we are not in a network session, draw the // menu screen that will let us create or join one. DrawMenuScreen(); } else { // If we are in a network session, draw it. DrawNetworkSession(); } base.Draw(gameTime); } /// <summary> /// Draws the startup screen used to create and join network sessions. /// </summary> void DrawMenuScreen() { string message = string.Empty; if (!string.IsNullOrEmpty(errorMessage)) message += "Error:\n" + errorMessage.Replace(". ", ".\n") + "\n\n"; message += "A = create session\n" + "B = join session"; spriteBatch.Begin(); spriteBatch.DrawString(font, message, new Vector2(161, 161), Color.Black); spriteBatch.DrawString(font, message, new Vector2(160, 160), Color.White); spriteBatch.End(); } /// <summary> /// Draws the state of an active network session. /// </summary> void DrawNetworkSession() { spriteBatch.Begin(); DrawOptions(); // For each person in the session... foreach (NetworkGamer gamer in networkSession.AllGamers) { // Look up the tank object belonging to this network gamer. Tank tank = gamer.Tag as Tank; // Draw the tank. tank.Draw(spriteBatch); // Draw a gamertag label. spriteBatch.DrawString(font, gamer.Gamertag, tank.Position, Color.Black, 0, new Vector2(100, 150), 0.6f, SpriteEffects.None, 0); } spriteBatch.End(); } /// <summary> /// Draws the current latency and packet loss simulation settings. /// </summary> void DrawOptions() { string quality = string.Format("Network simulation = {0} ms, {1}% packet loss", networkSession.SimulatedLatency.TotalMilliseconds, networkSession.SimulatedPacketLoss * 100); string sendRate = string.Format("Packets per second = {0}", 60 / framesBetweenPackets); string prediction = string.Format("Prediction = {0}", enablePrediction ? "on" : "off"); string smoothing = string.Format("Smoothing = {0}", enableSmoothing ? "on" : "off"); // If we are the host, include prompts telling how to change the settings. if (networkSession.IsHost) { quality += " (A to change)"; sendRate += " (B to change)"; prediction += " (X to toggle)"; smoothing += " (Y to toggle)"; } // Draw combined text to the screen. string message = quality + "\n" + sendRate + "\n" + prediction + "\n" + smoothing; spriteBatch.DrawString(font, message, new Vector2(161, 321), Color.Black); spriteBatch.DrawString(font, message, new Vector2(160, 320), Color.White); } /// <summary> /// Helper draws notification messages before calling blocking network methods. /// </summary> void DrawMessage(string message) { if (!BeginDraw()) return; GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); spriteBatch.DrawString(font, message, new Vector2(161, 161), Color.Black); spriteBatch.DrawString(font, message, new Vector2(160, 160), Color.White); spriteBatch.End(); EndDraw(); } #endregion #region Handle Input /// <summary> /// Handles input. /// </summary> private void HandleInput() { previousKeyboardState = currentKeyboardState; previousGamePadState = currentGamePadState; currentKeyboardState = Keyboard.GetState(); currentGamePadState = GamePad.GetState(PlayerIndex.One); // Check for exit. if (IsActive && IsPressed(Keys.Escape, Buttons.Back)) { Exit(); } } /// <summary> /// Checks if the specified button is pressed on either keyboard or gamepad. /// </summary> bool IsPressed(Keys key, Buttons button) { return ((currentKeyboardState.IsKeyDown(key) && previousKeyboardState.IsKeyUp(key)) || (currentGamePadState.IsButtonDown(button) && previousGamePadState.IsButtonUp(button))); } /// <summary> /// Reads input data from keyboard and gamepad, and returns /// this as output parameters ready for use by the tank update. /// </summary> static void ReadTankInputs(PlayerIndex playerIndex, out Vector2 tankInput, out Vector2 turretInput) { // Read the gamepad. GamePadState gamePad = GamePad.GetState(playerIndex); tankInput = gamePad.ThumbSticks.Left; turretInput = gamePad.ThumbSticks.Right; // Read the keyboard. KeyboardState keyboard = Keyboard.GetState(playerIndex); if (keyboard.IsKeyDown(Keys.Left)) tankInput.X = -1; else if (keyboard.IsKeyDown(Keys.Right)) tankInput.X = 1; if (keyboard.IsKeyDown(Keys.Up)) tankInput.Y = 1; else if (keyboard.IsKeyDown(Keys.Down)) tankInput.Y = -1; if (keyboard.IsKeyDown(Keys.K)) turretInput.X = -1; else if (keyboard.IsKeyDown(Keys.OemSemicolon)) turretInput.X = 1; if (keyboard.IsKeyDown(Keys.O)) turretInput.Y = 1; else if (keyboard.IsKeyDown(Keys.L)) turretInput.Y = -1; // Normalize the input vectors. if (tankInput.Length() > 1) tankInput.Normalize(); if (turretInput.Length() > 1) turretInput.Normalize(); } #endregion } #region Entry Point /// <summary> /// The main entry point for the application. /// </summary> static class Program { static void Main() { using (NetworkPredictionGame game = new NetworkPredictionGame()) { game.Run(); } } } #endregion }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.Activities.Runtime { using System; using System.Collections.Generic; using System.Globalization; using System.Diagnostics.CodeAnalysis; using System.Runtime; using System.Runtime.Serialization; using System.Activities.DynamicUpdate; using System.Activities.Statements; using System.Collections.ObjectModel; [DataContract(Name = XD.Runtime.ActivityInstanceMap, Namespace = XD.Runtime.Namespace)] class ActivityInstanceMap { // map from activities to (active) associated activity instances IDictionary<Activity, InstanceList> instanceMapping; InstanceList[] rawDeserializedLists; IList<InstanceListNeedingUpdate> updateList; internal ActivityInstanceMap() { } [SuppressMessage(FxCop.Category.Performance, FxCop.Rule.AvoidUncalledPrivateCode, Justification = "Called by serialization")] [DataMember(EmitDefaultValue = false)] internal InstanceList[] SerializedInstanceLists { get { if (this.instanceMapping == null || this.instanceMapping.Count == 0) { return this.rawDeserializedLists; } else { InstanceList[] lists = new InstanceList[this.instanceMapping.Count]; int index = 0; foreach (KeyValuePair<Activity, InstanceList> entry in this.instanceMapping) { entry.Value.ActivityId = entry.Key.QualifiedId.AsByteArray(); lists[index] = entry.Value; index++; } return lists; } } set { Fx.Assert(value != null, "We don't serialize the default value."); this.rawDeserializedLists = value; } } IDictionary<Activity, InstanceList> InstanceMapping { get { if (this.instanceMapping == null) { this.instanceMapping = new Dictionary<Activity, InstanceList>(); } return this.instanceMapping; } } private static void AddBlockingActivity(ref Collection<ActivityBlockingUpdate> updateErrors, DynamicUpdateMap.UpdatedActivity updatedActivity, QualifiedId originalId, string reason, string activityInstanceId) { if (updatedActivity.NewActivity != null) { ActivityBlockingUpdate.AddBlockingActivity(ref updateErrors, updatedActivity.NewActivity, originalId.ToString(), reason, activityInstanceId); } else { string updatedId = updatedActivity.MapEntry.IsRemoval ? null : updatedActivity.NewId.ToString(); ActivityBlockingUpdate.AddBlockingActivity(ref updateErrors, updatedId, originalId.ToString(), reason, activityInstanceId); } } public void GetActivitiesBlockingUpdate(DynamicUpdateMap updateMap, List<ActivityInstance> secondaryRootInstances, ref Collection<ActivityBlockingUpdate> updateErrors) { this.GetInstanceListsNeedingUpdate(updateMap, null, secondaryRootInstances, ref updateErrors); } // searching secondaryRootInstances list is necessary because instance in InstanceList doesn't have its Parent set until it's fixed up. // so the only way to find out if an instance in InstanceList is a secondary root is to lookup in secondaryRootInstances list. private static bool IsNonDefaultSecondaryRoot(ActivityInstance instance, List<ActivityInstance> secondaryRootInstances) { if (secondaryRootInstances != null && secondaryRootInstances.Contains(instance)) { // Non-default secondary roots are CompensationParticipant type, and their environment will always have a non-null parent which is the environment owned by a CompensableActivity. // A secondary root whose environment parent is null is the default secondary root, WorkflowCompensationBehavior. if (instance.IsEnvironmentOwner && instance.Environment.Parent != null) { return true; } } return false; } private static bool CanCompensationOrConfirmationHandlerReferenceAddedSymbols(InstanceList instanceList, DynamicUpdateMap rootUpdateMap, IdSpace rootIdSpace, List<ActivityInstance> secondaryRootInstances, ref Collection<ActivityBlockingUpdate> updateErrors) { for (int j = 0; j < instanceList.Count; j++) { ActivityInstance activityInstance = instanceList[j] as ActivityInstance; if (activityInstance == null || !IsNonDefaultSecondaryRoot(activityInstance, secondaryRootInstances)) { continue; } // here, find out if the given non-default secondary root references an environment to which a symbol is to be added via DU. // we start from a secondary root instead of starting from the enviroment with the already completed owner that was added symbols. // It is becuase for the case of adding symbols to noSymbols activities, the environment doesn't even exist from which we can start looking for referencing secondary root. int[] secondaryRootOriginalQID = new QualifiedId(instanceList.ActivityId).AsIDArray(); Fx.Assert(secondaryRootOriginalQID != null && secondaryRootOriginalQID.Length > 1, "CompensationParticipant is always an implementation child of a CompensableActivity, therefore it's IdSpace must be at least one level deep."); int[] parentOfSecondaryRootOriginalQID = new int[secondaryRootOriginalQID.Length - 1]; Array.Copy(secondaryRootOriginalQID, parentOfSecondaryRootOriginalQID, secondaryRootOriginalQID.Length - 1); List<int> currentQIDBuilder = new List<int>(); for (int i = 0; i < parentOfSecondaryRootOriginalQID.Length; i++) { // // for each iteration of this for-loop, // we are finding out if at every IdSpace level the map has any map entry whose activity has the CompensableActivity as an implementation decendant. // The map may not exist for every IdSpace between the root and the CompensableActivity. // If the matching map and the entry is found, then we find out if that matching entry's activity is a public decendant of any NoSymbols activity DU is to add variables or arguments to. // // This walk on the definition activity tree determines the hypothetical execution-time chain of instances and environments. // The ultimate goal is to prevent adding variables or arguments to a NoSymbols activity which has already completed, // but its decendant CompensableActivity's compensation or confirmation handlers in the future may need to reference the added variables or arguments. currentQIDBuilder.Add(parentOfSecondaryRootOriginalQID[i]); DynamicUpdateMap.UpdatedActivity updatedActivity = rootUpdateMap.GetUpdatedActivity(new QualifiedId(currentQIDBuilder.ToArray()), rootIdSpace); if (updatedActivity.MapEntry != null) { // the activity of this entry either has the CompensableActivity as an implementation decendant, or is the CompensableActivity itself. // walk the same-IdSpace-parent chain of the entry, // look for an entry whose EnvironmentUpdateMap.IsAdditionToNoSymbols is true. DynamicUpdateMapEntry entry = updatedActivity.MapEntry; do { if (!entry.IsRemoval && entry.HasEnvironmentUpdates && entry.EnvironmentUpdateMap.IsAdditionToNoSymbols) { int[] noSymbolAddActivityIDArray = currentQIDBuilder.ToArray(); noSymbolAddActivityIDArray[noSymbolAddActivityIDArray.Length - 1] = entry.OldActivityId; QualifiedId noSymbolAddActivityQID = new QualifiedId(noSymbolAddActivityIDArray); DynamicUpdateMap.UpdatedActivity noSymbolAddUpdatedActivity = rootUpdateMap.GetUpdatedActivity(noSymbolAddActivityQID, rootIdSpace); AddBlockingActivity(ref updateErrors, noSymbolAddUpdatedActivity, noSymbolAddActivityQID, SR.VariableOrArgumentAdditionToReferencedEnvironmentNoDUSupported, null); return true; } entry = entry.Parent; } while (entry != null); } } } return false; } private static bool IsInvalidEnvironmentUpdate(InstanceList instanceList, DynamicUpdateMap.UpdatedActivity updatedActivity, ref Collection<ActivityBlockingUpdate> updateErrors) { if (updatedActivity.MapEntry == null || !updatedActivity.MapEntry.HasEnvironmentUpdates) { return false; } for (int j = 0; j < instanceList.Count; j++) { ActivityInstance activityInstance = instanceList[j] as ActivityInstance; if (activityInstance != null) { string error = null; if (activityInstance.SubState == ActivityInstance.Substate.ResolvingVariables) { // if the entry has Environment update to do when the instance is in the middle of resolving variable, it is an error. error = SR.CannotUpdateEnvironmentInTheMiddleOfResolvingVariables; } else if (activityInstance.SubState == ActivityInstance.Substate.ResolvingArguments) { // if the entry has Environment update to do when the instance is in the middle of resolving arguments, it is an error. error = SR.CannotUpdateEnvironmentInTheMiddleOfResolvingArguments; } if (error != null) { AddBlockingActivity(ref updateErrors, updatedActivity, new QualifiedId(instanceList.ActivityId), error, activityInstance.Id); return true; } } else { LocationEnvironment environment = instanceList[j] as LocationEnvironment; if (environment != null) { // // environment that is referenced by a secondary root // Adding a variable or argument that requires expression scheduling to this instanceless environment is not allowed. // List<int> dummyIndexes; EnvironmentUpdateMap envMap = updatedActivity.MapEntry.EnvironmentUpdateMap; if ((envMap.HasVariableEntries && TryGatherSchedulableExpressions(envMap.VariableEntries, out dummyIndexes)) || (envMap.HasPrivateVariableEntries && TryGatherSchedulableExpressions(envMap.PrivateVariableEntries, out dummyIndexes)) || (envMap.HasArgumentEntries && TryGatherSchedulableExpressions(envMap.ArgumentEntries, out dummyIndexes))) { AddBlockingActivity(ref updateErrors, updatedActivity, new QualifiedId(instanceList.ActivityId), SR.VariableOrArgumentAdditionToReferencedEnvironmentNoDUSupported, null); return true; } } } } return false; } private static bool IsRemovalOrRTUpdateBlockedOrBlockedByUser(DynamicUpdateMap.UpdatedActivity updatedActivity, QualifiedId oldQualifiedId, out string error) { error = null; if (updatedActivity.MapEntry.IsRemoval) { // error = SR.CannotRemoveExecutingActivityUpdateError(oldQualifiedId, updatedActivity.MapEntry.DisplayName); } else if (updatedActivity.MapEntry.IsRuntimeUpdateBlocked) { error = updatedActivity.MapEntry.BlockReasonMessage ?? UpdateBlockedReasonMessages.Get(updatedActivity.MapEntry.BlockReason); } else if (updatedActivity.MapEntry.IsUpdateBlockedByUpdateAuthor) { error = SR.BlockedUpdateInsideActivityUpdateByUserError; } return error != null; } // targetDefinition argument is optional. private IList<InstanceListNeedingUpdate> GetInstanceListsNeedingUpdate(DynamicUpdateMap updateMap, Activity targetDefinition, List<ActivityInstance> secondaryRootInstances, ref Collection<ActivityBlockingUpdate> updateErrors) { IList<InstanceListNeedingUpdate> instanceListsToUpdate = new List<InstanceListNeedingUpdate>(); if (this.rawDeserializedLists == null) { // This instance doesn't have any active instances (it is complete). return instanceListsToUpdate; } IdSpace rootIdSpace = null; if (targetDefinition != null) { rootIdSpace = targetDefinition.MemberOf; } for (int i = 0; i < this.rawDeserializedLists.Length; i++) { InstanceList list = this.rawDeserializedLists[i]; QualifiedId oldQualifiedId = new QualifiedId(list.ActivityId); if (updateMap.IsImplementationAsRoot) { int[] oldIdArray = oldQualifiedId.AsIDArray(); if (oldIdArray.Length == 1 && oldIdArray[0] != 1) { throw FxTrace.Exception.AsError(new InstanceUpdateException(SR.InvalidImplementationAsWorkflowRootForRuntimeState)); } } string error; InstanceListNeedingUpdate update; DynamicUpdateMap.UpdatedActivity updatedActivity = updateMap.GetUpdatedActivity(oldQualifiedId, rootIdSpace); if (CanCompensationOrConfirmationHandlerReferenceAddedSymbols(list, updateMap, rootIdSpace, secondaryRootInstances, ref updateErrors)) { update = null; } else if (updatedActivity.MapEntry == null) { if (updatedActivity.IdChanged) { // this newQualifiedId is the new id for those InstanceLists whose IDs shifted by their parents' ID change update = new InstanceListNeedingUpdate { InstanceList = list, NewId = updatedActivity.NewId }; } else { // nothing changed, no map, no mapEntry update = new InstanceListNeedingUpdate { InstanceList = list, NewId = null, }; } } else if (updatedActivity.MapEntry.IsParentRemovedOrBlocked) { update = null; } else if (IsRemovalOrRTUpdateBlockedOrBlockedByUser(updatedActivity, oldQualifiedId, out error)) { string instanceId = null; for (int j = 0; j < list.Count; j++) { ActivityInstance activityInstance = list[j] as ActivityInstance; if (activityInstance != null) { instanceId = activityInstance.Id; break; } } AddBlockingActivity(ref updateErrors, updatedActivity, oldQualifiedId, error, instanceId); update = null; } else if (IsInvalidEnvironmentUpdate(list, updatedActivity, ref updateErrors)) { update = null; } else { // no validation error for this InstanceList // add it to the list of InstanceLists to be updated update = new InstanceListNeedingUpdate { InstanceList = list, NewId = updatedActivity.NewId, UpdateMap = updatedActivity.Map, MapEntry = updatedActivity.MapEntry, NewActivity = updatedActivity.NewActivity }; } if (update != null) { update.OriginalId = list.ActivityId; instanceListsToUpdate.Add(update); } } return instanceListsToUpdate; } public void UpdateRawInstance(DynamicUpdateMap updateMap, Activity targetDefinition, List<ActivityInstance> secondaryRootInstances, ref Collection<ActivityBlockingUpdate> updateErrors) { this.updateList = GetInstanceListsNeedingUpdate(updateMap, targetDefinition, secondaryRootInstances, ref updateErrors); if (updateErrors != null && updateErrors.Count > 0) { // error found. // there is no need to proceed to updating the instances return; } // if UpdateType is either MapEntryExists or ParentIdShiftOnly, // update the ActivityIDs and update Environments // also, update the ImplementationVersion. foreach (InstanceListNeedingUpdate update in this.updateList) { Fx.Assert(update.InstanceList != null, "update.InstanceList must not be null."); if (update.NothingChanged) { continue; } Fx.Assert(update.NewId != null, "update.NewId must not be null."); InstanceList instanceList = update.InstanceList; instanceList.ActivityId = update.NewId.AsByteArray(); if (update.ParentIdShiftOnly) { // this InstanceList must have been one of those whose IDs shifted by their parent's ID change, // but no involvement in DU. continue; } bool implementationVersionUpdateNeeded = false; if (update.MapEntry.ImplementationUpdateMap != null) { implementationVersionUpdateNeeded = true; } if (update.MapEntry.HasEnvironmentUpdates) { // update LocationEnvironemnt Fx.Assert(update.NewActivity != null, "TryGetUpdateMapEntryFromRootMap should have thrown if it couldn't map to an activity"); instanceList.UpdateEnvironments(update.MapEntry.EnvironmentUpdateMap, update.NewActivity); } for (int i = 0; i < instanceList.Count; i++) { ActivityInstance activityInstance = instanceList[i] as ActivityInstance; if (implementationVersionUpdateNeeded) { activityInstance.ImplementationVersion = update.NewActivity.ImplementationVersion; } } } } private static bool TryGatherSchedulableExpressions(IList<EnvironmentUpdateMapEntry> entries, out List<int> addedLocationReferenceIndexes) { addedLocationReferenceIndexes = null; for (int i = 0; i < entries.Count; i++) { EnvironmentUpdateMapEntry entry = entries[i]; if (entry.IsAddition) { if (addedLocationReferenceIndexes == null) { addedLocationReferenceIndexes = new List<int>(); } addedLocationReferenceIndexes.Add(entry.NewOffset); } } return addedLocationReferenceIndexes != null; } // this is called after all instances have been loaded and fixedup public void UpdateInstanceByActivityParticipation(ActivityExecutor activityExecutor, DynamicUpdateMap rootMap, ref Collection<ActivityBlockingUpdate> updateErrors) { foreach (InstanceListNeedingUpdate participant in this.updateList) { if (participant.NothingChanged || participant.ParentIdShiftOnly) { Fx.Assert(participant.UpdateMap == null && participant.MapEntry == null, "UpdateMap and MapEntry must be null if we are here."); // create a temporary NoChanges UpdateMap as well as a temporary no change MapEntry // so that we can create a NativeActivityUpdateContext object in order to invoke UpdateInstance() on an activity which // doesn't have a corresponding map and an map entry. // The scenario enabled here is scheduling a newly added reference branch to a Parallel inside an activity's implementation. participant.UpdateMap = DynamicUpdateMap.DummyMap; participant.MapEntry = DynamicUpdateMapEntry.DummyMapEntry; } // now let activities participate in update for (int i = 0; i < participant.InstanceList.Count; i++) { ActivityInstance instance = participant.InstanceList[i] as ActivityInstance; if (instance == null) { continue; } IInstanceUpdatable activity = instance.Activity as IInstanceUpdatable; if (activity != null && instance.SubState == ActivityInstance.Substate.Executing) { NativeActivityUpdateContext updateContext = new NativeActivityUpdateContext(this, activityExecutor, instance, participant.UpdateMap, participant.MapEntry, rootMap); try { activity.InternalUpdateInstance(updateContext); if (updateContext.IsUpdateDisallowed) { ActivityBlockingUpdate.AddBlockingActivity(ref updateErrors, instance.Activity, new QualifiedId(participant.OriginalId).ToString(), updateContext.DisallowedReason, instance.Id); continue; } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } throw FxTrace.Exception.AsError(new InstanceUpdateException(SR.NativeActivityUpdateInstanceThrewException(e.Message), e)); } finally { updateContext.Dispose(); } } } } // Schedule evaluation of newly added arguments and newly added variables. // This needs to happen after all the invokations of UpdateInstance above, so that newly // added arguments and newly added variables get evaluated before any newly added activities get executed. // We iterate the list in reverse so that parents are always scheduled after (and thus // execute before) their children, which may depend on the parents. for (int i = this.updateList.Count - 1; i >= 0; i--) { InstanceListNeedingUpdate participant = this.updateList[i]; if (!participant.MapEntryExists) { // if the given InstanceList has no map entry, // then there is no new LocationReferences to resolve. continue; } Fx.Assert(participant.MapEntry != null, "MapEntry must be non-null here."); if (!participant.MapEntry.HasEnvironmentUpdates) { // if there is no environment updates for this MapEntry, // then there is no new LocationReferences to resolve. continue; } for (int j = 0; j < participant.InstanceList.Count; j++) { ActivityInstance instance = participant.InstanceList[j] as ActivityInstance; if (instance == null || instance.SubState != ActivityInstance.Substate.Executing) { // if the given ActivityInstance is not in Substate.Executing, // then, do not try to resolve new LocationReferences continue; } List<int> addedArgumentIndexes; List<int> addedVariableIndexes; List<int> addedPrivateVariableIndexes; EnvironmentUpdateMap envMap = participant.MapEntry.EnvironmentUpdateMap; if (envMap.HasVariableEntries && TryGatherSchedulableExpressions(envMap.VariableEntries, out addedVariableIndexes)) { // schedule added variable default expressions instance.ResolveNewVariableDefaultsDuringDynamicUpdate(activityExecutor, addedVariableIndexes, false); } if (envMap.HasPrivateVariableEntries && TryGatherSchedulableExpressions(envMap.PrivateVariableEntries, out addedPrivateVariableIndexes)) { // schedule added private variable default expressions // HasPrivateMemberChanged() check disallows addition of private variable default that offsets the private IdSpace, // However, the added private variable default expression can be an imported activity, which has no affect on the private IdSpace. // For such case, we want to be able to schedule the imported default expressions here. instance.ResolveNewVariableDefaultsDuringDynamicUpdate(activityExecutor, addedPrivateVariableIndexes, true); } if (envMap.HasArgumentEntries && TryGatherSchedulableExpressions(envMap.ArgumentEntries, out addedArgumentIndexes)) { // schedule added arguments instance.ResolveNewArgumentsDuringDynamicUpdate(activityExecutor, addedArgumentIndexes); } } } } public void AddEntry(IActivityReference reference, bool skipIfDuplicate) { Activity activity = reference.Activity; InstanceList mappedInstances; if (this.InstanceMapping.TryGetValue(activity, out mappedInstances)) { mappedInstances.Add(reference, skipIfDuplicate); } else { this.InstanceMapping.Add(activity, new InstanceList(reference)); } } public void AddEntry(IActivityReference reference) { AddEntry(reference, false); } public void LoadActivityTree(Activity rootActivity, ActivityInstance rootInstance, List<ActivityInstance> secondaryRootInstances, ActivityExecutor executor) { Fx.Assert(this.rawDeserializedLists != null, "We should always have deserialized some lists."); this.instanceMapping = new Dictionary<Activity, InstanceList>(this.rawDeserializedLists.Length); for (int i = 0; i < this.rawDeserializedLists.Length; i++) { InstanceList list = this.rawDeserializedLists[i]; Activity activity; if (!QualifiedId.TryGetElementFromRoot(rootActivity, list.ActivityId, out activity)) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.ActivityInstanceFixupFailed)); } this.instanceMapping.Add(activity, list); list.Load(activity, this); } // We need to null this out once we've recreated the dictionary to avoid // having out of [....] data this.rawDeserializedLists = null; // then walk our instance list, fixup parent references, and perform basic validation Func<ActivityInstance, ActivityExecutor, bool> processInstanceCallback = new Func<ActivityInstance, ActivityExecutor, bool>(OnActivityInstanceLoaded); rootInstance.FixupInstance(null, this, executor); ActivityUtilities.ProcessActivityInstanceTree(rootInstance, executor, processInstanceCallback); if (secondaryRootInstances != null) { foreach (ActivityInstance instance in secondaryRootInstances) { instance.FixupInstance(null, this, executor); ActivityUtilities.ProcessActivityInstanceTree(instance, executor, processInstanceCallback); } } } bool OnActivityInstanceLoaded(ActivityInstance activityInstance, ActivityExecutor executor) { return activityInstance.TryFixupChildren(this, executor); } public bool RemoveEntry(IActivityReference reference) { if (this.instanceMapping == null) { return false; } Activity activity = reference.Activity; InstanceList mappedInstances; if (!this.InstanceMapping.TryGetValue(activity, out mappedInstances)) { return false; } if (mappedInstances.Count == 1) { this.InstanceMapping.Remove(activity); } else { mappedInstances.Remove(reference); } return true; } [DataContract] internal class InstanceList : HybridCollection<IActivityReference> { public InstanceList(IActivityReference reference) : base(reference) { } [SuppressMessage(FxCop.Category.Performance, FxCop.Rule.AvoidUncalledPrivateCode, Justification = "Called by serialization")] [DataMember] public byte[] ActivityId { get; set; } [OnSerializing] [SuppressMessage(FxCop.Category.Usage, FxCop.Rule.ReviewUnusedParameters)] [SuppressMessage(FxCop.Category.Usage, "CA2238:ImplementSerializationMethodsCorrectly", Justification = "Needs to be internal for serialization in partial trust. We have set InternalsVisibleTo(System.Runtime.Serialization) to allow this.")] internal void OnSerializing(StreamingContext context) { base.Compress(); } public void Add(IActivityReference reference, bool skipIfDuplicate) { Fx.Assert(this.Count >= 1, "instance list should never be empty when we call Add"); if (skipIfDuplicate) { if (base.SingleItem != null) { if (base.SingleItem == reference) { return; } } else { if (base.MultipleItems.Contains(reference)) { return; } } } Add(reference); } public void Load(Activity activity, ActivityInstanceMap instanceMap) { Fx.Assert(this.Count >= 1, "instance list should never be empty on load"); if (base.SingleItem != null) { base.SingleItem.Load(activity, instanceMap); } else { for (int i = 0; i < base.MultipleItems.Count; i++) { base.MultipleItems[i].Load(activity, instanceMap); } } } public void UpdateEnvironments(EnvironmentUpdateMap map, Activity activity) { if (base.SingleItem != null) { IActivityReferenceWithEnvironment reference = base.SingleItem as IActivityReferenceWithEnvironment; if (reference != null) { reference.UpdateEnvironment(map, activity); } } else { for (int i = 0; i < base.MultipleItems.Count; i++) { IActivityReferenceWithEnvironment reference = base.MultipleItems[i] as IActivityReferenceWithEnvironment; if (reference != null) { reference.UpdateEnvironment(map, activity); } } } } } public interface IActivityReference { Activity Activity { get; } void Load(Activity activity, ActivityInstanceMap instanceMap); } public interface IActivityReferenceWithEnvironment : IActivityReference { void UpdateEnvironment(EnvironmentUpdateMap map, Activity activity); } class InstanceListNeedingUpdate { // The list of IActivityReferences to be updated public InstanceList InstanceList { get; set; } public byte[] OriginalId { get; set; } // The new ActivityId for these ActivityReferences. public QualifiedId NewId { get; set; } // The Map & MapEntry for this ActivityId, if there is one. // Null if the activity's parent Id was updated, but not the activity itself, // Or null if nothing changed. public DynamicUpdateMap UpdateMap { get; set; } public DynamicUpdateMapEntry MapEntry { get; set; } // A pointer to this activity, in the new definition. // Null if we don't have the definition loaded. public Activity NewActivity { get; set; } // // the following three properties are mutual exlusive, // meaning, one and only one of them evaluates to TRUE. // public bool NothingChanged { get { return this.MapEntry == null && this.NewId == null; } } public bool MapEntryExists { get { return this.MapEntry != null; } } public bool ParentIdShiftOnly { get { return this.MapEntry == null && this.NewId != null; } } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Microsoft.WindowsAzure.Management.ExpressRoute; using Microsoft.WindowsAzure.Management.ExpressRoute.Models; namespace Microsoft.WindowsAzure.Management.ExpressRoute { internal partial class DedicatedCircuitPeeringRouteTableSummaryOperations : IServiceOperations<ExpressRouteManagementClient>, IDedicatedCircuitPeeringRouteTableSummaryOperations { /// <summary> /// Initializes a new instance of the /// DedicatedCircuitPeeringRouteTableSummaryOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DedicatedCircuitPeeringRouteTableSummaryOperations(ExpressRouteManagementClient client) { this._client = client; } private ExpressRouteManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.ExpressRoute.ExpressRouteManagementClient. /// </summary> public ExpressRouteManagementClient Client { get { return this._client; } } /// <summary> /// The Get DedicatedCircuitPeeringRouteTableSummary operation retrives /// RouteTableSummary. /// </summary> /// <param name='serviceKey'> /// Required. The service key representing the circuit. /// </param> /// <param name='accessType'> /// Required. Whether the peering is private or public or microsoft. /// </param> /// <param name='devicePath'> /// Required. Whether the device is primary or secondary. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<ExpressRouteOperationResponse> BeginGetAsync(string serviceKey, BgpPeeringAccessType accessType, DevicePath devicePath, CancellationToken cancellationToken) { // Validate if (serviceKey == null) { throw new ArgumentNullException("serviceKey"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("accessType", accessType); tracingParameters.Add("devicePath", devicePath); TracingAdapter.Enter(invocationId, this, "BeginGetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/networking/dedicatedcircuits/"; url = url + Uri.EscapeDataString(serviceKey); url = url + "/bgppeerings/"; url = url + Uri.EscapeDataString(ExpressRouteManagementClient.BgpPeeringAccessTypeToString(accessType)); url = url + "/routeTableSummary/"; url = url + Uri.EscapeDataString(ExpressRouteManagementClient.DevicePathToString(devicePath)); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=1.0"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ExpressRouteOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ExpressRouteOperationResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure")); if (gatewayOperationAsyncResponseElement != null) { XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.OperationId = idInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Get DedicatedCircuitPeeringRouteTableSummary operation retrives /// RouteTableSummary. /// </summary> /// <param name='serviceKey'> /// Required. The service key representing the circuit. /// </param> /// <param name='accessType'> /// Required. Whether the peering is private or public or microsoft. /// </param> /// <param name='devicePath'> /// Required. Whether the device is primary or secondary. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<ExpressRouteOperationStatusResponse> GetAsync(string serviceKey, BgpPeeringAccessType accessType, DevicePath devicePath, CancellationToken cancellationToken) { ExpressRouteManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("accessType", accessType); tracingParameters.Add("devicePath", devicePath); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); ExpressRouteOperationResponse response = await client.DedicatedCircuitPeeringRouteTableSummary.BeginGetAsync(serviceKey, accessType, devicePath, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); ExpressRouteOperationStatusResponse result = await client.DedicatedCircuitPeeringArpInfo.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == ExpressRouteOperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.DedicatedCircuitPeeringArpInfo.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != ExpressRouteOperationStatus.Successful) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } /// <summary> /// The Get Express Route operation status gets information on the /// status of Express Route operations in Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154112.aspx /// for more information) /// </summary> /// <param name='operationId'> /// Required. The id of the operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<ExpressRouteOperationStatusResponse> GetOperationStatusAsync(string operationId, CancellationToken cancellationToken) { // Validate if (operationId == null) { throw new ArgumentNullException("operationId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationId", operationId); TracingAdapter.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/networking/operation/"; url = url + Uri.EscapeDataString(operationId); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ExpressRouteOperationStatusResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ExpressRouteOperationStatusResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement gatewayOperationElement = responseDoc.Element(XName.Get("GatewayOperation", "http://schemas.microsoft.com/windowsazure")); if (gatewayOperationElement != null) { XElement idElement = gatewayOperationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.Id = idInstance; } XElement statusElement = gatewayOperationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure")); if (statusElement != null) { ExpressRouteOperationStatus statusInstance = ((ExpressRouteOperationStatus)Enum.Parse(typeof(ExpressRouteOperationStatus), statusElement.Value, true)); result.Status = statusInstance; } XElement httpStatusCodeElement = gatewayOperationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure")); if (httpStatusCodeElement != null) { HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true)); result.HttpStatusCode = httpStatusCodeInstance; } XElement dataElement = gatewayOperationElement.Element(XName.Get("Data", "http://schemas.microsoft.com/windowsazure")); if (dataElement != null) { string dataInstance = dataElement.Value; result.Data = dataInstance; } XElement errorElement = gatewayOperationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure")); if (errorElement != null) { ExpressRouteOperationStatusResponse.ErrorDetails errorInstance = new ExpressRouteOperationStatusResponse.ErrorDetails(); result.Error = errorInstance; XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure")); if (codeElement != null) { string codeInstance = codeElement.Value; errorInstance.Code = codeInstance; } XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure")); if (messageElement != null) { string messageInstance = messageElement.Value; errorInstance.Message = messageInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace LabSwparkWs1.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.ObjectModel; using System.Data; using System.Data.Common; using System.Text; using NetTopologySuite.Geometries; using SharpMap.Converters.WellKnownBinary; namespace SharpMap.Data.Providers { /// <summary> /// Abstract provider for spatially enabled databases /// </summary> [Serializable] public abstract class SpatialDbProvider : BaseProvider { private static readonly Common.Logging.ILog Logger = Common.Logging.LogManager.GetLogger(typeof(SpatialDbProvider)); private bool Initialized { get; set; } //private bool _isOpen; private string _schema; private string _table; // ReSharper disable InconsistentNaming internal readonly SharpMapFeatureColumn _oidColumn; internal readonly SharpMapFeatureColumn _geometryColumn; // ReSharper restore InconsistentNaming private readonly SharpMapFeatureColumns _featureColumns; private string _definitionQuery; private string _orderQuery; private int _targetSrid; private SpatialDbUtility _dbUtility; /// <summary> /// Gets or sets the <see cref="SpatialDbUtility"/> class. /// </summary> /// <remarks>This property can only be set once to a non-<value>null</value> value.</remarks> protected SpatialDbUtility DbUtility { get { return _dbUtility; } set { // make sure this is only set once! if (_dbUtility != null) return; _dbUtility = value; } } /// <summary> /// Gets the SQL-FROM statement /// </summary> protected virtual string From { get { return _dbUtility.DecorateTable(_schema, _table); } } [NonSerialized] private Envelope _cachedExtent; [NonSerialized] private int _cachedFeatureCount = -1; private Envelope _areaOfInterest; /// <summary> /// Event raised when the database schema for this provider has changed; /// </summary> public event EventHandler SchemaChanged; /// <summary> /// Method called when the <see cref="Schema"/> has been changed. This invokes the /// <see cref="E:SharpMap.Data.Providers.SpatialDbProvider.SchemaChanged"/> event. /// </summary> /// <param name="e">The arguments associated with the event</param> protected virtual void OnSchemaChanged(EventArgs e) { Logger.Debug(t => t("Schema changed to {0}", _schema)); Initialized = false; var handler = SchemaChanged; if (handler != null) handler(this, e); } /// <summary> /// Event raised when the table for this provider has changed; /// </summary> public event EventHandler TableChanged; /// <summary> /// Method called when the <see cref="Table"/> has been changed. This invokes the /// <see cref="E:SharpMap.Data.Providers.SpatialDbProvider.TableChanged"/> event. /// </summary> /// <param name="e">The arguments associated with the event</param> protected virtual void OnTableChanged(EventArgs e) { Logger.Debug(t => t("Table changed to {0}", _table)); Initialized = false; var handler = TableChanged; if (handler != null) handler(this, e); } /// <summary> /// Event raised when the object id (oid) column for this provider has changed; /// </summary> public event EventHandler OidColumnChanged; /// <summary> /// Method called when the <see cref="ObjectIdColumn"/> has been changed. This invokes the /// <see cref="E:SharpMap.Data.Providers.SpatialDbProvider.OidColumnChanged"/> event. /// </summary> /// <param name="e">The arguments associated with the event</param> protected virtual void OnOidColumnChanged(EventArgs e) { Logger.Debug(t => t("OidColumnChanged changed to {0}", _oidColumn.Column)); Initialized = false; var handler = OidColumnChanged; if (handler != null) handler(this, e); } /// <summary> /// Event raised when the geometry column for this provider has changed; /// </summary> public event EventHandler GeometryColumnChanged; /// <summary> /// Method called when the <see cref="GeometryColumn"/> has been changed. This invokes the /// <see cref="E:SharpMap.Data.Providers.SpatialDbProvider.GeometryColumnChanged"/> event. /// </summary> /// <param name="e">The arguments associated with the event</param> protected virtual void OnGeometryColumnChanged(EventArgs e) { Logger.Debug(t => t("Geometry column changed to {0}", _geometryColumn.Column)); Initialized = false; var handler = GeometryColumnChanged; if (handler != null) handler(this, e); } /// <summary> /// Event raised when the feature columns string for this provider has changed; /// </summary> public event EventHandler DefinitionQueryChanged; /// <summary> /// Method called when the <see cref="DefinitionQuery"/> has been changed. This invokes the /// <see cref="E:SharpMap.Data.Providers.SpatialDbProvider.DefinitionQueryChanged"/> event. /// </summary> /// <param name="e">The arguments associated with the event</param> [Obsolete] protected virtual void OnDefinitionQueryChanged(EventArgs e) { Logger.Debug(t => t("DefinitionQuery changed to {0}", _definitionQuery)); Initialized = false; var handler = DefinitionQueryChanged; if (handler != null) handler(this, e); } /// <summary> /// Event raised when the <see cref="FeatureColumns"/> string for this provider has changed; /// </summary> public event EventHandler FeatureColumnsChanged; /// <summary> /// Method that handles when the <see cref="SharpMapFeatureColumns.FeatureColumnsChanged"/> event. This invokes the /// <see cref="E:SharpMap.Data.Providers.SpatialDbProvider.FeatureColumnsChanged"/> event. /// </summary> /// <param name="sender">The sender</param> /// <param name="e">The arguments associated with the event</param> private void OnFeatureColumnsChanged(object sender, EventArgs e) { Logger.Debug(t => t("FeatureColumns changed")); Initialized = false; var handler = FeatureColumnsChanged; if (handler != null) handler(this, e); } /// <summary> /// Event raised when the <see cref="TargetSRID"/> for this provider has changed; /// </summary> public event EventHandler TargetSridChanged; /// <summary> /// Method called when the <see cref="TargetSRID"/> has been changed. This invokes the /// <see cref="E:SharpMap.Data.Providers.SpatialDbProvider.TargetSridChanged"/> event. /// </summary> /// <param name="e">The arguments associated with the event</param> protected virtual void OnTargetSridChanged(EventArgs e) { Logger.Debug(t => t("TragetSrid changed to {0}", _targetSrid)); Initialized = false; var handler = TargetSridChanged; if (handler != null) handler(this, e); } /// <summary> /// Event raised when <see cref="AreaOfInterest"/> for this provider has changed /// </summary> public event EventHandler AreaOfInterestChanged; /// <summary> /// Method called when the <see cref="AreaOfInterest"/> has been changed. This invokes the /// <see cref="E:SharpMap.Data.Providers.SpatialDbProvider.AreaOfInterestChanged"/> event. /// </summary> /// <param name="e">The arguments associated with the event</param> protected void OnAreaOfInterestChanged(EventArgs e) { Logger.Debug(t => t("Area of interst changed to {0}", _areaOfInterest)); var handler = AreaOfInterestChanged; if (handler != null) handler(this, e); } #region construction and disposal /// <summary> /// Creates an instance of this class /// </summary> /// <param name="spatialDbUtility">The spatial db utility class</param> /// <param name="connectionString">The connection string</param> /// <param name="table">The table name</param> protected SpatialDbProvider(SpatialDbUtility spatialDbUtility, string connectionString, string table) : this(spatialDbUtility, connectionString, string.Empty, table, string.Empty, string.Empty) { } /// <summary> /// Creates an instance of this class /// </summary> /// <param name="spatialDbUtility">The spatial db utility class</param> /// <param name="connectionString">The connection string</param> /// <param name="schema">The name of the schema</param> /// <param name="table">The table name</param> protected SpatialDbProvider(SpatialDbUtility spatialDbUtility, string connectionString, string schema, string table) : this(spatialDbUtility, connectionString, schema, table, string.Empty, string.Empty) { } /// <summary> /// Creates an instance of this class /// </summary> /// <param name="spatialDbUtility">The spatial db utility class</param> /// <param name="connectionString">The connection string</param> /// <param name="schema">The name of the schema</param> /// <param name="table">The table name</param> /// <param name="oidColumn">The object ID column</param> /// <param name="geometryColumn">The geometry column</param> protected SpatialDbProvider(SpatialDbUtility spatialDbUtility, string connectionString, string schema, string table, string oidColumn, string geometryColumn) : base(0) { ConnectionID = connectionString; _dbUtility = spatialDbUtility; _schema = schema; _table = table; _oidColumn = new SharpMapFeatureColumn { Column = oidColumn }; _geometryColumn = new SharpMapFeatureColumn { Column = geometryColumn }; // Additional columns _featureColumns = new SharpMapFeatureColumns(this, spatialDbUtility); _featureColumns.FeatureColumnsChanged += OnFeatureColumnsChanged; } /// <summary> /// Releases all managed resources /// </summary> protected override void ReleaseManagedResources() { _featureColumns.FeatureColumnsChanged -= OnFeatureColumnsChanged; base.ReleaseManagedResources(); } #endregion construction and disposal /// <summary> /// Convenience function to create and open a connection to the database backend. /// </summary> /// <returns>An open connection to the database backend.</returns> protected abstract DbConnection CreateOpenDbConnection(); /// <summary> /// Convenience function to create a data adapter. /// </summary> /// <returns>An open connection to the database backend.</returns> protected abstract DbDataAdapter CreateDataAdapter(); /// <summary> /// Function to initialize the provider /// </summary> protected void Initialize() { CheckDisposed(); if (Initialized) return; // make sure the cached extent gets cleared _cachedExtent = null; _cachedFeatureCount = -1; InitializeInternal(); } /// <summary> /// Method to initialize the spatial provider /// </summary> protected virtual void InitializeInternal() { Initialized = true; } /// <summary> /// Gets the connection string. /// </summary> public string ConnectionString { get { return ConnectionID; } } /// <summary> /// Gets or sets the name of the database schema /// </summary> public virtual string Schema { get { return _schema; } set { if (!string.Equals(value, _schema, StringComparison.InvariantCultureIgnoreCase)) { _schema = value; OnSchemaChanged(EventArgs.Empty); } } } /// <summary> /// Gets or sets the name oft the database table /// </summary> public string Table { get { return _table; } set { if (!string.Equals(value, _table, StringComparison.InvariantCultureIgnoreCase)) { _table = value; OnTableChanged(EventArgs.Empty); } } } /// <summary> /// Gets or sets the name oft the object id (oid) column /// </summary> public string ObjectIdColumn { get { return _oidColumn.Column; } set { if (!string.Equals(value, ObjectIdColumn, StringComparison.InvariantCultureIgnoreCase)) { _oidColumn.Column = value; OnOidColumnChanged(EventArgs.Empty); } } } /// <summary> /// Gets or sets the name oft the geometry column /// </summary> public string GeometryColumn { get { return _geometryColumn.Column; } set { if (!string.Equals(value, GeometryColumn, StringComparison.InvariantCultureIgnoreCase)) { _geometryColumn.Column = value; OnGeometryColumnChanged(EventArgs.Empty); } } } /// <summary> /// Gets or sets the name oft the geometry column /// </summary> public SharpMapFeatureColumns FeatureColumns { get { return _featureColumns; } } /// <summary> /// Gets or sets the definition query /// </summary> [Obsolete("Define constraints via FeatureColumns")] public string DefinitionQuery { get { return _definitionQuery; } set { if (!string.Equals(value, _definitionQuery, StringComparison.InvariantCultureIgnoreCase)) { _definitionQuery = value; OnDefinitionQueryChanged(EventArgs.Empty); } } } /// <summary> /// Columns or T-SQL expressions for sorting (ORDER BY clause) /// </summary> [Obsolete("Define order by via FeatureColumns")] public string OrderQuery { get { return _orderQuery; } set { _orderQuery = value; } } /// <summary> /// Expression template for geometry column evaluation. /// </summary> /// <example> /// You could, for instance, simplify your geometries before they're displayed. /// Simplification helps to speed the rendering of big geometries. /// Here's a sample code to simplify geometries using 100 meters of threshold. /// <code> /// datasource.GeometryExpression = "ST.Simplify({0}, 100)"; /// </code> /// Also you could draw a 20 meters buffer around those little points: /// <code> /// datasource.GeometryExpression = "ST.Buffer({0}, 20)"; /// </code> /// </example> public string GeometryExpression { get { return _geometryExpression ?? "{0}"; } set { _geometryExpression = value; } } /// <summary> /// Gets or sets the area of interest. Setting this property /// </summary> public Envelope AreaOfInterest { get { return _areaOfInterest; } set { if (ReferenceEquals(_areaOfInterest, value)) return; if (_areaOfInterest != null && _areaOfInterest.Equals(value)) return; if (value != null && value.Equals(_areaOfInterest)) return; _areaOfInterest = value; OnAreaOfInterestChanged(EventArgs.Empty); } } /// <summary> /// Gets or sets the target SRID. Setting this helps to avoid using on-the-fly reprojection /// </summary> public virtual int TargetSRID { get { return _targetSrid < 0 ? SRID : _targetSrid; } set { if (value != TargetSRID) { _targetSrid = value; OnTargetSridChanged(EventArgs.Empty); } } } /// <summary> /// Gets whether the provider needs to use the transform function /// </summary> public bool NeedsTransform { get { return TargetSRID > -1 && TargetSRID != SRID; } } /// <summary> /// <see cref="Envelope"/> of dataset /// </summary> /// <returns>boundingbox</returns> public override sealed Envelope GetExtents() { if (_areaOfInterest != null) return _areaOfInterest; if (_cachedExtent != null) return _cachedExtent; Initialize(); return _cachedExtent = GetExtentsInternal(); } /// <summary> /// Function to determine the extents of the datasource /// </summary> /// <returns>The extents</returns> protected abstract Envelope GetExtentsInternal(); /// <summary> /// Returns the number of features in the dataset /// </summary> /// <returns>number of features</returns> public override sealed int GetFeatureCount() { if (_cachedFeatureCount >= 0) return _cachedFeatureCount; Initialize(); return _cachedFeatureCount = GetFeatureCountInternal(); } /// <summary> /// Method to get the number of features in the datasource /// </summary> /// <returns>The number of features</returns> protected virtual int GetFeatureCountInternal() { using (var conn = CreateOpenDbConnection()) { using (var command = conn.CreateCommand()) { var sql = new StringBuilder(); sql.AppendFormat("SELECT COUNT(*) FROM {0}", _dbUtility.DecorateTable(Schema, Table)); #pragma warning disable 612,618 if (!string.IsNullOrEmpty(DefinitionQuery)) sql.AppendFormat(" WHERE {0}", DefinitionQuery); #pragma warning restore 612,618 else sql.Append(FeatureColumns.GetWhereClause()); sql.Append(";"); command.CommandText = sql.ToString(); return (int)command.ExecuteScalar(); } } } /// <summary> /// Returns a <see cref="SharpMap.Data.FeatureDataRow"/> based on a RowID /// </summary> /// <param name="rowId">The id of the row</param> /// <returns>The feature data row</returns> public override sealed FeatureDataRow GetFeature(uint rowId) { Initialize(); return GetFeatureInternal(rowId); } /// <summary> /// Gets a name describing the provider. This name is made up of <see cref="Schema"/>, <see cref="Table"/> and <see cref="GeometryColumn"/>. /// </summary> protected string Name { get { var sb = new StringBuilder(_dbUtility.DecorateTable(_schema, _table)); sb.AppendFormat(".{0}", GeometryColumn); return sb.ToString(); } } private FeatureDataTable _baseTable; private string _geometryExpression; /// <summary> /// Function to create a new, empty <see cref="FeatureDataTable"/> /// </summary> /// <returns>A feature data table</returns> protected virtual FeatureDataTable CreateNewTable() { return CreateNewTable(false); } /// <summary> /// Function to create a new, empty <see cref="FeatureDataTable"/> /// </summary> /// <param name="force">Value indicating that a new feature data table should be created, no matter what.</param> /// <returns>A feature data table</returns> protected virtual FeatureDataTable CreateNewTable(bool force) { if (force || _baseTable == null) { var fdt = new FeatureDataTable { TableName = Name }; using (var cn = CreateOpenDbConnection()) { using (var cmd = cn.CreateCommand()) { cmd.CommandText = FeatureColumns.GetSelectClause(From); using (var da = CreateDataAdapter()) { da.SelectCommand = cmd; fdt = (FeatureDataTable)da.FillSchema(fdt, SchemaType.Source); } } } //Remove the geometry column, which is always the last! fdt.Columns.RemoveAt(fdt.Columns.Count - 1); if (_baseTable == null) { _baseTable = fdt; return _baseTable; } return fdt; } return _baseTable; /* var res = new FeatureDataTable(dt); var resColumns = res.Columns; foreach (var column in dt.Columns) { resColumns.Add(new DataColumn(column.)) } res.PrimaryKey = new [] {res.Columns[0]}; return res; */ } /// <summary> /// Function to get a specific feature from the database. /// </summary> /// <param name="oid">The object id</param> /// <returns>A feature data row</returns> protected virtual FeatureDataRow GetFeatureInternal(uint oid) { using (var cn = CreateOpenDbConnection()) { using (var cmd = cn.CreateCommand()) { cmd.CommandText = FeatureColumns.GetSelectClause(From) + string.Format(" WHERE {0}={1};", _dbUtility.DecorateEntity(ObjectIdColumn), oid); Logger.Debug(t => t("Executing query:\n{0}", PrintCommand(cmd))); using (var dr = cmd.ExecuteReader()) { if (dr.HasRows) { dr.Read(); var fdt = CreateNewTable(); FeatureDataRow row = null; fdt.BeginLoadData(); var numColumns = fdt.Columns.Count; var data = new object[numColumns+1]; if (dr.GetValues(data) > 0) { var loadData = new object[numColumns]; Array.Copy(data, 0, loadData, 0, numColumns); row = (FeatureDataRow)fdt.LoadDataRow(loadData, true); row.Geometry = GeometryFromWKB.Parse((byte[])data[numColumns], Factory); } fdt.EndLoadData(); return row; } } } } return null; } private static string PrintCommand(DbCommand cmd) { var sb = new StringBuilder(); foreach (DbParameter parameter in cmd.Parameters) { if (sb.Length == 0) sb.Append("Parameter:"); sb.AppendFormat("\n{0}({1}) = {2}", parameter.ParameterName, parameter.DbType, parameter.Value); } sb.AppendFormat("\n{0}", cmd.CommandText); return sb.ToString(); } /// <summary> /// Function to get a specific feature's geometry from the database. /// </summary> /// <param name="oid">The object id</param> /// <returns>A geometry</returns> public override sealed Geometry GetGeometryByID(uint oid) { Initialize(); return GetGeometryByIDInternal(oid); } /// <summary> /// Function to get a specific feature's geometry from the database. /// </summary> /// <param name="oid">The object id</param> /// <returns>A geometry</returns> protected virtual Geometry GetGeometryByIDInternal(uint oid) { using (var cn = CreateOpenDbConnection()) { using (var cmd = cn.CreateCommand()) { cmd.CommandText = FeatureColumns.GetSelectColumnClause(cmd, _geometryColumn, oid); Logger.Debug(t => t("Executing query:\n{0}", PrintCommand(cmd))); using (var dr = cmd.ExecuteReader()) { if (dr.HasRows) { while (dr.Read()) { var geometry = GeometryFromWKB.Parse((byte[])dr.GetValue(0), Factory); return geometry; } } } } } return null; } /// <summary> /// Gets the geometries of features that lie within the specified <see cref="NetTopologySuite.Geometries.Envelope"/> /// </summary> /// <param name="bbox">The bounding box</param> /// <returns>Geometries within the specified <see cref="NetTopologySuite.Geometries.Envelope"/></returns> public override sealed Collection<Geometry> GetGeometriesInView(Envelope bbox) { Initialize(); return GetGeometriesInViewInternal(bbox); } /// <summary> /// Gets the geometries of features that lie within the specified <see cref="NetTopologySuite.Geometries.Envelope"/> /// </summary> /// <param name="bbox">The bounding box</param> /// <returns>Geometries within the specified <see cref="NetTopologySuite.Geometries.Envelope"/></returns> protected virtual Collection<Geometry> GetGeometriesInViewInternal(Envelope bbox) { var res = new Collection<Geometry>(); using (var cn = CreateOpenDbConnection()) { using (var cmd = cn.CreateCommand()) { cmd.CommandText = FeatureColumns.GetSelectColumnClause(cmd, _geometryColumn, GetSpatialWhere(bbox, cmd)); Logger.Debug(t => t("Executing query:\n{0}", PrintCommand(cmd))); using (var dr = cmd.ExecuteReader()) { if (dr.HasRows) { while (dr.Read()) res.Add(GeometryFromWKB.Parse((byte[])dr.GetValue(0), Factory)); } } } } return res; } /// <summary> /// Function to generate a spatial where clause for the intersection queries. /// </summary> /// <param name="bbox">The bounding box</param> /// <param name="command">The command object, that is supposed to execute the query.</param> /// <returns>The spatial component of a SQL where clause</returns> protected abstract string GetSpatialWhere(Envelope bbox, DbCommand command); /// <summary> /// Function to generate a spatial where clause for the intersection queries. /// </summary> /// <param name="bbox">The geometry</param> /// <param name="command">The command object, that is supposed to execute the query.</param> /// <returns>The spatial component of a SQL where clause</returns> protected abstract string GetSpatialWhere(Geometry bbox, DbCommand command); /// <summary> /// Gets the object of features that lie within the specified <see cref="NetTopologySuite.Geometries.Envelope"/> /// </summary> /// <param name="bbox">The bounding box</param> /// <returns>A collection of object ids</returns> public override sealed Collection<uint> GetObjectIDsInView(Envelope bbox) { Initialize(); return GetObjectIDsInViewInternal(bbox); } /// <summary> /// Gets the object ids of features that lie within the specified <see cref="NetTopologySuite.Geometries.Envelope"/> /// </summary> /// <param name="bbox">The bounding box</param> /// <returns>A collection of object ids</returns> protected virtual Collection<uint> GetObjectIDsInViewInternal(Envelope bbox) { var res = new Collection<uint>(); using (var cn = CreateOpenDbConnection()) { using (var cmd = cn.CreateCommand()) { cmd.CommandText = FeatureColumns.GetSelectColumnClause(cmd, _oidColumn, GetSpatialWhere(bbox, cmd)); Logger.Debug(t => t("Executing query:\n{0}", PrintCommand(cmd))); using (var dr = cmd.ExecuteReader()) { if (dr.HasRows) { while (dr.Read()) res.Add(Convert.ToUInt32(dr.GetValue(0))); } } } } return res; } /// <summary> /// Returns the data associated with all the geometries that are intersected by 'geom' /// </summary> /// <param name="box">Geometry to intersect with</param> /// <param name="ds">FeatureDataSet to fill data into</param> public override sealed void ExecuteIntersectionQuery(Envelope box, FeatureDataSet ds) { Initialize(); ExecuteIntersectionQueryInternal(box, ds); } /// <summary> /// Returns the data associated with all the geometries that are intersected by 'geom' /// </summary> /// <param name="spatialWhere">Geometry to intersect with</param> /// <param name="fds">FeatureDataSet to fill data into</param> protected virtual void ExecuteIntersectionQueryInternal(object spatialWhere, FeatureDataSet fds) { var fdt = CreateNewTable(true); fdt.BeginLoadData(); using (var cn = CreateOpenDbConnection()) { using (var cmd = cn.CreateCommand()) { string from = null; var spatialWhereString = string.Empty; var env = spatialWhere as Envelope; if (env != null) { from = GetFrom(env, cmd); spatialWhereString = GetSpatialWhere(env, cmd); } else { var geom = spatialWhere as Geometry; if (geom != null) { from = GetFrom(geom, cmd); spatialWhereString = GetSpatialWhere(geom, cmd); } } cmd.CommandText = FeatureColumns.GetSelectClause(from) #pragma warning disable 612,618 + (string.IsNullOrEmpty(DefinitionQuery) #pragma warning restore 612,618 ? FeatureColumns.GetWhereClause(spatialWhereString) : (" WHERE " + _definitionQuery + (string.IsNullOrEmpty(spatialWhereString) ? "" : " AND " + spatialWhereString))) + FeatureColumns.GetGroupByClause() + FeatureColumns.GetOrderByClause(); var numColumns = fdt.Columns.Count; var geomIndex = numColumns; Logger.Debug(t => t("Executing query:\n{0}", PrintCommand(cmd))); using (var dr = cmd.ExecuteReader()) { while (dr.Read()) { var data = new object[numColumns+1]; if (dr.GetValues(data) > 0) { var loadData = new object[geomIndex]; Array.Copy(data, 0, loadData, 0, geomIndex); var row = (FeatureDataRow)fdt.LoadDataRow(loadData, true); row.Geometry = GeometryFromWKB.Parse((byte[])data[geomIndex], Factory); } } } } } fdt.EndLoadData(); fds.Tables.Add(fdt); } /// <summary> /// Method to generate a SQL-From statement for a bounding box query /// </summary> /// <param name="envelope">The envelope to query</param> /// <param name="command">The command object that is supposed to perform the query</param> /// <returns>A SQL From statement string</returns> protected virtual string GetFrom(Envelope envelope, DbCommand command) { return _dbUtility.DecorateTable(_schema, _table); } /// <summary> /// Method to generate a SQL-From statement for a geometry query /// </summary> /// <param name="geometry">The envelope to query</param> /// <param name="command">The command object that is supposed to perform the query</param> /// <returns>A SQL From statement string</returns> protected virtual string GetFrom(Geometry geometry, DbCommand command) { return _dbUtility.DecorateTable(_schema, _table); } /// <summary> /// Method to perform preparatory things for executing an intersection query against the data source /// </summary> /// <param name="geom">The geometry to use as filter.</param> protected override sealed void OnBeginExecuteIntersectionQuery(Geometry geom) { Initialize(); OnBeginExecuteIntersectionQueryInternal(geom); base.OnBeginExecuteIntersectionQuery(geom); } /// <summary> /// Method to perform the actual intersection query against a bounding box /// </summary> /// <param name="box">The bounding box</param> /// <param name="ds">The feature data set to store the results in.</param> protected virtual void ExecuteIntersectionQueryInternal(Envelope box, FeatureDataSet ds) { ExecuteIntersectionQueryInternal((object)box, ds); } /// <summary> /// Method to perform preparatory things for executing an intersection query against the data source /// </summary> /// <param name="geom">The geometry to use as filter.</param> protected virtual void OnBeginExecuteIntersectionQueryInternal(Geometry geom) { } /// <summary> /// Method to perform the intersection query against the data source /// </summary> /// <param name="geom">The geometry to use as filter</param> /// <param name="ds">The feature data set to store the results in</param> protected override void OnExecuteIntersectionQuery(Geometry geom, FeatureDataSet ds) { ExecuteIntersectionQueryInternal(geom, ds); } /// <summary> /// Handler method to handle changes of <see cref="BaseProvider.SRID"/>. /// </summary> /// <param name="eventArgs">Event arguments.</param> protected override void OnSridChanged(EventArgs eventArgs) { Initialized = false; base.OnSridChanged(eventArgs); } } }
// <copyright file="TFQMR.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2013 Math.NET // // 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. // </copyright> using System; using MathNet.Numerics.LinearAlgebra.Solvers; using MathNet.Numerics.Properties; namespace MathNet.Numerics.LinearAlgebra.Double.Solvers { /// <summary> /// A Transpose Free Quasi-Minimal Residual (TFQMR) iterative matrix solver. /// </summary> /// <remarks> /// <para> /// The TFQMR algorithm was taken from: <br/> /// Iterative methods for sparse linear systems. /// <br/> /// Yousef Saad /// <br/> /// Algorithm is described in Chapter 7, section 7.4.3, page 219 /// </para> /// <para> /// The example code below provides an indication of the possible use of the /// solver. /// </para> /// </remarks> public sealed class TFQMR : IIterativeSolver<double> { /// <summary> /// Calculates the <c>true</c> residual of the matrix equation Ax = b according to: residual = b - Ax /// </summary> /// <param name="matrix">Instance of the <see cref="Matrix"/> A.</param> /// <param name="residual">Residual values in <see cref="Vector"/>.</param> /// <param name="x">Instance of the <see cref="Vector"/> x.</param> /// <param name="b">Instance of the <see cref="Vector"/> b.</param> static void CalculateTrueResidual(Matrix<double> matrix, Vector<double> residual, Vector<double> x, Vector<double> b) { // -Ax = residual matrix.Multiply(x, residual); residual.Multiply(-1, residual); // residual + b residual.Add(b, residual); } /// <summary> /// Is <paramref name="number"/> even? /// </summary> /// <param name="number">Number to check</param> /// <returns><c>true</c> if <paramref name="number"/> even, otherwise <c>false</c></returns> static bool IsEven(int number) { return number % 2 == 0; } /// <summary> /// Solves the matrix equation Ax = b, where A is the coefficient matrix, b is the /// solution vector and x is the unknown vector. /// </summary> /// <param name="matrix">The coefficient matrix, <c>A</c>.</param> /// <param name="input">The solution vector, <c>b</c></param> /// <param name="result">The result vector, <c>x</c></param> /// <param name="iterator">The iterator to use to control when to stop iterating.</param> /// <param name="preconditioner">The preconditioner to use for approximations.</param> public void Solve(Matrix<double> matrix, Vector<double> input, Vector<double> result, Iterator<double> iterator, IPreconditioner<double> preconditioner) { if (matrix.RowCount != matrix.ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix"); } if (result.Count != input.Count) { throw new ArgumentException(Resources.ArgumentVectorsSameLength); } if (input.Count != matrix.RowCount) { throw Matrix.DimensionsDontMatch<ArgumentException>(input, matrix); } if (iterator == null) { iterator = new Iterator<double>(); } if (preconditioner == null) { preconditioner = new UnitPreconditioner<double>(); } preconditioner.Initialize(matrix); var d = new DenseVector(input.Count); var r = DenseVector.OfVector(input); var uodd = new DenseVector(input.Count); var ueven = new DenseVector(input.Count); var v = new DenseVector(input.Count); var pseudoResiduals = DenseVector.OfVector(input); var x = new DenseVector(input.Count); var yodd = new DenseVector(input.Count); var yeven = DenseVector.OfVector(input); // Temp vectors var temp = new DenseVector(input.Count); var temp1 = new DenseVector(input.Count); var temp2 = new DenseVector(input.Count); // Define the scalars double alpha = 0; double eta = 0; double theta = 0; // Initialize var tau = input.L2Norm(); var rho = tau*tau; // Calculate the initial values for v // M temp = yEven preconditioner.Approximate(yeven, temp); // v = A temp matrix.Multiply(temp, v); // Set uOdd v.CopyTo(ueven); // Start the iteration var iterationNumber = 0; while (iterator.DetermineStatus(iterationNumber, result, input, pseudoResiduals) == IterationStatus.Continue) { // First part of the step, the even bit if (IsEven(iterationNumber)) { // sigma = (v, r) var sigma = v.DotProduct(r); if (sigma.AlmostEqualNumbersBetween(0, 1)) { // FAIL HERE iterator.Cancel(); break; } // alpha = rho / sigma alpha = rho/sigma; // yOdd = yEven - alpha * v v.Multiply(-alpha, temp1); yeven.Add(temp1, yodd); // Solve M temp = yOdd preconditioner.Approximate(yodd, temp); // uOdd = A temp matrix.Multiply(temp, uodd); } // The intermediate step which is equal for both even and // odd iteration steps. // Select the correct vector var uinternal = IsEven(iterationNumber) ? ueven : uodd; var yinternal = IsEven(iterationNumber) ? yeven : yodd; // pseudoResiduals = pseudoResiduals - alpha * uOdd uinternal.Multiply(-alpha, temp1); pseudoResiduals.Add(temp1, temp2); temp2.CopyTo(pseudoResiduals); // d = yOdd + theta * theta * eta / alpha * d d.Multiply(theta*theta*eta/alpha, temp); yinternal.Add(temp, d); // theta = ||pseudoResiduals||_2 / tau theta = pseudoResiduals.L2Norm()/tau; var c = 1/Math.Sqrt(1 + (theta*theta)); // tau = tau * theta * c tau *= theta*c; // eta = c^2 * alpha eta = c*c*alpha; // x = x + eta * d d.Multiply(eta, temp1); x.Add(temp1, temp2); temp2.CopyTo(x); // Check convergence and see if we can bail if (iterator.DetermineStatus(iterationNumber, result, input, pseudoResiduals) != IterationStatus.Continue) { // Calculate the real values preconditioner.Approximate(x, result); // Calculate the true residual. Use the temp vector for that // so that we don't pollute the pseudoResidual vector for no // good reason. CalculateTrueResidual(matrix, temp, result, input); // Now recheck the convergence if (iterator.DetermineStatus(iterationNumber, result, input, temp) != IterationStatus.Continue) { // We're all good now. return; } } // The odd step if (!IsEven(iterationNumber)) { if (rho.AlmostEqualNumbersBetween(0, 1)) { // FAIL HERE iterator.Cancel(); break; } var rhoNew = pseudoResiduals.DotProduct(r); var beta = rhoNew/rho; // Update rho for the next loop rho = rhoNew; // yOdd = pseudoResiduals + beta * yOdd yodd.Multiply(beta, temp1); pseudoResiduals.Add(temp1, yeven); // Solve M temp = yOdd preconditioner.Approximate(yeven, temp); // uOdd = A temp matrix.Multiply(temp, ueven); // v = uEven + beta * (uOdd + beta * v) v.Multiply(beta, temp1); uodd.Add(temp1, temp); temp.Multiply(beta, temp1); ueven.Add(temp1, v); } // Calculate the real values preconditioner.Approximate(x, result); iterationNumber++; } } } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using EverReader.Models; namespace EverReader.Migrations { [DbContext(typeof(EverReaderContext))] [Migration("20151107154227_EvernoteAuthAdjustments")] partial class EvernoteAuthAdjustments { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .Annotation("ProductVersion", "7.0.0-beta8-15964") .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("EverReader.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .Annotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<DateTime?>("EvernoteAuthorisedUntilDate"); b.Property<int?>("EvernoteCredentialsId"); b.Property<bool>("HasAuthorisedEvernote"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .Annotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .Annotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .Annotation("MaxLength", 256); b.HasKey("Id"); b.Index("NormalizedEmail") .Annotation("Relational:Name", "EmailIndex"); b.Index("NormalizedUserName") .Annotation("Relational:Name", "UserNameIndex"); b.Annotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("EverReader.Models.EFDbEvernoteCredentials", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("AuthToken"); b.Property<DateTime>("Expires"); b.Property<string>("NotebookUrl"); b.Property<string>("Shard"); b.Property<string>("UserId"); b.Property<string>("WebApiUrlPrefix"); b.HasKey("Id"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .Annotation("MaxLength", 256); b.Property<string>("NormalizedName") .Annotation("MaxLength", 256); b.HasKey("Id"); b.Index("NormalizedName") .Annotation("Relational:Name", "RoleNameIndex"); b.Annotation("Relational:TableName", "AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId"); b.HasKey("Id"); b.Annotation("Relational:TableName", "AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId"); b.HasKey("Id"); b.Annotation("Relational:TableName", "AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId"); b.HasKey("LoginProvider", "ProviderKey"); b.Annotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.Annotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("EverReader.Models.ApplicationUser", b => { b.HasOne("EverReader.Models.EFDbEvernoteCredentials") .WithMany() .ForeignKey("EvernoteCredentialsId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .ForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.HasOne("EverReader.Models.ApplicationUser") .WithMany() .ForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.HasOne("EverReader.Models.ApplicationUser") .WithMany() .ForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .ForeignKey("RoleId"); b.HasOne("EverReader.Models.ApplicationUser") .WithMany() .ForeignKey("UserId"); }); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Microsoft.DotNet.ProjectModel.FileSystemGlobbing.Internal.PathSegments; using Microsoft.DotNet.ProjectModel.FileSystemGlobbing.Internal.PatternContexts; namespace Microsoft.DotNet.ProjectModel.FileSystemGlobbing.Internal.Patterns { public class PatternBuilder { private static readonly char[] _slashes = new[] { '/', '\\' }; private static readonly char[] _star = new[] { '*' }; public PatternBuilder() { ComparisonType = StringComparison.OrdinalIgnoreCase; } public PatternBuilder(StringComparison comparisonType) { ComparisonType = comparisonType; } public StringComparison ComparisonType { get; } public IPattern Build(string pattern) { if (pattern == null) { throw new ArgumentNullException("pattern"); } pattern = pattern.TrimStart(_slashes); if (pattern.TrimEnd(_slashes).Length < pattern.Length) { // If the pattern end with a slash, it is considered as // a directory. pattern = pattern.TrimEnd(_slashes) + "/**"; } var allSegments = new List<IPathSegment>(); var isParentSegmentLegal = true; IList<IPathSegment> segmentsPatternStartsWith = null; IList<IList<IPathSegment>> segmentsPatternContains = null; IList<IPathSegment> segmentsPatternEndsWith = null; var endPattern = pattern.Length; for (int scanPattern = 0; scanPattern < endPattern;) { var beginSegment = scanPattern; var endSegment = NextIndex(pattern, _slashes, scanPattern, endPattern); IPathSegment segment = null; if (segment == null && endSegment - beginSegment == 3) { if (pattern[beginSegment] == '*' && pattern[beginSegment + 1] == '.' && pattern[beginSegment + 2] == '*') { // turn *.* into * beginSegment += 2; } } if (segment == null && endSegment - beginSegment == 2) { if (pattern[beginSegment] == '*' && pattern[beginSegment + 1] == '*') { // recognized ** segment = new RecursiveWildcardSegment(); } else if (pattern[beginSegment] == '.' && pattern[beginSegment + 1] == '.') { // recognized .. if (!isParentSegmentLegal) { throw new ArgumentException("\"..\" can be only added at the beginning of the pattern."); } segment = new ParentPathSegment(); } } if (segment == null && endSegment - beginSegment == 1) { if (pattern[beginSegment] == '.') { // recognized . segment = new CurrentPathSegment(); } } if (segment == null && endSegment - beginSegment > 2) { if (pattern[beginSegment] == '*' && pattern[beginSegment + 1] == '*' && pattern[beginSegment + 2] == '.') { // recognize **. // swallow the first *, add the recursive path segment and // the remaining part will be treat as wild card in next loop. segment = new RecursiveWildcardSegment(); endSegment = beginSegment; } } if (segment == null) { var beginsWith = string.Empty; var contains = new List<string>(); var endsWith = string.Empty; for (int scanSegment = beginSegment; scanSegment < endSegment;) { var beginLiteral = scanSegment; var endLiteral = NextIndex(pattern, _star, scanSegment, endSegment); if (beginLiteral == beginSegment) { if (endLiteral == endSegment) { // and the only bit segment = new LiteralPathSegment(Portion(pattern, beginLiteral, endLiteral), ComparisonType); } else { // this is the first bit beginsWith = Portion(pattern, beginLiteral, endLiteral); } } else if (endLiteral == endSegment) { // this is the last bit endsWith = Portion(pattern, beginLiteral, endLiteral); } else { if (beginLiteral != endLiteral) { // this is a middle bit contains.Add(Portion(pattern, beginLiteral, endLiteral)); } else { // note: NOOP here, adjacent *'s are collapsed when they // are mixed with literal text in a path segment } } scanSegment = endLiteral + 1; } if (segment == null) { segment = new WildcardPathSegment(beginsWith, contains, endsWith, ComparisonType); } } if (!(segment is ParentPathSegment)) { isParentSegmentLegal = false; } if (segment is CurrentPathSegment) { // ignore ".\" } else { if (segment is RecursiveWildcardSegment) { if (segmentsPatternStartsWith == null) { segmentsPatternStartsWith = new List<IPathSegment>(allSegments); segmentsPatternEndsWith = new List<IPathSegment>(); segmentsPatternContains = new List<IList<IPathSegment>>(); } else if (segmentsPatternEndsWith.Count != 0) { segmentsPatternContains.Add(segmentsPatternEndsWith); segmentsPatternEndsWith = new List<IPathSegment>(); } } else if (segmentsPatternEndsWith != null) { segmentsPatternEndsWith.Add(segment); } allSegments.Add(segment); } scanPattern = endSegment + 1; } if (segmentsPatternStartsWith == null) { return new LinearPattern(allSegments); } else { return new RaggedPattern(allSegments, segmentsPatternStartsWith, segmentsPatternEndsWith, segmentsPatternContains); } } private static int NextIndex(string pattern, char[] anyOf, int beginIndex, int endIndex) { var index = pattern.IndexOfAny(anyOf, beginIndex, endIndex - beginIndex); return index == -1 ? endIndex : index; } private static string Portion(string pattern, int beginIndex, int endIndex) { return pattern.Substring(beginIndex, endIndex - beginIndex); } private class LinearPattern : ILinearPattern { public LinearPattern(List<IPathSegment> allSegments) { Segments = allSegments; } public IList<IPathSegment> Segments { get; } public IPatternContext CreatePatternContextForInclude() { return new PatternContextLinearInclude(this); } public IPatternContext CreatePatternContextForExclude() { return new PatternContextLinearExclude(this); } } private class RaggedPattern : IRaggedPattern { public RaggedPattern(List<IPathSegment> allSegments, IList<IPathSegment> segmentsPatternStartsWith, IList<IPathSegment> segmentsPatternEndsWith, IList<IList<IPathSegment>> segmentsPatternContains) { Segments = allSegments; StartsWith = segmentsPatternStartsWith; Contains = segmentsPatternContains; EndsWith = segmentsPatternEndsWith; } public IList<IList<IPathSegment>> Contains { get; } public IList<IPathSegment> EndsWith { get; } public IList<IPathSegment> Segments { get; } public IList<IPathSegment> StartsWith { get; } public IPatternContext CreatePatternContextForInclude() { return new PatternContextRaggedInclude(this); } public IPatternContext CreatePatternContextForExclude() { return new PatternContextRaggedExclude(this); } } } }
//--------------------------------------------------------------------------- // // <copyright file="QuaternionKeyFrameCollection.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Windows.Media.Animation; using System.Windows.Media.Media3D; namespace System.Windows.Media.Animation { /// <summary> /// This collection is used in conjunction with a KeyFrameQuaternionAnimation /// to animate a Quaternion property value along a set of key frames. /// </summary> public class QuaternionKeyFrameCollection : Freezable, IList { #region Data private List<QuaternionKeyFrame> _keyFrames; private static QuaternionKeyFrameCollection s_emptyCollection; #endregion #region Constructors /// <Summary> /// Creates a new QuaternionKeyFrameCollection. /// </Summary> public QuaternionKeyFrameCollection() : base() { _keyFrames = new List< QuaternionKeyFrame>(2); } #endregion #region Static Methods /// <summary> /// An empty QuaternionKeyFrameCollection. /// </summary> public static QuaternionKeyFrameCollection Empty { get { if (s_emptyCollection == null) { QuaternionKeyFrameCollection emptyCollection = new QuaternionKeyFrameCollection(); emptyCollection._keyFrames = new List< QuaternionKeyFrame>(0); emptyCollection.Freeze(); s_emptyCollection = emptyCollection; } return s_emptyCollection; } } #endregion #region Freezable /// <summary> /// Creates a freezable copy of this QuaternionKeyFrameCollection. /// </summary> /// <returns>The copy</returns> public new QuaternionKeyFrameCollection Clone() { return (QuaternionKeyFrameCollection)base.Clone(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new QuaternionKeyFrameCollection(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>. /// </summary> protected override void CloneCore(Freezable sourceFreezable) { QuaternionKeyFrameCollection sourceCollection = (QuaternionKeyFrameCollection) sourceFreezable; base.CloneCore(sourceFreezable); int count = sourceCollection._keyFrames.Count; _keyFrames = new List< QuaternionKeyFrame>(count); for (int i = 0; i < count; i++) { QuaternionKeyFrame keyFrame = (QuaternionKeyFrame)sourceCollection._keyFrames[i].Clone(); _keyFrames.Add(keyFrame); OnFreezablePropertyChanged(null, keyFrame); } } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(System.Windows.Freezable)">Freezable.CloneCurrentValueCore</see>. /// </summary> protected override void CloneCurrentValueCore(Freezable sourceFreezable) { QuaternionKeyFrameCollection sourceCollection = (QuaternionKeyFrameCollection) sourceFreezable; base.CloneCurrentValueCore(sourceFreezable); int count = sourceCollection._keyFrames.Count; _keyFrames = new List< QuaternionKeyFrame>(count); for (int i = 0; i < count; i++) { QuaternionKeyFrame keyFrame = (QuaternionKeyFrame)sourceCollection._keyFrames[i].CloneCurrentValue(); _keyFrames.Add(keyFrame); OnFreezablePropertyChanged(null, keyFrame); } } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(System.Windows.Freezable)">Freezable.GetAsFrozenCore</see>. /// </summary> protected override void GetAsFrozenCore(Freezable sourceFreezable) { QuaternionKeyFrameCollection sourceCollection = (QuaternionKeyFrameCollection) sourceFreezable; base.GetAsFrozenCore(sourceFreezable); int count = sourceCollection._keyFrames.Count; _keyFrames = new List< QuaternionKeyFrame>(count); for (int i = 0; i < count; i++) { QuaternionKeyFrame keyFrame = (QuaternionKeyFrame)sourceCollection._keyFrames[i].GetAsFrozen(); _keyFrames.Add(keyFrame); OnFreezablePropertyChanged(null, keyFrame); } } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(System.Windows.Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>. /// </summary> protected override void GetCurrentValueAsFrozenCore(Freezable sourceFreezable) { QuaternionKeyFrameCollection sourceCollection = (QuaternionKeyFrameCollection) sourceFreezable; base.GetCurrentValueAsFrozenCore(sourceFreezable); int count = sourceCollection._keyFrames.Count; _keyFrames = new List< QuaternionKeyFrame>(count); for (int i = 0; i < count; i++) { QuaternionKeyFrame keyFrame = (QuaternionKeyFrame)sourceCollection._keyFrames[i].GetCurrentValueAsFrozen(); _keyFrames.Add(keyFrame); OnFreezablePropertyChanged(null, keyFrame); } } /// <summary> /// /// </summary> protected override bool FreezeCore(bool isChecking) { bool canFreeze = base.FreezeCore(isChecking); for (int i = 0; i < _keyFrames.Count && canFreeze; i++) { canFreeze &= Freezable.Freeze(_keyFrames[i], isChecking); } return canFreeze; } #endregion #region IEnumerable /// <summary> /// Returns an enumerator of the QuaternionKeyFrames in the collection. /// </summary> public IEnumerator GetEnumerator() { ReadPreamble(); return _keyFrames.GetEnumerator(); } #endregion #region ICollection /// <summary> /// Returns the number of QuaternionKeyFrames in the collection. /// </summary> public int Count { get { ReadPreamble(); return _keyFrames.Count; } } /// <summary> /// See <see cref="System.Collections.ICollection.IsSynchronized">ICollection.IsSynchronized</see>. /// </summary> public bool IsSynchronized { get { ReadPreamble(); return (IsFrozen || Dispatcher != null); } } /// <summary> /// See <see cref="System.Collections.ICollection.SyncRoot">ICollection.SyncRoot</see>. /// </summary> public object SyncRoot { get { ReadPreamble(); return ((ICollection)_keyFrames).SyncRoot; } } /// <summary> /// Copies all of the QuaternionKeyFrames in the collection to an /// array. /// </summary> void ICollection.CopyTo(Array array, int index) { ReadPreamble(); ((ICollection)_keyFrames).CopyTo(array, index); } /// <summary> /// Copies all of the QuaternionKeyFrames in the collection to an /// array of QuaternionKeyFrames. /// </summary> public void CopyTo(QuaternionKeyFrame[] array, int index) { ReadPreamble(); _keyFrames.CopyTo(array, index); } #endregion #region IList /// <summary> /// Adds a QuaternionKeyFrame to the collection. /// </summary> int IList.Add(object keyFrame) { return Add((QuaternionKeyFrame)keyFrame); } /// <summary> /// Adds a QuaternionKeyFrame to the collection. /// </summary> public int Add(QuaternionKeyFrame keyFrame) { if (keyFrame == null) { throw new ArgumentNullException("keyFrame"); } WritePreamble(); OnFreezablePropertyChanged(null, keyFrame); _keyFrames.Add(keyFrame); WritePostscript(); return _keyFrames.Count - 1; } /// <summary> /// Removes all QuaternionKeyFrames from the collection. /// </summary> public void Clear() { WritePreamble(); if (_keyFrames.Count > 0) { for (int i = 0; i < _keyFrames.Count; i++) { OnFreezablePropertyChanged(_keyFrames[i], null); } _keyFrames.Clear(); WritePostscript(); } } /// <summary> /// Returns true of the collection contains the given QuaternionKeyFrame. /// </summary> bool IList.Contains(object keyFrame) { return Contains((QuaternionKeyFrame)keyFrame); } /// <summary> /// Returns true of the collection contains the given QuaternionKeyFrame. /// </summary> public bool Contains(QuaternionKeyFrame keyFrame) { ReadPreamble(); return _keyFrames.Contains(keyFrame); } /// <summary> /// Returns the index of a given QuaternionKeyFrame in the collection. /// </summary> int IList.IndexOf(object keyFrame) { return IndexOf((QuaternionKeyFrame)keyFrame); } /// <summary> /// Returns the index of a given QuaternionKeyFrame in the collection. /// </summary> public int IndexOf(QuaternionKeyFrame keyFrame) { ReadPreamble(); return _keyFrames.IndexOf(keyFrame); } /// <summary> /// Inserts a QuaternionKeyFrame into a specific location in the collection. /// </summary> void IList.Insert(int index, object keyFrame) { Insert(index, (QuaternionKeyFrame)keyFrame); } /// <summary> /// Inserts a QuaternionKeyFrame into a specific location in the collection. /// </summary> public void Insert(int index, QuaternionKeyFrame keyFrame) { if (keyFrame == null) { throw new ArgumentNullException("keyFrame"); } WritePreamble(); OnFreezablePropertyChanged(null, keyFrame); _keyFrames.Insert(index, keyFrame); WritePostscript(); } /// <summary> /// Returns true if the collection is frozen. /// </summary> public bool IsFixedSize { get { ReadPreamble(); return IsFrozen; } } /// <summary> /// Returns true if the collection is frozen. /// </summary> public bool IsReadOnly { get { ReadPreamble(); return IsFrozen; } } /// <summary> /// Removes a QuaternionKeyFrame from the collection. /// </summary> void IList.Remove(object keyFrame) { Remove((QuaternionKeyFrame)keyFrame); } /// <summary> /// Removes a QuaternionKeyFrame from the collection. /// </summary> public void Remove(QuaternionKeyFrame keyFrame) { WritePreamble(); if (_keyFrames.Contains(keyFrame)) { OnFreezablePropertyChanged(keyFrame, null); _keyFrames.Remove(keyFrame); WritePostscript(); } } /// <summary> /// Removes the QuaternionKeyFrame at the specified index from the collection. /// </summary> public void RemoveAt(int index) { WritePreamble(); OnFreezablePropertyChanged(_keyFrames[index], null); _keyFrames.RemoveAt(index); WritePostscript(); } /// <summary> /// Gets or sets the QuaternionKeyFrame at a given index. /// </summary> object IList.this[int index] { get { return this[index]; } set { this[index] = (QuaternionKeyFrame)value; } } /// <summary> /// Gets or sets the QuaternionKeyFrame at a given index. /// </summary> public QuaternionKeyFrame this[int index] { get { ReadPreamble(); return _keyFrames[index]; } set { if (value == null) { throw new ArgumentNullException(String.Format(CultureInfo.InvariantCulture, "QuaternionKeyFrameCollection[{0}]", index)); } WritePreamble(); if (value != _keyFrames[index]) { OnFreezablePropertyChanged(_keyFrames[index], value); _keyFrames[index] = value; Debug.Assert(_keyFrames[index] != null); WritePostscript(); } } } #endregion } }
using Lucene.Net.Codecs; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using Lucene.Net.Store; using Lucene.Net.Util; using NUnit.Framework; using System; using System.IO; using Assert = Lucene.Net.TestFramework.Assert; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Index { /* * 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 Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using FieldType = FieldType; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper; using NumericDocValuesField = NumericDocValuesField; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using ScoreDoc = Lucene.Net.Search.ScoreDoc; using TermQuery = Lucene.Net.Search.TermQuery; using TestUtil = Lucene.Net.Util.TestUtil; using TextField = TextField; /// <summary> /// Tests for IndexWriter when the disk runs out of space /// </summary> [TestFixture] [Timeout(900000)] public class TestIndexWriterOnDiskFull : LuceneTestCase { /* * Make sure IndexWriter cleans up on hitting a disk * full exception in addDocument. * TODO: how to do this on windows with FSDirectory? */ [Test] public virtual void TestAddDocumentOnDiskFull() { for (int pass = 0; pass < 2; pass++) { if (Verbose) { Console.WriteLine("TEST: pass=" + pass); } bool doAbort = pass == 1; long diskFree = TestUtil.NextInt32(Random, 100, 300); while (true) { if (Verbose) { Console.WriteLine("TEST: cycle: diskFree=" + diskFree); } MockDirectoryWrapper dir = new MockDirectoryWrapper(Random, new RAMDirectory()); dir.MaxSizeInBytes = diskFree; IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); IMergeScheduler ms = writer.Config.MergeScheduler; if (ms is IConcurrentMergeScheduler) { // this test intentionally produces exceptions // in the threads that CMS launches; we don't // want to pollute test output with these. ((IConcurrentMergeScheduler)ms).SetSuppressExceptions(); } bool hitError = false; try { for (int i = 0; i < 200; i++) { AddDoc(writer); } if (Verbose) { Console.WriteLine("TEST: done adding docs; now commit"); } writer.Commit(); } catch (IOException e) { if (Verbose) { Console.WriteLine("TEST: exception on addDoc"); Console.WriteLine(e.StackTrace); } hitError = true; } if (hitError) { if (doAbort) { if (Verbose) { Console.WriteLine("TEST: now rollback"); } writer.Rollback(); } else { try { if (Verbose) { Console.WriteLine("TEST: now close"); } writer.Dispose(); } catch (IOException e) { if (Verbose) { Console.WriteLine("TEST: exception on close; retry w/ no disk space limit"); Console.WriteLine(e.StackTrace); } dir.MaxSizeInBytes = 0; writer.Dispose(); } } //TestUtil.SyncConcurrentMerges(ms); if (TestUtil.AnyFilesExceptWriteLock(dir)) { TestIndexWriter.AssertNoUnreferencedFiles(dir, "after disk full during addDocument"); // Make sure reader can open the index: DirectoryReader.Open(dir).Dispose(); } dir.Dispose(); // Now try again w/ more space: diskFree += TestNightly ? TestUtil.NextInt32(Random, 400, 600) : TestUtil.NextInt32(Random, 3000, 5000); } else { //TestUtil.SyncConcurrentMerges(writer); dir.MaxSizeInBytes = 0; writer.Dispose(); dir.Dispose(); break; } } } } // TODO: make @Nightly variant that provokes more disk // fulls // TODO: have test fail if on any given top // iter there was not a single IOE hit /* Test: make sure when we run out of disk space or hit random IOExceptions in any of the addIndexes(*) calls that 1) index is not corrupt (searcher can open/search it) and 2) transactional semantics are followed: either all or none of the incoming documents were in fact added. */ [Test] public virtual void TestAddIndexOnDiskFull() { // MemoryCodec, since it uses FST, is not necessarily // "additive", ie if you add up N small FSTs, then merge // them, the merged result can easily be larger than the // sum because the merged FST may use array encoding for // some arcs (which uses more space): string idFormat = TestUtil.GetPostingsFormat("id"); string contentFormat = TestUtil.GetPostingsFormat("content"); AssumeFalse("this test cannot run with Memory codec", idFormat.Equals("Memory", StringComparison.Ordinal) || contentFormat.Equals("Memory", StringComparison.Ordinal)); int START_COUNT = 57; int NUM_DIR = TestNightly ? 50 : 5; int END_COUNT = START_COUNT + NUM_DIR * (TestNightly ? 25 : 5); // Build up a bunch of dirs that have indexes which we // will then merge together by calling addIndexes(*): Directory[] dirs = new Directory[NUM_DIR]; long inputDiskUsage = 0; for (int i = 0; i < NUM_DIR; i++) { dirs[i] = NewDirectory(); IndexWriter writer = new IndexWriter(dirs[i], NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); for (int j = 0; j < 25; j++) { AddDocWithIndex(writer, 25 * i + j); } writer.Dispose(); string[] files = dirs[i].ListAll(); for (int j = 0; j < files.Length; j++) { inputDiskUsage += dirs[i].FileLength(files[j]); } } // Now, build a starting index that has START_COUNT docs. We // will then try to addIndexes into a copy of this: MockDirectoryWrapper startDir = NewMockDirectory(); IndexWriter indWriter = new IndexWriter(startDir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); for (int j = 0; j < START_COUNT; j++) { AddDocWithIndex(indWriter, j); } indWriter.Dispose(); // Make sure starting index seems to be working properly: Term searchTerm = new Term("content", "aaa"); IndexReader reader = DirectoryReader.Open(startDir); Assert.AreEqual(57, reader.DocFreq(searchTerm), "first docFreq"); IndexSearcher searcher = NewSearcher(reader); ScoreDoc[] hits = searcher.Search(new TermQuery(searchTerm), null, 1000).ScoreDocs; Assert.AreEqual(57, hits.Length, "first number of hits"); reader.Dispose(); // Iterate with larger and larger amounts of free // disk space. With little free disk space, // addIndexes will certainly run out of space & // fail. Verify that when this happens, index is // not corrupt and index in fact has added no // documents. Then, we increase disk space by 2000 // bytes each iteration. At some point there is // enough free disk space and addIndexes should // succeed and index should show all documents were // added. // String[] files = startDir.ListAll(); long diskUsage = startDir.GetSizeInBytes(); long startDiskUsage = 0; string[] files_ = startDir.ListAll(); for (int i = 0; i < files_.Length; i++) { startDiskUsage += startDir.FileLength(files_[i]); } for (int iter = 0; iter < 3; iter++) { if (Verbose) { Console.WriteLine("TEST: iter=" + iter); } // Start with 100 bytes more than we are currently using: long diskFree = diskUsage + TestUtil.NextInt32(Random, 50, 200); int method = iter; bool success = false; bool done = false; string methodName; if (0 == method) { methodName = "addIndexes(Directory[]) + forceMerge(1)"; } else if (1 == method) { methodName = "addIndexes(IndexReader[])"; } else { methodName = "addIndexes(Directory[])"; } while (!done) { if (Verbose) { Console.WriteLine("TEST: cycle..."); } // Make a new dir that will enforce disk usage: MockDirectoryWrapper dir = new MockDirectoryWrapper(Random, new RAMDirectory(startDir, NewIOContext(Random))); indWriter = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetOpenMode(OpenMode.APPEND).SetMergePolicy(NewLogMergePolicy(false))); IOException err = null; IMergeScheduler ms = indWriter.Config.MergeScheduler; for (int x = 0; x < 2; x++) { if (ms is IConcurrentMergeScheduler) // this test intentionally produces exceptions // in the threads that CMS launches; we don't // want to pollute test output with these. { if (0 == x) { ((IConcurrentMergeScheduler)ms).SetSuppressExceptions(); } else { ((IConcurrentMergeScheduler)ms).ClearSuppressExceptions(); } } // Two loops: first time, limit disk space & // throw random IOExceptions; second time, no // disk space limit: double rate = 0.05; double diskRatio = ((double)diskFree) / diskUsage; long thisDiskFree; string testName = null; if (0 == x) { dir.RandomIOExceptionRateOnOpen = Random.NextDouble() * 0.01; thisDiskFree = diskFree; if (diskRatio >= 2.0) { rate /= 2; } if (diskRatio >= 4.0) { rate /= 2; } if (diskRatio >= 6.0) { rate = 0.0; } if (Verbose) { testName = "disk full test " + methodName + " with disk full at " + diskFree + " bytes"; } } else { dir.RandomIOExceptionRateOnOpen = 0.0; thisDiskFree = 0; rate = 0.0; if (Verbose) { testName = "disk full test " + methodName + " with unlimited disk space"; } } if (Verbose) { Console.WriteLine("\ncycle: " + testName); } dir.TrackDiskUsage = true; dir.MaxSizeInBytes = thisDiskFree; dir.RandomIOExceptionRate = rate; try { if (0 == method) { if (Verbose) { Console.WriteLine("TEST: now addIndexes count=" + dirs.Length); } indWriter.AddIndexes(dirs); if (Verbose) { Console.WriteLine("TEST: now forceMerge"); } indWriter.ForceMerge(1); } else if (1 == method) { IndexReader[] readers = new IndexReader[dirs.Length]; for (int i = 0; i < dirs.Length; i++) { readers[i] = DirectoryReader.Open(dirs[i]); } try { indWriter.AddIndexes(readers); } finally { for (int i = 0; i < dirs.Length; i++) { readers[i].Dispose(); } } } else { indWriter.AddIndexes(dirs); } success = true; if (Verbose) { Console.WriteLine(" success!"); } if (0 == x) { done = true; } } catch (IOException e) { success = false; err = e; if (Verbose) { Console.WriteLine(" hit IOException: " + e); Console.WriteLine(e.StackTrace); } if (1 == x) { Console.WriteLine(e.StackTrace); Assert.Fail(methodName + " hit IOException after disk space was freed up"); } } // Make sure all threads from // ConcurrentMergeScheduler are done TestUtil.SyncConcurrentMerges(indWriter); if (Verbose) { Console.WriteLine(" now test readers"); } // Finally, verify index is not corrupt, and, if // we succeeded, we see all docs added, and if we // failed, we see either all docs or no docs added // (transactional semantics): dir.RandomIOExceptionRateOnOpen = 0.0; try { reader = DirectoryReader.Open(dir); } catch (IOException e) { Console.WriteLine(e.StackTrace); Assert.Fail(testName + ": exception when creating IndexReader: " + e); } int result = reader.DocFreq(searchTerm); if (success) { if (result != START_COUNT) { Assert.Fail(testName + ": method did not throw exception but docFreq('aaa') is " + result + " instead of expected " + START_COUNT); } } else { // On hitting exception we still may have added // all docs: if (result != START_COUNT && result != END_COUNT) { Console.WriteLine(err.StackTrace); Assert.Fail(testName + ": method did throw exception but docFreq('aaa') is " + result + " instead of expected " + START_COUNT + " or " + END_COUNT); } } searcher = NewSearcher(reader); try { hits = searcher.Search(new TermQuery(searchTerm), null, END_COUNT).ScoreDocs; } catch (IOException e) { Console.WriteLine(e.StackTrace); Assert.Fail(testName + ": exception when searching: " + e); } int result2 = hits.Length; if (success) { if (result2 != result) { Assert.Fail(testName + ": method did not throw exception but hits.Length for search on term 'aaa' is " + result2 + " instead of expected " + result); } } else { // On hitting exception we still may have added // all docs: if (result2 != result) { Console.WriteLine(err.StackTrace); Assert.Fail(testName + ": method did throw exception but hits.Length for search on term 'aaa' is " + result2 + " instead of expected " + result); } } reader.Dispose(); if (Verbose) { Console.WriteLine(" count is " + result); } if (done || result == END_COUNT) { break; } } if (Verbose) { Console.WriteLine(" start disk = " + startDiskUsage + "; input disk = " + inputDiskUsage + "; max used = " + dir.MaxUsedSizeInBytes); } if (done) { // Javadocs state that temp free Directory space // required is at most 2X total input size of // indices so let's make sure: Assert.IsTrue((dir.MaxUsedSizeInBytes - startDiskUsage) < 2 * (startDiskUsage + inputDiskUsage), "max free Directory space required exceeded 1X the total input index sizes during " + methodName + ": max temp usage = " + (dir.MaxUsedSizeInBytes - startDiskUsage) + " bytes vs limit=" + (2 * (startDiskUsage + inputDiskUsage)) + "; starting disk usage = " + startDiskUsage + " bytes; " + "input index disk usage = " + inputDiskUsage + " bytes"); } // Make sure we don't hit disk full during close below: dir.MaxSizeInBytes = 0; dir.RandomIOExceptionRate = 0.0; dir.RandomIOExceptionRateOnOpen = 0.0; indWriter.Dispose(); // Wait for all BG threads to finish else // dir.Dispose() will throw IOException because // there are still open files TestUtil.SyncConcurrentMerges(ms); dir.Dispose(); // Try again with more free space: diskFree += TestNightly ? TestUtil.NextInt32(Random, 4000, 8000) : TestUtil.NextInt32(Random, 40000, 80000); } } startDir.Dispose(); foreach (Directory dir in dirs) { dir.Dispose(); } } private class FailTwiceDuringMerge : Failure { public bool didFail1; public bool didFail2; public override void Eval(MockDirectoryWrapper dir) { if (!m_doFail) { return; } // LUCENENET specific: for these to work in release mode, we have added [MethodImpl(MethodImplOptions.NoInlining)] // to each possible target of the StackTraceHelper. If these change, so must the attribute on the target methods. if (StackTraceHelper.DoesStackTraceContainMethod(typeof(SegmentMerger).Name, "MergeTerms") && !didFail1) { didFail1 = true; throw new IOException("fake disk full during mergeTerms"); } // LUCENENET specific: for these to work in release mode, we have added [MethodImpl(MethodImplOptions.NoInlining)] // to each possible target of the StackTraceHelper. If these change, so must the attribute on the target methods. if (StackTraceHelper.DoesStackTraceContainMethod(typeof(LiveDocsFormat).Name, "WriteLiveDocs") && !didFail2) { didFail2 = true; throw new IOException("fake disk full while writing LiveDocs"); } } } // LUCENE-2593 [Test] public virtual void TestCorruptionAfterDiskFullDuringMerge() { MockDirectoryWrapper dir = NewMockDirectory(); //IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).setReaderPooling(true)); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergeScheduler(new SerialMergeScheduler()).SetReaderPooling(true).SetMergePolicy(NewLogMergePolicy(2))); // we can do this because we add/delete/add (and dont merge to "nothing") w.KeepFullyDeletedSegments = true; Document doc = new Document(); doc.Add(NewTextField("f", "doctor who", Field.Store.NO)); w.AddDocument(doc); w.Commit(); w.DeleteDocuments(new Term("f", "who")); w.AddDocument(doc); // disk fills up! FailTwiceDuringMerge ftdm = new FailTwiceDuringMerge(); ftdm.SetDoFail(); dir.FailOn(ftdm); try { w.Commit(); Assert.Fail("fake disk full IOExceptions not hit"); } #pragma warning disable 168 catch (IOException ioe) #pragma warning restore 168 { // expected Assert.IsTrue(ftdm.didFail1 || ftdm.didFail2); } TestUtil.CheckIndex(dir); ftdm.ClearDoFail(); w.AddDocument(doc); w.Dispose(); dir.Dispose(); } // LUCENE-1130: make sure immeidate disk full on creating // an IndexWriter (hit during DW.ThreadState.Init()) is // OK: [Test] public virtual void TestImmediateDiskFull([ValueSource(typeof(ConcurrentMergeSchedulerFactories), "Values")]Func<IConcurrentMergeScheduler> newScheduler) { MockDirectoryWrapper dir = NewMockDirectory(); var config = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)) .SetMaxBufferedDocs(2) .SetMergeScheduler(newScheduler()); IndexWriter writer = new IndexWriter(dir, config); dir.MaxSizeInBytes = Math.Max(1, dir.GetRecomputedActualSizeInBytes()); Document doc = new Document(); FieldType customType = new FieldType(TextField.TYPE_STORED); doc.Add(NewField("field", "aaa bbb ccc ddd eee fff ggg hhh iii jjj", customType)); try { writer.AddDocument(doc); Assert.Fail("did not hit disk full"); } catch (IOException) { } // Without fix for LUCENE-1130: this call will hang: try { writer.AddDocument(doc); Assert.Fail("did not hit disk full"); } catch (IOException) { } try { writer.Dispose(false); Assert.Fail("did not hit disk full"); } catch (IOException) { } // Make sure once disk space is avail again, we can // cleanly close: dir.MaxSizeInBytes = 0; writer.Dispose(false); dir.Dispose(); } // TODO: these are also in TestIndexWriter... add a simple doc-writing method // like this to LuceneTestCase? private void AddDoc(IndexWriter writer) { Document doc = new Document(); doc.Add(NewTextField("content", "aaa", Field.Store.NO)); if (DefaultCodecSupportsDocValues) { doc.Add(new NumericDocValuesField("numericdv", 1)); } writer.AddDocument(doc); } private void AddDocWithIndex(IndexWriter writer, int index) { Document doc = new Document(); doc.Add(NewTextField("content", "aaa " + index, Field.Store.NO)); doc.Add(NewTextField("id", "" + index, Field.Store.NO)); if (DefaultCodecSupportsDocValues) { doc.Add(new NumericDocValuesField("numericdv", 1)); } writer.AddDocument(doc); } } }
/* * 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 Apache.Ignite.Core.Tests.Binary { using System; using System.Collections.Generic; #if !NETCOREAPP using System.Linq; using System.Reflection; #endif using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Impl.Binary; using NUnit.Framework; /// <summary> /// <see cref="TypeResolver"/> tests. /// </summary> public class TypeResolverTest { /// <summary> /// Tests basic types. /// </summary> [Test] public void TestBasicTypes() { var resolver = new TypeResolver(); Assert.AreEqual(typeof(int), resolver.ResolveType("System.Int32")); Assert.AreEqual(GetType(), resolver.ResolveType(GetType().FullName)); Assert.IsNull(resolver.ResolveType("invalidType")); } /// <summary> /// Tests basic types. /// </summary> [Test] public void TestBasicTypesSimpleMapper() { var resolver = new TypeResolver(); var mapper = BinaryBasicNameMapper.SimpleNameInstance; Assert.AreEqual(typeof(int), resolver.ResolveType("Int32", nameMapper: mapper)); Assert.AreEqual(GetType(), resolver.ResolveType("TypeResolverTest", nameMapper: mapper)); Assert.IsNull(resolver.ResolveType("invalidType", nameMapper: mapper)); } /// <summary> /// Tests generic type resolve. /// </summary> [Test] public void TestGenerics() { var testTypes = new[] { typeof (TestGenericBinarizable<int>), typeof (TestGenericBinarizable<string>), typeof (TestGenericBinarizable<TestGenericBinarizable<int>>), typeof (TestGenericBinarizable<List<Tuple<int, string>>>), typeof (TestGenericBinarizable<List<TestGenericBinarizable<List<Tuple<int, string>>>>>), typeof (List<TestGenericBinarizable<List<TestGenericBinarizable<List<Tuple<int, string>>>>>>), typeof (TestGenericBinarizable<int, string>), typeof (TestGenericBinarizable<int, TestGenericBinarizable<string>>), typeof (TestGenericBinarizable<int, string, Type>), typeof (TestGenericBinarizable<int, string, TestGenericBinarizable<int, string, Type>>) }; foreach (var type in testTypes) { // Without assembly var resolvedType = new TypeResolver().ResolveType(type.FullName); Assert.AreEqual(type.FullName, resolvedType.FullName); // With assembly resolvedType = new TypeResolver().ResolveType(type.FullName, type.Assembly.FullName); Assert.AreEqual(type.FullName, resolvedType.FullName); // Assembly-qualified resolvedType = new TypeResolver().ResolveType(type.AssemblyQualifiedName); Assert.AreEqual(type.FullName, resolvedType.FullName); } } /// <summary> /// Tests generic type resolve. /// </summary> [Test] public void TestGenericsSimpleName() { var resolver = new TypeResolver(); var mapper = BinaryBasicNameMapper.SimpleNameInstance; Assert.AreEqual(typeof(TestGenericBinarizable<int>), resolver.ResolveType("TestGenericBinarizable`1[[Int32]]", nameMapper: mapper)); Assert.IsNull(resolver.ResolveType("TestGenericBinarizable`1[[Invalid-Type]]", nameMapper: mapper)); var testTypes = new[] { typeof (TestGenericBinarizable<int>), typeof (TestGenericBinarizable<string>), typeof (TestGenericBinarizable<TestGenericBinarizable<int>>), typeof (TestGenericBinarizable<List<Tuple<int, string>>>), typeof (TestGenericBinarizable<List<TestGenericBinarizable<List<Tuple<int, string>>>>>), typeof (List<TestGenericBinarizable<List<TestGenericBinarizable<List<Tuple<int, string>>>>>>), typeof (TestGenericBinarizable<int, string>), typeof (TestGenericBinarizable<int, TestGenericBinarizable<string>>), typeof (TestGenericBinarizable<int, string, Type>), typeof (TestGenericBinarizable<int, string, TestGenericBinarizable<int, string, Type>>) }; foreach (var type in testTypes) { var typeName = mapper.GetTypeName(type.AssemblyQualifiedName); var resolvedType = resolver.ResolveType(typeName, nameMapper: mapper); Assert.AreEqual(type, resolvedType); } } /// <summary> /// Tests array type resolve. /// </summary> [Test] public void TestArrays() { var resolver = new TypeResolver(); Assert.AreEqual(typeof(int[]), resolver.ResolveType("System.Int32[]")); Assert.AreEqual(typeof(int[][]), resolver.ResolveType("System.Int32[][]")); Assert.AreEqual(typeof(int[,,][,]), resolver.ResolveType("System.Int32[,][,,]")); Assert.AreEqual(typeof(int).MakeArrayType(1), resolver.ResolveType("System.Int32[*]")); Assert.AreEqual(typeof(TestGenericBinarizable<TypeResolverTest>[]), resolver.ResolveType("Apache.Ignite.Core.Tests.TestGenericBinarizable`1" + "[[Apache.Ignite.Core.Tests.Binary.TypeResolverTest]][]")); } /// <summary> /// Tests array type resolve. /// </summary> [Test] public void TestArraysSimpleName() { var resolver = new TypeResolver(); var mapper = BinaryBasicNameMapper.SimpleNameInstance; Assert.AreEqual(typeof(int[]), resolver.ResolveType("Int32[]", nameMapper: mapper)); Assert.AreEqual(typeof(int[][]), resolver.ResolveType("Int32[][]", nameMapper: mapper)); Assert.AreEqual(typeof(int[,,][,]), resolver.ResolveType("Int32[,][,,]", nameMapper: mapper)); Assert.AreEqual(typeof(int).MakeArrayType(1), resolver.ResolveType("Int32[*]", nameMapper: mapper)); Assert.AreEqual(typeof(TestGenericBinarizable<TypeResolverTest>[]), resolver.ResolveType("TestGenericBinarizable`1[[TypeResolverTest]][]", nameMapper: mapper)); } #if !NETCOREAPP /// <summary> /// Tests loading a type from referenced assembly that is not yet loaded. /// </summary> [Test] public void TestReferencedAssemblyLoading() { const string dllName = "Apache.Ignite.Core.Tests.TestDll"; const string typeName = "Apache.Ignite.Core.Tests.TestDll.TestClass"; // Check that the dll is not yet loaded Assert.IsFalse(AppDomain.CurrentDomain.GetAssemblies().Any(x => x.FullName.StartsWith(dllName))); // Check that the dll is referenced by current assembly Assert.IsTrue(Assembly.GetExecutingAssembly().GetReferencedAssemblies() .Any(x => x.FullName.StartsWith(dllName))); // Check resolver var type = new TypeResolver().ResolveType(typeName); Assert.IsNotNull(type); Assert.AreEqual(typeName, type.FullName); Assert.IsNotNull(Activator.CreateInstance(type)); // At this moment the dll should be loaded Assert.IsTrue(AppDomain.CurrentDomain.GetAssemblies().Any(x => x.FullName.StartsWith(dllName))); } /// <summary> /// Unused method that forces C# compiler to include TestDll assembly reference. /// Without this, compiler will remove the reference as unused. /// However, since it is never called, TestDll does not get loaded. /// </summary> public void UnusedMethod() { Assert.IsNotNull(typeof(TestDll.TestClass)); } #endif } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Umbraco.Core.Auditing; using Umbraco.Core.Events; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.UnitOfWork; using Umbraco.Core.PropertyEditors; using umbraco.interfaces; namespace Umbraco.Core.Services { /// <summary> /// Represents the DataType Service, which is an easy access to operations involving <see cref="IDataTypeDefinition"/> /// </summary> public class DataTypeService : RepositoryService, IDataTypeService { [Obsolete("Use the constructors that specify all dependencies instead")] public DataTypeService() : this(new RepositoryFactory()) {} [Obsolete("Use the constructors that specify all dependencies instead")] public DataTypeService(RepositoryFactory repositoryFactory) : this(new PetaPocoUnitOfWorkProvider(), repositoryFactory) { } [Obsolete("Use the constructors that specify all dependencies instead")] public DataTypeService(IDatabaseUnitOfWorkProvider provider) : this(provider, new RepositoryFactory()) { } [Obsolete("Use the constructors that specify all dependencies instead")] public DataTypeService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory) : this(provider, repositoryFactory, LoggerResolver.Current.Logger) { } public DataTypeService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, ILogger logger) : base(provider, repositoryFactory, logger) { } /// <summary> /// Gets a <see cref="IDataTypeDefinition"/> by its Name /// </summary> /// <param name="name">Name of the <see cref="IDataTypeDefinition"/></param> /// <returns><see cref="IDataTypeDefinition"/></returns> public IDataTypeDefinition GetDataTypeDefinitionByName(string name) { using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(UowProvider.GetUnitOfWork())) { return repository.GetByQuery(new Query<IDataTypeDefinition>().Where(x => x.Name == name)).FirstOrDefault(); } } /// <summary> /// Gets a <see cref="IDataTypeDefinition"/> by its Id /// </summary> /// <param name="id">Id of the <see cref="IDataTypeDefinition"/></param> /// <returns><see cref="IDataTypeDefinition"/></returns> public IDataTypeDefinition GetDataTypeDefinitionById(int id) { using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(UowProvider.GetUnitOfWork())) { return repository.Get(id); } } /// <summary> /// Gets a <see cref="IDataTypeDefinition"/> by its unique guid Id /// </summary> /// <param name="id">Unique guid Id of the DataType</param> /// <returns><see cref="IDataTypeDefinition"/></returns> public IDataTypeDefinition GetDataTypeDefinitionById(Guid id) { using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(UowProvider.GetUnitOfWork())) { var query = Query<IDataTypeDefinition>.Builder.Where(x => x.Key == id); var definitions = repository.GetByQuery(query); return definitions.FirstOrDefault(); } } /// <summary> /// Gets a <see cref="IDataTypeDefinition"/> by its control Id /// </summary> /// <param name="id">Id of the DataType control</param> /// <returns>Collection of <see cref="IDataTypeDefinition"/> objects with a matching contorl id</returns> [Obsolete("Property editor's are defined by a string alias from version 7 onwards, use the overload GetDataTypeDefinitionByPropertyEditorAlias instead")] public IEnumerable<IDataTypeDefinition> GetDataTypeDefinitionByControlId(Guid id) { var alias = LegacyPropertyEditorIdToAliasConverter.GetAliasFromLegacyId(id, true); return GetDataTypeDefinitionByPropertyEditorAlias(alias); } /// <summary> /// Gets a <see cref="IDataTypeDefinition"/> by its control Id /// </summary> /// <param name="propertyEditorAlias">Alias of the property editor</param> /// <returns>Collection of <see cref="IDataTypeDefinition"/> objects with a matching contorl id</returns> public IEnumerable<IDataTypeDefinition> GetDataTypeDefinitionByPropertyEditorAlias(string propertyEditorAlias) { using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(UowProvider.GetUnitOfWork())) { var query = Query<IDataTypeDefinition>.Builder.Where(x => x.PropertyEditorAlias == propertyEditorAlias); var definitions = repository.GetByQuery(query); return definitions; } } /// <summary> /// Gets all <see cref="IDataTypeDefinition"/> objects or those with the ids passed in /// </summary> /// <param name="ids">Optional array of Ids</param> /// <returns>An enumerable list of <see cref="IDataTypeDefinition"/> objects</returns> public IEnumerable<IDataTypeDefinition> GetAllDataTypeDefinitions(params int[] ids) { using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(UowProvider.GetUnitOfWork())) { return repository.GetAll(ids); } } /// <summary> /// Gets all prevalues for an <see cref="IDataTypeDefinition"/> /// </summary> /// <param name="id">Id of the <see cref="IDataTypeDefinition"/> to retrieve prevalues from</param> /// <returns>An enumerable list of string values</returns> public IEnumerable<string> GetPreValuesByDataTypeId(int id) { using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(UowProvider.GetUnitOfWork())) { var collection = repository.GetPreValuesCollectionByDataTypeId(id); //now convert the collection to a string list var list = collection.FormatAsDictionary() .Select(x => x.Value.Value) .ToList(); return list; } } /// <summary> /// Returns the PreValueCollection for the specified data type /// </summary> /// <param name="id"></param> /// <returns></returns> public PreValueCollection GetPreValuesCollectionByDataTypeId(int id) { using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(UowProvider.GetUnitOfWork())) { return repository.GetPreValuesCollectionByDataTypeId(id); } } /// <summary> /// Gets a specific PreValue by its Id /// </summary> /// <param name="id">Id of the PreValue to retrieve the value from</param> /// <returns>PreValue as a string</returns> public string GetPreValueAsString(int id) { using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(UowProvider.GetUnitOfWork())) { return repository.GetPreValueAsString(id); } } /// <summary> /// Saves an <see cref="IDataTypeDefinition"/> /// </summary> /// <param name="dataTypeDefinition"><see cref="IDataTypeDefinition"/> to save</param> /// <param name="userId">Id of the user issueing the save</param> public void Save(IDataTypeDefinition dataTypeDefinition, int userId = 0) { if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinition), this)) return; var uow = UowProvider.GetUnitOfWork(); using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow)) { dataTypeDefinition.CreatorId = userId; repository.AddOrUpdate(dataTypeDefinition); uow.Commit(); Saved.RaiseEvent(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinition, false), this); } Audit(AuditType.Save, string.Format("Save DataTypeDefinition performed by user"), userId, dataTypeDefinition.Id); } /// <summary> /// Saves a collection of <see cref="IDataTypeDefinition"/> /// </summary> /// <param name="dataTypeDefinitions"><see cref="IDataTypeDefinition"/> to save</param> /// <param name="userId">Id of the user issueing the save</param> public void Save(IEnumerable<IDataTypeDefinition> dataTypeDefinitions, int userId = 0) { Save(dataTypeDefinitions, userId, true); } /// <summary> /// Saves a collection of <see cref="IDataTypeDefinition"/> /// </summary> /// <param name="dataTypeDefinitions"><see cref="IDataTypeDefinition"/> to save</param> /// <param name="userId">Id of the user issueing the save</param> /// <param name="raiseEvents">Boolean indicating whether or not to raise events</param> public void Save(IEnumerable<IDataTypeDefinition> dataTypeDefinitions, int userId, bool raiseEvents) { if (raiseEvents) { if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinitions), this)) return; } var uow = UowProvider.GetUnitOfWork(); using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow)) { foreach (var dataTypeDefinition in dataTypeDefinitions) { dataTypeDefinition.CreatorId = userId; repository.AddOrUpdate(dataTypeDefinition); } uow.Commit(); if (raiseEvents) Saved.RaiseEvent(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinitions, false), this); } Audit(AuditType.Save, string.Format("Save DataTypeDefinition performed by user"), userId, -1); } /// <summary> /// Saves a list of PreValues for a given DataTypeDefinition /// </summary> /// <param name="dataTypeId">Id of the DataTypeDefinition to save PreValues for</param> /// <param name="values">List of string values to save</param> [Obsolete("This should no longer be used, use the alternative SavePreValues or SaveDataTypeAndPreValues methods instead. This will only insert pre-values without keys")] public void SavePreValues(int dataTypeId, IEnumerable<string> values) { //TODO: Should we raise an event here since we are really saving values for the data type? using (var uow = UowProvider.GetUnitOfWork()) { using (var transaction = uow.Database.GetTransaction()) { var sortOrderObj = uow.Database.ExecuteScalar<object>( "SELECT max(sortorder) FROM cmsDataTypePreValues WHERE datatypeNodeId = @DataTypeId", new { DataTypeId = dataTypeId }); int sortOrder; if (sortOrderObj == null || int.TryParse(sortOrderObj.ToString(), out sortOrder) == false) { sortOrder = 1; } foreach (var value in values) { var dto = new DataTypePreValueDto { DataTypeNodeId = dataTypeId, Value = value, SortOrder = sortOrder }; uow.Database.Insert(dto); sortOrder++; } transaction.Complete(); } } } /// <summary> /// Saves/updates the pre-values /// </summary> /// <param name="dataTypeId"></param> /// <param name="values"></param> /// <remarks> /// We need to actually look up each pre-value and maintain it's id if possible - this is because of silly property editors /// like 'dropdown list publishing keys' /// </remarks> public void SavePreValues(int dataTypeId, IDictionary<string, PreValue> values) { var dtd = this.GetDataTypeDefinitionById(dataTypeId); if (dtd == null) { throw new InvalidOperationException("No data type found for id " + dataTypeId); } SavePreValues(dtd, values); } /// <summary> /// Saves/updates the pre-values /// </summary> /// <param name="dataTypeDefinition"></param> /// <param name="values"></param> /// <remarks> /// We need to actually look up each pre-value and maintain it's id if possible - this is because of silly property editors /// like 'dropdown list publishing keys' /// </remarks> public void SavePreValues(IDataTypeDefinition dataTypeDefinition, IDictionary<string, PreValue> values) { //TODO: Should we raise an event here since we are really saving values for the data type? var uow = UowProvider.GetUnitOfWork(); using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow)) { repository.AddOrUpdatePreValues(dataTypeDefinition, values); uow.Commit(); } } /// <summary> /// This will save a data type and it's pre-values in one transaction /// </summary> /// <param name="dataTypeDefinition"></param> /// <param name="values"></param> /// <param name="userId"></param> public void SaveDataTypeAndPreValues(IDataTypeDefinition dataTypeDefinition, IDictionary<string, PreValue> values, int userId = 0) { if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinition), this)) return; var uow = UowProvider.GetUnitOfWork(); using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow)) { dataTypeDefinition.CreatorId = userId; //add/update the dtd repository.AddOrUpdate(dataTypeDefinition); //add/update the prevalues repository.AddOrUpdatePreValues(dataTypeDefinition, values); uow.Commit(); Saved.RaiseEvent(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinition, false), this); } Audit(AuditType.Save, string.Format("Save DataTypeDefinition performed by user"), userId, dataTypeDefinition.Id); } /// <summary> /// Deletes an <see cref="IDataTypeDefinition"/> /// </summary> /// <remarks> /// Please note that deleting a <see cref="IDataTypeDefinition"/> will remove /// all the <see cref="PropertyType"/> data that references this <see cref="IDataTypeDefinition"/>. /// </remarks> /// <param name="dataTypeDefinition"><see cref="IDataTypeDefinition"/> to delete</param> /// <param name="userId">Optional Id of the user issueing the deletion</param> public void Delete(IDataTypeDefinition dataTypeDefinition, int userId = 0) { if (Deleting.IsRaisedEventCancelled(new DeleteEventArgs<IDataTypeDefinition>(dataTypeDefinition), this)) return; var uow = UowProvider.GetUnitOfWork(); using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow)) { repository.Delete(dataTypeDefinition); uow.Commit(); Deleted.RaiseEvent(new DeleteEventArgs<IDataTypeDefinition>(dataTypeDefinition, false), this); } Audit(AuditType.Delete, string.Format("Delete DataTypeDefinition performed by user"), userId, dataTypeDefinition.Id); } /// <summary> /// Gets the <see cref="IDataType"/> specified by it's unique ID /// </summary> /// <param name="id">Id of the DataType, which corresponds to the Guid Id of the control</param> /// <returns><see cref="IDataType"/> object</returns> [Obsolete("IDataType is obsolete and is no longer used, it will be removed from the codebase in future versions")] public IDataType GetDataTypeById(Guid id) { return DataTypesResolver.Current.GetById(id); } /// <summary> /// Gets a complete list of all registered <see cref="IDataType"/>'s /// </summary> /// <returns>An enumerable list of <see cref="IDataType"/> objects</returns> [Obsolete("IDataType is obsolete and is no longer used, it will be removed from the codebase in future versions")] public IEnumerable<IDataType> GetAllDataTypes() { return DataTypesResolver.Current.DataTypes; } private void Audit(AuditType type, string message, int userId, int objectId) { var uow = UowProvider.GetUnitOfWork(); using (var auditRepo = RepositoryFactory.CreateAuditRepository(uow)) { auditRepo.AddOrUpdate(new AuditItem(objectId, message, type, userId)); uow.Commit(); } } #region Event Handlers /// <summary> /// Occurs before Delete /// </summary> public static event TypedEventHandler<IDataTypeService, DeleteEventArgs<IDataTypeDefinition>> Deleting; /// <summary> /// Occurs after Delete /// </summary> public static event TypedEventHandler<IDataTypeService, DeleteEventArgs<IDataTypeDefinition>> Deleted; /// <summary> /// Occurs before Save /// </summary> public static event TypedEventHandler<IDataTypeService, SaveEventArgs<IDataTypeDefinition>> Saving; /// <summary> /// Occurs after Save /// </summary> public static event TypedEventHandler<IDataTypeService, SaveEventArgs<IDataTypeDefinition>> Saved; #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. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Composition.Hosting; using System.Composition.Hosting.Core; using System.Composition.UnitTests.Util; using System.Composition.Runtime; using Xunit; namespace System.Composition.UnitTests { public class CircularityTests : ContainerTests { public interface IA { } [Export, Shared] public class BLazy { public Lazy<IA> A; [ImportingConstructor] public BLazy(Lazy<IA> ia) { A = ia; } } [Export(typeof(IA))] public class ACircular : IA { public BLazy B; [ImportingConstructor] public ACircular(BLazy b) { B = b; } } [Export, Shared] public class PropertyPropertyA { [Import] public PropertyPropertyB B { get; set; } } [Export] public class PropertyPropertyB { [Import] public PropertyPropertyA A { get; set; } } [Export] public class ConstructorPropertyA { [Import] public ConstructorPropertyB B { get; set; } } [Export, Shared] public class ConstructorPropertyB { [ImportingConstructor] public ConstructorPropertyB(ConstructorPropertyA a) { A = a; } public ConstructorPropertyA A { get; private set; } } public class CircularM { public string Name { get; set; } } [Export, ExportMetadata("Name", "A")] public class MetadataCircularityA { [Import] public Lazy<MetadataCircularityB, CircularM> B { get; set; } } [Export, ExportMetadata("Name", "B"), Shared] public class MetadataCircularityB { [Import] public Lazy<MetadataCircularityA, CircularM> A { get; set; } } [Export, Shared] public class NonPrereqSelfDependency { [Import] public NonPrereqSelfDependency Self { get; set; } } [Export] public class PrDepA { [ImportingConstructor] public PrDepA(PrDepB b) { } } [Export] public class PrDepB { [ImportingConstructor] public PrDepB(PrDepA a) { } } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void CanHandleDefinitionCircularity() { var cc = CreateContainer(typeof(ACircular), typeof(BLazy)); var x = cc.GetExport<BLazy>(); Assert.IsAssignableFrom(typeof(ACircular), x.A.Value); Assert.IsAssignableFrom(typeof(BLazy), ((ACircular)x.A.Value).B); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void CanHandleDefinitionCircularity2() { var cc = CreateContainer(typeof(ACircular), typeof(BLazy)); var x = cc.GetExport<IA>(); Assert.IsAssignableFrom(typeof(BLazy), ((ACircular)((ACircular)x).B.A.Value).B); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void HandlesPropertyPropertyCircularity() { var cc = CreateContainer(typeof(PropertyPropertyA), typeof(PropertyPropertyB)); var a = cc.GetExport<PropertyPropertyA>(); Assert.Same(a.B.A, a); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void HandlesPropertyPropertyCircularityReversed() { var cc = CreateContainer(typeof(PropertyPropertyA), typeof(PropertyPropertyB)); var b = cc.GetExport<PropertyPropertyB>(); Assert.Same(b.A.B, b.A.B.A.B); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void HandlesConstructorPropertyCircularity() { var cc = CreateContainer(typeof(ConstructorPropertyA), typeof(ConstructorPropertyB)); var a = cc.GetExport<ConstructorPropertyA>(); Assert.Same(a.B.A.B.A, a.B.A); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void HandlesConstructorPropertyCircularityReversed() { var cc = CreateContainer(typeof(ConstructorPropertyA), typeof(ConstructorPropertyB)); var b = cc.GetExport<ConstructorPropertyB>(); Assert.Same(b, b.A.B); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void HandlesMetadataCircularity() { var cc = CreateContainer(typeof(MetadataCircularityA), typeof(MetadataCircularityB)); var a = cc.GetExport<MetadataCircularityA>(); Assert.Equal(a.B.Metadata.Name, "B"); Assert.Equal(a.B.Value.A.Metadata.Name, "A"); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void SharedPartCanHaveNonPrereqDependencyOnSelf() { var cc = CreateContainer(typeof(NonPrereqSelfDependency)); var npsd = cc.GetExport<NonPrereqSelfDependency>(); Assert.Same(npsd, npsd.Self); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void PrerequisiteCircularitiesAreDetected() { var cc = CreateContainer(typeof(PrDepA), typeof(PrDepB)); var x = Assert.Throws<CompositionFailedException>(() => { cc.GetExport<PrDepA>(); }); } } }
// 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 Xunit; namespace Microsoft.Win32.RegistryTests { public class RegistryKey_SetValueKind_str_obj_valueKind : RegistryTestsBase { public static IEnumerable<object[]> TestObjects { get { return TestData.TestObjects; } } [Theory] [MemberData(nameof(TestObjects))] public void SetValueWithUnknownValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { string valueName = "Testing_" + testIndex.ToString(); TestRegistryKey.SetValue(valueName, testValue, RegistryValueKind.Unknown); Assert.Equal(testValue.ToString(), TestRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, TestRegistryKey.GetValueKind(valueName)); TestRegistryKey.DeleteValue(valueName); } [Theory] [MemberData(nameof(TestObjects))] public void SetValueWithStringValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { string valueName = "Testing_" + testIndex.ToString(); expectedValueKind = RegistryValueKind.String; TestRegistryKey.SetValue(valueName, testValue, expectedValueKind); Assert.Equal(testValue.ToString(), TestRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, TestRegistryKey.GetValueKind(valueName)); TestRegistryKey.DeleteValue(valueName); } [Theory] [MemberData(nameof(TestObjects))] public void SetValueWithExpandStringValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { string valueName = "Testing_" + testIndex.ToString(); expectedValueKind = RegistryValueKind.ExpandString; TestRegistryKey.SetValue(valueName, testValue, expectedValueKind); Assert.Equal(testValue.ToString(), TestRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, TestRegistryKey.GetValueKind(valueName)); TestRegistryKey.DeleteValue(valueName); } [Theory] [MemberData(nameof(TestObjects))] public void SetValueWithMultiStringValeKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { try { string valueName = "Testing_" + testIndex.ToString(); expectedValueKind = RegistryValueKind.MultiString; TestRegistryKey.SetValue(valueName, testValue, expectedValueKind); Assert.Equal(testValue.ToString(), TestRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, TestRegistryKey.GetValueKind(valueName)); TestRegistryKey.DeleteValue(valueName); } catch (ArgumentException) { Assert.IsNotType<string[]>(testValue); } } [Theory] [MemberData(nameof(TestObjects))] public void SetValueWithBinaryValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { try { string valueName = "Testing_" + testIndex.ToString(); expectedValueKind = RegistryValueKind.Binary; TestRegistryKey.SetValue(valueName, testValue, expectedValueKind); Assert.Equal(testValue.ToString(), TestRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, TestRegistryKey.GetValueKind(valueName)); TestRegistryKey.DeleteValue(valueName); } catch (ArgumentException) { Assert.IsNotType<byte[]>(testValue); } } [Theory] [MemberData(nameof(TestObjects))] public void SetValueWithDWordValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { try { string valueName = "Testing_" + testIndex.ToString(); expectedValueKind = RegistryValueKind.DWord; TestRegistryKey.SetValue(valueName, testValue, expectedValueKind); Assert.Equal(Convert.ToInt32(testValue).ToString(), TestRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, TestRegistryKey.GetValueKind(valueName)); Assert.True(testIndex <= 15); TestRegistryKey.DeleteValue(valueName); } catch (ArgumentException ioe) { Assert.False(testIndex <= 15, ioe.ToString()); } } [Theory] [MemberData(nameof(TestObjects))] public void SetValueWithQWordValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { try { string valueName = "Testing_" + testIndex.ToString(); expectedValueKind = RegistryValueKind.QWord; TestRegistryKey.SetValue(valueName, testValue, expectedValueKind); Assert.Equal(Convert.ToInt64(testValue).ToString(), TestRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, TestRegistryKey.GetValueKind(valueName)); Assert.True(testIndex <= 25); TestRegistryKey.DeleteValue(valueName); } catch (ArgumentException ioe) { Assert.False(testIndex <= 25, ioe.ToString()); } } [Fact] public void SetValueForNonExistingKey() { const string valueName = "FooBar"; const int expectedValue1 = int.MaxValue; const long expectedValue2 = long.MinValue; const RegistryValueKind expectedValueKind1 = RegistryValueKind.DWord; const RegistryValueKind expectedValueKind2 = RegistryValueKind.QWord; Assert.True(TestRegistryKey.GetValue(valueName) == null, "Registry key already exists"); TestRegistryKey.SetValue(valueName, expectedValue1, expectedValueKind1); Assert.True(TestRegistryKey.GetValue(valueName) != null, "Registry key doesn't exists"); Assert.Equal(expectedValue1, (int)TestRegistryKey.GetValue(valueName)); Assert.Equal(expectedValueKind1, TestRegistryKey.GetValueKind(valueName)); TestRegistryKey.SetValue(valueName, expectedValue2, expectedValueKind2); Assert.Equal(expectedValue2, (long)TestRegistryKey.GetValue(valueName)); Assert.Equal(expectedValueKind2, TestRegistryKey.GetValueKind(valueName)); } public static IEnumerable<object[]> TestValueNames { get { return TestData.TestValueNames; } } [Theory] [MemberData(nameof(TestValueNames))] public void SetValueWithNameTest(string valueName) { const long expectedValue = long.MaxValue; const RegistryValueKind expectedValueKind = RegistryValueKind.QWord; TestRegistryKey.SetValue(valueName, expectedValue, expectedValueKind); Assert.Equal(expectedValue, (long)TestRegistryKey.GetValue(valueName)); Assert.Equal(expectedValueKind, TestRegistryKey.GetValueKind(valueName)); } [Fact] public void NegativeTests() { // Should throw if key length above 255 characters but prior to V4 the limit is 16383 const int maxValueNameLength = 16383; string tooLongValueName = new string('a', maxValueNameLength + 1); AssertExtensions.Throws<ArgumentException>("name", null, () => TestRegistryKey.SetValue(tooLongValueName, ulong.MaxValue, RegistryValueKind.String)); const string valueName = "FooBar"; // Should throw if passed value is null Assert.Throws<ArgumentNullException>(() => TestRegistryKey.SetValue(valueName, null, RegistryValueKind.QWord)); // Should throw because valueKind is equal to -2 which is not an acceptable value AssertExtensions.Throws<ArgumentException>("valueKind", () => TestRegistryKey.SetValue(valueName, int.MinValue, (RegistryValueKind)(-2))); // Should throw because passed array contains null string[] strArr = { "one", "two", null, "three" }; AssertExtensions.Throws<ArgumentException>(null, () => TestRegistryKey.SetValue(valueName, strArr, RegistryValueKind.MultiString)); // Should throw because passed array has wrong type AssertExtensions.Throws<ArgumentException>(null, () => TestRegistryKey.SetValue(valueName, new[] { new object() }, RegistryValueKind.MultiString)); // Should throw because passed array has wrong type object[] objTemp = { "my string", "your string", "Any once string" }; AssertExtensions.Throws<ArgumentException>(null, () => TestRegistryKey.SetValue(valueName, objTemp, RegistryValueKind.Unknown)); // Should throw because RegistryKey is readonly using (var rk = Registry.CurrentUser.OpenSubKey(TestRegistryKeyName, false)) { Assert.Throws<UnauthorizedAccessException>(() => rk.SetValue(valueName, int.MaxValue, RegistryValueKind.DWord)); } // Should throw if RegistryKey is closed Assert.Throws<ObjectDisposedException>(() => { TestRegistryKey.Dispose(); TestRegistryKey.SetValue(valueName, int.MinValue, RegistryValueKind.DWord); }); } } }
//------------------------------------------------------------------------------ // // <copyright file="MediaContextNotificationWindow.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // A wrapper for a top-level hidden window that is used to process // messages broadcasted to top-level windows only (such as DWM's // WM_DWMCOMPOSITIONCHANGED). If the WPF application doesn't have // a top-level window (as it is the case for XBAP applications), // such messages would have been ignored. // //------------------------------------------------------------------------------ using System; using System.Windows.Threading; using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using Microsoft.Win32; using Microsoft.Internal; using MS.Internal; using MS.Internal.PresentationCore; using MS.Internal.Interop; using MS.Win32; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using DllImport=MS.Internal.PresentationCore.DllImport; namespace System.Windows.Media { /// <summary> /// The MediaContextNotificationWindow class provides its owner /// MediaContext with the ability to receive and forward window /// messages broadcasted to top-level windows. /// </summary> internal class MediaContextNotificationWindow : IDisposable { /// <summary> /// Initializes static variables for this class. /// </summary> /// <SecurityNote> /// Critical - Sets the SecurityCritical static variables holding the message ids; calls RegisterWindowMessage. /// TreatAsSafe - The message ids are not exposed; no external parameters are taken in. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] static MediaContextNotificationWindow() { s_channelNotifyMessage = UnsafeNativeMethods.RegisterWindowMessage("MilChannelNotify"); s_dwmRedirectionEnvironmentChanged = UnsafeNativeMethods.RegisterWindowMessage("DwmRedirectionEnvironmentChangedHint"); } //+--------------------------------------------------------------------- // // Internal Methods // //---------------------------------------------------------------------- #region Internal Methods /// <summary> /// Sets the owner MediaContext and creates the notification window. /// </summary> /// <SecurityNote> /// Critical - Creates an HwndWrapper and adds a hook. /// TreatAsSafe: Critical data is not exposed. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal MediaContextNotificationWindow(MediaContext ownerMediaContext) { // Remember the pointer to the owner MediaContext that we'll forward the broadcasts to. _ownerMediaContext = ownerMediaContext; // Create a top-level, invisible window so we can get the WM_DWMCOMPOSITIONCHANGED // and other DWM notifications that are broadcasted to top-level windows only. HwndWrapper hwndNotification; hwndNotification = new HwndWrapper(0, NativeMethods.WS_POPUP, 0, 0, 0, 0, 0, "MediaContextNotificationWindow", IntPtr.Zero, null); _hwndNotificationHook = new HwndWrapperHook(MessageFilter); _hwndNotification = new SecurityCriticalDataClass<HwndWrapper>(hwndNotification); _hwndNotification.Value.AddHook(_hwndNotificationHook); _isDisposed = false; // // On Vista, we need to know when the Magnifier goes on and off // in order to switch to and from software rendering because the // Vista Magnifier cannot magnify D3D content. To receive the // window message informing us of this, we must tell the DWM // we are MIL content. // // The Win7 Magnifier can magnify D3D content so it's not an // issue there. In fact, Win7 doesn't even send the WM. // // If the DWM is not running, this call will result in NoOp. // ChangeWindowMessageFilter(s_dwmRedirectionEnvironmentChanged, 1 /* MSGFLT_ADD */); MS.Internal.HRESULT.Check(MilContent_AttachToHwnd(_hwndNotification.Value.Handle)); } ///<SecurityNote> /// Critical - Calls dispose on the critical hwnd wrapper. /// TreatAsSafe: It is safe to dispose the wrapper ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe] public void Dispose() { if (!_isDisposed) { // // If DWM is not running, this call will result in NoOp. // MS.Internal.HRESULT.Check(MilContent_DetachFromHwnd(_hwndNotification.Value.Handle)); _hwndNotification.Value.Dispose(); _hwndNotificationHook = null; _hwndNotification = null; _ownerMediaContext = null; _isDisposed = true; GC.SuppressFinalize(this); } } #endregion Internal Methods //+--------------------------------------------------------------------- // // Private Methods // //---------------------------------------------------------------------- #region Private Methods /// <summary> /// Tells a channel to send notifications to a particular target's window. /// </summary> /// <param name="channel"> /// The channel from which we want notifications. /// </param> /// <securitynote> /// Critical - Calls a critical channel method. /// TreatAsSafe - We are associated with the window handle that we /// are passing to the channel, so somebody already /// decided that it's OK for us to interact with that /// window. We also registered a window message so /// that we can avoid collisions with other messages. /// </securitynote> [SecurityCritical, SecurityTreatAsSafe] internal void SetAsChannelNotificationWindow() { if (_isDisposed) { throw new ObjectDisposedException("MediaContextNotificationWindow"); } _ownerMediaContext.Channel.SetNotificationWindow(_hwndNotification.Value.Handle, s_channelNotifyMessage); } /// <summary> /// If any of the interesting broadcast messages is seen, forward them to the owner MediaContext. /// </summary> /// <SecurityNote> /// Critical: Calls into unmanaged code, uses sensitive HWND data /// TreatAsSafe: No sensitive information is disclosed. It's safe to "attach" the window to the DWM. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private IntPtr MessageFilter(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (_isDisposed) { throw new ObjectDisposedException("MediaContextNotificationWindow"); } WindowMessage message = (WindowMessage)msg; Debug.Assert(_ownerMediaContext != null); if (message == WindowMessage.WM_DWMCOMPOSITIONCHANGED) { // // We need to register as MIL content to receive the Vista Magnifier messages // (see comments in ctor). // // We're going to attempt to attach to DWM every time the desktop composition // state changes to ensure that we properly handle DWM crashing/restarting/etc. // MS.Internal.HRESULT.Check(MilContent_AttachToHwnd(_hwndNotification.Value.Handle)); } else if (message == s_channelNotifyMessage) { _ownerMediaContext.NotifyChannelMessage(); } else if (message == s_dwmRedirectionEnvironmentChanged) { MediaSystem.NotifyRedirectionEnvironmentChanged(); } return IntPtr.Zero; } /// <SecurityNote> /// Critical: This code causes unmanaged code elevation /// </SecurityNote> [SecurityCritical, SuppressUnmanagedCodeSecurity] [DllImport(DllImport.MilCore)] private static extern int MilContent_AttachToHwnd( IntPtr hwnd ); /// <SecurityNote> /// Critical: This code causes unmanaged code elevation /// </SecurityNote> [SecurityCritical, SuppressUnmanagedCodeSecurity] [DllImport(DllImport.MilCore)] private static extern int MilContent_DetachFromHwnd( IntPtr hwnd ); /// <summary> /// Allow lower integrity applications to send specified window messages /// in case we are elevated. Failure is non-fatal and on down-level /// platforms this call will result in a no-op. /// </summary> /// <SecurityNote> /// Critical -- Calls unsafe native methods GetModuleHandle and GetProcAddress. /// Manually elevates unmanaged code permissions to pinvoke through /// a function pointer. /// </SecurityNote> [SecurityCritical] private void ChangeWindowMessageFilter(WindowMessage message, uint flag) { // Find the address of ChangeWindowMessageFilter in user32.dll. IntPtr user32Module = UnsafeNativeMethods.GetModuleHandle("user32.dll"); // Get the address of the function. If this fails it means the OS // doesn't support this function, in which case we don't // need to do anything further. IntPtr functionAddress = UnsafeNativeMethods.GetProcAddressNoThrow( new HandleRef(null, user32Module), "ChangeWindowMessageFilter"); if (functionAddress != IntPtr.Zero) { // Convert the function pointer into a callable delegate and then call it ChangeWindowMessageFilterNative function = Marshal.GetDelegateForFunctionPointer( functionAddress, typeof(ChangeWindowMessageFilterNative)) as ChangeWindowMessageFilterNative; // In order to call the function we need unmanaged code access, // because the function is native code. (new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Assert(); try { function(message, flag); } finally { SecurityPermission.RevertAssert(); } } } /// <summary> /// Prototype for user32's ChangeWindowMessageFilter function, which we load dynamically on Vista+. /// </summary> [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate void ChangeWindowMessageFilterNative(WindowMessage message, uint flag); #endregion Private Methods //+--------------------------------------------------------------------- // // Private Fields // //---------------------------------------------------------------------- #region Private Fields private bool _isDisposed; // The owner MediaContext private MediaContext _ownerMediaContext; // A top-level hidden window. private SecurityCriticalDataClass<HwndWrapper> _hwndNotification; // The message filter hook for the top-level hidden window. /// <SecurityNote> /// Critical - Field for Critical type /// </SecurityNote> [SecurityCritical] private HwndWrapperHook _hwndNotificationHook; // The window message used to announce a channel notification. private static WindowMessage s_channelNotifyMessage; // We receive this when the Vista Magnifier goes on/off private static WindowMessage s_dwmRedirectionEnvironmentChanged; #endregion Private Fields } }
using System; public class TestClass { } public class TestFormatProvider : IFormatProvider { public bool ToSByteMaxValue = true; #region IFormatProvider Members public object GetFormat(Type formatType) { if (formatType.Equals(typeof(TestFormatProvider))) { return this; } else { return null; } } #endregion } public class TestConvertableClass : IConvertible { #region IConvertible Members public TypeCode GetTypeCode() { throw new Exception("The method or operation is not implemented."); } public bool ToBoolean(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public byte ToByte(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public char ToChar(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public DateTime ToDateTime(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public decimal ToDecimal(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public double ToDouble(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public short ToInt16(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public int ToInt32(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public long ToInt64(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public sbyte ToSByte(IFormatProvider provider) { bool toMinValue = true; if (provider != null) { TestFormatProvider format = provider.GetFormat(typeof(TestFormatProvider)) as TestFormatProvider; if ((format != null) && format.ToSByteMaxValue) { toMinValue = false; } } if (toMinValue) { return SByte.MinValue; } else { return SByte.MaxValue; } } public float ToSingle(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public string ToString(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public object ToType(Type conversionType, IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public ushort ToUInt16(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public uint ToUInt32(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } public ulong ToUInt64(IFormatProvider provider) { throw new Exception("The method or operation is not implemented."); } #endregion } /// <summary> /// ToSByte(System.Object,System.IFormatProvider) /// </summary> public class ConvertToSByte10 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Call Convert.ToSByte when value implements IConvertible"); try { retVal = VerificationHelper(true, null, 1, "001.1") && retVal; retVal = VerificationHelper(1, null, 1, "001.2") && retVal; retVal = VerificationHelper(0, null, 0, "001.3") && retVal; retVal = VerificationHelper(new TestConvertableClass(), null, SByte.MinValue, "001.4") && retVal; retVal = VerificationHelper(true, new TestFormatProvider(), 1, "001.5") && retVal; retVal = VerificationHelper(1, new TestFormatProvider(), 1, "001.6") && retVal; retVal = VerificationHelper(0, new TestFormatProvider(), 0, "001.7") && retVal; retVal = VerificationHelper(new TestConvertableClass(), new TestFormatProvider(), SByte.MaxValue, "001.8") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Call Convert.ToSByte when value is null"); try { retVal = VerificationHelper(null, null, 0, "002.1") && retVal; retVal = VerificationHelper(null, new TestFormatProvider(), 0, "002.2") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: InvalidCastException should be thrown when value does not implement IConvertible. "); try { sbyte actual = Convert.ToSByte(new TestClass()); TestLibrary.TestFramework.LogError("101.1", "InvalidCastException is not thrown when value does not implement IConvertible. "); retVal = false; } catch (InvalidCastException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ConvertToSByte10 test = new ConvertToSByte10(); TestLibrary.TestFramework.BeginTestCase("ConvertToSByte10"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } #region Private Methods private bool VerificationHelper(object obj, IFormatProvider provider, sbyte desired, string errorno) { bool retVal = true; sbyte actual = Convert.ToSByte(obj, provider); if (actual != desired) { TestLibrary.TestFramework.LogError(errorno, "Convert.ToSByte returns unexpected values"); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", desired = " + desired + ", obj = " + obj); retVal = false; } return retVal; } #endregion }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmSelComp { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmSelComp() : base() { Load += frmSelComp_Load; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; private System.Windows.Forms.Button withEventsField_cmdDatabase; public System.Windows.Forms.Button cmdDatabase { get { return withEventsField_cmdDatabase; } set { if (withEventsField_cmdDatabase != null) { withEventsField_cmdDatabase.Click -= cmdDatabase_Click; } withEventsField_cmdDatabase = value; if (withEventsField_cmdDatabase != null) { withEventsField_cmdDatabase.Click += cmdDatabase_Click; } } } private System.Windows.Forms.Button withEventsField_cmdCompany; public System.Windows.Forms.Button cmdCompany { get { return withEventsField_cmdCompany; } set { if (withEventsField_cmdCompany != null) { withEventsField_cmdCompany.Click -= cmdCompany_Click; } withEventsField_cmdCompany = value; if (withEventsField_cmdCompany != null) { withEventsField_cmdCompany.Click += cmdCompany_Click; } } } private System.Windows.Forms.TextBox withEventsField_txtKey; public System.Windows.Forms.TextBox txtKey { get { return withEventsField_txtKey; } set { if (withEventsField_txtKey != null) { withEventsField_txtKey.Enter -= txtKey_Enter; } withEventsField_txtKey = value; if (withEventsField_txtKey != null) { withEventsField_txtKey.Enter += txtKey_Enter; } } } private System.Windows.Forms.Button withEventsField_cmdRegistration; public System.Windows.Forms.Button cmdRegistration { get { return withEventsField_cmdRegistration; } set { if (withEventsField_cmdRegistration != null) { withEventsField_cmdRegistration.Click -= cmdRegistration_Click; } withEventsField_cmdRegistration = value; if (withEventsField_cmdRegistration != null) { withEventsField_cmdRegistration.Click += cmdRegistration_Click; } } } private System.Windows.Forms.TextBox withEventsField_txtCompany; public System.Windows.Forms.TextBox txtCompany { get { return withEventsField_txtCompany; } set { if (withEventsField_txtCompany != null) { withEventsField_txtCompany.Enter -= txtCompany_Enter; withEventsField_txtCompany.Leave -= txtCompany_Leave; } withEventsField_txtCompany = value; if (withEventsField_txtCompany != null) { withEventsField_txtCompany.Enter += txtCompany_Enter; withEventsField_txtCompany.Leave += txtCompany_Leave; } } } public System.Windows.Forms.Label _Label2_1; public System.Windows.Forms.Label _Label2_0; public System.Windows.Forms.Label lblCode; public System.Windows.Forms.Label _lbl_0; public System.Windows.Forms.GroupBox frmRegister; private System.Windows.Forms.TextBox withEventsField_txtPassword; public System.Windows.Forms.TextBox txtPassword { get { return withEventsField_txtPassword; } set { if (withEventsField_txtPassword != null) { withEventsField_txtPassword.Enter -= txtPassword_Enter; withEventsField_txtPassword.KeyPress -= txtPassword_KeyPress; } withEventsField_txtPassword = value; if (withEventsField_txtPassword != null) { withEventsField_txtPassword.Enter += txtPassword_Enter; withEventsField_txtPassword.KeyPress += txtPassword_KeyPress; } } } private System.Windows.Forms.Button withEventsField_cmdCancel; public System.Windows.Forms.Button cmdCancel { get { return withEventsField_cmdCancel; } set { if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click -= cmdCancel_Click; } withEventsField_cmdCancel = value; if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click += cmdCancel_Click; } } } private System.Windows.Forms.Button withEventsField_cmdOK; public System.Windows.Forms.Button cmdOK { get { return withEventsField_cmdOK; } set { if (withEventsField_cmdOK != null) { withEventsField_cmdOK.Click -= cmdOK_Click; } withEventsField_cmdOK = value; if (withEventsField_cmdOK != null) { withEventsField_cmdOK.Click += cmdOK_Click; } } } private System.Windows.Forms.TextBox withEventsField_txtUserName; public System.Windows.Forms.TextBox txtUserName { get { return withEventsField_txtUserName; } set { if (withEventsField_txtUserName != null) { withEventsField_txtUserName.Enter -= txtUserName_Enter; withEventsField_txtUserName.KeyPress -= txtUserName_KeyPress; } withEventsField_txtUserName = value; if (withEventsField_txtUserName != null) { withEventsField_txtUserName.Enter += txtUserName_Enter; withEventsField_txtUserName.KeyPress += txtUserName_KeyPress; } } } //Public WithEvents MAPISession1 As MSMAPI.MAPISession 'MSMAPI.MAPISession //Public WithEvents MAPIMessages1 As MSMAPI.MAPISession 'MSMAPI.MAPIMessages public System.Windows.Forms.Timer tmrStart; public System.Windows.Forms.OpenFileDialog CDmasterOpen; private System.Windows.Forms.Button withEventsField_cmdBuild; public System.Windows.Forms.Button cmdBuild { get { return withEventsField_cmdBuild; } set { if (withEventsField_cmdBuild != null) { withEventsField_cmdBuild.Click -= cmdBuild_Click; } withEventsField_cmdBuild = value; if (withEventsField_cmdBuild != null) { withEventsField_cmdBuild.Click += cmdBuild_Click; } } } public System.Windows.Forms.ColumnHeader _lvLocation_ColumnHeader_1; public System.Windows.Forms.ColumnHeader _lvLocation_ColumnHeader_2; public System.Windows.Forms.ColumnHeader _lvLocation_ColumnHeader_3; private System.Windows.Forms.ListView withEventsField_lvLocation; public System.Windows.Forms.ListView lvLocation { get { return withEventsField_lvLocation; } set { if (withEventsField_lvLocation != null) { withEventsField_lvLocation.DoubleClick -= lvLocation_DoubleClick; } withEventsField_lvLocation = value; if (withEventsField_lvLocation != null) { withEventsField_lvLocation.DoubleClick += lvLocation_DoubleClick; } } } public System.Windows.Forms.ImageList ILtree; public System.Windows.Forms.Label _Label1_4; public System.Windows.Forms.Label _Label1_3; public System.Windows.Forms.Label _Label1_2; public System.Windows.Forms.Label _Label1_0; public System.Windows.Forms.Label _Label1_1; public System.Windows.Forms.Label lblDir; public System.Windows.Forms.Label lblPath; public System.Windows.Forms.Label lblCompany; //Public WithEvents Label1 As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents Label2 As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmSelComp)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.cmdDatabase = new System.Windows.Forms.Button(); this.cmdCompany = new System.Windows.Forms.Button(); this.frmRegister = new System.Windows.Forms.GroupBox(); this.txtKey = new System.Windows.Forms.TextBox(); this.cmdRegistration = new System.Windows.Forms.Button(); this.txtCompany = new System.Windows.Forms.TextBox(); this._Label2_1 = new System.Windows.Forms.Label(); this._Label2_0 = new System.Windows.Forms.Label(); this.lblCode = new System.Windows.Forms.Label(); this._lbl_0 = new System.Windows.Forms.Label(); this.txtPassword = new System.Windows.Forms.TextBox(); this.cmdCancel = new System.Windows.Forms.Button(); this.cmdOK = new System.Windows.Forms.Button(); this.txtUserName = new System.Windows.Forms.TextBox(); //Me.MAPISession1 = New MSMAPI.MAPISession 'MSMAPI.MAPISession //Me.MAPIMessages1 = New MSMAPI.MAPISession 'MSMAPI.MAPIMessages this.tmrStart = new System.Windows.Forms.Timer(components); this.CDmasterOpen = new System.Windows.Forms.OpenFileDialog(); this.cmdBuild = new System.Windows.Forms.Button(); this.lvLocation = new System.Windows.Forms.ListView(); this._lvLocation_ColumnHeader_1 = new System.Windows.Forms.ColumnHeader(); this._lvLocation_ColumnHeader_2 = new System.Windows.Forms.ColumnHeader(); this._lvLocation_ColumnHeader_3 = new System.Windows.Forms.ColumnHeader(); this.ILtree = new System.Windows.Forms.ImageList(); this._Label1_4 = new System.Windows.Forms.Label(); this._Label1_3 = new System.Windows.Forms.Label(); this._Label1_2 = new System.Windows.Forms.Label(); this._Label1_0 = new System.Windows.Forms.Label(); this._Label1_1 = new System.Windows.Forms.Label(); this.lblDir = new System.Windows.Forms.Label(); this.lblPath = new System.Windows.Forms.Label(); this.lblCompany = new System.Windows.Forms.Label(); //Me.Label1 = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) //Me.Label2 = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) //Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) this.frmRegister.SuspendLayout(); this.lvLocation.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; //CType(Me.MAPISession1, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.MAPIMessages1, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.Label1, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.Label2, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit() this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Text = "4POS Company Loader ..."; this.ClientSize = new System.Drawing.Size(610, 283); this.Location = new System.Drawing.Point(3, 29); this.Icon = (System.Drawing.Icon)resources.GetObject("frmSelComp.Icon"); this.MaximizeBox = false; this.MinimizeBox = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.ControlBox = true; this.Enabled = true; this.KeyPreview = false; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ShowInTaskbar = true; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmSelComp"; this.cmdDatabase.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.CancelButton = this.cmdDatabase; this.cmdDatabase.Text = "..."; this.cmdDatabase.Enabled = false; this.cmdDatabase.Size = new System.Drawing.Size(25, 16); this.cmdDatabase.Location = new System.Drawing.Point(15, 309); this.cmdDatabase.TabIndex = 23; this.cmdDatabase.TabStop = false; this.cmdDatabase.BackColor = System.Drawing.SystemColors.Control; this.cmdDatabase.CausesValidation = true; this.cmdDatabase.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdDatabase.Cursor = System.Windows.Forms.Cursors.Default; this.cmdDatabase.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdDatabase.Name = "cmdDatabase"; this.cmdCompany.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdCompany.Text = "..."; this.cmdCompany.Enabled = false; this.cmdCompany.Size = new System.Drawing.Size(25, 16); this.cmdCompany.Location = new System.Drawing.Point(15, 288); this.cmdCompany.TabIndex = 22; this.cmdCompany.TabStop = false; this.cmdCompany.BackColor = System.Drawing.SystemColors.Control; this.cmdCompany.CausesValidation = true; this.cmdCompany.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdCompany.Cursor = System.Windows.Forms.Cursors.Default; this.cmdCompany.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdCompany.Name = "cmdCompany"; this.frmRegister.Text = "Unregisted Version"; this.frmRegister.Size = new System.Drawing.Size(292, 139); this.frmRegister.Location = new System.Drawing.Point(288, 351); this.frmRegister.TabIndex = 14; this.frmRegister.Visible = false; this.frmRegister.BackColor = System.Drawing.SystemColors.Control; this.frmRegister.Enabled = true; this.frmRegister.ForeColor = System.Drawing.SystemColors.ControlText; this.frmRegister.RightToLeft = System.Windows.Forms.RightToLeft.No; this.frmRegister.Padding = new System.Windows.Forms.Padding(0); this.frmRegister.Name = "frmRegister"; this.txtKey.AutoSize = false; this.txtKey.Size = new System.Drawing.Size(157, 19); this.txtKey.Location = new System.Drawing.Point(117, 78); this.txtKey.TabIndex = 19; this.txtKey.TabStop = false; this.txtKey.AcceptsReturn = true; this.txtKey.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtKey.BackColor = System.Drawing.SystemColors.Window; this.txtKey.CausesValidation = true; this.txtKey.Enabled = true; this.txtKey.ForeColor = System.Drawing.SystemColors.WindowText; this.txtKey.HideSelection = true; this.txtKey.ReadOnly = false; this.txtKey.MaxLength = 0; this.txtKey.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtKey.Multiline = false; this.txtKey.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtKey.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtKey.Visible = true; this.txtKey.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtKey.Name = "txtKey"; this.cmdRegistration.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdRegistration.Text = "Register"; this.cmdRegistration.Size = new System.Drawing.Size(100, 22); this.cmdRegistration.Location = new System.Drawing.Point(177, 105); this.cmdRegistration.TabIndex = 17; this.cmdRegistration.TabStop = false; this.cmdRegistration.BackColor = System.Drawing.SystemColors.Control; this.cmdRegistration.CausesValidation = true; this.cmdRegistration.Enabled = true; this.cmdRegistration.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdRegistration.Cursor = System.Windows.Forms.Cursors.Default; this.cmdRegistration.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdRegistration.Name = "cmdRegistration"; this.txtCompany.AutoSize = false; this.txtCompany.Size = new System.Drawing.Size(154, 19); this.txtCompany.Location = new System.Drawing.Point(117, 21); this.txtCompany.MaxLength = 50; this.txtCompany.TabIndex = 15; this.txtCompany.TabStop = false; this.txtCompany.AcceptsReturn = true; this.txtCompany.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtCompany.BackColor = System.Drawing.SystemColors.Window; this.txtCompany.CausesValidation = true; this.txtCompany.Enabled = true; this.txtCompany.ForeColor = System.Drawing.SystemColors.WindowText; this.txtCompany.HideSelection = true; this.txtCompany.ReadOnly = false; this.txtCompany.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtCompany.Multiline = false; this.txtCompany.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtCompany.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtCompany.Visible = true; this.txtCompany.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtCompany.Name = "txtCompany"; this._Label2_1.Text = "Activation key:"; this._Label2_1.Size = new System.Drawing.Size(70, 13); this._Label2_1.Location = new System.Drawing.Point(39, 81); this._Label2_1.TabIndex = 21; this._Label2_1.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._Label2_1.BackColor = System.Drawing.Color.Transparent; this._Label2_1.Enabled = true; this._Label2_1.ForeColor = System.Drawing.SystemColors.ControlText; this._Label2_1.Cursor = System.Windows.Forms.Cursors.Default; this._Label2_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label2_1.UseMnemonic = true; this._Label2_1.Visible = true; this._Label2_1.AutoSize = true; this._Label2_1.BorderStyle = System.Windows.Forms.BorderStyle.None; this._Label2_1.Name = "_Label2_1"; this._Label2_0.TextAlign = System.Drawing.ContentAlignment.TopRight; this._Label2_0.Text = "Registration code:"; this._Label2_0.Size = new System.Drawing.Size(93, 13); this._Label2_0.Location = new System.Drawing.Point(15, 51); this._Label2_0.TabIndex = 20; this._Label2_0.BackColor = System.Drawing.Color.Transparent; this._Label2_0.Enabled = true; this._Label2_0.ForeColor = System.Drawing.SystemColors.ControlText; this._Label2_0.Cursor = System.Windows.Forms.Cursors.Default; this._Label2_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label2_0.UseMnemonic = true; this._Label2_0.Visible = true; this._Label2_0.AutoSize = false; this._Label2_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._Label2_0.Name = "_Label2_0"; this.lblCode.TextAlign = System.Drawing.ContentAlignment.TopCenter; this.lblCode.BackColor = System.Drawing.Color.FromArgb(192, 255, 192); this.lblCode.Text = "Label2"; this.lblCode.ForeColor = System.Drawing.SystemColors.WindowText; this.lblCode.Size = new System.Drawing.Size(156, 22); this.lblCode.Location = new System.Drawing.Point(117, 48); this.lblCode.TabIndex = 18; this.lblCode.Enabled = true; this.lblCode.Cursor = System.Windows.Forms.Cursors.Default; this.lblCode.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblCode.UseMnemonic = true; this.lblCode.Visible = true; this.lblCode.AutoSize = false; this.lblCode.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lblCode.Name = "lblCode"; this._lbl_0.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lbl_0.Text = "Store Name:"; this._lbl_0.Size = new System.Drawing.Size(82, 16); this._lbl_0.Location = new System.Drawing.Point(24, 24); this._lbl_0.TabIndex = 16; this._lbl_0.BackColor = System.Drawing.Color.Transparent; this._lbl_0.Enabled = true; this._lbl_0.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_0.UseMnemonic = true; this._lbl_0.Visible = true; this._lbl_0.AutoSize = false; this._lbl_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_0.Name = "_lbl_0"; this.txtPassword.AutoSize = false; this.txtPassword.Enabled = false; this.txtPassword.Size = new System.Drawing.Size(149, 16); this.txtPassword.ImeMode = System.Windows.Forms.ImeMode.Disable; this.txtPassword.Location = new System.Drawing.Point(98, 377); this.txtPassword.PasswordChar = Strings.ChrW(42); this.txtPassword.TabIndex = 3; this.txtPassword.Text = "password"; this.txtPassword.AcceptsReturn = true; this.txtPassword.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtPassword.BackColor = System.Drawing.SystemColors.Window; this.txtPassword.CausesValidation = true; this.txtPassword.ForeColor = System.Drawing.SystemColors.WindowText; this.txtPassword.HideSelection = true; this.txtPassword.ReadOnly = false; this.txtPassword.MaxLength = 0; this.txtPassword.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtPassword.Multiline = false; this.txtPassword.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtPassword.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtPassword.TabStop = true; this.txtPassword.Visible = true; this.txtPassword.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtPassword.Name = "txtPassword"; this.cmdCancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdCancel.Text = "E&xit"; this.cmdCancel.Size = new System.Drawing.Size(76, 26); this.cmdCancel.Location = new System.Drawing.Point(171, 407); this.cmdCancel.TabIndex = 5; this.cmdCancel.BackColor = System.Drawing.SystemColors.Control; this.cmdCancel.CausesValidation = true; this.cmdCancel.Enabled = true; this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default; this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdCancel.TabStop = true; this.cmdCancel.Name = "cmdCancel"; this.cmdOK.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdOK.Text = "&OK"; this.cmdOK.Enabled = false; this.cmdOK.Size = new System.Drawing.Size(76, 26); this.cmdOK.Location = new System.Drawing.Point(24, 407); this.cmdOK.TabIndex = 4; this.cmdOK.BackColor = System.Drawing.SystemColors.Control; this.cmdOK.CausesValidation = true; this.cmdOK.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdOK.Cursor = System.Windows.Forms.Cursors.Default; this.cmdOK.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdOK.TabStop = true; this.cmdOK.Name = "cmdOK"; this.txtUserName.AutoSize = false; this.txtUserName.Enabled = false; this.txtUserName.Size = new System.Drawing.Size(149, 16); this.txtUserName.Location = new System.Drawing.Point(98, 354); this.txtUserName.TabIndex = 1; this.txtUserName.Text = "default"; this.txtUserName.AcceptsReturn = true; this.txtUserName.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtUserName.BackColor = System.Drawing.SystemColors.Window; this.txtUserName.CausesValidation = true; this.txtUserName.ForeColor = System.Drawing.SystemColors.WindowText; this.txtUserName.HideSelection = true; this.txtUserName.ReadOnly = false; this.txtUserName.MaxLength = 0; this.txtUserName.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtUserName.Multiline = false; this.txtUserName.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtUserName.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtUserName.TabStop = true; this.txtUserName.Visible = true; this.txtUserName.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtUserName.Name = "txtUserName"; //MAPISession1.OcxState = CType(resources.GetObject("MAPISession1.OcxState"), System.Windows.Forms.AxHost.State) //Me.MAPISession1.Location = New System.Drawing.Point(606, 381) //Me.MAPISession1.Name = "MAPISession1" //MAPIMessages1.OcxState = CType(resources.GetObject("MAPIMessages1.OcxState"), System.Windows.Forms.AxHost.State) //Me.MAPIMessages1.Location = New System.Drawing.Point(603, 447) //Me.MAPIMessages1.Name = "MAPIMessages1" this.tmrStart.Interval = 1; this.tmrStart.Enabled = true; this.cmdBuild.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdBuild.Text = "Synchronize Via Email"; this.cmdBuild.Enabled = false; this.cmdBuild.Size = new System.Drawing.Size(223, 46); this.cmdBuild.Location = new System.Drawing.Point(24, 447); this.cmdBuild.TabIndex = 7; this.cmdBuild.TabStop = false; this.cmdBuild.BackColor = System.Drawing.SystemColors.Control; this.cmdBuild.CausesValidation = true; this.cmdBuild.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdBuild.Cursor = System.Windows.Forms.Cursors.Default; this.cmdBuild.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdBuild.Name = "cmdBuild"; this.lvLocation.Size = new System.Drawing.Size(592, 265); this.lvLocation.Location = new System.Drawing.Point(9, 9); this.lvLocation.TabIndex = 6; this.lvLocation.TabStop = 0; this.lvLocation.View = System.Windows.Forms.View.Details; this.lvLocation.LabelEdit = false; this.lvLocation.LabelWrap = true; this.lvLocation.HideSelection = true; this.lvLocation.SmallImageList = ILtree; this.lvLocation.ForeColor = System.Drawing.SystemColors.WindowText; this.lvLocation.BackColor = System.Drawing.SystemColors.Window; this.lvLocation.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lvLocation.Name = "lvLocation"; this._lvLocation_ColumnHeader_1.Text = "Company"; this._lvLocation_ColumnHeader_1.Width = 236; this._lvLocation_ColumnHeader_2.Text = "Location"; this._lvLocation_ColumnHeader_2.Width = 236; this._lvLocation_ColumnHeader_3.Text = "Path"; this._lvLocation_ColumnHeader_3.Width = 530; this.ILtree.ImageSize = new System.Drawing.Size(16, 16); this.ILtree.TransparentColor = System.Drawing.Color.White; this.ILtree.ImageStream = (System.Windows.Forms.ImageListStreamer)resources.GetObject("ILtree.ImageStream"); this.ILtree.Images.SetKeyName(0, "cm"); this.ILtree.Images.SetKeyName(1, ""); this._Label1_4.TextAlign = System.Drawing.ContentAlignment.TopRight; this._Label1_4.Text = "Directory:"; this._Label1_4.Enabled = false; this._Label1_4.Size = new System.Drawing.Size(45, 13); this._Label1_4.Location = new System.Drawing.Point(48, 330); this._Label1_4.TabIndex = 13; this._Label1_4.BackColor = System.Drawing.Color.Transparent; this._Label1_4.ForeColor = System.Drawing.SystemColors.ControlText; this._Label1_4.Cursor = System.Windows.Forms.Cursors.Default; this._Label1_4.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label1_4.UseMnemonic = true; this._Label1_4.Visible = true; this._Label1_4.AutoSize = true; this._Label1_4.BorderStyle = System.Windows.Forms.BorderStyle.None; this._Label1_4.Name = "_Label1_4"; this._Label1_3.TextAlign = System.Drawing.ContentAlignment.TopRight; this._Label1_3.Text = "Database:"; this._Label1_3.Enabled = false; this._Label1_3.Size = new System.Drawing.Size(49, 13); this._Label1_3.Location = new System.Drawing.Point(44, 309); this._Label1_3.TabIndex = 12; this._Label1_3.BackColor = System.Drawing.Color.Transparent; this._Label1_3.ForeColor = System.Drawing.SystemColors.ControlText; this._Label1_3.Cursor = System.Windows.Forms.Cursors.Default; this._Label1_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label1_3.UseMnemonic = true; this._Label1_3.Visible = true; this._Label1_3.AutoSize = true; this._Label1_3.BorderStyle = System.Windows.Forms.BorderStyle.None; this._Label1_3.Name = "_Label1_3"; this._Label1_2.TextAlign = System.Drawing.ContentAlignment.TopRight; this._Label1_2.Text = "Company:"; this._Label1_2.Enabled = false; this._Label1_2.Size = new System.Drawing.Size(47, 13); this._Label1_2.Location = new System.Drawing.Point(46, 288); this._Label1_2.TabIndex = 11; this._Label1_2.BackColor = System.Drawing.Color.Transparent; this._Label1_2.ForeColor = System.Drawing.SystemColors.ControlText; this._Label1_2.Cursor = System.Windows.Forms.Cursors.Default; this._Label1_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label1_2.UseMnemonic = true; this._Label1_2.Visible = true; this._Label1_2.AutoSize = true; this._Label1_2.BorderStyle = System.Windows.Forms.BorderStyle.None; this._Label1_2.Name = "_Label1_2"; this._Label1_0.TextAlign = System.Drawing.ContentAlignment.TopRight; this._Label1_0.Text = "User ID:"; this._Label1_0.Enabled = false; this._Label1_0.Size = new System.Drawing.Size(39, 13); this._Label1_0.Location = new System.Drawing.Point(54, 357); this._Label1_0.TabIndex = 0; this._Label1_0.BackColor = System.Drawing.Color.Transparent; this._Label1_0.ForeColor = System.Drawing.SystemColors.ControlText; this._Label1_0.Cursor = System.Windows.Forms.Cursors.Default; this._Label1_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label1_0.UseMnemonic = true; this._Label1_0.Visible = true; this._Label1_0.AutoSize = true; this._Label1_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._Label1_0.Name = "_Label1_0"; this._Label1_1.TextAlign = System.Drawing.ContentAlignment.TopRight; this._Label1_1.Text = "Password:"; this._Label1_1.Enabled = false; this._Label1_1.Size = new System.Drawing.Size(49, 13); this._Label1_1.Location = new System.Drawing.Point(44, 381); this._Label1_1.TabIndex = 2; this._Label1_1.BackColor = System.Drawing.Color.Transparent; this._Label1_1.ForeColor = System.Drawing.SystemColors.ControlText; this._Label1_1.Cursor = System.Windows.Forms.Cursors.Default; this._Label1_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label1_1.UseMnemonic = true; this._Label1_1.Visible = true; this._Label1_1.AutoSize = true; this._Label1_1.BorderStyle = System.Windows.Forms.BorderStyle.None; this._Label1_1.Name = "_Label1_1"; this.lblDir.Text = "..."; this.lblDir.Size = new System.Drawing.Size(9, 16); this.lblDir.Location = new System.Drawing.Point(96, 327); this.lblDir.TabIndex = 10; this.lblDir.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblDir.BackColor = System.Drawing.Color.Transparent; this.lblDir.Enabled = true; this.lblDir.ForeColor = System.Drawing.SystemColors.ControlText; this.lblDir.Cursor = System.Windows.Forms.Cursors.Default; this.lblDir.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblDir.UseMnemonic = true; this.lblDir.Visible = true; this.lblDir.AutoSize = true; this.lblDir.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lblDir.Name = "lblDir"; this.lblPath.Text = "..."; this.lblPath.Size = new System.Drawing.Size(9, 16); this.lblPath.Location = new System.Drawing.Point(96, 306); this.lblPath.TabIndex = 9; this.lblPath.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblPath.BackColor = System.Drawing.Color.Transparent; this.lblPath.Enabled = true; this.lblPath.ForeColor = System.Drawing.SystemColors.ControlText; this.lblPath.Cursor = System.Windows.Forms.Cursors.Default; this.lblPath.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblPath.UseMnemonic = true; this.lblPath.Visible = true; this.lblPath.AutoSize = true; this.lblPath.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lblPath.Name = "lblPath"; this.lblCompany.Text = "..."; this.lblCompany.Size = new System.Drawing.Size(9, 16); this.lblCompany.Location = new System.Drawing.Point(96, 285); this.lblCompany.TabIndex = 8; this.lblCompany.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblCompany.BackColor = System.Drawing.Color.Transparent; this.lblCompany.Enabled = true; this.lblCompany.ForeColor = System.Drawing.SystemColors.ControlText; this.lblCompany.Cursor = System.Windows.Forms.Cursors.Default; this.lblCompany.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblCompany.UseMnemonic = true; this.lblCompany.Visible = true; this.lblCompany.AutoSize = true; this.lblCompany.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lblCompany.Name = "lblCompany"; this.Controls.Add(cmdDatabase); this.Controls.Add(cmdCompany); this.Controls.Add(frmRegister); this.Controls.Add(txtPassword); this.Controls.Add(cmdCancel); this.Controls.Add(cmdOK); this.Controls.Add(txtUserName); //Me.Controls.Add(MAPISession1) //Me.Controls.Add(MAPIMessages1) this.Controls.Add(cmdBuild); this.Controls.Add(lvLocation); this.Controls.Add(_Label1_4); this.Controls.Add(_Label1_3); this.Controls.Add(_Label1_2); this.Controls.Add(_Label1_0); this.Controls.Add(_Label1_1); this.Controls.Add(lblDir); this.Controls.Add(lblPath); this.Controls.Add(lblCompany); this.frmRegister.Controls.Add(txtKey); this.frmRegister.Controls.Add(cmdRegistration); this.frmRegister.Controls.Add(txtCompany); this.frmRegister.Controls.Add(_Label2_1); this.frmRegister.Controls.Add(_Label2_0); this.frmRegister.Controls.Add(lblCode); this.frmRegister.Controls.Add(_lbl_0); this.lvLocation.Columns.Add(_lvLocation_ColumnHeader_1); this.lvLocation.Columns.Add(_lvLocation_ColumnHeader_2); this.lvLocation.Columns.Add(_lvLocation_ColumnHeader_3); //Me.Label1.SetIndex(_Label1_4, CType(4, Short)) //Me.Label1.SetIndex(_Label1_3, CType(3, Short)) //Me.Label1.SetIndex(_Label1_2, CType(2, Short)) //Me.Label1.SetIndex(_Label1_0, CType(0, Short)) //Me.Label1.SetIndex(_Label1_1, CType(1, Short)) //Me.Label2.SetIndex(_Label2_1, CType(1, Short)) //Me.Label2.SetIndex(_Label2_0, CType(0, Short)) //Me.lbl.SetIndex(_lbl_0, CType(0, Short)) //CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.Label2, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.Label1, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.MAPIMessages1, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.MAPISession1, System.ComponentModel.ISupportInitialize).EndInit() this.frmRegister.ResumeLayout(false); this.lvLocation.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #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. using System; using Microsoft.Xml; using Microsoft.Xml.Schema; using System.Reflection; using System.Reflection.Emit; using System.Collections; using System.Collections.Generic; using System.Security; namespace System.Runtime.Serialization { #if USE_REFEMIT || NET_NATIVE public delegate object XmlFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces); public delegate object XmlFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract); public delegate void XmlFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract); public sealed class XmlFormatReaderGenerator #else internal delegate object XmlFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces); internal delegate object XmlFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract); internal delegate void XmlFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract); internal sealed class XmlFormatReaderGenerator #endif { #if !NET_NATIVE [SecurityCritical] /// <SecurityNote> /// Critical - holds instance of CriticalHelper which keeps state that was produced within an assert /// </SecurityNote> private CriticalHelper _helper; /// <SecurityNote> /// Critical - initializes SecurityCritical field 'helper' /// </SecurityNote> [SecurityCritical] public XmlFormatReaderGenerator() { _helper = new CriticalHelper(); } /// <SecurityNote> /// Critical - accesses SecurityCritical helper class 'CriticalHelper' /// </SecurityNote> [SecurityCritical] public XmlFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract) { return _helper.GenerateClassReader(classContract); } /// <SecurityNote> /// Critical - accesses SecurityCritical helper class 'CriticalHelper' /// </SecurityNote> [SecurityCritical] public XmlFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract) { return _helper.GenerateCollectionReader(collectionContract); } /// <SecurityNote> /// Critical - accesses SecurityCritical helper class 'CriticalHelper' /// </SecurityNote> [SecurityCritical] public XmlFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract) { return _helper.GenerateGetOnlyCollectionReader(collectionContract); } /// <SecurityNote> /// Review - handles all aspects of IL generation including initializing the DynamicMethod. /// changes to how IL generated could affect how data is deserialized and what gets access to data, /// therefore we mark it for review so that changes to generation logic are reviewed. /// </SecurityNote> private class CriticalHelper { private CodeGenerator _ilg; private LocalBuilder _objectLocal; private Type _objectType; private ArgBuilder _xmlReaderArg; private ArgBuilder _contextArg; private ArgBuilder _memberNamesArg; private ArgBuilder _memberNamespacesArg; private ArgBuilder _collectionContractArg; public XmlFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract) { _ilg = new CodeGenerator(); bool memberAccessFlag = classContract.RequiresMemberAccessForRead(null); try { _ilg.BeginMethod("Read" + classContract.StableName.Name + "FromXml", Globals.TypeOfXmlFormatClassReaderDelegate, memberAccessFlag); } catch (SecurityException securityException) { if (memberAccessFlag) { classContract.RequiresMemberAccessForRead(securityException); } else { throw; } } InitArgs(); CreateObject(classContract); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal); InvokeOnDeserializing(classContract); LocalBuilder objectId = null; ReadClass(classContract); InvokeOnDeserialized(classContract); if (objectId == null) { _ilg.Load(_objectLocal); // Do a conversion back from DateTimeOffsetAdapter to DateTimeOffset after deserialization. // DateTimeOffsetAdapter is used here for deserialization purposes to bypass the ISerializable implementation // on DateTimeOffset; which does not work in partial trust. if (classContract.UnderlyingType == Globals.TypeOfDateTimeOffsetAdapter) { _ilg.ConvertValue(_objectLocal.LocalType, Globals.TypeOfDateTimeOffsetAdapter); _ilg.Call(XmlFormatGeneratorStatics.GetDateTimeOffsetMethod); _ilg.ConvertValue(Globals.TypeOfDateTimeOffset, _ilg.CurrentMethod.ReturnType); } //Copy the KeyValuePairAdapter<K,T> to a KeyValuePair<K,T>. else if (classContract.IsKeyValuePairAdapter) { _ilg.Call(classContract.GetKeyValuePairMethodInfo); _ilg.ConvertValue(Globals.TypeOfKeyValuePair.MakeGenericType(classContract.KeyValuePairGenericArguments), _ilg.CurrentMethod.ReturnType); } else { _ilg.ConvertValue(_objectLocal.LocalType, _ilg.CurrentMethod.ReturnType); } } return (XmlFormatClassReaderDelegate)_ilg.EndMethod(); } public XmlFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract) { _ilg = GenerateCollectionReaderHelper(collectionContract, false /*isGetOnlyCollection*/); ReadCollection(collectionContract); _ilg.Load(_objectLocal); _ilg.ConvertValue(_objectLocal.LocalType, _ilg.CurrentMethod.ReturnType); return (XmlFormatCollectionReaderDelegate)_ilg.EndMethod(); } public XmlFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract) { _ilg = GenerateCollectionReaderHelper(collectionContract, true /*isGetOnlyCollection*/); ReadGetOnlyCollection(collectionContract); return (XmlFormatGetOnlyCollectionReaderDelegate)_ilg.EndMethod(); } private CodeGenerator GenerateCollectionReaderHelper(CollectionDataContract collectionContract, bool isGetOnlyCollection) { _ilg = new CodeGenerator(); bool memberAccessFlag = collectionContract.RequiresMemberAccessForRead(null); try { if (isGetOnlyCollection) { _ilg.BeginMethod("Read" + collectionContract.StableName.Name + "FromXml" + "IsGetOnly", Globals.TypeOfXmlFormatGetOnlyCollectionReaderDelegate, memberAccessFlag); } else { _ilg.BeginMethod("Read" + collectionContract.StableName.Name + "FromXml" + string.Empty, Globals.TypeOfXmlFormatCollectionReaderDelegate, memberAccessFlag); } } catch (SecurityException securityException) { if (memberAccessFlag) { collectionContract.RequiresMemberAccessForRead(securityException); } else { throw; } } InitArgs(); _collectionContractArg = _ilg.GetArg(4); return _ilg; } private void InitArgs() { _xmlReaderArg = _ilg.GetArg(0); _contextArg = _ilg.GetArg(1); _memberNamesArg = _ilg.GetArg(2); _memberNamespacesArg = _ilg.GetArg(3); } private void CreateObject(ClassDataContract classContract) { Type type = _objectType = classContract.UnderlyingType; if (type.GetTypeInfo().IsValueType && !classContract.IsNonAttributedType) type = Globals.TypeOfValueType; _objectLocal = _ilg.DeclareLocal(type, "objectDeserialized"); if (classContract.UnderlyingType == Globals.TypeOfDBNull) { _ilg.LoadMember(Globals.TypeOfDBNull.GetField("Value")); _ilg.Stloc(_objectLocal); } else if (classContract.IsNonAttributedType) { if (type.GetTypeInfo().IsValueType) { _ilg.Ldloca(_objectLocal); _ilg.InitObj(type); } else { _ilg.New(classContract.GetNonAttributedTypeConstructor()); _ilg.Stloc(_objectLocal); } } else { _ilg.Call(null, XmlFormatGeneratorStatics.GetUninitializedObjectMethod, DataContract.GetIdForInitialization(classContract)); _ilg.ConvertValue(Globals.TypeOfObject, type); _ilg.Stloc(_objectLocal); } } private void InvokeOnDeserializing(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnDeserializing(classContract.BaseContract); if (classContract.OnDeserializing != null) { _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(classContract.OnDeserializing); } } private void InvokeOnDeserialized(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnDeserialized(classContract.BaseContract); if (classContract.OnDeserialized != null) { _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(classContract.OnDeserialized); } } private void ReadClass(ClassDataContract classContract) { ReadMembers(classContract, null /*extensionDataLocal*/); } private void ReadMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal) { int memberCount = classContract.MemberNames.Length; _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, memberCount); LocalBuilder memberIndexLocal = _ilg.DeclareLocal(Globals.TypeOfInt, "memberIndex", -1); int firstRequiredMember; bool[] requiredMembers = GetRequiredMembers(classContract, out firstRequiredMember); bool hasRequiredMembers = (firstRequiredMember < memberCount); LocalBuilder requiredIndexLocal = hasRequiredMembers ? _ilg.DeclareLocal(Globals.TypeOfInt, "requiredIndex", firstRequiredMember) : null; object forReadElements = _ilg.For(null, null, null); _ilg.Call(null, XmlFormatGeneratorStatics.MoveToNextElementMethod, _xmlReaderArg); _ilg.IfFalseBreak(forReadElements); if (hasRequiredMembers) _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetMemberIndexWithRequiredMembersMethod, _xmlReaderArg, _memberNamesArg, _memberNamespacesArg, memberIndexLocal, requiredIndexLocal, extensionDataLocal); else _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetMemberIndexMethod, _xmlReaderArg, _memberNamesArg, _memberNamespacesArg, memberIndexLocal, extensionDataLocal); Label[] memberLabels = _ilg.Switch(memberCount); ReadMembers(classContract, requiredMembers, memberLabels, memberIndexLocal, requiredIndexLocal); _ilg.EndSwitch(); _ilg.EndFor(); if (hasRequiredMembers) { _ilg.If(requiredIndexLocal, Cmp.LessThan, memberCount); _ilg.Call(null, XmlFormatGeneratorStatics.ThrowRequiredMemberMissingExceptionMethod, _xmlReaderArg, memberIndexLocal, requiredIndexLocal, _memberNamesArg); _ilg.EndIf(); } } private int ReadMembers(ClassDataContract classContract, bool[] requiredMembers, Label[] memberLabels, LocalBuilder memberIndexLocal, LocalBuilder requiredIndexLocal) { int memberCount = (classContract.BaseContract == null) ? 0 : ReadMembers(classContract.BaseContract, requiredMembers, memberLabels, memberIndexLocal, requiredIndexLocal); for (int i = 0; i < classContract.Members.Count; i++, memberCount++) { DataMember dataMember = classContract.Members[i]; Type memberType = dataMember.MemberType; _ilg.Case(memberLabels[memberCount], dataMember.Name); if (dataMember.IsRequired) { int nextRequiredIndex = memberCount + 1; for (; nextRequiredIndex < requiredMembers.Length; nextRequiredIndex++) if (requiredMembers[nextRequiredIndex]) break; _ilg.Set(requiredIndexLocal, nextRequiredIndex); } LocalBuilder value = null; if (dataMember.IsGetOnlyCollection) { _ilg.LoadAddress(_objectLocal); _ilg.LoadMember(dataMember.MemberInfo); value = _ilg.DeclareLocal(memberType, dataMember.Name + "Value"); _ilg.Stloc(value); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.StoreCollectionMemberInfoMethod, value); ReadValue(memberType, dataMember.Name, classContract.StableName.Namespace); } else { value = ReadValue(memberType, dataMember.Name, classContract.StableName.Namespace); _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType); _ilg.Ldloc(value); _ilg.StoreMember(dataMember.MemberInfo); } #if FEATURE_LEGACYNETCF // The DataContractSerializer in the full framework doesn't support unordered elements: // deserialization will fail if the data members in the XML are not sorted alphabetically. // But the NetCF DataContractSerializer does support unordered element. To maintain compatibility // with Mango we always search for the member from the beginning of the member list. // We set memberIndexLocal to -1 because GetMemberIndex always starts from memberIndex+1. if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) ilg.Set(memberIndexLocal, (int)-1); else #endif // FEATURE_LEGACYNETCF _ilg.Set(memberIndexLocal, memberCount); _ilg.EndCase(); } return memberCount; } private bool[] GetRequiredMembers(ClassDataContract contract, out int firstRequiredMember) { int memberCount = contract.MemberNames.Length; bool[] requiredMembers = new bool[memberCount]; GetRequiredMembers(contract, requiredMembers); for (firstRequiredMember = 0; firstRequiredMember < memberCount; firstRequiredMember++) if (requiredMembers[firstRequiredMember]) break; return requiredMembers; } private int GetRequiredMembers(ClassDataContract contract, bool[] requiredMembers) { int memberCount = (contract.BaseContract == null) ? 0 : GetRequiredMembers(contract.BaseContract, requiredMembers); List<DataMember> members = contract.Members; for (int i = 0; i < members.Count; i++, memberCount++) { requiredMembers[memberCount] = members[i].IsRequired; } return memberCount; } private LocalBuilder ReadValue(Type type, string name, string ns) { LocalBuilder value = _ilg.DeclareLocal(type, "valueRead"); LocalBuilder nullableValue = null; int nullables = 0; while (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) { nullables++; type = type.GetGenericArguments()[0]; } PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.GetTypeInfo().IsValueType) { LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadAttributesMethod, _xmlReaderArg); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadIfNullOrRefMethod, _xmlReaderArg, type, DataContract.IsTypeSerializable(type)); _ilg.Stloc(objectId); // Deserialize null _ilg.If(objectId, Cmp.EqualTo, Globals.NullObjectId); if (nullables != 0) { _ilg.LoadAddress(value); _ilg.InitObj(value.LocalType); } else if (type.GetTypeInfo().IsValueType) ThrowValidationException(string.Format(SRSerialization.ValueTypeCannotBeNull, DataContract.GetClrTypeFullName(type))); else { _ilg.Load(null); _ilg.Stloc(value); } // Deserialize value // Compare against Globals.NewObjectId, which is set to string.Empty _ilg.ElseIfIsEmptyString(objectId); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod); _ilg.Stloc(objectId); if (type.GetTypeInfo().IsValueType) { _ilg.IfNotIsEmptyString(objectId); ThrowValidationException(string.Format(SRSerialization.ValueTypeCannotHaveId, DataContract.GetClrTypeFullName(type))); _ilg.EndIf(); } if (nullables != 0) { nullableValue = value; value = _ilg.DeclareLocal(type, "innerValueRead"); } if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) { _ilg.Call(_xmlReaderArg, primitiveContract.XmlFormatReaderMethod); _ilg.Stloc(value); if (!type.GetTypeInfo().IsValueType) _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, value); } else { InternalDeserialize(value, type, name, ns); } // Deserialize ref _ilg.Else(); if (type.GetTypeInfo().IsValueType) ThrowValidationException(string.Format(SRSerialization.ValueTypeCannotHaveRef, DataContract.GetClrTypeFullName(type))); else { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetExistingObjectMethod, objectId, type, name, ns); _ilg.ConvertValue(Globals.TypeOfObject, type); _ilg.Stloc(value); } _ilg.EndIf(); if (nullableValue != null) { _ilg.If(objectId, Cmp.NotEqualTo, Globals.NullObjectId); WrapNullableObject(value, nullableValue, nullables); _ilg.EndIf(); value = nullableValue; } } else { InternalDeserialize(value, type, name, ns); } return value; } private void InternalDeserialize(LocalBuilder value, Type type, string name, string ns) { _ilg.Load(_contextArg); _ilg.Load(_xmlReaderArg); Type declaredType = type; _ilg.Load(DataContract.GetId(declaredType.TypeHandle)); _ilg.Ldtoken(declaredType); _ilg.Load(name); _ilg.Load(ns); _ilg.Call(XmlFormatGeneratorStatics.InternalDeserializeMethod); _ilg.ConvertValue(Globals.TypeOfObject, type); _ilg.Stloc(value); } private void WrapNullableObject(LocalBuilder innerValue, LocalBuilder outerValue, int nullables) { Type innerType = innerValue.LocalType, outerType = outerValue.LocalType; _ilg.LoadAddress(outerValue); _ilg.Load(innerValue); for (int i = 1; i < nullables; i++) { Type type = Globals.TypeOfNullable.MakeGenericType(innerType); _ilg.New(type.GetConstructor(new Type[] { innerType })); innerType = type; } _ilg.Call(outerType.GetConstructor(new Type[] { innerType })); } private void ReadCollection(CollectionDataContract collectionContract) { Type type = collectionContract.UnderlyingType; Type itemType = collectionContract.ItemType; bool isArray = (collectionContract.Kind == CollectionKind.Array); ConstructorInfo constructor = collectionContract.Constructor; if (type.GetTypeInfo().IsInterface) { switch (collectionContract.Kind) { case CollectionKind.GenericDictionary: type = Globals.TypeOfDictionaryGeneric.MakeGenericType(itemType.GetGenericArguments()); constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>()); break; case CollectionKind.Dictionary: type = Globals.TypeOfHashtable; constructor = XmlFormatGeneratorStatics.HashtableCtor; break; case CollectionKind.Collection: case CollectionKind.GenericCollection: case CollectionKind.Enumerable: case CollectionKind.GenericEnumerable: case CollectionKind.List: case CollectionKind.GenericList: type = itemType.MakeArrayType(); isArray = true; break; } } string itemName = collectionContract.ItemName; string itemNs = collectionContract.StableName.Namespace; _objectLocal = _ilg.DeclareLocal(type, "objectDeserialized"); if (!isArray) { if (type.GetTypeInfo().IsValueType) { _ilg.Ldloca(_objectLocal); _ilg.InitObj(type); } else { _ilg.New(constructor); _ilg.Stloc(_objectLocal); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal); } } LocalBuilder size = _ilg.DeclareLocal(Globals.TypeOfInt, "arraySize"); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetArraySizeMethod); _ilg.Stloc(size); LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod); _ilg.Stloc(objectId); bool canReadPrimitiveArray = false; if (isArray && TryReadPrimitiveArray(type, itemType, size)) { canReadPrimitiveArray = true; _ilg.IfNot(); } _ilg.If(size, Cmp.EqualTo, -1); LocalBuilder growingCollection = null; if (isArray) { growingCollection = _ilg.DeclareLocal(type, "growingCollection"); _ilg.NewArray(itemType, 32); _ilg.Stloc(growingCollection); } LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i"); object forLoop = _ilg.For(i, 0, Int32.MaxValue); IsStartElement(_memberNamesArg, _memberNamespacesArg); _ilg.If(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); LocalBuilder value = ReadCollectionItem(collectionContract, itemType, itemName, itemNs); if (isArray) { MethodInfo ensureArraySizeMethod = XmlFormatGeneratorStatics.EnsureArraySizeMethod.MakeGenericMethod(itemType); _ilg.Call(null, ensureArraySizeMethod, growingCollection, i); _ilg.Stloc(growingCollection); _ilg.StoreArrayElement(growingCollection, i, value); } else StoreCollectionValue(_objectLocal, value, collectionContract); _ilg.Else(); IsEndElement(); _ilg.If(); _ilg.Break(forLoop); _ilg.Else(); HandleUnexpectedItemInCollection(i); _ilg.EndIf(); _ilg.EndIf(); _ilg.EndFor(); if (isArray) { MethodInfo trimArraySizeMethod = XmlFormatGeneratorStatics.TrimArraySizeMethod.MakeGenericMethod(itemType); _ilg.Call(null, trimArraySizeMethod, growingCollection, i); _ilg.Stloc(_objectLocal); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectWithIdMethod, objectId, _objectLocal); } _ilg.Else(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, size); if (isArray) { _ilg.NewArray(itemType, size); _ilg.Stloc(_objectLocal); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal); } LocalBuilder j = _ilg.DeclareLocal(Globals.TypeOfInt, "j"); _ilg.For(j, 0, size); IsStartElement(_memberNamesArg, _memberNamespacesArg); _ilg.If(); LocalBuilder itemValue = ReadCollectionItem(collectionContract, itemType, itemName, itemNs); if (isArray) _ilg.StoreArrayElement(_objectLocal, j, itemValue); else StoreCollectionValue(_objectLocal, itemValue, collectionContract); _ilg.Else(); HandleUnexpectedItemInCollection(j); _ilg.EndIf(); _ilg.EndFor(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.CheckEndOfArrayMethod, _xmlReaderArg, size, _memberNamesArg, _memberNamespacesArg); _ilg.EndIf(); if (canReadPrimitiveArray) { _ilg.Else(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectWithIdMethod, objectId, _objectLocal); _ilg.EndIf(); } } private void ReadGetOnlyCollection(CollectionDataContract collectionContract) { Type type = collectionContract.UnderlyingType; Type itemType = collectionContract.ItemType; bool isArray = (collectionContract.Kind == CollectionKind.Array); string itemName = collectionContract.ItemName; string itemNs = collectionContract.StableName.Namespace; _objectLocal = _ilg.DeclareLocal(type, "objectDeserialized"); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetCollectionMemberMethod); _ilg.ConvertValue(Globals.TypeOfObject, type); _ilg.Stloc(_objectLocal); //check that items are actually going to be deserialized into the collection IsStartElement(_memberNamesArg, _memberNamespacesArg); _ilg.If(); _ilg.If(_objectLocal, Cmp.EqualTo, null); _ilg.Call(null, XmlFormatGeneratorStatics.ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod, type); _ilg.Else(); LocalBuilder size = _ilg.DeclareLocal(Globals.TypeOfInt, "arraySize"); if (isArray) { _ilg.Load(_objectLocal); _ilg.Call(XmlFormatGeneratorStatics.GetArrayLengthMethod); _ilg.Stloc(size); } _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal); LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i"); object forLoop = _ilg.For(i, 0, Int32.MaxValue); IsStartElement(_memberNamesArg, _memberNamespacesArg); _ilg.If(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); LocalBuilder value = ReadCollectionItem(collectionContract, itemType, itemName, itemNs); if (isArray) { _ilg.If(size, Cmp.EqualTo, i); _ilg.Call(null, XmlFormatGeneratorStatics.ThrowArrayExceededSizeExceptionMethod, size, type); _ilg.Else(); _ilg.StoreArrayElement(_objectLocal, i, value); _ilg.EndIf(); } else StoreCollectionValue(_objectLocal, value, collectionContract); _ilg.Else(); IsEndElement(); _ilg.If(); _ilg.Break(forLoop); _ilg.Else(); HandleUnexpectedItemInCollection(i); _ilg.EndIf(); _ilg.EndIf(); _ilg.EndFor(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.CheckEndOfArrayMethod, _xmlReaderArg, size, _memberNamesArg, _memberNamespacesArg); _ilg.EndIf(); _ilg.EndIf(); } private bool TryReadPrimitiveArray(Type type, Type itemType, LocalBuilder size) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) return false; string readArrayMethod = null; switch (itemType.GetTypeCode()) { case TypeCode.Boolean: readArrayMethod = "TryReadBooleanArray"; break; case TypeCode.DateTime: readArrayMethod = "TryReadDateTimeArray"; break; case TypeCode.Decimal: readArrayMethod = "TryReadDecimalArray"; break; case TypeCode.Int32: readArrayMethod = "TryReadInt32Array"; break; case TypeCode.Int64: readArrayMethod = "TryReadInt64Array"; break; case TypeCode.Single: readArrayMethod = "TryReadSingleArray"; break; case TypeCode.Double: readArrayMethod = "TryReadDoubleArray"; break; default: break; } if (readArrayMethod != null) { _ilg.Load(_xmlReaderArg); _ilg.Load(_contextArg); _ilg.Load(_memberNamesArg); _ilg.Load(_memberNamespacesArg); _ilg.Load(size); _ilg.Ldloca(_objectLocal); _ilg.Call(typeof(XmlReaderDelegator).GetMethod(readArrayMethod, Globals.ScanAllMembers)); return true; } return false; } private LocalBuilder ReadCollectionItem(CollectionDataContract collectionContract, Type itemType, string itemName, string itemNs) { if (collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary) { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ResetAttributesMethod); LocalBuilder value = _ilg.DeclareLocal(itemType, "valueRead"); _ilg.Load(_collectionContractArg); _ilg.Call(XmlFormatGeneratorStatics.GetItemContractMethod); _ilg.Load(_xmlReaderArg); _ilg.Load(_contextArg); _ilg.Call(XmlFormatGeneratorStatics.ReadXmlValueMethod); _ilg.ConvertValue(Globals.TypeOfObject, itemType); _ilg.Stloc(value); return value; } else { return ReadValue(itemType, itemName, itemNs); } } private void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, CollectionDataContract collectionContract) { if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary) { ClassDataContract keyValuePairContract = DataContract.GetDataContract(value.LocalType) as ClassDataContract; if (keyValuePairContract == null) { DiagnosticUtility.DebugAssert("Failed to create contract for KeyValuePair type"); } DataMember keyMember = keyValuePairContract.Members[0]; DataMember valueMember = keyValuePairContract.Members[1]; LocalBuilder pairKey = _ilg.DeclareLocal(keyMember.MemberType, keyMember.Name); LocalBuilder pairValue = _ilg.DeclareLocal(valueMember.MemberType, valueMember.Name); _ilg.LoadAddress(value); _ilg.LoadMember(keyMember.MemberInfo); _ilg.Stloc(pairKey); _ilg.LoadAddress(value); _ilg.LoadMember(valueMember.MemberInfo); _ilg.Stloc(pairValue); _ilg.Call(collection, collectionContract.AddMethod, pairKey, pairValue); if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid) _ilg.Pop(); } else { _ilg.Call(collection, collectionContract.AddMethod, value); if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid) _ilg.Pop(); } } private void HandleUnexpectedItemInCollection(LocalBuilder iterator) { IsStartElement(); _ilg.If(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.SkipUnknownElementMethod, _xmlReaderArg); _ilg.Dec(iterator); _ilg.Else(); ThrowUnexpectedStateException(XmlNodeType.Element); _ilg.EndIf(); } private void IsStartElement(ArgBuilder nameArg, ArgBuilder nsArg) { _ilg.Call(_xmlReaderArg, XmlFormatGeneratorStatics.IsStartElementMethod2, nameArg, nsArg); } private void IsStartElement() { _ilg.Call(_xmlReaderArg, XmlFormatGeneratorStatics.IsStartElementMethod0); } private void IsEndElement() { _ilg.Load(_xmlReaderArg); _ilg.LoadMember(XmlFormatGeneratorStatics.NodeTypeProperty); _ilg.Load(XmlNodeType.EndElement); _ilg.Ceq(); } private void ThrowUnexpectedStateException(XmlNodeType expectedState) { _ilg.Call(null, XmlFormatGeneratorStatics.CreateUnexpectedStateExceptionMethod, expectedState, _xmlReaderArg); _ilg.Throw(); } private void ThrowValidationException(string msg, params object[] values) { { _ilg.Load(msg); } ThrowValidationException(); } private void ThrowValidationException() { //SerializationException is internal in SL and so cannot be directly invoked from DynamicMethod //So use helper function to create SerializationException _ilg.Call(XmlFormatGeneratorStatics.CreateSerializationExceptionMethod); _ilg.Throw(); } } #endif [SecuritySafeCritical] static internal object UnsafeGetUninitializedObject(Type type) { throw new NotImplementedException(); } /// <SecurityNote> /// Critical - Elevates by calling GetUninitializedObject which has a LinkDemand /// Safe - marked as such so that it's callable from transparent generated IL. Takes id as parameter which /// is guaranteed to be in internal serialization cache. /// </SecurityNote> [SecuritySafeCritical] #if USE_REFEMIT public static object UnsafeGetUninitializedObject(int id) #else static internal object UnsafeGetUninitializedObject(int id) #endif { var type = DataContract.GetDataContractForInitialization(id).TypeForInitialization; return UnsafeGetUninitializedObject(type); } static internal object TryGetUninitializedObjectWithFormatterServices(Type type) { object obj = null; var formatterServiceType = typeof(string).GetTypeInfo().Assembly.GetType("System.Runtime.Serialization.FormatterServices"); if (formatterServiceType != null) { var methodInfo = formatterServiceType.GetMethod("GetUninitializedObject", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); if (methodInfo != null) { obj = methodInfo.Invoke(null, new object[] { type }); } } return obj; } } }
// DateTimeEx.cs // using System; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace Xrm.Sdk { [ScriptNamespace("SparkleXrm.Sdk")] public class DateTimeEx { public static string ToXrmString(DateTime date) { // Get a date string from the Date object //2011-04-20T14:00:00Z // NOTE: we assume that the local date is in fact converted to UTC already // This avoids any local browser timezone missmatches with the user settings timezone string month = DateTimeEx.PadNumber(date.GetMonth() + 1, 2); string day = DateTimeEx.PadNumber(date.GetDate(), 2); string hours = DateTimeEx.PadNumber(date.GetHours(), 2); string mins = DateTimeEx.PadNumber(date.GetMinutes(), 2); string secs = DateTimeEx.PadNumber(date.GetSeconds(), 2); return String.Format("{0}-{1}-{2}T{3}:{4}:{5}Z", date.GetFullYear(), month, day, hours, mins, secs); } public static string ToXrmStringUTC(DateTime date) { // Get a date string from the Date object //2011-04-20T14:00:00Z // NOTE: we assume that the local date is in fact converted to UTC already // This avoids any local browser timezone missmatches with the user settings timezone string month = DateTimeEx.PadNumber(date.GetUTCMonth() + 1, 2); string day = DateTimeEx.PadNumber(date.GetUTCDate(), 2); string hours = DateTimeEx.PadNumber(date.GetUTCHours(), 2); string mins = DateTimeEx.PadNumber(date.GetUTCMinutes(), 2); string secs = DateTimeEx.PadNumber(date.GetUTCSeconds(), 2); return String.Format("{0}-{1}-{2}T{3}:{4}:{5}Z", date.GetUTCFullYear(), month, day, hours, mins, secs); } private static string PadNumber(int number, int length) { string str = number.ToString(); while (str.Length < length) str = '0' + str; return str; } public static DateTime Parse(string dateString) { if (!String.IsNullOrEmpty(dateString)) { DateTime dateTimeParsed = (DateTime)((object)Date.Parse(dateString)); return dateTimeParsed; } else return null; } /// <summary> /// Formats a duration in minutes to a string /// </summary> /// <param name="hours"></param> /// <param name="minutes"></param> /// <returns></returns> public static string FormatDuration(int? totalMinutes) { if (totalMinutes != null) { int? toatalSeconds = totalMinutes * 60; int? days = Math.Floor(toatalSeconds / 86400); int? hours = Math.Floor((toatalSeconds % 86400) / 3600); int? minutes = Math.Floor(((toatalSeconds % 86400) % 3600) / 60); int? seconds = ((toatalSeconds % 86400) % 3600) % 60; List<string> formatString = new List<string>(); if (days>0) ArrayEx.Add(formatString,"{0}d"); if (hours>0) ArrayEx.Add(formatString,"{1}h"); if (minutes > 0) ArrayEx.Add(formatString, "{2}m"); // LED: 9/26/2013: If days and hours are 0 and minutes are 0 we want to at least show 0m so the value can be editited. if (days == 0 && hours == 0 && minutes == 0) { ArrayEx.Add(formatString, "{2}m"); } return String.Format(ArrayEx.Join((Array)formatString," "), days, hours, minutes); } else return ""; } public static int? ParseDuration(string duration) { bool isEmpty = (duration == null) || (duration.Length == 0); if (isEmpty) { return null; } // Get the value as minutes decimal // ([0-9]*) ((h(our)?[s]?)|(m(inute)?[s]?)|(d(ay)?[s]?)) string pattern = @"/([0-9.]*)[ ]?((h(our)?[s]?)|(m(inute)?[s]?)|(d(ay)?[s]?))/g"; RegularExpression regex = RegularExpression.Parse(pattern); bool matched = false; bool thisMatch = false; int totalDuration = 0; do { string[] match = regex.Exec(duration); thisMatch = (match != null && match.Length > 0); matched = matched || thisMatch; if (thisMatch) { // Get value decimal durationNumber = decimal.Parse(match[1]); switch (match[2].Substr(0, 1).ToLowerCase()) { case "d": durationNumber = durationNumber * 60 * 24; break; case "h": durationNumber = durationNumber * 60; break; } totalDuration += Math.Floor(durationNumber); // Remove matched item duration.Replace(match[0], ""); } } while (thisMatch); if (matched) return (int?)totalDuration; else return null; } public static DateTime AddTimeToDate(DateTime date, string time) { if (date == null) { date = DateTime.Now; } if (time != null) { DateTime dateWithTime = DateTime.Parse("01 Jan 2000 " + time.Replace(".", ":").Replace("-", ":").Replace(",", ":")); DateTime newDate = new DateTime(date.GetTime()); if (!Number.IsNaN((Number)((object)dateWithTime))) { newDate.SetHours(dateWithTime.GetHours()); newDate.SetMinutes(dateWithTime.GetMinutes()); newDate.SetSeconds(dateWithTime.GetSeconds()); newDate.SetMilliseconds(dateWithTime.GetMilliseconds()); return newDate; } return null; } return date; } public static DateTime LocalTimeToUTCFromSettings(DateTime LocalTime, UserSettings settings) { return LocalTimeToUTC(LocalTime, settings.TimeZoneBias, settings.TimeZoneDaylightBias, settings.TimeZoneDaylightYear, settings.TimeZoneDaylightMonth, settings.TimeZoneDaylightDay, settings.TimeZoneDaylightHour, settings.TimeZoneDaylightMinute, settings.TimeZoneDaylightSecond, 0, settings.TimeZoneDaylightDayOfWeek, settings.TimeZoneStandardBias, settings.TimeZoneStandardYear, settings.TimeZoneStandardMonth, settings.TimeZoneStandardDay, settings.TimeZoneStandardHour, settings.TimeZoneStandardMinute, settings.TimeZoneStandardSecond, 0, settings.TimeZoneStandardDayOfWeek); } public static DateTime LocalTimeToUTC(DateTime LocalTime, int? Bias, int? DaylightBias, int? DaylightYear, int? DaylightMonth, int? DaylightDay, int? DaylightHour, int? DaylightMinute, int? DaylightSecond, int? DaylightMilliseconds, int? DaylightWeekday, int? StandardBias, int? StandardYear, int? StandardMonth, int? StandardDay, int? StandardHour, int? StandardMinute, int? StandardSecond, int? StandardMilliseconds, int? StandardWeekday) { int? TimeZoneBias; int? NewTimeZoneBias; int? LocalCustomBias; DateTime StandardTime; DateTime DaylightTime; DateTime ComputedUniversalTime; bool bDaylightTimeZone; // Get the new timezone bias NewTimeZoneBias = Bias; // Now see if we have stored cutover times if ((StandardMonth != 0) && (DaylightMonth != 0)) { // We have timezone cutover information. Compute the // cutover dates and compute what our current bias // is StandardTime = GetCutoverTime(LocalTime, StandardYear, StandardMonth, StandardDay, StandardHour, StandardMinute, StandardSecond, StandardMilliseconds, StandardWeekday); if (StandardTime == null) { return null; } DaylightTime = GetCutoverTime(LocalTime, DaylightYear, DaylightMonth, DaylightDay, DaylightHour, DaylightMinute, DaylightSecond, DaylightMilliseconds, DaylightWeekday); if (DaylightTime == null) { return null; } // If daylight < standard, then time >= daylight and // less than standard is daylight if (DaylightTime < StandardTime) { // If today is >= DaylightTime and < StandardTime, then // We are in daylight savings time if ((LocalTime >= DaylightTime) && (LocalTime < StandardTime)) { bDaylightTimeZone = true; } else { bDaylightTimeZone = false; } } else { // If today is >= StandardTime and < DaylightTime, then // We are in standard time if ((LocalTime >= StandardTime) && (LocalTime < DaylightTime)) { bDaylightTimeZone = false; } else { bDaylightTimeZone = true; } } // At this point, we know our current timezone and the // local time of the next cutover. if (bDaylightTimeZone) { LocalCustomBias = DaylightBias; } else { LocalCustomBias = StandardBias; } TimeZoneBias = NewTimeZoneBias + LocalCustomBias; } else { TimeZoneBias = NewTimeZoneBias; } ComputedUniversalTime = DateAdd(DateInterval.Minutes, (int)TimeZoneBias, LocalTime); return ComputedUniversalTime; } public static DateTime UTCToLocalTimeFromSettings(DateTime UTCTime, UserSettings settings) { return UTCToLocalTime(UTCTime, settings.TimeZoneBias, settings.TimeZoneDaylightBias, settings.TimeZoneDaylightYear, settings.TimeZoneDaylightMonth, settings.TimeZoneDaylightDay, settings.TimeZoneDaylightHour, settings.TimeZoneDaylightMinute, settings.TimeZoneDaylightSecond, 0, settings.TimeZoneDaylightDayOfWeek, settings.TimeZoneStandardBias, settings.TimeZoneStandardYear, settings.TimeZoneStandardMonth, settings.TimeZoneStandardDay, settings.TimeZoneStandardHour, settings.TimeZoneStandardMinute, settings.TimeZoneStandardSecond, 0, settings.TimeZoneStandardDayOfWeek); } public static DateTime UTCToLocalTime(DateTime UTCTime, int? Bias, int? DaylightBias, int? DaylightYear, int? DaylightMonth, int? DaylightDay, int? DaylightHour, int? DaylightMinute, int? DaylightSecond, int? DaylightMilliseconds, int? DaylightWeekday, int? StandardBias, int? StandardYear, int? StandardMonth, int? StandardDay, int? StandardHour, int? StandardMinute, int? StandardSecond, int? StandardMilliseconds, int? StandardWeekday) { int? TimeZoneBias = 0; int? NewTimeZoneBias = 0; int? LocalCustomBias = 0; DateTime StandardTime; DateTime DaylightTime; DateTime UtcStandardTime; DateTime UtcDaylightTime; DateTime ComputedLocalTime; bool bDaylightTimeZone; // Get the timezone information into a useful format // Get the new timezone bias NewTimeZoneBias = Bias; // Now see if we have stored cutover times if ((StandardMonth != 0) && (DaylightMonth != 0)) { // We have timezone cutover information. Compute the // cutover dates and compute what our current bias // is StandardTime = GetCutoverTime(UTCTime, StandardYear, StandardMonth, StandardDay, StandardHour, StandardMinute, StandardSecond, StandardMilliseconds, StandardWeekday); if (StandardTime == null) { return null; } DaylightTime = GetCutoverTime(UTCTime, DaylightYear, DaylightMonth, DaylightDay, DaylightHour, DaylightMinute, DaylightSecond, DaylightMilliseconds, DaylightWeekday); if (DaylightTime == null) { return null; } // Convert standard time and daylight time to utc LocalCustomBias = StandardBias; TimeZoneBias = NewTimeZoneBias + LocalCustomBias; UtcDaylightTime = DateTimeEx.DateAdd(DateInterval.Minutes, (int)TimeZoneBias, DaylightTime); LocalCustomBias = DaylightBias; TimeZoneBias = NewTimeZoneBias + LocalCustomBias; UtcStandardTime = DateTimeEx.DateAdd(DateInterval.Minutes, (int)TimeZoneBias, StandardTime); //If daylight < standard, then time >= daylight and //less than standard is daylight if (UtcDaylightTime < UtcStandardTime) { // If today is >= DaylightTime and < StandardTime, then // We are in daylight savings time if ((UTCTime >= UtcDaylightTime) && (UTCTime < UtcStandardTime)) { bDaylightTimeZone = true; } else { bDaylightTimeZone = false; } } else { // If today is >= StandardTime and < DaylightTime, then // We are in standard time if ((UTCTime >= UtcStandardTime) && (UTCTime < UtcDaylightTime)) { bDaylightTimeZone = false; } else { bDaylightTimeZone = true; } } // At this point, we know our current timezone and the // Universal time of the next cutover. if (bDaylightTimeZone) { LocalCustomBias = DaylightBias; } else { LocalCustomBias = StandardBias; } TimeZoneBias = NewTimeZoneBias + LocalCustomBias; } else { TimeZoneBias = NewTimeZoneBias; } ComputedLocalTime = DateTimeEx.DateAdd(DateInterval.Minutes, (int)TimeZoneBias * -1, UTCTime); return ComputedLocalTime; } private static DateTime GetCutoverTime(DateTime CurrentTime, int? Year, int? Month, int? Day, int? Hour, int? Minute, int? Second, int? Milliseconds, int? Weekday ) { if (Year != 0) return null; DateTime WorkingTime; DateTime ScratchTime; int? BestWeekdayDate; int? WorkingWeekdayNumber; int? TargetWeekdayNumber; int? TargetYear; int? TargetMonth; int? TargetWeekday; // range [0..6] == [Sunday..Saturday] // The time is an day in the month style time // the convention is the Day is 1-5 specifying 1st, 2nd... Last // day within the month. The day is WeekDay. // Compute the target month and year TargetWeekdayNumber = Day; if ((TargetWeekdayNumber > 5) || (TargetWeekdayNumber == 0)) { return null; } TargetWeekday = Weekday; TargetMonth = Month; TargetYear = CurrentTime.GetFullYear(); BestWeekdayDate = 0; WorkingTime = DateTimeEx.FirstDayOfMonth(CurrentTime, (int)TargetMonth); WorkingTime = DateTimeEx.DateAdd(DateInterval.Hours, (int)Hour, WorkingTime); WorkingTime = DateTimeEx.DateAdd(DateInterval.Minutes, (int)Minute, WorkingTime); WorkingTime = DateTimeEx.DateAdd(DateInterval.Seconds, (int)Second, WorkingTime); WorkingTime = DateTimeEx.DateAdd(DateInterval.Milliseconds, (int)Milliseconds, WorkingTime); ScratchTime = WorkingTime; // Compute bias to target weekday if (ScratchTime.GetDay() > TargetWeekday) { WorkingTime = DateTimeEx.DateAdd(DateInterval.Days, (int)(7 - (ScratchTime.GetDay() - TargetWeekday)), WorkingTime); } else if (ScratchTime.GetDay() < TargetWeekday) { WorkingTime = DateTimeEx.DateAdd(DateInterval.Days, (int)(TargetWeekday - ScratchTime.GetDay()), WorkingTime); } // We are now at the first weekday that matches our target weekday BestWeekdayDate = WorkingTime.GetDay(); WorkingWeekdayNumber = 1; // Keep going one week at a time until we either pass the // target weekday, or we match exactly ScratchTime = WorkingTime; while (WorkingWeekdayNumber < TargetWeekdayNumber) { WorkingTime = DateTimeEx.DateAdd(DateInterval.Days, 7, WorkingTime); if (WorkingTime.GetMonth() != ScratchTime.GetMonth()) break; ScratchTime = WorkingTime; WorkingWeekdayNumber = WorkingWeekdayNumber + 1; } return ScratchTime; } public static DateTime FirstDayOfMonth(DateTime date, int Month) { DateTime startOfMonth = new DateTime(date.GetTime()); startOfMonth.SetMonth(Month-1); startOfMonth.SetDate(1); startOfMonth.SetHours(0); startOfMonth.SetMinutes(0); startOfMonth.SetSeconds(0); startOfMonth.SetMilliseconds(0); return startOfMonth; } public static DateTime DateAdd(DateInterval interval, int value, DateTime date) { int ms = date.GetTime(); DateTime result; switch (interval) { case DateInterval.Milliseconds: result = new DateTime(ms + value); break; case DateInterval.Seconds: result = new DateTime(ms + (value * 1000)); break; case DateInterval.Minutes: result = new DateTime(ms + (value * 1000 * 60)); break; case DateInterval.Hours: result = new DateTime(ms + (value * 1000 * 60 * 60)); break; case DateInterval.Days: result = new DateTime(ms + (value * 1000 * 60 * 60 * 24)); break; default: result = date; break; } return result; } public static DateTime FirstDayOfWeek(DateTime date) { int weekStartOffset = 0; if (OrganizationServiceProxy.OrganizationSettings != null) { weekStartOffset = OrganizationServiceProxy.OrganizationSettings.WeekStartDayCode.Value.Value; } DateTime startOfWeek = new DateTime(date.GetTime()); int dayOfWeek = startOfWeek.GetDay(); dayOfWeek = dayOfWeek - weekStartOffset; if (dayOfWeek < 0) dayOfWeek = 7+dayOfWeek; if (dayOfWeek > 0) { startOfWeek = DateTimeEx.DateAdd(DateInterval.Days, (int)(dayOfWeek*-1), startOfWeek); } startOfWeek.SetHours(0); startOfWeek.SetMinutes(0); startOfWeek.SetSeconds(0); startOfWeek.SetMilliseconds(0); return startOfWeek; } public static DateTime LastDayOfWeek(DateTime date) { int weekStartOffset = 0; if (OrganizationServiceProxy.OrganizationSettings != null) { weekStartOffset = OrganizationServiceProxy.OrganizationSettings.WeekStartDayCode.Value.Value; } DateTime endOfWeek = new DateTime(date.GetTime()); int dayOfWeek = endOfWeek.GetDay(); dayOfWeek = dayOfWeek - weekStartOffset; if (dayOfWeek < 0) dayOfWeek = 7 + dayOfWeek; endOfWeek = DateTimeEx.DateAdd(DateInterval.Days, (int)(6 - dayOfWeek), endOfWeek); endOfWeek.SetHours(23); endOfWeek.SetMinutes(59); endOfWeek.SetSeconds(59); endOfWeek.SetMilliseconds(999); return endOfWeek; } public static string FormatTimeSpecific(DateTime dateValue, string formatString) { formatString = formatString.Replace(".", ":").Replace("-", ":").Replace(",", ":"); if (dateValue != null && (typeof(DateTime) == dateValue.GetType())) return dateValue.Format(formatString); else return ""; } public static string FormatDateSpecific(DateTime dateValue, string formatString) { if (dateValue != null) { return (string)Script.Literal(@"xrmjQuery.datepicker.formatDate( {0}, {1} )", formatString, dateValue); } else return ""; } public static DateTime ParseDateSpecific(string dateValue, string formatString) { return (DateTime)Script.Literal(@"xrmjQuery.datepicker.parseDate( {0}, {1} )", formatString, dateValue); } public static void SetTime(DateTime date, DateTime time) { if (date != null && time != null) { date.SetHours(time.GetHours()); date.SetMinutes(time.GetMinutes()); date.SetSeconds(time.GetSeconds()); date.SetMilliseconds(time.GetMilliseconds()); } } public static void SetUTCTime(DateTime date, DateTime time) { if (date != null && time != null) { date.SetUTCHours(time.GetUTCHours()); date.SetUTCMinutes(time.GetUTCMinutes()); date.SetUTCSeconds(time.GetUTCSeconds()); date.SetUTCMilliseconds(time.GetUTCMilliseconds()); } } /// <summary> /// Gets the duration since midnight in seconds /// </summary> /// <param name="date"></param> /// <returns></returns> public static int GetTimeDuration(DateTime date) { return (date.GetHours() * (60 * 60)) + (date.GetMinutes() * 60) + (date.GetSeconds()); } } [Imported] [IgnoreNamespace] [NamedValues] public enum DateInterval { Milliseconds = 0, Seconds = 1, Minutes = 2, Hours = 3, Days = 4 } }
using System; using System.Collections.Generic; using InAudioLeanTween; using InAudioSystem.ExtensionMethods; using InAudioSystem.ReorderableList; using InAudioSystem.Runtime; using UnityEditor; using UnityEngine; using UnityEngine.Audio; namespace InAudioSystem.InAudioEditor { public static class AudioEventDrawer { private static InAudioEventNode lastEvent; private static AudioEventAction audioEventAction = null; private static Vector2 scrollPos; //private static Rect drawArea; private static AudioEventAction toRemove = null; private static EventActionListAdapter ListAdapter ; private static GUIStyle leftStyle = new GUIStyle(GUI.skin.label); private static GameObject eventObjectTarget; public static bool Draw(InAudioEventNode audioevent) { if (ListAdapter == null) { ListAdapter = new EventActionListAdapter(); ListAdapter.DrawEvent = DrawItem; ListAdapter.ClickedInArea = ClickedInArea; } if (lastEvent != audioevent) { ListAdapter.Event = audioevent; audioEventAction = null; if (audioevent._actionList.Count > 0) { audioEventAction = audioevent._actionList[0]; } } EditorGUILayout.BeginVertical(); lastEvent = audioevent; InUndoHelper.GUIUndo(audioevent, "Name Change", ref audioevent.Name, () => EditorGUILayout.TextField("Name", audioevent.Name)); bool repaint = false; if (audioevent._type == EventNodeType.Event) { EditorGUIHelper.DrawID(audioevent._guid); if (Application.isPlaying) { eventObjectTarget = EditorGUILayout.ObjectField("Event preview target", eventObjectTarget, typeof(GameObject), true) as GameObject; if (eventObjectTarget != null ) { bool prefab = PrefabUtility.GetPrefabParent(eventObjectTarget) == null && PrefabUtility.GetPrefabObject(eventObjectTarget) != null; if (!prefab) { EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Post event")) { InAudio.PostEvent(eventObjectTarget, audioevent); } if (GUILayout.Button("Stop All Sounds/Music in Event")) { InAudio.StopAll(eventObjectTarget); foreach (var eventAction in audioevent._actionList) { var music = eventAction.Target as InMusicGroup; if (music != null) { InAudio.Music.Stop(music); } } } EditorGUILayout.EndHorizontal(); } else { EditorGUILayout.HelpBox("Cannot post events on Prefab", MessageType.Error); } } EditorGUILayout.Separator(); } InUndoHelper.GUIUndo(audioevent, "Delay", ref audioevent.Delay, () => Mathf.Max(EditorGUILayout.FloatField("Delay", audioevent.Delay), 0)); NewEventArea(audioevent); EditorGUILayout.Separator(); EditorGUILayout.Separator(); scrollPos = EditorGUILayout.BeginScrollView(scrollPos); repaint = DrawContent(); EditorGUILayout.EndScrollView(); DrawSelected(audioEventAction); } else if (audioevent._type == EventNodeType.Folder) { if (audioevent.PlacedExternaly) { EditorGUILayout.Separator(); GUI.enabled = false; EditorGUILayout.ObjectField("Placed on", audioevent.gameObject, typeof(GameObject), false); GUI.enabled = true; EditorGUILayout.Separator(); } } EditorGUILayout.EndVertical(); if (toRemove != null) { InUndoHelper.DoInGroup(() => { //Remove the required piece int index = audioevent._actionList.FindIndex(toRemove); AudioEventWorker.DeleteActionAtIndex(audioevent, index); }); toRemove = null; } else //Remove all actions that does not excist. { audioevent._actionList.RemoveAll(p => p == null); } return repaint; } private static void ClickedInArea(int i) { audioEventAction = lastEvent._actionList[i]; } private static void DrawSelected(AudioEventAction eventAction) { if (eventAction != null) { Rect thisArea = EditorGUILayout.BeginVertical(GUILayout.Height(120)); EditorGUILayout.LabelField(""); var buttonArea = thisArea; buttonArea.height = 16; GUI.skin.label.alignment = TextAnchor.UpperLeft; InUndoHelper.GUIUndo(eventAction, "Event Action Delay", ref eventAction.Delay, () => Mathf.Max(EditorGUI.FloatField(buttonArea, "Seconds Delay", eventAction.Delay), 0)); buttonArea.y += 33; var bankLoadingAction = eventAction as InEventBankLoadingAction; var audioAction = eventAction as InEventAudioAction; var snapshotAction = eventAction as InEventSnapshotAction; var mixerAction = eventAction as InEventMixerValueAction; var musicControlAction = eventAction as InEventMusicControl; var musicFadeAction = eventAction as InEventMusicFade; var musicSoloMuteAction = eventAction as InEventSoloMuteMusic; if (audioAction != null) { if (audioAction._eventActionType == EventActionTypes.Play || audioAction._eventActionType == EventActionTypes.Stop || audioAction._eventActionType == EventActionTypes.StopAll) { InUndoHelper.GUIUndo(audioAction, "Fade Time", ref audioAction.Fadetime, () => Mathf.Max(0, EditorGUILayout.FloatField("Fade Time", audioAction.Fadetime))); InUndoHelper.GUIUndo(audioAction, "Fade Type", ref audioAction.TweenType, () => (LeanTweenType) EditorGUILayout.EnumPopup("Fade Type", audioAction.TweenType)); if (audioAction.TweenType == LeanTweenType.animationCurve) { EditorGUILayout.HelpBox("Animation curve type is not supported", MessageType.Warning); } } } else if (bankLoadingAction != null) { //todo } else if (snapshotAction != null) { InUndoHelper.GUIUndo(snapshotAction, "Snapshot Transition Action", ref snapshotAction.Snapshot, () => (AudioMixerSnapshot)EditorGUILayout.ObjectField("Transition Action", snapshotAction.Snapshot, typeof(AudioMixerSnapshot), false)); InUndoHelper.GUIUndo(snapshotAction, "Snapshot Transition Time", ref snapshotAction.TransitionTime, () => EditorGUILayout.FloatField("Transition Time", snapshotAction.TransitionTime)); } else if (mixerAction != null) { InUndoHelper.GUIUndo(mixerAction, "Mixer Value", ref mixerAction.Mixer, () => (AudioMixer)EditorGUILayout.ObjectField("Audio Mixer", mixerAction.Mixer, typeof(AudioMixer), false)); InUndoHelper.GUIUndo(mixerAction, "Parameter", ref mixerAction.Parameter, () => EditorGUILayout.TextField("Parameter", mixerAction.Parameter)); InUndoHelper.GUIUndo(mixerAction, "Value", ref mixerAction.Value, () => EditorGUILayout.FloatField("Value", mixerAction.Value)); EditorGUILayout.Separator(); InUndoHelper.GUIUndo(mixerAction, "Transition Time", ref mixerAction.TransitionTime, () => Mathf.Max(0, EditorGUILayout.FloatField("Transition Time", mixerAction.TransitionTime))); InUndoHelper.GUIUndo(mixerAction, "Transition Type", ref mixerAction.TransitionType, () => (LeanTweenType)EditorGUILayout.EnumPopup("Transition Type", mixerAction.TransitionType)); if (mixerAction.TransitionType == LeanTweenType.animationCurve) { EditorGUILayout.HelpBox("Animation curve type is not supported", MessageType.Warning); } } else if (musicControlAction != null) { InUndoHelper.GUIUndo(musicControlAction, "Fade Action", ref musicControlAction.Fade, () => EditorGUILayout.Toggle("Fade Action", musicControlAction.Fade)); if (musicControlAction.Fade) { InUndoHelper.GUIUndo(musicControlAction, "Transition Time", ref musicControlAction.Duration, () => Mathf.Max(0, EditorGUILayout.FloatField("Transition Time", musicControlAction.Duration))); InUndoHelper.GUIUndo(musicControlAction, "Transition Type", ref musicControlAction.TweenType, () => (LeanTweenType) EditorGUILayout.EnumPopup("Transition Type", musicControlAction.TweenType)); } InUndoHelper.GUIUndo(musicControlAction, "Set Volume Target", ref musicControlAction.ChangeVolume, () => EditorGUILayout.Toggle("Set Volume Target", musicControlAction.ChangeVolume)); if (musicControlAction.ChangeVolume) { InUndoHelper.GUIUndo(musicControlAction, "Volume Target", ref musicControlAction.Duration, () => Mathf.Clamp01(EditorGUILayout.Slider("Volume Target", musicControlAction.Duration, 0, 1))); } } else if (musicFadeAction != null) { if (musicFadeAction._eventActionType == EventActionTypes.CrossfadeMusic) { InUndoHelper.GUIUndo(musicFadeAction, "Fade Target", ref musicFadeAction.From, () => EditorGUILayout.ObjectField("From Target", musicFadeAction.To, typeof(InEventMusicFade),false) as InMusicGroup); InUndoHelper.GUIUndo(musicFadeAction, "Fade Target", ref musicFadeAction.To, () => EditorGUILayout.ObjectField("To Target", musicFadeAction.To, typeof(InEventMusicFade), false) as InMusicGroup); } if (musicFadeAction._eventActionType == EventActionTypes.FadeMusic) { InUndoHelper.GUIUndo(musicFadeAction, "Volume Target", ref musicFadeAction.ToVolumeTarget, () => EditorGUILayout.Slider("Volume Target", musicFadeAction.ToVolumeTarget, 0f, 1f)); } InUndoHelper.GUIUndo(musicFadeAction, "Transition Time", ref musicFadeAction.Duration, () => Mathf.Max(0, EditorGUILayout.FloatField("Transition Time", musicFadeAction.Duration))); InUndoHelper.GUIUndo(musicFadeAction, "Transition Type", ref musicFadeAction.TweenType, () => (LeanTweenType)EditorGUILayout.EnumPopup("Transition Type", musicFadeAction.TweenType)); if (musicFadeAction.TweenType == LeanTweenType.animationCurve) { EditorGUILayout.HelpBox("Animation curve type is not supported", MessageType.Warning); } if (musicFadeAction._eventActionType == EventActionTypes.FadeMusic) { InUndoHelper.GUIUndo(musicFadeAction, "Do At End", ref musicFadeAction.DoAtEndTo, () => (MusicState)EditorGUILayout.EnumPopup("Do At End", musicFadeAction.DoAtEndTo)); if (musicFadeAction.DoAtEndTo == MusicState.Playing) { EditorGUILayout.HelpBox("\"Playing\" does the same as \"Nothing\", it does not start playing", MessageType.Info ); } } } else if (musicSoloMuteAction != null) { InUndoHelper.GUIUndo(musicSoloMuteAction, "Set Solo", ref musicSoloMuteAction.SetSolo, () => EditorGUILayout.Toggle("Set Solo", musicSoloMuteAction.SetSolo)); if (musicSoloMuteAction.SetSolo) { InUndoHelper.GUIUndo(musicSoloMuteAction, "Solo Target", ref musicSoloMuteAction.SoloTarget, () => EditorGUILayout.Toggle("Solo Target", musicSoloMuteAction.SoloTarget)); } EditorGUILayout.Separator(); InUndoHelper.GUIUndo(musicSoloMuteAction, "Set Mute", ref musicSoloMuteAction.SetMute, () => EditorGUILayout.Toggle("Set Mute", musicSoloMuteAction.SetMute)); if (musicSoloMuteAction.SetMute) { InUndoHelper.GUIUndo(musicSoloMuteAction, "Solo Mute", ref musicSoloMuteAction.MuteTarget, () => EditorGUILayout.Toggle("Solo Mute", musicSoloMuteAction.MuteTarget)); } } EditorGUILayout.EndVertical(); } } private static void NewEventArea(InAudioEventNode audioevent) { var defaultAlignment = GUI.skin.label.alignment; EditorGUILayout.BeginHorizontal(); GUI.skin.label.alignment = TextAnchor.MiddleLeft; EditorGUILayout.LabelField(""); EditorGUILayout.EndHorizontal(); Rect lastArea = GUILayoutUtility.GetLastRect(); lastArea.height *= 1.5f; if (GUI.Button(lastArea, "Click or drag here to add event action")) { ShowCreationContext(audioevent); } var dragging = DragAndDrop.objectReferences; OnDragging.OnDraggingObject(dragging, lastArea, objects => AudioEventWorker.CanDropObjects(audioevent, dragging), objects => AudioEventWorker.OnDrop(audioevent, dragging)); GUI.skin.label.alignment = defaultAlignment; } private static bool DrawContent() { ReorderableListGUI.ListField(ListAdapter, ReorderableListFlags.DisableContextMenu | ReorderableListFlags.HideAddButton | ReorderableListFlags.HideRemoveButtons ); return false; } private static void DrawItem(Rect position, int i) { var item = lastEvent._actionList[i]; leftStyle.alignment = TextAnchor.MiddleLeft; if(item == audioEventAction) DrawBackground(position); Rect fullArea = position; Rect typePos = position; typePos.width = 110; if (item != null) { if (GUI.Button(typePos, EventActionExtension.GetList().Find(p => p.Value == (int)item._eventActionType).Name)) { ShowChangeContext(lastEvent, item); Event.current.UseEvent(); } } else GUI.Label(position, "Missing data", leftStyle); typePos.x += 130; if (item != null && item._eventActionType != EventActionTypes.StopAll && item._eventActionType != EventActionTypes.StopAllMusic) { Rect area = typePos; area.width = position.width - 200; GUI.Label(area, item.ObjectName); } HandleDragging(item, typePos); position.x = position.x + position.width - 75; position.width = 45; if (item != null && item._eventActionType != EventActionTypes.StopAll && item._eventActionType != EventActionTypes.StopAllMusic) { if (GUI.Button(position, "Find")) { SearchHelper.SearchForActionTarget(item); } } position.x += 50; position.width = 20; if (audioEventAction == item) { DrawBackground(position); } if (GUI.Button(position, "X")) { toRemove = item; } if (Event.current.ClickedWithin(fullArea)) { audioEventAction = item; Event.current.UseEvent(); } } private static void HandleDragging(AudioEventAction currentAction, Rect dragArea) { if (currentAction != null) { if (currentAction is InEventAudioAction) { InAudioNode dragged = OnDragging.DraggingObject<InAudioNode>(dragArea, node => node.IsPlayable); if (dragged != null) { InUndoHelper.RecordObject(currentAction, "Change Action Type"); currentAction.Target = dragged; } } else if (currentAction is InEventBankLoadingAction) { //todo } else if(currentAction is InEventMixerValueAction) { AudioMixer dragged = OnDragging.DraggingObject<AudioMixer>(dragArea); if (dragged != null) { InUndoHelper.RecordObject(currentAction, "Change Action Type"); currentAction.Target = dragged; } } else if (currentAction is InEventMusicControl || currentAction is InEventMusicFade || currentAction is InEventSoloMuteMusic) { InMusicGroup dragged = OnDragging.DraggingObject<InMusicGroup>(dragArea); if (dragged != null) { InUndoHelper.RecordObject(currentAction, "Change Action Type"); currentAction.Target = dragged; } } } } private static void DrawBackground(Rect area) { GUI.depth += 10; GUI.DrawTexture(area, EditorResources.Instance.GetBackground()); GUI.depth -= 10; } private static void ShowChangeContext(InAudioEventNode audioEvent, AudioEventAction action) { var menu = new GenericMenu(); List<EventActionExtension.ActionMeta> actionList = EventActionExtension.GetList(); foreach (EventActionExtension.ActionMeta currentType in actionList) { var enumType = currentType.ActionType; menu.AddItem( new GUIContent(currentType.Name), false, f => ChangeAction(audioEvent, action, enumType), currentType.ActionType ); } menu.ShowAsContext(); } private static void ChangeAction(InAudioEventNode audioEvent, AudioEventAction action, EventActionTypes newEnumType) { for (int i = 0; i < audioEvent._actionList.Count; ++i) { if (audioEvent._actionList[i] == action) { Type oldType = AudioEventAction.ActionEnumToType(action._eventActionType); Type newType = AudioEventAction.ActionEnumToType(newEnumType); if (oldType != newType) { InUndoHelper.DoInGroup(() => AudioEventWorker.ReplaceActionDestructiveAt(audioEvent, newEnumType, i)); } else { InUndoHelper.RecordObject(action, "Change Event Action Type"); action._eventActionType = newEnumType; } break; } } } private static void ShowCreationContext(InAudioEventNode audioevent) { var menu = new GenericMenu(); List<EventActionExtension.ActionMeta> actionList = EventActionExtension.GetList(); foreach (EventActionExtension.ActionMeta currentType in actionList) { Type newType = AudioEventAction.ActionEnumToType(currentType.ActionType); var enumType = currentType.ActionType; menu.AddItem(new GUIContent(currentType.Name), false, f => AudioEventWorker.AddEventAction(audioevent, newType, enumType), currentType); } menu.ShowAsContext(); } } }
/// Copyright (C) 2012-2014 Soomla Inc. /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. using UnityEngine; using System.Collections; namespace Soomla.Store { /// <summary> /// An upgrade virtual good is one VG in a series of VGs that define an upgrade scale of an /// associated <c>VirtualGood</c>. /// /// This type of virtual good is best explained with an example: /// Let's say there's a strength attribute to one of the characters in your game and that strength is /// on a scale of 1-5. You want to provide your users with the ability to upgrade that strength. /// /// This is what you'll need to create: /// 1. <c>SingleUseVG</c> for 'strength' /// 2. <c>UpgradeVG</c> for strength 'level 1' /// 3. <c>UpgradeVG</c> for strength 'level 2' /// 4. <c>UpgradeVG</c> for strength 'level 3' /// 5. <c>UpgradeVG</c> for strength 'level 4' /// 6. <c>UpgradeVG</c> for strength 'level 5' /// /// When the user buys this <c>UpgradeVG</c>, we check and make sure the appropriate conditions /// are met and buy it for you (which actually means we upgrade the associated <c>VirtualGood</c>). /// /// NOTE: In case you want this item to be available for purchase with real money /// you will need to define the item in the market (App Store, Google Play...). /// /// Inheritance: UpgradeVG > /// <see cref="com.soomla.store.domain.virtualGoods.VirtualGood"/> > /// <see cref="com.soomla.store.domain.PurchasableVirtualItem"/> > /// <see cref="com.soomla.store.domain.VirtualItem"/> /// </summary> public class UpgradeVG : LifetimeVG { private static string TAG = "SOOMLA UpgradeVG"; /// <summary> /// The itemId of the associated <c>VirtualGood</c>. /// </summary> public string GoodItemId; /// <summary> /// The itemId of the <c>UpgradeVG</c> that comes after this one (or null this is the last one) /// </summary> public string NextItemId; /// <summary> /// The itemId of the <c>UpgradeVG</c> that comes before this one (or null this is the first one) /// </summary> public string PrevItemId; /// <summary> /// Constructor. /// </summary> /// <param name="goodItemId">The itemId of the <c>VirtualGood</c> associated with this upgrade.</param> /// <param name="nextItemId">The itemId of the <c>UpgradeVG</c> after, or if this is the last /// <c>UpgradeVG</c> in the scale then the value is null.</param> /// <param name="prevItemId">The itemId of the <c>UpgradeVG</c> before, or if this is the first /// <c>UpgradeVG</c> in the scale then the value is null.</param> /// <param name="name">nName.</param> /// <param name="description">Description.</param> /// <param name="itemId">Item id.</param> /// <param name="purchaseType">Purchase type.</param> public UpgradeVG(string goodItemId, string nextItemId, string prevItemId, string name, string description, string itemId, PurchaseType purchaseType) : base(name, description, itemId, purchaseType) { this.GoodItemId = goodItemId; this.PrevItemId = prevItemId; this.NextItemId = nextItemId; } #if UNITY_WP8 && !UNITY_EDITOR public UpgradeVG(SoomlaWpStore.domain.virtualGoods.UpgradeVG wpUpgradeVG) : base(wpUpgradeVG) { GoodItemId = wpUpgradeVG.getGoodItemId(); NextItemId = wpUpgradeVG.getNextItemId(); PrevItemId = wpUpgradeVG.getPrevItemId(); } #endif /// <summary> /// see parent. /// </summary> public UpgradeVG(JSONObject jsonItem) : base(jsonItem) { GoodItemId = jsonItem[StoreJSONConsts.VGU_GOOD_ITEMID].str; PrevItemId = jsonItem[StoreJSONConsts.VGU_PREV_ITEMID].str; NextItemId = jsonItem[StoreJSONConsts.VGU_NEXT_ITEMID].str; } /// <summary> /// see parent. /// </summary> public override JSONObject toJSONObject() { JSONObject jsonObject = base.toJSONObject(); jsonObject.AddField(StoreJSONConsts.VGU_GOOD_ITEMID, this.GoodItemId); jsonObject.AddField(StoreJSONConsts.VGU_PREV_ITEMID, string.IsNullOrEmpty(this.PrevItemId) ? "" : this.PrevItemId); jsonObject.AddField(StoreJSONConsts.VGU_NEXT_ITEMID, string.IsNullOrEmpty(this.NextItemId) ? "" : this.NextItemId); return jsonObject; } /// <summary> /// Determines if the user is in a state that allows him/her to buy an <code>UpgradeVG</code> /// This method enforces allowing/rejecting of upgrades here so users won't buy them when /// they are not supposed to. /// If you want to give your users free upgrades, use the <code>give</code> function. /// </summary> /// <returns><c>true</c>, if can buy, <c>false</c> otherwise.</returns> protected override bool canBuy() { VirtualGood good = null; try { good = (VirtualGood) StoreInfo.GetItemByItemId(GoodItemId); } catch (VirtualItemNotFoundException) { SoomlaUtils.LogError(TAG, "VirtualGood with itemId: " + GoodItemId + " doesn't exist! Returning NO (can't buy)."); return false; } UpgradeVG upgradeVG = VirtualGoodsStorage.GetCurrentUpgrade(good); return ((upgradeVG == null && string.IsNullOrEmpty(PrevItemId)) || (upgradeVG != null && ((upgradeVG.NextItemId == this.ItemId) || (upgradeVG.PrevItemId == this.ItemId)))) && base.canBuy(); } /// <summary> /// Assigns the current upgrade to the associated <code>VirtualGood</code> (mGood). /// </summary> /// <param name="amount">NOT USED HERE!</param> /// <param name="notify">notify of change in user's balance of current virtual item.</param> public override int Give(int amount, bool notify) { SoomlaUtils.LogDebug(TAG, "Assigning " + Name + " to: " + GoodItemId); VirtualGood good = null; try { good = (VirtualGood) StoreInfo.GetItemByItemId(GoodItemId); } catch (VirtualItemNotFoundException) { SoomlaUtils.LogError(TAG, "VirtualGood with itemId: " + GoodItemId + " doesn't exist! Can't upgrade."); return 0; } VirtualGoodsStorage.AssignCurrentUpgrade(good, this, notify); return base.Give(amount, notify); } /// <summary> /// Takes upgrade from the user, or in other words DOWNGRADES the associated /// <code>VirtualGood</code> (mGood). /// Checks if the current Upgrade is really associated with the <code>VirtualGood</code> and: /// </summary> /// <param name="amount">NOT USED HERE!.</param> /// <param name="notify">see parent.</param> public override int Take(int amount, bool notify) { VirtualGood good = null; try { good = (VirtualGood) StoreInfo.GetItemByItemId(GoodItemId); } catch (VirtualItemNotFoundException) { SoomlaUtils.LogError(TAG, "VirtualGood with itemId: " + GoodItemId + " doesn't exist! Can't downgrade."); return 0; } UpgradeVG upgradeVG = VirtualGoodsStorage.GetCurrentUpgrade(good); // Case: Upgrade is not assigned to this Virtual Good if (upgradeVG != this) { SoomlaUtils.LogError(TAG, "You can't take an upgrade that's not currently assigned." + "The UpgradeVG " + Name + " is not assigned to " + "the VirtualGood: " + good.Name); return 0; } if (!string.IsNullOrEmpty(PrevItemId)) { UpgradeVG prevUpgradeVG = null; // Case: downgrade is not possible because previous upgrade does not exist try { prevUpgradeVG = (UpgradeVG)StoreInfo.GetItemByItemId(PrevItemId); } catch (VirtualItemNotFoundException) { SoomlaUtils.LogError(TAG, "Previous UpgradeVG with itemId: " + PrevItemId + " doesn't exist! Can't downgrade."); return 0; } // Case: downgrade is successful! SoomlaUtils.LogDebug(TAG, "Downgrading " + good.Name + " to: " + prevUpgradeVG.Name); VirtualGoodsStorage.AssignCurrentUpgrade(good, prevUpgradeVG, notify); } // Case: first Upgrade in the series - so we downgrade to NO upgrade. else { SoomlaUtils.LogDebug(TAG, "Downgrading " + good.Name + " to NO-UPGRADE"); VirtualGoodsStorage.RemoveUpgrades(good, notify); } return base.Take(amount, notify); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using TankLib; using TankLib.ExportFormats; using TankLib.STU; using TankLib.STU.Types; using TACTLib.Client; using TACTLib.Client.HandlerArgs; using TACTLib.Container; using TACTLib.Core; using TACTLib.Core.Product.Tank; using TACTLib.Exceptions; namespace CASCEncDump { internal class Program { private static uint BuildVersion; private static string RawIdxDir => $"dump\\{BuildVersion}\\idx\\raw"; private static string RawEncDir => $"dump\\{BuildVersion}\\enc\\raw"; private static string ConvertIdxDir => $"dump\\{BuildVersion}\\idx\\convert"; private static string ConvertEncDir => $"dump\\{BuildVersion}\\enc\\convert"; private static string NonBLTEDir => $"dump\\{BuildVersion}\\nonblte"; private static string KeyFilesDir => $"dump\\{BuildVersion}\\keyfiles"; private static string AllCMFDir => $"dump\\{BuildVersion}\\allcmf"; private static string GUIDDir => $"dump\\{BuildVersion}\\guids"; private static ClientHandler Client; private static ProductHandler_Tank TankHandler; public static void Main(string[] args) { string overwatchDir = args[0]; string mode = args[1]; const string language = "enUS"; // Usage: // {overwatch dir} dump -- Dump hashes // {overwatch dir} compare-enc {other ver num} -- Extract added files from encoding (requires dump from other version) // {overwatch dir} compare-idx {other ver num} -- Extract added files from indices (requires dump from other version) // {overwatch dir} allcmf -- Extract all files from the cmf // casc setup TankLib.TACT.LoadHelper.PreLoad(); ClientCreateArgs createArgs = new ClientCreateArgs { SpeechLanguage = language, TextLanguage = language, Online = false }; if (mode != "allcmf" && mode != "dump-guids" && mode != "compare-guids" && mode != "dump-cmf") { createArgs.HandlerArgs = new ClientCreateArgs_Tank { LoadManifest = false }; } Client = new ClientHandler(overwatchDir, createArgs); TankHandler = (ProductHandler_Tank)Client.ProductHandler; TankLib.TACT.LoadHelper.PostLoad(Client); BuildVersion = uint.Parse(Client.InstallationInfo.Values["Version"].Split('.').Last()); switch (mode) { case "dump": Dump(args); break; case "compare-enc": CompareEnc(args); break; case "compare-idx": CompareIdx(args); break; case "allcmf": AllCMF(args); break; case "dump-guids": DumpGUIDs(args); break; case "compare-guids": CompareGUIDs(args); break; case "dump-cmf": DumpCMF(args); break; default: throw new Exception($"unknown mode: {mode}"); } } private static void DumpCMF(string[] args) { HashSet<CKey> cKeys = new HashSet<CKey>(CASCKeyComparer.Instance); foreach (ContentManifestFile contentManifestFile in new [] {TankHandler.m_rootContentManifest, TankHandler.m_textContentManifest, TankHandler.m_speechContentManifest}) { if (contentManifestFile == null) continue; foreach (ContentManifestFile.HashData hashData in contentManifestFile.m_hashList) { cKeys.Add(hashData.ContentKey); } } Diff.WriteBinaryCKeys($"{BuildVersion}.cmfhashes", cKeys); //Diff.WriteBinaryCKeys(TankHandler, $"{BuildVersion}.cmfhashes", guids); } private static void DumpGUIDs(string[] args) { List<ulong> guids = TankHandler.m_assets.Select(x => x.Key).ToList(); Diff.WriteBinaryGUIDs($"{BuildVersion}.guids", guids); //Diff.WriteTextGUIDs(TankHandler, $"{BuildVersion}.guids", guids); } private static void CompareGUIDs(string[] args) { string otherVerNum = args[2]; Directory.CreateDirectory(GUIDDir); // file name is the version it is compared to HashSet<ulong> last; using (Stream lastStream = File.OpenRead($"{otherVerNum}.guids")) { last = Diff.ReadGUIDs(lastStream); } List<ulong> added = TankHandler.m_assets.Keys.Except(last).ToList(); List<ulong> removed = last.Except(TankHandler.m_assets.Keys).ToList(); using (StreamWriter writer = new StreamWriter(Path.Combine(GUIDDir, $"{otherVerNum}.added"))) { foreach (ulong addedFile in added) { writer.WriteLine(teResourceGUID.AsString(addedFile)); } } using (StreamWriter writer = new StreamWriter(Path.Combine(GUIDDir, $"{otherVerNum}.removed"))) { foreach (ulong removedFile in removed) { writer.WriteLine(teResourceGUID.AsString(removedFile)); } } } private static void AllCMF(string[] args) { ushort[] types = args.Skip(2).Select(x => ushort.Parse(x, NumberStyles.HexNumber)).ToArray(); Directory.CreateDirectory(AllCMFDir); foreach (KeyValuePair<ulong, ProductHandler_Tank.Asset> asset in TankHandler.m_assets) { ushort type = teResourceGUID.Type(asset.Key); if (!types.Contains(type)) continue; try { using (Stream stream = TankHandler.OpenFile(asset.Key)) { if (stream == null) continue; string typeDir = Path.Combine(AllCMFDir, type.ToString("X3")); Directory.CreateDirectory(typeDir); using (Stream file = File.OpenWrite(Path.Combine(typeDir, teResourceGUID.AsString(asset.Key)))) { stream.CopyTo(file); } } } catch (Exception e) { Console.Out.WriteLine(e); } } } private static void Dump(string[] args) { using (StreamWriter writer = new StreamWriter($"{BuildVersion}.enchashes")) { foreach (KeyValuePair<CKey, EncodingHandler.CKeyEntry> entry in Client.EncodingHandler.Entries) { string md5 = entry.Key.ToHexString(); writer.WriteLine(md5); } } using (StreamWriter writer = new StreamWriter($"{BuildVersion}.idxhashes")) { foreach (KeyValuePair<EKey, ContainerHandler.IndexEntry> entry in Client.ContainerHandler.IndexEntries) { string md5 = entry.Key.ToHexString(); writer.WriteLine(md5); } } } private static void CompareIdx(string[] args) { string otherVerNum = args[2]; HashSet<ulong> missingKeys = new HashSet<ulong>(); Directory.CreateDirectory(RawIdxDir); Directory.CreateDirectory(ConvertIdxDir); HashSet<CKey> otherHashes; using (Stream stream = File.OpenRead($"{otherVerNum}.idxhashes")) { otherHashes = Diff.ReadCKeys(stream); } HashSet<EKey> eKeys = new HashSet<EKey>(); foreach (CKey cKey in otherHashes) { eKeys.Add(cKey.AsEKey()); } foreach (KeyValuePair<EKey, ContainerHandler.IndexEntry> indexEntry in Client.ContainerHandler.IndexEntries) { string md5 = indexEntry.Key.ToHexString(); if (!eKeys.Contains(indexEntry.Key)) { try { Stream stream = Client.OpenEKey(indexEntry.Key); TryConvertFile(stream, ConvertIdxDir, md5); stream.Dispose(); } catch (Exception e) { if (e is BLTEKeyException exception) { if (missingKeys.Add(exception.MissingKey)) { Console.Out.WriteLine($"Missing key: {exception.MissingKey:X16}"); } } //else { // Console.Out.WriteLine(e); //} } } } Console.Write("done"); Console.ReadLine(); } private static void CompareEnc(string[] args) { string otherVerNum = args[2]; HashSet<ulong> missingKeys = new HashSet<ulong>(); Directory.CreateDirectory(RawEncDir); Directory.CreateDirectory(ConvertEncDir); string[] otherHashes; using (StreamReader reader = new StreamReader($"{otherVerNum}.enchashes")) { otherHashes = reader.ReadToEnd().Split('\n').Select(x => x.TrimEnd('\r')).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray(); } HashSet<CKey> hashSet = new HashSet<CKey>(CASCKeyComparer.Instance); foreach (CKey hash in otherHashes.Select(CKey.FromString)) { hashSet.Add(hash); } foreach (KeyValuePair<CKey, EncodingHandler.CKeyEntry> entry in Client.EncodingHandler.Entries) { if (hashSet.Contains(entry.Key)) continue; try { Stream stream = Client.OpenCKey(entry.Key); if (stream == null) continue; string md5 = entry.Key.ToHexString(); using (Stream fileStream = File.OpenWrite(Path.Combine(RawEncDir, md5))) { stream.CopyTo(fileStream); } //TryConvertFile(stream, ConvertEncDir, md5); } catch (Exception e) { if (e is BLTEKeyException exception) { if (missingKeys.Add(exception.MissingKey)) { Console.Out.WriteLine($"Missing key: {exception.MissingKey:X16}"); } } else { Console.Out.WriteLine(e); } } } } private static void TryConvertFile(Stream stream, string convertDir, string md5) { using (BinaryReader reader = new BinaryReader(stream, Encoding.UTF8, true)) { uint magic = reader.ReadUInt32(); stream.Position = 0; if (magic == teChunkedData.Magic) { teChunkedData chunkedData = new teChunkedData(reader); if (chunkedData.Header.StringIdentifier == "MODL") { OverwatchModel model = new OverwatchModel(chunkedData, 0); using (Stream file = File.OpenWrite(Path.Combine(convertDir, md5) + ".owmdl")) { file.SetLength(0); model.Write(file); } } } else if (magic == 0x4D4F5649) { // MOVI stream.Position = 128; using (Stream file = File.OpenWrite(Path.Combine(convertDir, md5) + ".bk2")) { file.SetLength(0); stream.CopyTo(file); } } else { // ok might be a heckin bundle /*int i = 0; while (reader.BaseStream.Position < reader.BaseStream.Length) { try { magic = reader.ReadUInt32(); if (magic != teChunkedData.Magic) { reader.BaseStream.Position -= 3; continue; } reader.BaseStream.Position -= 4; teChunkedData chunkedData = new teChunkedData(reader); if (chunkedData.Header.StringIdentifier == "MODL") { OverwatchModel model = new OverwatchModel(chunkedData, 0); using (Stream file = File.OpenWrite(Path.Combine(convertDir, md5) + $"-{i}.owmdl")) { file.SetLength(0); model.Write(file); } } i++; } catch (Exception) { // fine } }*/ try { //teStructuredData structuredData =new teStructuredData(stream, true); teTexture texture = new teTexture(reader); if (!texture.PayloadRequired && texture.Header.DataSize <= stream.Length && (texture.Header.Flags == teTexture.Flags.Tex1D || texture.Header.Flags == teTexture.Flags.Tex2D || texture.Header.Flags == teTexture.Flags.Tex3D || texture.Header.Flags == teTexture.Flags.Cube || texture.Header.Flags == teTexture.Flags.Array || texture.Header.Flags == teTexture.Flags.Unk16 || texture.Header.Flags == teTexture.Flags.Unk32 || texture.Header.Flags == teTexture.Flags.Unk128) && texture.Header.Height < 10000 && texture.Header.Width < 10000 && texture.Header.DataSize > 68) { using (Stream file = File.OpenWrite(Path.Combine(convertDir, md5) + ".dds")) { file.SetLength(0); texture.SaveToDDS(file, false, texture.Header.MipCount); } } } catch (Exception) { // fine } try { stream.Position = 0; teStructuredData structuredData =new teStructuredData(stream, true); if (structuredData.GetInstance<STUResourceKey>() != null) { var key = structuredData.GetInstance<STUResourceKey>(); Console.Out.WriteLine("found key"); var longKey = ulong.Parse(key.m_keyID, NumberStyles.HexNumber); var longRevKey = BitConverter.ToUInt64(BitConverter.GetBytes(longKey).Reverse().ToArray(), 0); var keyValueString = BitConverter.ToString(key.m_key).Replace("-", string.Empty); var keyNameProper = longRevKey.ToString("X16"); Console.Out.WriteLine("Added Encryption Key {0}, Value: {1}",keyNameProper, keyValueString); } // if (structuredData.GetInstance<STUHero>() != null) { // // } } catch (Exception) { // fine } } } } } }
// snippet-sourcedescription:[ ] // snippet-service:[dynamodb] // snippet-keyword:[dotNET] // snippet-keyword:[Amazon DynamoDB] // snippet-keyword:[Code Sample] // snippet-keyword:[ ] // snippet-sourcetype:[full-example] // snippet-sourcedate:[ ] // snippet-sourceauthor:[AWS] // snippet-start:[dynamodb.dotNET.CodeExample.LowLevelGlobalSecondaryIndexExample] /** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * This file is 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/ * * 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. */ using System; using System.Collections.Generic; using System.Linq; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DataModel; using Amazon.DynamoDBv2.DocumentModel; using Amazon.DynamoDBv2.Model; using Amazon.Runtime; using Amazon.SecurityToken; namespace com.amazonaws.codesamples { class LowLevelGlobalSecondaryIndexExample { private static AmazonDynamoDBClient client = new AmazonDynamoDBClient(); public static String tableName = "Issues"; public static void Main(string[] args) { CreateTable(); LoadData(); QueryIndex("CreateDateIndex"); QueryIndex("TitleIndex"); QueryIndex("DueDateIndex"); DeleteTable(tableName); Console.WriteLine("To continue, press enter"); Console.Read(); } private static void CreateTable() { // Attribute definitions var attributeDefinitions = new List<AttributeDefinition>() { {new AttributeDefinition { AttributeName = "IssueId", AttributeType = "S" }}, {new AttributeDefinition { AttributeName = "Title", AttributeType = "S" }}, {new AttributeDefinition { AttributeName = "CreateDate", AttributeType = "S" }}, {new AttributeDefinition { AttributeName = "DueDate", AttributeType = "S" }} }; // Key schema for table var tableKeySchema = new List<KeySchemaElement>() { { new KeySchemaElement { AttributeName= "IssueId", KeyType = "HASH" //Partition key } }, { new KeySchemaElement { AttributeName = "Title", KeyType = "RANGE" //Sort key } } }; // Initial provisioned throughput settings for the indexes var ptIndex = new ProvisionedThroughput { ReadCapacityUnits = 1L, WriteCapacityUnits = 1L }; // CreateDateIndex var createDateIndex = new GlobalSecondaryIndex() { IndexName = "CreateDateIndex", ProvisionedThroughput = ptIndex, KeySchema = { new KeySchemaElement { AttributeName = "CreateDate", KeyType = "HASH" //Partition key }, new KeySchemaElement { AttributeName = "IssueId", KeyType = "RANGE" //Sort key } }, Projection = new Projection { ProjectionType = "INCLUDE", NonKeyAttributes = { "Description", "Status" } } }; // TitleIndex var titleIndex = new GlobalSecondaryIndex() { IndexName = "TitleIndex", ProvisionedThroughput = ptIndex, KeySchema = { new KeySchemaElement { AttributeName = "Title", KeyType = "HASH" //Partition key }, new KeySchemaElement { AttributeName = "IssueId", KeyType = "RANGE" //Sort key } }, Projection = new Projection { ProjectionType = "KEYS_ONLY" } }; // DueDateIndex var dueDateIndex = new GlobalSecondaryIndex() { IndexName = "DueDateIndex", ProvisionedThroughput = ptIndex, KeySchema = { new KeySchemaElement { AttributeName = "DueDate", KeyType = "HASH" //Partition key } }, Projection = new Projection { ProjectionType = "ALL" } }; var createTableRequest = new CreateTableRequest { TableName = tableName, ProvisionedThroughput = new ProvisionedThroughput { ReadCapacityUnits = (long)1, WriteCapacityUnits = (long)1 }, AttributeDefinitions = attributeDefinitions, KeySchema = tableKeySchema, GlobalSecondaryIndexes = { createDateIndex, titleIndex, dueDateIndex } }; Console.WriteLine("Creating table " + tableName + "..."); client.CreateTable(createTableRequest); WaitUntilTableReady(tableName); } private static void LoadData() { Console.WriteLine("Loading data into table " + tableName + "..."); // IssueId, Title, // Description, // CreateDate, LastUpdateDate, DueDate, // Priority, Status putItem("A-101", "Compilation error", "Can't compile Project X - bad version number. What does this mean?", "2013-11-01", "2013-11-02", "2013-11-10", 1, "Assigned"); putItem("A-102", "Can't read data file", "The main data file is missing, or the permissions are incorrect", "2013-11-01", "2013-11-04", "2013-11-30", 2, "In progress"); putItem("A-103", "Test failure", "Functional test of Project X produces errors", "2013-11-01", "2013-11-02", "2013-11-10", 1, "In progress"); putItem("A-104", "Compilation error", "Variable 'messageCount' was not initialized.", "2013-11-15", "2013-11-16", "2013-11-30", 3, "Assigned"); putItem("A-105", "Network issue", "Can't ping IP address 127.0.0.1. Please fix this.", "2013-11-15", "2013-11-16", "2013-11-19", 5, "Assigned"); } private static void putItem( String issueId, String title, String description, String createDate, String lastUpdateDate, String dueDate, Int32 priority, String status) { Dictionary<String, AttributeValue> item = new Dictionary<string, AttributeValue>(); item.Add("IssueId", new AttributeValue { S = issueId }); item.Add("Title", new AttributeValue { S = title }); item.Add("Description", new AttributeValue { S = description }); item.Add("CreateDate", new AttributeValue { S = createDate }); item.Add("LastUpdateDate", new AttributeValue { S = lastUpdateDate }); item.Add("DueDate", new AttributeValue { S = dueDate }); item.Add("Priority", new AttributeValue { N = priority.ToString() }); item.Add("Status", new AttributeValue { S = status }); try { client.PutItem(new PutItemRequest { TableName = tableName, Item = item }); } catch (Exception e) { Console.WriteLine(e.ToString()); } } private static void QueryIndex(string indexName) { Console.WriteLine ("\n***********************************************************\n"); Console.WriteLine("Querying index " + indexName + "..."); QueryRequest queryRequest = new QueryRequest { TableName = tableName, IndexName = indexName, ScanIndexForward = true }; String keyConditionExpression; Dictionary<string, AttributeValue> expressionAttributeValues = new Dictionary<string, AttributeValue>(); if (indexName == "CreateDateIndex") { Console.WriteLine("Issues filed on 2013-11-01\n"); keyConditionExpression = "CreateDate = :v_date and begins_with(IssueId, :v_issue)"; expressionAttributeValues.Add(":v_date", new AttributeValue { S = "2013-11-01" }); expressionAttributeValues.Add(":v_issue", new AttributeValue { S = "A-" }); } else if (indexName == "TitleIndex") { Console.WriteLine("Compilation errors\n"); keyConditionExpression = "Title = :v_title and begins_with(IssueId, :v_issue)"; expressionAttributeValues.Add(":v_title", new AttributeValue { S = "Compilation error" }); expressionAttributeValues.Add(":v_issue", new AttributeValue { S = "A-" }); // Select queryRequest.Select = "ALL_PROJECTED_ATTRIBUTES"; } else if (indexName == "DueDateIndex") { Console.WriteLine("Items that are due on 2013-11-30\n"); keyConditionExpression = "DueDate = :v_date"; expressionAttributeValues.Add(":v_date", new AttributeValue { S = "2013-11-30" }); // Select queryRequest.Select = "ALL_PROJECTED_ATTRIBUTES"; } else { Console.WriteLine("\nNo valid index name provided"); return; } queryRequest.KeyConditionExpression = keyConditionExpression; queryRequest.ExpressionAttributeValues = expressionAttributeValues; var result = client.Query(queryRequest); var items = result.Items; foreach (var currentItem in items) { foreach (string attr in currentItem.Keys) { if (attr == "Priority") { Console.WriteLine(attr + "---> " + currentItem[attr].N); } else { Console.WriteLine(attr + "---> " + currentItem[attr].S); } } Console.WriteLine(); } } private static void DeleteTable(string tableName) { Console.WriteLine("Deleting table " + tableName + "..."); client.DeleteTable(new DeleteTableRequest { TableName = tableName }); WaitForTableToBeDeleted(tableName); } private static void WaitUntilTableReady(string tableName) { string status = null; // Let us wait until table is created. Call DescribeTable. do { System.Threading.Thread.Sleep(5000); // Wait 5 seconds. try { var res = client.DescribeTable(new DescribeTableRequest { TableName = tableName }); Console.WriteLine("Table name: {0}, status: {1}", res.Table.TableName, res.Table.TableStatus); status = res.Table.TableStatus; } catch (ResourceNotFoundException) { // DescribeTable is eventually consistent. So you might // get resource not found. So we handle the potential exception. } } while (status != "ACTIVE"); } private static void WaitForTableToBeDeleted(string tableName) { bool tablePresent = true; while (tablePresent) { System.Threading.Thread.Sleep(5000); // Wait 5 seconds. try { var res = client.DescribeTable(new DescribeTableRequest { TableName = tableName }); Console.WriteLine("Table name: {0}, status: {1}", res.Table.TableName, res.Table.TableStatus); } catch (ResourceNotFoundException) { tablePresent = false; } } } } } // snippet-end:[dynamodb.dotNET.CodeExample.LowLevelGlobalSecondaryIndexExample]
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Microsoft.Extensions.Configuration; using Serilog.Configuration; namespace Serilog.Settings.Configuration { class ObjectArgumentValue : IConfigurationArgumentValue { readonly IConfigurationSection _section; readonly IReadOnlyCollection<Assembly> _configurationAssemblies; public ObjectArgumentValue(IConfigurationSection section, IReadOnlyCollection<Assembly> configurationAssemblies) { _section = section ?? throw new ArgumentNullException(nameof(section)); // used by nested logger configurations to feed a new pass by ConfigurationReader _configurationAssemblies = configurationAssemblies ?? throw new ArgumentNullException(nameof(configurationAssemblies)); } public object ConvertTo(Type toType, ResolutionContext resolutionContext) { // return the entire section for internal processing if (toType == typeof(IConfigurationSection)) return _section; // process a nested configuration to populate an Action<> logger/sink config parameter? var typeInfo = toType.GetTypeInfo(); if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() is Type genericType && genericType == typeof(Action<>)) { var configType = typeInfo.GenericTypeArguments[0]; IConfigurationReader configReader = new ConfigurationReader(_section, _configurationAssemblies, resolutionContext); return configType switch { _ when configType == typeof(LoggerConfiguration) => new Action<LoggerConfiguration>(configReader.Configure), _ when configType == typeof(LoggerSinkConfiguration) => new Action<LoggerSinkConfiguration>(configReader.ApplySinks), _ when configType == typeof(LoggerEnrichmentConfiguration) => new Action<LoggerEnrichmentConfiguration>(configReader.ApplyEnrichment), _ => throw new ArgumentException($"Configuration resolution for Action<{configType.Name}> parameter type at the path {_section.Path} is not implemented.") }; } if (toType.IsArray) return CreateArray(); if (IsContainer(toType, out var elementType) && TryCreateContainer(out var result)) return result; if (TryBuildCtorExpression(_section, toType, resolutionContext, out var ctorExpression)) { return Expression.Lambda<Func<object>>(ctorExpression).Compile().Invoke(); } // MS Config binding can work with a limited set of primitive types and collections return _section.Get(toType); object CreateArray() { var elementType = toType.GetElementType(); var configurationElements = _section.GetChildren().ToArray(); var result = Array.CreateInstance(elementType, configurationElements.Length); for (int i = 0; i < configurationElements.Length; ++i) { var argumentValue = ConfigurationReader.GetArgumentValue(configurationElements[i], _configurationAssemblies); var value = argumentValue.ConvertTo(elementType, resolutionContext); result.SetValue(value, i); } return result; } bool TryCreateContainer(out object result) { result = null; if (toType.GetConstructor(Type.EmptyTypes) == null) return false; // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers#collection-initializers var addMethod = toType.GetMethods().FirstOrDefault(m => !m.IsStatic && m.Name == "Add" && m.GetParameters()?.Length == 1 && m.GetParameters()[0].ParameterType == elementType); if (addMethod == null) return false; var configurationElements = _section.GetChildren().ToArray(); result = Activator.CreateInstance(toType); for (int i = 0; i < configurationElements.Length; ++i) { var argumentValue = ConfigurationReader.GetArgumentValue(configurationElements[i], _configurationAssemblies); var value = argumentValue.ConvertTo(elementType, resolutionContext); addMethod.Invoke(result, new object[] { value }); } return true; } } internal static bool TryBuildCtorExpression( IConfigurationSection section, Type parameterType, ResolutionContext resolutionContext, out NewExpression ctorExpression) { ctorExpression = null; var typeDirective = section.GetValue<string>("$type") switch { not null => "$type", null => section.GetValue<string>("type") switch { not null => "type", null => null, }, }; var type = typeDirective switch { not null => Type.GetType(section.GetValue<string>(typeDirective), throwOnError: false), null => parameterType, }; if (type is null or { IsAbstract: true }) { return false; } var suppliedArguments = section.GetChildren().Where(s => s.Key != typeDirective) .ToDictionary(s => s.Key, StringComparer.OrdinalIgnoreCase); if (suppliedArguments.Count == 0 && type.GetConstructor(Type.EmptyTypes) is ConstructorInfo parameterlessCtor) { ctorExpression = Expression.New(parameterlessCtor); return true; } var ctor = (from c in type.GetConstructors() from p in c.GetParameters() let argumentBindResult = suppliedArguments.TryGetValue(p.Name, out var argValue) switch { true => new { success = true, hasMatch = true, value = (object)argValue }, false => p.HasDefaultValue switch { true => new { success = true, hasMatch = false, value = p.DefaultValue }, false => new { success = false, hasMatch = false, value = (object)null }, }, } group new { argumentBindResult, p.ParameterType } by c into gr where gr.All(z => z.argumentBindResult.success) let matchedArgs = gr.Where(z => z.argumentBindResult.hasMatch).ToList() orderby matchedArgs.Count descending, matchedArgs.Count(p => p.ParameterType == typeof(string)) descending select new { ConstructorInfo = gr.Key, ArgumentValues = gr.Select(z => new { Value = z.argumentBindResult.value, Type = z.ParameterType }) .ToList() }).FirstOrDefault(); if (ctor is null) { return false; } var ctorArguments = new List<Expression>(); foreach (var argumentValue in ctor.ArgumentValues) { if (TryBindToCtorArgument(argumentValue.Value, argumentValue.Type, resolutionContext, out var argumentExpression)) { ctorArguments.Add(argumentExpression); } else { return false; } } ctorExpression = Expression.New(ctor.ConstructorInfo, ctorArguments); return true; static bool TryBindToCtorArgument(object value, Type type, ResolutionContext resolutionContext, out Expression argumentExpression) { argumentExpression = null; if (value is IConfigurationSection s) { if (s.Value is string argValue) { var stringArgumentValue = new StringArgumentValue(argValue); try { argumentExpression = Expression.Constant( stringArgumentValue.ConvertTo(type, resolutionContext), type); return true; } catch (Exception) { return false; } } else if (s.GetChildren().Any()) { if (TryBuildCtorExpression(s, type, resolutionContext, out var ctorExpression)) { argumentExpression = ctorExpression; return true; } return false; } } argumentExpression = Expression.Constant(value, type); return true; } } static bool IsContainer(Type type, out Type elementType) { elementType = null; foreach (var iface in type.GetInterfaces()) { if (iface.IsGenericType) { if (iface.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { elementType = iface.GetGenericArguments()[0]; return true; } } } return false; } } }
using UnityEngine; using System; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; #endif // TODO: Have a move list in the inspector instead of order value [AddComponentMenu("Modifiers/Modify Object")] [ExecuteInEditMode] public class MegaModifyObject : MegaModifiers { [HideInInspector] public Mesh cachedMesh; public bool InvisibleUpdate = false; bool visible = true; int restorekeep = 0; private static int CompareOrder(MegaModifier m1, MegaModifier m2) { return m1.Order - m2.Order; } [ContextMenu("Resort")] public virtual void Resort() { BuildList(); } [ContextMenu("Help")] public virtual void Help() { Application.OpenURL("http://www.west-racing.com/mf/?page_id=444"); } [ContextMenu("Remove Modify Object (Keep deformed mesh)")] public virtual void RemoveKeep() { MegaModifier[] mods = GetComponents<MegaModifier>(); for ( int i = 0; i < mods.Length; i++ ) { if ( Application.isEditor ) DestroyImmediate(mods[i]); else Destroy(mods[i]); } restorekeep = 1; if ( Application.isEditor ) DestroyImmediate(this); else Destroy(this); } [ContextMenu("Remove Modify Object (Restore Mesh)")] public virtual void RemoveRestore() { MegaModifier[] mods = GetComponents<MegaModifier>(); for ( int i = 0; i < mods.Length; i++ ) { if ( Application.isEditor ) DestroyImmediate(mods[i]); else Destroy(mods[i]); } restorekeep = 2; if ( Application.isEditor ) DestroyImmediate(this); else Destroy(this); } void OnDestroy() { if ( mesh != cachedMesh ) { if ( restorekeep == 0 || restorekeep == 2 ) { if ( !SetMeshNew(gameObject, cachedMesh) ) { if ( Application.isEditor ) DestroyImmediate(mesh); else Destroy(mesh); } } } } void Start() { if ( dynamicMesh ) cachedMesh = null; } void OnRenderObject() { if ( UpdateMode == MegaUpdateMode.OnRender ) { ModifyObjectMT(); } } public void GetMesh(bool force) { if ( mesh == null || cachedMesh == null || sverts.Length == 0 || mesh.vertexCount != sverts.Length || force ) { if ( dynamicMesh ) { cachedMesh = FindMesh(gameObject, out sourceObj); mesh = cachedMesh; if ( mesh.vertexCount != 0 ) SetMeshData(); } else { cachedMesh = FindMesh(gameObject, out sourceObj); mesh = MegaCopyObject.DupMesh(cachedMesh, ""); SetMesh(gameObject, mesh); if ( mesh.vertexCount != 0 ) SetMeshData(); } } } void SetMeshData() { bbox = cachedMesh.bounds; sverts = new Vector3[cachedMesh.vertexCount]; verts = cachedMesh.vertices; uvs = cachedMesh.uv; suvs = new Vector2[cachedMesh.uv.Length]; cols = cachedMesh.colors; //BuildNormalMapping(cachedMesh, false); mods = GetComponents<MegaModifier>(); Array.Sort(mods, CompareOrder); for ( int i = 0; i < mods.Length; i++ ) { if ( mods[i] != null ) { mods[i].SetModMesh(mesh); mods[i].ModStart(this); // Some mods like push error if we dont do this, put in error check and disable } } mapping = null; UpdateMesh = -1; } public void ModReset(MegaModifier m) { if ( m != null ) { m.SetModMesh(cachedMesh); BuildList(); } } // Check, do we need these? void Update() { GetMesh(false); if ( visible || InvisibleUpdate ) { if ( UpdateMode == MegaUpdateMode.Update ) ModifyObjectMT(); } } void LateUpdate() { if ( visible || InvisibleUpdate ) { if ( UpdateMode == MegaUpdateMode.LateUpdate ) ModifyObjectMT(); } } void OnBecameVisible() { visible = true; } void OnBecameInvisible() { visible = false; } [ContextMenu("Reset")] public void Reset() { ResetMeshInfo(); } // Mesh related stuff [ContextMenu("Reset Mesh Info")] public void ResetMeshInfo() { if ( mods != null ) { if ( mods.Length > 0 ) { mesh.vertices = mods[0].verts; //_verts; // mesh.vertices = GetVerts(true); } mesh.uv = uvs; //GetUVs(true); if ( recalcnorms ) RecalcNormals(); if ( recalcbounds ) mesh.RecalculateBounds(); } #if false if ( cachedMesh == null ) cachedMesh = (Mesh)Mesh.Instantiate(FindMesh(gameObject, out sourceObj)); GetMeshData(false); mesh.vertices = verts; //_verts; // mesh.vertices = GetVerts(true); mesh.uv = uvs; //GetUVs(true); if ( recalcnorms ) RecalcNormals(); if ( recalcbounds ) mesh.RecalculateBounds(); #endif } #if false void Reset() { if ( cachedMesh == null ) cachedMesh = (Mesh)Mesh.Instantiate(FindMesh(gameObject, out sourceObj)); BuildList(); ReStart1(true); } #endif // Called by my scripts when the mesh has changed public void MeshUpdated() { GetMesh(true); //cachedMesh = (Mesh)Mesh.Instantiate(FindMesh(gameObject, out sourceObj)); //GetMeshData(true); foreach ( MegaModifier mod in mods ) // Added back in? mod.SetModMesh(cachedMesh); } // Replace mesh data with data from newmesh, called from scripts not used internally public void MeshChanged(Mesh newmesh) { if ( mesh ) { mesh.vertices = newmesh.vertices; mesh.normals = newmesh.normals; mesh.uv = newmesh.uv; #if UNITY_5_0 || UNITY_5_1 || UNITY_5 || UNITY_2017 mesh.uv2 = newmesh.uv2; mesh.uv3 = newmesh.uv3; mesh.uv4 = newmesh.uv4; #else mesh.uv1 = newmesh.uv1; mesh.uv2 = newmesh.uv2; #endif mesh.colors = newmesh.colors; mesh.tangents = newmesh.tangents; mesh.subMeshCount = newmesh.subMeshCount; for ( int i = 0; i < newmesh.subMeshCount; i++ ) mesh.SetTriangles(newmesh.GetTriangles(i), i); bbox = newmesh.bounds; sverts = new Vector3[mesh.vertexCount]; verts = mesh.vertices; uvs = mesh.uv; suvs = new Vector2[mesh.uv.Length]; cols = mesh.colors; //BuildNormalMapping(cachedMesh, false); mods = GetComponents<MegaModifier>(); Array.Sort(mods, CompareOrder); foreach ( MegaModifier mod in mods ) { if ( mod != null ) { mod.SetModMesh(newmesh); mod.ModStart(this); // Some mods like push error if we dont do this, put in error check and disable } } mapping = null; UpdateMesh = -1; } } #if false public void GetMeshData(bool force) { if ( force || mesh == null ) mesh = FindMesh1(gameObject, out sourceObj); //Utils.GetMesh(gameObject); // Do we use mesh anymore if ( mesh != null ) // was mesh { bbox = cachedMesh.bounds; sverts = new Vector3[cachedMesh.vertexCount]; verts = cachedMesh.vertices; uvs = cachedMesh.uv; suvs = new Vector2[cachedMesh.uv.Length]; cols = cachedMesh.colors; //BuildNormalMapping(cachedMesh, false); mods = GetComponents<MegaModifier>(); Array.Sort(mods, CompareOrder); for ( int i = 0; i < mods.Length; i++ ) { if ( mods[i] != null ) mods[i].ModStart(this); // Some mods like push error if we dont do this, put in error check and disable } } UpdateMesh = -1; } #endif public void SetMesh(GameObject go, Mesh mesh) { if ( go ) { Transform[] trans = (Transform[])go.GetComponentsInChildren<Transform>(true); for ( int i = 0; i < trans.Length; i++ ) { MeshFilter mf = (MeshFilter)trans[i].GetComponent<MeshFilter>(); if ( mf ) { mf.sharedMesh = mesh; return; } SkinnedMeshRenderer skin = (SkinnedMeshRenderer)trans[i].GetComponent<SkinnedMeshRenderer>(); if ( skin ) { skin.sharedMesh = mesh; return; } } } } static public Mesh FindMesh(GameObject go, out GameObject obj) { if ( go ) { Transform[] trans = (Transform[])go.GetComponentsInChildren<Transform>(true); for ( int i = 0; i < trans.Length; i++ ) { MeshFilter mf = (MeshFilter)trans[i].GetComponent<MeshFilter>(); if ( mf ) { if ( mf.gameObject != go ) obj = mf.gameObject; else obj = null; return mf.sharedMesh; } SkinnedMeshRenderer skin = (SkinnedMeshRenderer)trans[i].GetComponent<SkinnedMeshRenderer>(); if ( skin ) { if ( skin.gameObject != go ) obj = skin.gameObject; else obj = null; return skin.sharedMesh; } } } obj = null; return null; } static public bool SetMeshNew(GameObject go, Mesh m) { if ( go ) { Transform[] trans = (Transform[])go.GetComponentsInChildren<Transform>(true); for ( int i = 0; i < trans.Length; i++ ) { MeshFilter mf = (MeshFilter)trans[i].GetComponent<MeshFilter>(); if ( mf ) { mf.sharedMesh = m; return true; } SkinnedMeshRenderer skin = (SkinnedMeshRenderer)trans[i].GetComponent<SkinnedMeshRenderer>(); if ( skin ) { skin.sharedMesh = m; return true; } } } return false; } #if false public Mesh FindMesh1(GameObject go, out GameObject obj) { if ( go ) { MeshFilter[] filters = (MeshFilter[])go.GetComponentsInChildren<MeshFilter>(true); if ( filters.Length > 0 ) { if ( filters[0].gameObject != go ) obj = filters[0].gameObject; else obj = null; return filters[0].mesh; } SkinnedMeshRenderer[] skins = (SkinnedMeshRenderer[])go.GetComponentsInChildren<SkinnedMeshRenderer>(true); if ( skins.Length > 0 ) { if ( skins[0].gameObject != go ) obj = skins[0].gameObject; else obj = null; return skins[0].sharedMesh; } } obj = null; return null; } #endif #if false void RestoreMesh(GameObject go, Mesh mesh) { if ( go ) { MeshFilter[] filters = (MeshFilter[])go.GetComponentsInChildren<MeshFilter>(true); if ( filters.Length > 0 ) { filters[0].sharedMesh = (Mesh)Instantiate(mesh); return; } SkinnedMeshRenderer[] skins = (SkinnedMeshRenderer[])go.GetComponentsInChildren<SkinnedMeshRenderer>(true); if ( skins.Length > 0 ) { skins[0].sharedMesh = (Mesh)Instantiate(mesh); return; } } } #endif }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: AddInToken ** ** Purpose: Represents a valid combination of add-ins and ** associated classes, like host adaptors, etc. ** ===========================================================*/ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Security.Permissions; using System.Security; using System.Text; using System.AddIn.MiniReflection; using System.Diagnostics.Contracts; using TypeInfo=System.AddIn.MiniReflection.TypeInfo; namespace System.AddIn.Hosting { [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming","CA1710:IdentifiersShouldHaveCorrectSuffix", Justification="Need approval for API change")] public sealed class AddInToken : IEnumerable<QualificationDataItem> { internal readonly TypeInfo[] _hostAddinViews; internal readonly HostAdapter _hostAdapter; internal readonly ContractComponent _contract; internal readonly AddInAdapter _addinAdapter; internal readonly AddInBase _addinBase; internal readonly AddIn _addin; private String _pipelineRootDir; private String _addInRootDir; private TypeInfo _resolvedHostAddinView; // Two representations of the qualification data. Anders says both may be needed. private IDictionary<AddInSegmentType, IDictionary<String, String>> _qualificationData; private List<QualificationDataItem> _qualificationDataItems; private static volatile bool _enableDirectConnect; public static bool EnableDirectConnect { get { return _enableDirectConnect; } set { _enableDirectConnect = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This read only collection is easy to use.")] public IDictionary<AddInSegmentType, IDictionary<String, String>> QualificationData { get { if (_qualificationData == null) { Dictionary<AddInSegmentType, IDictionary<String, String>> dictionary = new Dictionary<AddInSegmentType, IDictionary<String, String>>(); dictionary[AddInSegmentType.HostViewOfAddIn] = PipelineComponent.s_emptyDictionary; dictionary[AddInSegmentType.HostSideAdapter] = _hostAdapter.QualificationData; dictionary[AddInSegmentType.Contract] = _contract.QualificationData; dictionary[AddInSegmentType.AddInSideAdapter] = _addinAdapter.QualificationData; dictionary[AddInSegmentType.AddInView] = _addinBase.QualificationData; dictionary[AddInSegmentType.AddIn] = _addin.QualificationData; _qualificationData = new ReadOnlyDictionary<AddInSegmentType, IDictionary<String, String>>(dictionary); } return _qualificationData; } } // Needed for IEnumerable interface System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } // Useful for LINQ queries public IEnumerator<QualificationDataItem> GetEnumerator() { if (_qualificationDataItems == null) { _qualificationDataItems = new List<QualificationDataItem>(); for (AddInSegmentType t = AddInSegmentType.HostSideAdapter; t <= AddInSegmentType.AddIn; t++) { IDictionary<String, String> pairs = QualificationData[t]; foreach (KeyValuePair<String, String> pair in pairs) { QualificationDataItem item = new QualificationDataItem(t, pair.Key, pair.Value); _qualificationDataItems.Add(item); } } } return _qualificationDataItems.GetEnumerator(); } internal bool HasQualificationDataOnPipeline { get { for (AddInSegmentType t = AddInSegmentType.HostSideAdapter; t <= AddInSegmentType.AddInView; t++) { IDictionary<String, String> pairs = QualificationData[t]; if (pairs.Count != 0) return true; } return false; } } // The FullName of the addin type, not the "name" specified in the attribute. // This may be used to uniquely identify the addin. public String AddInFullName { get { return _addin.FullName; } } internal AddInToken(HostAdapter hostAdapter, ContractComponent contract, AddInAdapter addinAdapter, AddInBase addinBase, AddIn addin) { System.Diagnostics.Contracts.Contract.Requires(hostAdapter != null); System.Diagnostics.Contracts.Contract.Requires(contract != null); System.Diagnostics.Contracts.Contract.Requires(addinAdapter != null); System.Diagnostics.Contracts.Contract.Requires(addinBase != null); System.Diagnostics.Contracts.Contract.Requires(addin != null); _hostAddinViews = hostAdapter.HostAddinViews; _hostAdapter = hostAdapter; _contract = contract; _addinAdapter = addinAdapter; _addinBase = addinBase; _addin = addin; // _pipelineRootDir must be filled in after deserialization. } internal TypeInfo ResolvedHostAddInView { /* [Pure] get { return _resolvedHostAddinView; } */ set { System.Diagnostics.Contracts.Contract.Requires(value != null); System.Diagnostics.Contracts.Contract.Assert(AddInStore.Contains(_hostAddinViews, value)); _resolvedHostAddinView = value; } } internal String PipelineRootDirectory { [Pure] get { return _pipelineRootDir; } set { System.Diagnostics.Contracts.Contract.Requires(value != null); _pipelineRootDir = value; // Update the paths for each add-in model component. _hostAdapter.SetRootDirectory(_pipelineRootDir); _contract.SetRootDirectory(_pipelineRootDir); _addinAdapter.SetRootDirectory(_pipelineRootDir); _addinBase.SetRootDirectory(_pipelineRootDir); } } internal String AddInRootDirectory { set { System.Diagnostics.Contracts.Contract.Requires(value != null); _addInRootDir = value; _addin.SetRootDirectory(_addInRootDir); } } public String Name { get { return _addin.AddInName; } } public String Publisher { get { return _addin.Publisher; } } public String Version { get { return _addin.Version; } } public String Description { get { return _addin.Description; } } public override String ToString() { return _addin.AddInName; } public AssemblyName AssemblyName { get { return _addin.AssemblyName; } } internal TypeInfo[] HostAddinViews { get { return _hostAddinViews; } } internal String HostViewId { get { return _resolvedHostAddinView.FullName + " " + _addin.RelativeLocation + " " + _addin.TypeInfo.FullName; } } // base identity on the addin itself. This way, if a host // asks for addins for multiple HAV's, he can easily identify // addins that match for more than one HAV. public override bool Equals(object obj) { AddInToken thatToken = obj as AddInToken; if (thatToken != null) { return this.Equals(thatToken); } return false; } bool Equals(AddInToken addInToken) { // perf optimization. Check pointers. if (Object.ReferenceEquals(this, addInToken)) return true; if (_hostAdapter.TypeInfo.AssemblyQualifiedName == addInToken._hostAdapter.TypeInfo.AssemblyQualifiedName && _contract.TypeInfo.AssemblyQualifiedName == addInToken._contract.TypeInfo.AssemblyQualifiedName && _addinAdapter.TypeInfo.AssemblyQualifiedName == addInToken._addinAdapter.TypeInfo.AssemblyQualifiedName && _addinBase.TypeInfo.AssemblyQualifiedName == addInToken._addinBase.TypeInfo.AssemblyQualifiedName && _addin.TypeInfo.AssemblyQualifiedName == addInToken._addin.TypeInfo.AssemblyQualifiedName) return true; return false; } public override int GetHashCode() { // the TypeInfos base their hash codes on their AssemblyQualifiedNames, so we can use those return unchecked(_hostAdapter.TypeInfo.GetHashCode() + _contract.TypeInfo.GetHashCode() + _addinAdapter.TypeInfo.GetHashCode() + _addinBase.TypeInfo.GetHashCode() + _addin.TypeInfo.GetHashCode()); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Factory Method")] public T Activate<T>(AddInSecurityLevel trustLevel) { return AddInActivator.Activate<T>(this, trustLevel); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Factory Method")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming","CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId="appDomain")] public T Activate<T>(AddInSecurityLevel trustLevel, String appDomainName) { return AddInActivator.Activate<T>(this, trustLevel, appDomainName); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Factory Method")] public T Activate<T>(AppDomain target) { if (target != AppDomain.CurrentDomain && !Utils.HasFullTrust()) { throw new SecurityException(Res.PartialTrustCannotActivate); } return AddInActivator.Activate<T>(this, target); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")] public T Activate<T>(PermissionSet permissions) { if (permissions == null) throw new ArgumentNullException("permissions"); System.Diagnostics.Contracts.Contract.EndContractBlock(); return AddInActivator.Activate<T>(this, permissions); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")] [PermissionSet(SecurityAction.Demand, Name="FullTrust")] [SecuritySafeCritical] public T Activate<T>(AddInProcess process, PermissionSet permissionSet) { return AddInActivator.Activate<T>(this, process, permissionSet); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification="Factory Method")] [PermissionSet(SecurityAction.Demand, Name="FullTrust")] [SecuritySafeCritical] public T Activate<T>(AddInProcess process, AddInSecurityLevel level) { return AddInActivator.Activate<T>(this, process, level); } // no full-trust demand here because the environment may be local [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification="Factory method")] public T Activate<T>(AddInEnvironment environment) { return AddInActivator.Activate<T>(this, environment); } // The loader may load assemblies from the wrong place in certain cases. // We need to warn people. // 1. Contracts is not in AddInAdapter directory // 2. AddInView is not in AddInAdapter directory // 3. AddInView is not in AddIn directory // 4. Contracts is not in HostSideAdapter directory // // At discovery time, rootDir is passed in. // At activation time, it is not needed. internal bool HasDuplicatedAssemblies(String rootDir, Collection<String> warnings) { PipelineComponent[] componentsAndDependents = new PipelineComponent[] { _contract, _addinAdapter, _addinBase, _addinAdapter, _addinBase, _addin, _contract, _hostAdapter}; bool duplicates = false; for(int i = 0; i < componentsAndDependents.Length; i+=2) { if (ComponentInWrongLocation(componentsAndDependents[i], componentsAndDependents[i+1], rootDir, warnings)) duplicates = true; } return duplicates; } private bool ComponentInWrongLocation(PipelineComponent component, PipelineComponent dependentComponent, String rootDir, Collection<String> warnings) { System.Diagnostics.Contracts.Contract.Requires(rootDir != null || PipelineRootDirectory != null); string dependentPath = rootDir == null ? dependentComponent.Location : Path.Combine(rootDir, dependentComponent.Location); String fileName = Path.GetFileName(component.Location); String location = Path.GetDirectoryName(dependentPath); if (File.Exists(Path.Combine(location, fileName))) { warnings.Add(String.Format(CultureInfo.CurrentCulture, Res.ComponentInWrongLocation, fileName, location)); return true; } return false; } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Archiver.Codecs { public class AuthConnectRequestDecoder { public const ushort BLOCK_LENGTH = 16; public const ushort TEMPLATE_ID = 58; public const ushort SCHEMA_ID = 101; public const ushort SCHEMA_VERSION = 6; private AuthConnectRequestDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public AuthConnectRequestDecoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public AuthConnectRequestDecoder Wrap( IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { this._buffer = buffer; this._offset = offset; this._actingBlockLength = actingBlockLength; this._actingVersion = actingVersion; Limit(offset + actingBlockLength); return this; } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int CorrelationIdId() { return 1; } public static int CorrelationIdSinceVersion() { return 0; } public static int CorrelationIdEncodingOffset() { return 0; } public static int CorrelationIdEncodingLength() { return 8; } public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public long CorrelationId() { return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian); } public static int ResponseStreamIdId() { return 2; } public static int ResponseStreamIdSinceVersion() { return 0; } public static int ResponseStreamIdEncodingOffset() { return 8; } public static int ResponseStreamIdEncodingLength() { return 4; } public static string ResponseStreamIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int ResponseStreamIdNullValue() { return -2147483648; } public static int ResponseStreamIdMinValue() { return -2147483647; } public static int ResponseStreamIdMaxValue() { return 2147483647; } public int ResponseStreamId() { return _buffer.GetInt(_offset + 8, ByteOrder.LittleEndian); } public static int VersionId() { return 3; } public static int VersionSinceVersion() { return 0; } public static int VersionEncodingOffset() { return 12; } public static int VersionEncodingLength() { return 4; } public static string VersionMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "optional"; } return ""; } public static int VersionNullValue() { return 0; } public static int VersionMinValue() { return 2; } public static int VersionMaxValue() { return 16777215; } public int Version() { return _buffer.GetInt(_offset + 12, ByteOrder.LittleEndian); } public static int ResponseChannelId() { return 4; } public static int ResponseChannelSinceVersion() { return 0; } public static string ResponseChannelCharacterEncoding() { return "US-ASCII"; } public static string ResponseChannelMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int ResponseChannelHeaderLength() { return 4; } public int ResponseChannelLength() { int limit = _parentMessage.Limit(); return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); } public int GetResponseChannel(IMutableDirectBuffer dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public int GetResponseChannel(byte[] dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public string ResponseChannel() { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); _parentMessage.Limit(limit + headerLength + dataLength); byte[] tmp = new byte[dataLength]; _buffer.GetBytes(limit + headerLength, tmp, 0, dataLength); return Encoding.ASCII.GetString(tmp); } public static int EncodedCredentialsId() { return 5; } public static int EncodedCredentialsSinceVersion() { return 0; } public static string EncodedCredentialsMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int EncodedCredentialsHeaderLength() { return 4; } public int EncodedCredentialsLength() { int limit = _parentMessage.Limit(); return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); } public int GetEncodedCredentials(IMutableDirectBuffer dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public int GetEncodedCredentials(byte[] dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[AuthConnectRequest](sbeTemplateId="); builder.Append(TEMPLATE_ID); builder.Append("|sbeSchemaId="); builder.Append(SCHEMA_ID); builder.Append("|sbeSchemaVersion="); if (_parentMessage._actingVersion != SCHEMA_VERSION) { builder.Append(_parentMessage._actingVersion); builder.Append('/'); } builder.Append(SCHEMA_VERSION); builder.Append("|sbeBlockLength="); if (_actingBlockLength != BLOCK_LENGTH) { builder.Append(_actingBlockLength); builder.Append('/'); } builder.Append(BLOCK_LENGTH); builder.Append("):"); //Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("CorrelationId="); builder.Append(CorrelationId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='responseStreamId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("ResponseStreamId="); builder.Append(ResponseStreamId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='version', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=12, componentTokenCount=3, encoding=Encoding{presence=OPTIONAL, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='version_t', referencedName='null', description='Protocol suite version using semantic version form.', id=-1, version=0, deprecated=0, encodedLength=4, offset=12, componentTokenCount=1, encoding=Encoding{presence=OPTIONAL, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=2, maxValue=16777215, nullValue=0, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("Version="); builder.Append(Version()); builder.Append('|'); //Token{signal=BEGIN_VAR_DATA, name='responseChannel', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("ResponseChannel="); builder.Append(ResponseChannel()); builder.Append('|'); //Token{signal=BEGIN_VAR_DATA, name='encodedCredentials', referencedName='null', description='null', id=5, version=0, deprecated=0, encodedLength=0, offset=-1, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("EncodedCredentials="); builder.Append(EncodedCredentialsLength() + " raw bytes"); Limit(originalLimit); return builder; } } }
//------------------------------------------------------------------------------ // <copyright file="RegexGroupCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ // The GroupCollection lists the captured Capture numbers // contained in a compiled Regex. namespace System.Text.RegularExpressions { using System.Collections; using System.Collections.Generic; /// <devdoc> /// <para> /// Represents a sequence of capture substrings. The object is used /// to return the set of captures done by a single capturing group. /// </para> /// </devdoc> #if !SILVERLIGHT [ Serializable() ] #endif public class GroupCollection : ICollection { internal Match _match; #if SILVERLIGHT internal Dictionary<Int32, Int32> _captureMap; #else internal Hashtable _captureMap; #endif // cache of Group objects fed to the user internal Group[] _groups; /* * Nonpublic constructor */ #if SILVERLIGHT internal GroupCollection(Match match, Dictionary<Int32, Int32> caps) { #else internal GroupCollection(Match match, Hashtable caps) { #endif _match = match; _captureMap = caps; } /* * The object on which to synchronize */ /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Object SyncRoot { get { return _match; } } /* * ICollection */ /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool IsSynchronized { get { return false; } } /* * ICollection */ /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool IsReadOnly { get { return true; } } /// <devdoc> /// <para> /// Returns the number of groups. /// </para> /// </devdoc> public int Count { get { return _match._matchcount.Length; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Group this[int groupnum] { get { return GetGroup(groupnum); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Group this[String groupname] { get { if (_match._regex == null) return Group._emptygroup; return GetGroup(_match._regex.GroupNumberFromName(groupname)); } } internal Group GetGroup(int groupnum) { if (_captureMap != null) { Object o; o = _captureMap[groupnum]; if (o == null) return Group._emptygroup; //throw new ArgumentOutOfRangeException("groupnum"); return GetGroupImpl((int)o); } else { //if (groupnum >= _match._regex.CapSize || groupnum < 0) // throw new ArgumentOutOfRangeException("groupnum"); if (groupnum >= _match._matchcount.Length || groupnum < 0) return Group._emptygroup; return GetGroupImpl(groupnum); } } /* * Caches the group objects */ internal Group GetGroupImpl(int groupnum) { if (groupnum == 0) return _match; // Construct all the Group objects the first time GetGroup is called if (_groups == null) { _groups = new Group[_match._matchcount.Length - 1]; for (int i = 0; i < _groups.Length; i++) { _groups[i] = new Group(_match._text, _match._matches[i + 1], _match._matchcount[i + 1]); } } return _groups[groupnum - 1]; } /* * As required by ICollection */ /// <devdoc> /// <para> /// Copies all the elements of the collection to the given array /// beginning at the given index. /// </para> /// </devdoc> public void CopyTo(Array array, int arrayIndex) { if (array == null) throw new ArgumentNullException("array"); for (int i = arrayIndex, j = 0; j < Count; i++, j++) { array.SetValue(this[j], i); } } /* * As required by ICollection */ /// <devdoc> /// <para> /// Provides an enumerator in the same order as Item[]. /// </para> /// </devdoc> public IEnumerator GetEnumerator() { return new GroupEnumerator(this); } } /* * This non-public enumerator lists all the captures * Should it be public? */ internal class GroupEnumerator : IEnumerator { internal GroupCollection _rgc; internal int _curindex; /* * Nonpublic constructor */ internal GroupEnumerator(GroupCollection rgc) { _curindex = -1; _rgc = rgc; } /* * As required by IEnumerator */ public bool MoveNext() { int size = _rgc.Count; if (_curindex >= size) return false; _curindex++; return(_curindex < size); } /* * As required by IEnumerator */ public Object Current { get { return Capture;} } /* * Returns the current capture */ public Capture Capture { get { if (_curindex < 0 || _curindex >= _rgc.Count) throw new InvalidOperationException(SR.GetString(SR.EnumNotStarted)); return _rgc[_curindex]; } } /* * Reset to before the first item */ public void Reset() { _curindex = -1; } } }
using System; #if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif namespace Godot { public static partial class Mathf { // Define constants with Decimal precision and cast down to double or float. /// <summary> /// The circle constant, the circumference of the unit circle in radians. /// </summary> public const real_t Tau = (real_t) 6.2831853071795864769252867666M; // 6.2831855f and 6.28318530717959 /// <summary> /// Constant that represents how many times the diameter of a circle /// fits around its perimeter. This is equivalent to `Mathf.Tau / 2`. /// </summary> public const real_t Pi = (real_t) 3.1415926535897932384626433833M; // 3.1415927f and 3.14159265358979 /// <summary> /// Positive infinity. For negative infinity, use `-Mathf.Inf`. /// </summary> public const real_t Inf = real_t.PositiveInfinity; /// <summary> /// "Not a Number", an invalid value. `NaN` has special properties, including /// that it is not equal to itself. It is output by some invalid operations, /// such as dividing zero by zero. /// </summary> public const real_t NaN = real_t.NaN; private const real_t Deg2RadConst = (real_t) 0.0174532925199432957692369077M; // 0.0174532924f and 0.0174532925199433 private const real_t Rad2DegConst = (real_t) 57.295779513082320876798154814M; // 57.29578f and 57.2957795130823 /// <summary> /// Returns the absolute value of `s` (i.e. positive value). /// </summary> /// <param name="s">The input number.</param> /// <returns>The absolute value of `s`.</returns> public static int Abs(int s) { return Math.Abs(s); } /// <summary> /// Returns the absolute value of `s` (i.e. positive value). /// </summary> /// <param name="s">The input number.</param> /// <returns>The absolute value of `s`.</returns> public static real_t Abs(real_t s) { return Math.Abs(s); } /// <summary> /// Returns the arc cosine of `s` in radians. Use to get the angle of cosine s. /// </summary> /// <param name="s">The input cosine value. Must be on the range of -1.0 to 1.0.</param> /// <returns>An angle that would result in the given cosine value. On the range `0` to `Tau/2`.</returns> public static real_t Acos(real_t s) { return (real_t)Math.Acos(s); } /// <summary> /// Returns the arc sine of `s` in radians. Use to get the angle of sine s. /// </summary> /// <param name="s">The input sine value. Must be on the range of -1.0 to 1.0.</param> /// <returns>An angle that would result in the given sine value. On the range `-Tau/4` to `Tau/4`.</returns> public static real_t Asin(real_t s) { return (real_t)Math.Asin(s); } /// <summary> /// Returns the arc tangent of `s` in radians. Use to get the angle of tangent s. /// /// The method cannot know in which quadrant the angle should fall. /// See <see cref="Atan2(real_t, real_t)"/> if you have both `y` and `x`. /// </summary> /// <param name="s">The input tangent value.</param> /// <returns>An angle that would result in the given tangent value. On the range `-Tau/4` to `Tau/4`.</returns> public static real_t Atan(real_t s) { return (real_t)Math.Atan(s); } /// <summary> /// Returns the arc tangent of `y` and `x` in radians. Use to get the angle /// of the tangent of `y/x`. To compute the value, the method takes into /// account the sign of both arguments in order to determine the quadrant. /// /// Important note: The Y coordinate comes first, by convention. /// </summary> /// <param name="y">The Y coordinate of the point to find the angle to.</param> /// <param name="x">The X coordinate of the point to find the angle to.</param> /// <returns>An angle that would result in the given tangent value. On the range `-Tau/2` to `Tau/2`.</returns> public static real_t Atan2(real_t y, real_t x) { return (real_t)Math.Atan2(y, x); } /// <summary> /// Converts a 2D point expressed in the cartesian coordinate /// system (X and Y axis) to the polar coordinate system /// (a distance from the origin and an angle). /// </summary> /// <param name="x">The input X coordinate.</param> /// <param name="y">The input Y coordinate.</param> /// <returns>A <see cref="Vector2"/> with X representing the distance and Y representing the angle.</returns> public static Vector2 Cartesian2Polar(real_t x, real_t y) { return new Vector2(Sqrt(x * x + y * y), Atan2(y, x)); } /// <summary> /// Rounds `s` upward (towards positive infinity). /// </summary> /// <param name="s">The number to ceil.</param> /// <returns>The smallest whole number that is not less than `s`.</returns> public static real_t Ceil(real_t s) { return (real_t)Math.Ceiling(s); } /// <summary> /// Clamps a `value` so that it is not less than `min` and not more than `max`. /// </summary> /// <param name="value">The value to clamp.</param> /// <param name="min">The minimum allowed value.</param> /// <param name="max">The maximum allowed value.</param> /// <returns>The clamped value.</returns> public static int Clamp(int value, int min, int max) { return value < min ? min : value > max ? max : value; } /// <summary> /// Clamps a `value` so that it is not less than `min` and not more than `max`. /// </summary> /// <param name="value">The value to clamp.</param> /// <param name="min">The minimum allowed value.</param> /// <param name="max">The maximum allowed value.</param> /// <returns>The clamped value.</returns> public static real_t Clamp(real_t value, real_t min, real_t max) { return value < min ? min : value > max ? max : value; } /// <summary> /// Returns the cosine of angle `s` in radians. /// </summary> /// <param name="s">The angle in radians.</param> /// <returns>The cosine of that angle.</returns> public static real_t Cos(real_t s) { return (real_t)Math.Cos(s); } /// <summary> /// Returns the hyperbolic cosine of angle `s` in radians. /// </summary> /// <param name="s">The angle in radians.</param> /// <returns>The hyperbolic cosine of that angle.</returns> public static real_t Cosh(real_t s) { return (real_t)Math.Cosh(s); } /// <summary> /// Converts an angle expressed in degrees to radians. /// </summary> /// <param name="deg">An angle expressed in degrees.</param> /// <returns>The same angle expressed in radians.</returns> public static real_t Deg2Rad(real_t deg) { return deg * Deg2RadConst; } /// <summary> /// Easing function, based on exponent. The curve values are: /// `0` is constant, `1` is linear, `0` to `1` is ease-in, `1` or more is ease-out. /// Negative values are in-out/out-in. /// </summary> /// <param name="s">The value to ease.</param> /// <param name="curve">`0` is constant, `1` is linear, `0` to `1` is ease-in, `1` or more is ease-out.</param> /// <returns>The eased value.</returns> public static real_t Ease(real_t s, real_t curve) { if (s < 0f) { s = 0f; } else if (s > 1.0f) { s = 1.0f; } if (curve > 0f) { if (curve < 1.0f) { return 1.0f - Pow(1.0f - s, 1.0f / curve); } return Pow(s, curve); } if (curve < 0f) { if (s < 0.5f) { return Pow(s * 2.0f, -curve) * 0.5f; } return (1.0f - Pow(1.0f - (s - 0.5f) * 2.0f, -curve)) * 0.5f + 0.5f; } return 0f; } /// <summary> /// The natural exponential function. It raises the mathematical /// constant `e` to the power of `s` and returns it. /// </summary> /// <param name="s">The exponent to raise `e` to.</param> /// <returns>`e` raised to the power of `s`.</returns> public static real_t Exp(real_t s) { return (real_t)Math.Exp(s); } /// <summary> /// Rounds `s` downward (towards negative infinity). /// </summary> /// <param name="s">The number to floor.</param> /// <returns>The largest whole number that is not more than `s`.</returns> public static real_t Floor(real_t s) { return (real_t)Math.Floor(s); } /// <summary> /// Returns a normalized value considering the given range. /// This is the opposite of <see cref="Lerp(real_t, real_t, real_t)"/>. /// </summary> /// <param name="from">The interpolated value.</param> /// <param name="to">The destination value for interpolation.</param> /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param> /// <returns>The resulting value of the inverse interpolation.</returns> public static real_t InverseLerp(real_t from, real_t to, real_t weight) { return (weight - from) / (to - from); } /// <summary> /// Returns true if `a` and `b` are approximately equal to each other. /// The comparison is done using a tolerance calculation with <see cref="Epsilon"/>. /// </summary> /// <param name="a">One of the values.</param> /// <param name="b">The other value.</param> /// <returns>A bool for whether or not the two values are approximately equal.</returns> public static bool IsEqualApprox(real_t a, real_t b) { // Check for exact equality first, required to handle "infinity" values. if (a == b) { return true; } // Then check for approximate equality. real_t tolerance = Epsilon * Abs(a); if (tolerance < Epsilon) { tolerance = Epsilon; } return Abs(a - b) < tolerance; } /// <summary> /// Returns whether `s` is an infinity value (either positive infinity or negative infinity). /// </summary> /// <param name="s">The value to check.</param> /// <returns>A bool for whether or not the value is an infinity value.</returns> public static bool IsInf(real_t s) { return real_t.IsInfinity(s); } /// <summary> /// Returns whether `s` is a `NaN` ("Not a Number" or invalid) value. /// </summary> /// <param name="s">The value to check.</param> /// <returns>A bool for whether or not the value is a `NaN` value.</returns> public static bool IsNaN(real_t s) { return real_t.IsNaN(s); } /// <summary> /// Returns true if `s` is approximately zero. /// The comparison is done using a tolerance calculation with <see cref="Epsilon"/>. /// /// This method is faster than using <see cref="IsEqualApprox(real_t, real_t)"/> with one value as zero. /// </summary> /// <param name="s">The value to check.</param> /// <returns>A bool for whether or not the value is nearly zero.</returns> public static bool IsZeroApprox(real_t s) { return Abs(s) < Epsilon; } /// <summary> /// Linearly interpolates between two values by a normalized value. /// This is the opposite <see cref="InverseLerp(real_t, real_t, real_t)"/>. /// </summary> /// <param name="from">The start value for interpolation.</param> /// <param name="to">The destination value for interpolation.</param> /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param> /// <returns>The resulting value of the interpolation.</returns> public static real_t Lerp(real_t from, real_t to, real_t weight) { return from + (to - from) * weight; } /// <summary> /// Linearly interpolates between two angles (in radians) by a normalized value. /// /// Similar to <see cref="Lerp(real_t, real_t, real_t)"/>, /// but interpolates correctly when the angles wrap around <see cref="Tau"/>. /// </summary> /// <param name="from">The start angle for interpolation.</param> /// <param name="to">The destination angle for interpolation.</param> /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param> /// <returns>The resulting angle of the interpolation.</returns> public static real_t LerpAngle(real_t from, real_t to, real_t weight) { real_t difference = (to - from) % Mathf.Tau; real_t distance = ((2 * difference) % Mathf.Tau) - difference; return from + distance * weight; } /// <summary> /// Natural logarithm. The amount of time needed to reach a certain level of continuous growth. /// /// Note: This is not the same as the "log" function on most calculators, which uses a base 10 logarithm. /// </summary> /// <param name="s">The input value.</param> /// <returns>The natural log of `s`.</returns> public static real_t Log(real_t s) { return (real_t)Math.Log(s); } /// <summary> /// Returns the maximum of two values. /// </summary> /// <param name="a">One of the values.</param> /// <param name="b">The other value.</param> /// <returns>Whichever of the two values is higher.</returns> public static int Max(int a, int b) { return a > b ? a : b; } /// <summary> /// Returns the maximum of two values. /// </summary> /// <param name="a">One of the values.</param> /// <param name="b">The other value.</param> /// <returns>Whichever of the two values is higher.</returns> public static real_t Max(real_t a, real_t b) { return a > b ? a : b; } /// <summary> /// Returns the minimum of two values. /// </summary> /// <param name="a">One of the values.</param> /// <param name="b">The other value.</param> /// <returns>Whichever of the two values is lower.</returns> public static int Min(int a, int b) { return a < b ? a : b; } /// <summary> /// Returns the minimum of two values. /// </summary> /// <param name="a">One of the values.</param> /// <param name="b">The other value.</param> /// <returns>Whichever of the two values is lower.</returns> public static real_t Min(real_t a, real_t b) { return a < b ? a : b; } /// <summary> /// Moves `from` toward `to` by the `delta` value. /// /// Use a negative delta value to move away. /// </summary> /// <param name="from">The start value.</param> /// <param name="to">The value to move towards.</param> /// <param name="delta">The amount to move by.</param> /// <returns>The value after moving.</returns> public static real_t MoveToward(real_t from, real_t to, real_t delta) { return Abs(to - from) <= delta ? to : from + Sign(to - from) * delta; } /// <summary> /// Returns the nearest larger power of 2 for the integer `value`. /// </summary> /// <param name="value">The input value.</param> /// <returns>The nearest larger power of 2.</returns> public static int NearestPo2(int value) { value--; value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; value++; return value; } /// <summary> /// Converts a 2D point expressed in the polar coordinate /// system (a distance from the origin `r` and an angle `th`) /// to the cartesian coordinate system (X and Y axis). /// </summary> /// <param name="r">The distance from the origin.</param> /// <param name="th">The angle of the point.</param> /// <returns>A <see cref="Vector2"/> representing the cartesian coordinate.</returns> public static Vector2 Polar2Cartesian(real_t r, real_t th) { return new Vector2(r * Cos(th), r * Sin(th)); } /// <summary> /// Performs a canonical Modulus operation, where the output is on the range `[0, b)`. /// </summary> /// <param name="a">The dividend, the primary input.</param> /// <param name="b">The divisor. The output is on the range `[0, b)`.</param> /// <returns>The resulting output.</returns> public static int PosMod(int a, int b) { int c = a % b; if ((c < 0 && b > 0) || (c > 0 && b < 0)) { c += b; } return c; } /// <summary> /// Performs a canonical Modulus operation, where the output is on the range `[0, b)`. /// </summary> /// <param name="a">The dividend, the primary input.</param> /// <param name="b">The divisor. The output is on the range `[0, b)`.</param> /// <returns>The resulting output.</returns> public static real_t PosMod(real_t a, real_t b) { real_t c = a % b; if ((c < 0 && b > 0) || (c > 0 && b < 0)) { c += b; } return c; } /// <summary> /// Returns the result of `x` raised to the power of `y`. /// </summary> /// <param name="x">The base.</param> /// <param name="y">The exponent.</param> /// <returns>`x` raised to the power of `y`.</returns> public static real_t Pow(real_t x, real_t y) { return (real_t)Math.Pow(x, y); } /// <summary> /// Converts an angle expressed in radians to degrees. /// </summary> /// <param name="rad">An angle expressed in radians.</param> /// <returns>The same angle expressed in degrees.</returns> public static real_t Rad2Deg(real_t rad) { return rad * Rad2DegConst; } /// <summary> /// Rounds `s` to the nearest whole number, /// with halfway cases rounded towards the nearest multiple of two. /// </summary> /// <param name="s">The number to round.</param> /// <returns>The rounded number.</returns> public static real_t Round(real_t s) { return (real_t)Math.Round(s); } /// <summary> /// Returns the sign of `s`: `-1` or `1`. Returns `0` if `s` is `0`. /// </summary> /// <param name="s">The input number.</param> /// <returns>One of three possible values: `1`, `-1`, or `0`.</returns> public static int Sign(int s) { if (s == 0) return 0; return s < 0 ? -1 : 1; } /// <summary> /// Returns the sign of `s`: `-1` or `1`. Returns `0` if `s` is `0`. /// </summary> /// <param name="s">The input number.</param> /// <returns>One of three possible values: `1`, `-1`, or `0`.</returns> public static int Sign(real_t s) { if (s == 0) return 0; return s < 0 ? -1 : 1; } /// <summary> /// Returns the sine of angle `s` in radians. /// </summary> /// <param name="s">The angle in radians.</param> /// <returns>The sine of that angle.</returns> public static real_t Sin(real_t s) { return (real_t)Math.Sin(s); } /// <summary> /// Returns the hyperbolic sine of angle `s` in radians. /// </summary> /// <param name="s">The angle in radians.</param> /// <returns>The hyperbolic sine of that angle.</returns> public static real_t Sinh(real_t s) { return (real_t)Math.Sinh(s); } /// <summary> /// Returns a number smoothly interpolated between `from` and `to`, /// based on the `weight`. Similar to <see cref="Lerp(real_t, real_t, real_t)"/>, /// but interpolates faster at the beginning and slower at the end. /// </summary> /// <param name="from">The start value for interpolation.</param> /// <param name="to">The destination value for interpolation.</param> /// <param name="weight">A value representing the amount of interpolation.</param> /// <returns>The resulting value of the interpolation.</returns> public static real_t SmoothStep(real_t from, real_t to, real_t weight) { if (IsEqualApprox(from, to)) { return from; } real_t x = Clamp((weight - from) / (to - from), (real_t)0.0, (real_t)1.0); return x * x * (3 - 2 * x); } /// <summary> /// Returns the square root of `s`, where `s` is a non-negative number. /// /// If you need negative inputs, use `System.Numerics.Complex`. /// </summary> /// <param name="s">The input number. Must not be negative.</param> /// <returns>The square root of `s`.</returns> public static real_t Sqrt(real_t s) { return (real_t)Math.Sqrt(s); } /// <summary> /// Returns the position of the first non-zero digit, after the /// decimal point. Note that the maximum return value is 10, /// which is a design decision in the implementation. /// </summary> /// <param name="step">The input value.</param> /// <returns>The position of the first non-zero digit.</returns> public static int StepDecimals(real_t step) { double[] sd = new double[] { 0.9999, 0.09999, 0.009999, 0.0009999, 0.00009999, 0.000009999, 0.0000009999, 0.00000009999, 0.000000009999, }; double abs = Mathf.Abs(step); double decs = abs - (int)abs; // Strip away integer part for (int i = 0; i < sd.Length; i++) { if (decs >= sd[i]) { return i; } } return 0; } /// <summary> /// Snaps float value `s` to a given `step`. /// This can also be used to round a floating point /// number to an arbitrary number of decimals. /// </summary> /// <param name="s">The value to stepify.</param> /// <param name="step">The step size to snap to.</param> /// <returns></returns> public static real_t Stepify(real_t s, real_t step) { if (step != 0f) { return Floor(s / step + 0.5f) * step; } return s; } /// <summary> /// Returns the tangent of angle `s` in radians. /// </summary> /// <param name="s">The angle in radians.</param> /// <returns>The tangent of that angle.</returns> public static real_t Tan(real_t s) { return (real_t)Math.Tan(s); } /// <summary> /// Returns the hyperbolic tangent of angle `s` in radians. /// </summary> /// <param name="s">The angle in radians.</param> /// <returns>The hyperbolic tangent of that angle.</returns> public static real_t Tanh(real_t s) { return (real_t)Math.Tanh(s); } /// <summary> /// Wraps `value` between `min` and `max`. Usable for creating loop-alike /// behavior or infinite surfaces. If `min` is `0`, this is equivalent /// to <see cref="PosMod(int, int)"/>, so prefer using that instead. /// </summary> /// <param name="value">The value to wrap.</param> /// <param name="min">The minimum allowed value and lower bound of the range.</param> /// <param name="max">The maximum allowed value and upper bound of the range.</param> /// <returns>The wrapped value.</returns> public static int Wrap(int value, int min, int max) { int range = max - min; return range == 0 ? min : min + ((value - min) % range + range) % range; } /// <summary> /// Wraps `value` between `min` and `max`. Usable for creating loop-alike /// behavior or infinite surfaces. If `min` is `0`, this is equivalent /// to <see cref="PosMod(real_t, real_t)"/>, so prefer using that instead. /// </summary> /// <param name="value">The value to wrap.</param> /// <param name="min">The minimum allowed value and lower bound of the range.</param> /// <param name="max">The maximum allowed value and upper bound of the range.</param> /// <returns>The wrapped value.</returns> public static real_t Wrap(real_t value, real_t min, real_t max) { real_t range = max - min; return IsZeroApprox(range) ? min : min + ((value - min) % range + range) % range; } } }
// Copyright (c) 2015-present, Parse, LLC. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Parse.Infrastructure.Utilities; namespace Parse { /// <summary> /// Represents this app installed on this device. Use this class to track information you want /// to sample from (i.e. if you update a field on app launch, you can issue a query to see /// the number of devices which were active in the last N hours). /// </summary> [ParseClassName("_Installation")] public partial class ParseInstallation : ParseObject { static HashSet<string> ImmutableKeys { get; } = new HashSet<string> { "deviceType", "deviceUris", "installationId", "timeZone", "localeIdentifier", "parseVersion", "appName", "appIdentifier", "appVersion", "pushType" }; /// <summary> /// Constructs a new ParseInstallation. Generally, you should not need to construct /// ParseInstallations yourself. Instead use <see cref="CurrentInstallation"/>. /// </summary> public ParseInstallation() : base() { } /// <summary> /// A GUID that uniquely names this app installed on this device. /// </summary> [ParseFieldName("installationId")] public Guid InstallationId { get { string installationIdString = GetProperty<string>(nameof(InstallationId)); Guid? installationId = null; try { installationId = new Guid(installationIdString); } catch (Exception) { // Do nothing. } return installationId.Value; } internal set { Guid installationId = value; SetProperty(installationId.ToString(), nameof(InstallationId)); } } /// <summary> /// The runtime target of this installation object. /// </summary> [ParseFieldName("deviceType")] public string DeviceType { get => GetProperty<string>(nameof(DeviceType)); internal set => SetProperty(value, nameof(DeviceType)); } /// <summary> /// The user-friendly display name of this application. /// </summary> [ParseFieldName("appName")] public string AppName { get => GetProperty<string>(nameof(AppName)); internal set => SetProperty(value, nameof(AppName)); } /// <summary> /// A version string consisting of Major.Minor.Build.Revision. /// </summary> [ParseFieldName("appVersion")] public string AppVersion { get => GetProperty<string>(nameof(AppVersion)); internal set => SetProperty(value, nameof(AppVersion)); } /// <summary> /// The system-dependent unique identifier of this installation. This identifier should be /// sufficient to distinctly name an app on stores which may allow multiple apps with the /// same display name. /// </summary> [ParseFieldName("appIdentifier")] public string AppIdentifier { get => GetProperty<string>(nameof(AppIdentifier)); internal set => SetProperty(value, nameof(AppIdentifier)); } /// <summary> /// The time zone in which this device resides. This string is in the tz database format /// Parse uses for local-time pushes. Due to platform restrictions, the mapping is less /// granular on Windows than it may be on other systems. E.g. The zones /// America/Vancouver America/Dawson America/Whitehorse, America/Tijuana, PST8PDT, and /// America/Los_Angeles are all reported as America/Los_Angeles. /// </summary> [ParseFieldName("timeZone")] public string TimeZone { get => GetProperty<string>(nameof(TimeZone)); private set => SetProperty(value, nameof(TimeZone)); } /// <summary> /// The users locale. This field gets automatically populated by the SDK. /// Can be null (Parse Push uses default language in this case). /// </summary> [ParseFieldName("localeIdentifier")] public string LocaleIdentifier { get => GetProperty<string>(nameof(LocaleIdentifier)); private set => SetProperty(value, nameof(LocaleIdentifier)); } /// <summary> /// Gets the locale identifier in the format: [language code]-[COUNTRY CODE]. /// </summary> /// <returns>The locale identifier in the format: [language code]-[COUNTRY CODE].</returns> private string GetLocaleIdentifier() { string languageCode = null; string countryCode = null; if (CultureInfo.CurrentCulture != null) { languageCode = CultureInfo.CurrentCulture.TwoLetterISOLanguageName; } if (RegionInfo.CurrentRegion != null) { countryCode = RegionInfo.CurrentRegion.TwoLetterISORegionName; } if (String.IsNullOrEmpty(countryCode)) { return languageCode; } else { return String.Format("{0}-{1}", languageCode, countryCode); } } /// <summary> /// The version of the Parse SDK used to build this application. /// </summary> [ParseFieldName("parseVersion")] public Version ParseVersion { get { string versionString = GetProperty<string>(nameof(ParseVersion)); Version version = null; try { version = new Version(versionString); } catch (Exception) { // Do nothing. } return version; } private set { Version version = value; SetProperty(version.ToString(), nameof(ParseVersion)); } } /// <summary> /// A sequence of arbitrary strings which are used to identify this installation for push notifications. /// By convention, the empty string is known as the "Broadcast" channel. /// </summary> [ParseFieldName("channels")] public IList<string> Channels { get => GetProperty<IList<string>>(nameof(Channels)); set => SetProperty(value, nameof(Channels)); } protected override bool CheckKeyMutable(string key) => !ImmutableKeys.Contains(key); protected override Task SaveAsync(Task toAwait, CancellationToken cancellationToken) { Task platformHookTask = null; if (Services.CurrentInstallationController.IsCurrent(this)) { SetIfDifferent("deviceType", Services.MetadataController.EnvironmentData.Platform); SetIfDifferent("timeZone", Services.MetadataController.EnvironmentData.TimeZone); SetIfDifferent("localeIdentifier", GetLocaleIdentifier()); SetIfDifferent("parseVersion", ParseClient.Version); SetIfDifferent("appVersion", Services.MetadataController.HostManifestData.Version); SetIfDifferent("appIdentifier", Services.MetadataController.HostManifestData.Identifier); SetIfDifferent("appName", Services.MetadataController.HostManifestData.Name); #warning InstallationDataFinalizer needs to be injected here somehow or removed. //platformHookTask = Client.InstallationDataFinalizer.FinalizeAsync(this); } return platformHookTask.Safe().OnSuccess(_ => base.SaveAsync(toAwait, cancellationToken)).Unwrap().OnSuccess(_ => Services.CurrentInstallationController.IsCurrent(this) ? Task.CompletedTask : Services.CurrentInstallationController.SetAsync(this, cancellationToken)).Unwrap(); } /// <summary> /// This mapping of Windows names to a standard everyone else uses is maintained /// by the Unicode consortium, which makes this officially the first helpful /// interaction between Unicode and Microsoft. /// Unfortunately this is a little lossy in that we only store the first mapping in each zone because /// Microsoft does not give us more granular location information. /// Built from http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/zone_tzid.html /// </summary> internal static Dictionary<string, string> TimeZoneNameMap { get; } = new Dictionary<string, string> { ["Dateline Standard Time"] = "Etc/GMT+12", ["UTC-11"] = "Etc/GMT+11", ["Hawaiian Standard Time"] = "Pacific/Honolulu", ["Alaskan Standard Time"] = "America/Anchorage", ["Pacific Standard Time (Mexico)"] = "America/Santa_Isabel", ["Pacific Standard Time"] = "America/Los_Angeles", ["US Mountain Standard Time"] = "America/Phoenix", ["Mountain Standard Time (Mexico)"] = "America/Chihuahua", ["Mountain Standard Time"] = "America/Denver", ["Central America Standard Time"] = "America/Guatemala", ["Central Standard Time"] = "America/Chicago", ["Central Standard Time (Mexico)"] = "America/Mexico_City", ["Canada Central Standard Time"] = "America/Regina", ["SA Pacific Standard Time"] = "America/Bogota", ["Eastern Standard Time"] = "America/New_York", ["US Eastern Standard Time"] = "America/Indianapolis", ["Venezuela Standard Time"] = "America/Caracas", ["Paraguay Standard Time"] = "America/Asuncion", ["Atlantic Standard Time"] = "America/Halifax", ["Central Brazilian Standard Time"] = "America/Cuiaba", ["SA Western Standard Time"] = "America/La_Paz", ["Pacific SA Standard Time"] = "America/Santiago", ["Newfoundland Standard Time"] = "America/St_Johns", ["E. South America Standard Time"] = "America/Sao_Paulo", ["Argentina Standard Time"] = "America/Buenos_Aires", ["SA Eastern Standard Time"] = "America/Cayenne", ["Greenland Standard Time"] = "America/Godthab", ["Montevideo Standard Time"] = "America/Montevideo", ["Bahia Standard Time"] = "America/Bahia", ["UTC-02"] = "Etc/GMT+2", ["Azores Standard Time"] = "Atlantic/Azores", ["Cape Verde Standard Time"] = "Atlantic/Cape_Verde", ["Morocco Standard Time"] = "Africa/Casablanca", ["UTC"] = "Etc/GMT", ["GMT Standard Time"] = "Europe/London", ["Greenwich Standard Time"] = "Atlantic/Reykjavik", ["W. Europe Standard Time"] = "Europe/Berlin", ["Central Europe Standard Time"] = "Europe/Budapest", ["Romance Standard Time"] = "Europe/Paris", ["Central European Standard Time"] = "Europe/Warsaw", ["W. Central Africa Standard Time"] = "Africa/Lagos", ["Namibia Standard Time"] = "Africa/Windhoek", ["GTB Standard Time"] = "Europe/Bucharest", ["Middle East Standard Time"] = "Asia/Beirut", ["Egypt Standard Time"] = "Africa/Cairo", ["Syria Standard Time"] = "Asia/Damascus", ["E. Europe Standard Time"] = "Asia/Nicosia", ["South Africa Standard Time"] = "Africa/Johannesburg", ["FLE Standard Time"] = "Europe/Kiev", ["Turkey Standard Time"] = "Europe/Istanbul", ["Israel Standard Time"] = "Asia/Jerusalem", ["Jordan Standard Time"] = "Asia/Amman", ["Arabic Standard Time"] = "Asia/Baghdad", ["Kaliningrad Standard Time"] = "Europe/Kaliningrad", ["Arab Standard Time"] = "Asia/Riyadh", ["E. Africa Standard Time"] = "Africa/Nairobi", ["Iran Standard Time"] = "Asia/Tehran", ["Arabian Standard Time"] = "Asia/Dubai", ["Azerbaijan Standard Time"] = "Asia/Baku", ["Russian Standard Time"] = "Europe/Moscow", ["Mauritius Standard Time"] = "Indian/Mauritius", ["Georgian Standard Time"] = "Asia/Tbilisi", ["Caucasus Standard Time"] = "Asia/Yerevan", ["Afghanistan Standard Time"] = "Asia/Kabul", ["Pakistan Standard Time"] = "Asia/Karachi", ["West Asia Standard Time"] = "Asia/Tashkent", ["India Standard Time"] = "Asia/Calcutta", ["Sri Lanka Standard Time"] = "Asia/Colombo", ["Nepal Standard Time"] = "Asia/Katmandu", ["Central Asia Standard Time"] = "Asia/Almaty", ["Bangladesh Standard Time"] = "Asia/Dhaka", ["Ekaterinburg Standard Time"] = "Asia/Yekaterinburg", ["Myanmar Standard Time"] = "Asia/Rangoon", ["SE Asia Standard Time"] = "Asia/Bangkok", ["N. Central Asia Standard Time"] = "Asia/Novosibirsk", ["China Standard Time"] = "Asia/Shanghai", ["North Asia Standard Time"] = "Asia/Krasnoyarsk", ["Singapore Standard Time"] = "Asia/Singapore", ["W. Australia Standard Time"] = "Australia/Perth", ["Taipei Standard Time"] = "Asia/Taipei", ["Ulaanbaatar Standard Time"] = "Asia/Ulaanbaatar", ["North Asia East Standard Time"] = "Asia/Irkutsk", ["Tokyo Standard Time"] = "Asia/Tokyo", ["Korea Standard Time"] = "Asia/Seoul", ["Cen. Australia Standard Time"] = "Australia/Adelaide", ["AUS Central Standard Time"] = "Australia/Darwin", ["E. Australia Standard Time"] = "Australia/Brisbane", ["AUS Eastern Standard Time"] = "Australia/Sydney", ["West Pacific Standard Time"] = "Pacific/Port_Moresby", ["Tasmania Standard Time"] = "Australia/Hobart", ["Yakutsk Standard Time"] = "Asia/Yakutsk", ["Central Pacific Standard Time"] = "Pacific/Guadalcanal", ["Vladivostok Standard Time"] = "Asia/Vladivostok", ["New Zealand Standard Time"] = "Pacific/Auckland", ["UTC+12"] = "Etc/GMT-12", ["Fiji Standard Time"] = "Pacific/Fiji", ["Magadan Standard Time"] = "Asia/Magadan", ["Tonga Standard Time"] = "Pacific/Tongatapu", ["Samoa Standard Time"] = "Pacific/Apia" }; /// <summary> /// This is a mapping of odd TimeZone offsets to their respective IANA codes across the world. /// This list was compiled from painstakingly pouring over the information available at /// https://en.wikipedia.org/wiki/List_of_tz_database_time_zones. /// </summary> internal static Dictionary<TimeSpan, string> TimeZoneOffsetMap { get; } = new Dictionary<TimeSpan, string> { [new TimeSpan(12, 45, 0)] = "Pacific/Chatham", [new TimeSpan(10, 30, 0)] = "Australia/Lord_Howe", [new TimeSpan(9, 30, 0)] = "Australia/Adelaide", [new TimeSpan(8, 45, 0)] = "Australia/Eucla", [new TimeSpan(8, 30, 0)] = "Asia/Pyongyang", // Parse in North Korea confirmed. [new TimeSpan(6, 30, 0)] = "Asia/Rangoon", [new TimeSpan(5, 45, 0)] = "Asia/Kathmandu", [new TimeSpan(5, 30, 0)] = "Asia/Colombo", [new TimeSpan(4, 30, 0)] = "Asia/Kabul", [new TimeSpan(3, 30, 0)] = "Asia/Tehran", [new TimeSpan(-3, 30, 0)] = "America/St_Johns", [new TimeSpan(-4, 30, 0)] = "America/Caracas", [new TimeSpan(-9, 30, 0)] = "Pacific/Marquesas", }; } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using Delaunay; using Delaunay.Geo; using Vectrosity; public class VoronoiRegion{ public Vector2 center; public List<RoadSegment> boundary; public bool isBorderRegion = false; public Vector2 min; public Vector2 max; } public class VoronoiRunner : MonoBehaviour { [SerializeField] private int m_pointCount; private bool populated = false; public LSystem LSystem; public bool showExtraGraphics = false; public bool showDots = false; public bool newDiagramOnKeyPress = false; private List<Vector2> m_points; private float m_mapWidth; private float m_mapHeight; private List<LineSegment> m_edges = null; private List<LineSegment> m_spanningTree; private List<LineSegment> m_delaunayTriangulation; HeightmapParser hmp; List<VoronoiRegion> regions = new List<VoronoiRegion>(); List<RoadSegment> districtSegments = new List<RoadSegment>(); List<RoadSegment> borders = new List<RoadSegment>(); public Material mat; void Awake() { hmp = GameObject.FindGameObjectWithTag("HeightmapParser").GetComponent<HeightmapParser>(); m_mapWidth = hmp.heightmap.width; m_mapHeight = hmp.heightmap.height; RoadSegment seg1 = new RoadSegment(); seg1.start = new Vector2(0, 0); seg1.end = new Vector2(0, m_mapHeight); seg1.id = 100001; RoadSegment seg2 = new RoadSegment(); seg2.start = new Vector2(0, 0); seg2.end = new Vector2(m_mapWidth, 0); seg2.id = 100002; RoadSegment seg3 = new RoadSegment(); seg3.start = new Vector2(m_mapWidth, 0); seg3.end = new Vector2(m_mapWidth, m_mapHeight); seg3.id = 100003; RoadSegment seg4 = new RoadSegment(); seg4.start = new Vector2(0, m_mapHeight); seg4.end = new Vector2(m_mapWidth, m_mapHeight); seg4.id = 100004; borders.Add(seg1); borders.Add(seg2); borders.Add(seg3); borders.Add(seg4); } void Start (){ Run(); draw(m_edges); } void draw(List<LineSegment> segments){ foreach(LineSegment segment in segments){ Vector3[] line = new Vector3[]{(Vector3)segment.p0, (Vector3)segment.p1}; VectorLine l = new VectorLine("Road segment", line, mat, 3, LineType.Discrete); l.Draw3D(); } } void Update() { if (Input.anyKeyDown && newDiagramOnKeyPress) { Run(); } else if (Input.GetKeyDown(KeyCode.N) && !populated){ StartCoroutine(buildCity()); } } IEnumerator buildCity(){ populated = true; foreach(Vector2 point in m_points){ //yield return new WaitForSeconds(delay); yield return new WaitForEndOfFrame(); int counter = 0; List<RoadSegment> bounds = GetBoundaries(point, 10000); VoronoiRegion tmp = regions[counter]; List<Vector3[]> sides = new List<Vector3[]>(); List<Vector3> verts = new List<Vector3>(); foreach(RoadSegment seg in bounds){ sides.Add(seg.getLine()); verts.Add(seg.end); } LSystem clone = (LSystem) Instantiate(LSystem); clone.init(point); /* if (!tmp.isBorderRegion){ clone.center(clone.getCenter(), clone.getCenter(bounds)); clone.redraw(); }*/ clone.confineToBounds(sides); // clone.joinSegments(verts.ToArray(), 1.1f); //clone.JoinSegments(verts.ToArray(), 1.1f); /*if (!tmp.isBorderRegion){ while ((!clone.fillBounds(tmp.min, tmp.max) && counter < 1)){ yield return new WaitForSeconds(0.005f); clone.reset(); clone.init(point); counter++; } } clone.confineToBounds(sides);*/ } } private void Run() { m_pointCount = hmp.amountOfDistricts; List<uint> colors = new List<uint>(); m_points = new List<Vector2>(); for (int i = 0; i < m_pointCount; i++) { colors.Add(0); //m_points.Add (new Vector2 ( // UnityEngine.Random.Range (0, m_mapWidth), // UnityEngine.Random.Range (0, m_mapHeight)) //); } m_points = hmp.GetDistrictCenterPoints(); Delaunay.Voronoi v = new Delaunay.Voronoi(m_points, colors, new Rect(0, 0, m_mapWidth, m_mapHeight)); m_edges = v.VoronoiDiagram(); m_spanningTree = v.SpanningTree(KruskalType.MINIMUM); m_delaunayTriangulation = v.DelaunayTriangulation(); int counter = 0; for (int i = 0; i < m_edges.Count; i++) { Vector2 left = (Vector2)m_edges[i].p0; Vector2 right = (Vector2)m_edges[i].p1; RoadSegment segment = new RoadSegment(); segment.start = left; segment.end = right; segment.id = counter; districtSegments.Add(segment); counter++; } } List<RoadSegment> GetBoundaries(Vector2 origin, float dist, int testCount = 360){ Debug.Assert ( testCount > 0, "testCount has to be a positive non zero value"); float x = 360/testCount; // degrees Vector2 point = new Vector2(origin.x, origin.y + dist); // start checking above origin List <RoadSegment> boundary = new List<RoadSegment>(); bool isBorderRegion = false; for (int i = 0; i < testCount; i++){ float newX = origin.x + (point.x-origin.x) * Mathf.Cos(x) - (point.y-origin.y) * Mathf.Sin(x); float newY = origin.y + (point.x-origin.x) * Mathf.Sin(x) + (point.y-origin.y) * Mathf.Cos(x); point = new Vector2(newX, newY); RoadSegment intersected; if ((intersected = LineLineIntersection.instance.MultipleLineSegmentIntersection(origin, point, districtSegments.ToArray())) != null){ if (!boundary.Contains(intersected)){ boundary.Add(intersected); } } else { isBorderRegion = true; } } VoronoiRegion vr = new VoronoiRegion(); vr.center = origin; vr.boundary = boundary; vr.isBorderRegion = isBorderRegion; float minX = origin.x; float maxX = origin.x; float minY = origin.y; float maxY = origin.y; foreach (RoadSegment seg in boundary){ if (seg.start.x < minX) minX = seg.start.x; if (seg.end.x < minX) minX = seg.end.x; if (seg.start.x > maxX) maxX = seg.start.x; if (seg.end.x > maxX) maxX = seg.end.x; if (seg.start.y < minY) minY = seg.start.y; if (seg.end.y < minY) minY = seg.end.y; if (seg.start.y > maxY) maxY = seg.start.y; if (seg.end.y > maxY) maxY = seg.end.y; } vr.min = new Vector2(minX, minY); vr.max = new Vector2(maxX, maxY); //print("pos : " + vr.center+ ", min " + vr.min + ", max: "+ vr.max); regions.Add(vr); return boundary; } void OnDrawGizmos() { /* if (m_edges != null) { Gizmos.color = Color.black; for (int i = 0; i < m_edges.Count; i++) { Vector2 left = (Vector2)m_edges[i].p0; Vector2 right = (Vector2)m_edges[i].p1; Gizmos.DrawLine((Vector3)left, (Vector3)right); } }*/ if (showExtraGraphics || showDots){ Gizmos.color = Color.red; if (m_points != null) { for (int i = 0; i < m_points.Count; i++) { if (i == 0) Gizmos.color = Color.cyan; else Gizmos.color = Color.red; Gizmos.DrawSphere(m_points[i], 1f); } } } if (showExtraGraphics){ Gizmos.color = Color.magenta; if (m_delaunayTriangulation != null) { for (int i = 0; i < m_delaunayTriangulation.Count; i++) { Vector2 left = (Vector2)m_delaunayTriangulation[i].p0; Vector2 right = (Vector2)m_delaunayTriangulation[i].p1; Gizmos.DrawLine((Vector3)left, (Vector3)right); } } if (m_spanningTree != null) { Gizmos.color = Color.green; for (int i = 0; i < m_spanningTree.Count; i++) { LineSegment seg = m_spanningTree[i]; Vector2 left = (Vector2)seg.p0; Vector2 right = (Vector2)seg.p1; Gizmos.DrawLine((Vector3)left, (Vector3)right); } } } Gizmos.color = Color.yellow; Gizmos.DrawLine(new Vector2(0, 0), new Vector2(0, m_mapHeight)); Gizmos.DrawLine(new Vector2(0, 0), new Vector2(m_mapWidth, 0)); Gizmos.DrawLine(new Vector2(m_mapWidth, 0), new Vector2(m_mapWidth, m_mapHeight)); Gizmos.DrawLine(new Vector2(0, m_mapHeight), new Vector2(m_mapWidth, m_mapHeight)); } public List<Vector2> getPoints(){ return m_points; } }
// Copyright (c) Alexandre Mutel. All rights reserved. // This file is licensed under the BSD-Clause 2 license. // See the license.txt file in the project root for more information. using System; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Text; using Markdig.Helpers; using Markdig.Renderers.Html; using Markdig.Renderers.Html.Inlines; using Markdig.Syntax; namespace Markdig.Renderers { /// <summary> /// Default HTML renderer for a Markdown <see cref="MarkdownDocument"/> object. /// </summary> /// <seealso cref="TextRendererBase{HtmlRenderer}" /> public class HtmlRenderer : TextRendererBase<HtmlRenderer> { /// <summary> /// Initializes a new instance of the <see cref="HtmlRenderer"/> class. /// </summary> /// <param name="writer">The writer.</param> public HtmlRenderer(TextWriter writer) : base(writer) { // Default block renderers ObjectRenderers.Add(new CodeBlockRenderer()); ObjectRenderers.Add(new ListRenderer()); ObjectRenderers.Add(new HeadingRenderer()); ObjectRenderers.Add(new HtmlBlockRenderer()); ObjectRenderers.Add(new ParagraphRenderer()); ObjectRenderers.Add(new QuoteBlockRenderer()); ObjectRenderers.Add(new ThematicBreakRenderer()); // Default inline renderers ObjectRenderers.Add(new AutolinkInlineRenderer()); ObjectRenderers.Add(new CodeInlineRenderer()); ObjectRenderers.Add(new DelimiterInlineRenderer()); ObjectRenderers.Add(new EmphasisInlineRenderer()); ObjectRenderers.Add(new LineBreakInlineRenderer()); ObjectRenderers.Add(new HtmlInlineRenderer()); ObjectRenderers.Add(new HtmlEntityInlineRenderer()); ObjectRenderers.Add(new LinkInlineRenderer()); ObjectRenderers.Add(new LiteralInlineRenderer()); EnableHtmlForBlock = true; EnableHtmlForInline = true; EnableHtmlEscape = true; } /// <summary> /// Gets or sets a value indicating whether to output HTML tags when rendering. See remarks. /// </summary> /// <remarks> /// This is used by some renderers to disable HTML tags when rendering some inline elements (for image links). /// </remarks> public bool EnableHtmlForInline { get; set; } /// <summary> /// Gets or sets a value indicating whether to output HTML tags when rendering. See remarks. /// </summary> /// <remarks> /// This is used by some renderers to disable HTML tags when rendering some block elements (for image links). /// </remarks> public bool EnableHtmlForBlock { get; set; } public bool EnableHtmlEscape { get; set; } /// <summary> /// Gets or sets a value indicating whether to use implicit paragraph (optional &lt;p&gt;) /// </summary> public bool ImplicitParagraph { get; set; } public bool UseNonAsciiNoEscape { get; set; } /// <summary> /// Gets a value to use as the base url for all relative links /// </summary> public Uri BaseUrl { get; set; } /// <summary> /// Allows links to be rewritten /// </summary> public Func<string, string> LinkRewriter { get; set; } /// <summary> /// Writes the content escaped for HTML. /// </summary> /// <param name="content">The content.</param> /// <returns>This instance</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public HtmlRenderer WriteEscape(string content) { if (string.IsNullOrEmpty(content)) return this; WriteEscape(content, 0, content.Length); return this; } /// <summary> /// Writes the content escaped for HTML. /// </summary> /// <param name="slice">The slice.</param> /// <param name="softEscape">Only escape &lt; and &amp;</param> /// <returns>This instance</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public HtmlRenderer WriteEscape(ref StringSlice slice, bool softEscape = false) { if (slice.Start > slice.End) { return this; } return WriteEscape(slice.Text, slice.Start, slice.Length, softEscape); } /// <summary> /// Writes the content escaped for HTML. /// </summary> /// <param name="slice">The slice.</param> /// <param name="softEscape">Only escape &lt; and &amp;</param> /// <returns>This instance</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public HtmlRenderer WriteEscape(StringSlice slice, bool softEscape = false) { return WriteEscape(ref slice, softEscape); } /// <summary> /// Writes the content escaped for HTML. /// </summary> /// <param name="content">The content.</param> /// <param name="offset">The offset.</param> /// <param name="length">The length.</param> /// <param name="softEscape">Only escape &lt; and &amp;</param> /// <returns>This instance</returns> public HtmlRenderer WriteEscape(string content, int offset, int length, bool softEscape = false) { if (string.IsNullOrEmpty(content) || length == 0) return this; var end = offset + length; int previousOffset = offset; for (;offset < end; offset++) { switch (content[offset]) { case '<': Write(content, previousOffset, offset - previousOffset); if (EnableHtmlEscape) { Write("&lt;"); } previousOffset = offset + 1; break; case '>': if (!softEscape) { Write(content, previousOffset, offset - previousOffset); if (EnableHtmlEscape) { Write("&gt;"); } previousOffset = offset + 1; } break; case '&': Write(content, previousOffset, offset - previousOffset); if (EnableHtmlEscape) { Write("&amp;"); } previousOffset = offset + 1; break; case '"': if (!softEscape) { Write(content, previousOffset, offset - previousOffset); if (EnableHtmlEscape) { Write("&quot;"); } previousOffset = offset + 1; } break; } } Write(content, previousOffset, end - previousOffset); return this; } private static readonly IdnMapping IdnMapping = new IdnMapping(); /// <summary> /// Writes the URL escaped for HTML. /// </summary> /// <param name="content">The content.</param> /// <returns>This instance</returns> public HtmlRenderer WriteEscapeUrl(string content) { if (content == null) return this; if (BaseUrl != null // According to https://github.com/dotnet/runtime/issues/22718 // this is the proper cross-platform way to check whether a uri is absolute or not: && Uri.TryCreate(content, UriKind.RelativeOrAbsolute, out var contentUri) && !contentUri.IsAbsoluteUri) { content = new Uri(BaseUrl, contentUri).AbsoluteUri; } if (LinkRewriter != null) { content = LinkRewriter(content); } // ab://c.d = 8 chars int schemeOffset = content.Length < 8 ? -1 : content.IndexOf("://", 2, StringComparison.Ordinal); if (schemeOffset != -1) // This is an absolute URL { schemeOffset += 3; // skip :// WriteEscapeUrl(content, 0, schemeOffset); bool idnaEncodeDomain = false; int endOfDomain = schemeOffset; for (; endOfDomain < content.Length; endOfDomain++) { char c = content[endOfDomain]; if (c == '/' || c == '?' || c == '#' || c == ':') // End of domain part { break; } if (c > 127) { idnaEncodeDomain = true; } } if (idnaEncodeDomain) { string domainName; try { domainName = IdnMapping.GetAscii(content, schemeOffset, endOfDomain - schemeOffset); } catch { // Not a valid IDN, fallback to non-punycode encoding WriteEscapeUrl(content, schemeOffset, content.Length); return this; } // Escape the characters (see Commonmark example 327 and think of it with a non-ascii symbol) int previousPosition = 0; for (int i = 0; i < domainName.Length; i++) { var escape = HtmlHelper.EscapeUrlCharacter(domainName[i]); if (escape != null) { Write(domainName, previousPosition, i - previousPosition); previousPosition = i + 1; Write(escape); } } Write(domainName, previousPosition, domainName.Length - previousPosition); WriteEscapeUrl(content, endOfDomain, content.Length); } else { WriteEscapeUrl(content, schemeOffset, content.Length); } } else // This is a relative URL { WriteEscapeUrl(content, 0, content.Length); } return this; } private void WriteEscapeUrl(string content, int start, int length) { int previousPosition = start; for (var i = previousPosition; i < length; i++) { var c = content[i]; if (c < 128) { var escape = HtmlHelper.EscapeUrlCharacter(c); if (escape != null) { Write(content, previousPosition, i - previousPosition); previousPosition = i + 1; Write(escape); } } else { Write(content, previousPosition, i - previousPosition); previousPosition = i + 1; // Special case for Edge/IE workaround for MarkdownEditor, don't escape non-ASCII chars to make image links working if (UseNonAsciiNoEscape) { Write(c); } else { byte[] bytes; if (c >= '\ud800' && c <= '\udfff' && previousPosition < length) { bytes = Encoding.UTF8.GetBytes(new[] { c, content[previousPosition] }); // Skip next char as it is decoded above i++; previousPosition = i + 1; } else { bytes = Encoding.UTF8.GetBytes(new[] { c }); } for (var j = 0; j < bytes.Length; j++) { Write($"%{bytes[j]:X2}"); } } } } Write(content, previousPosition, length - previousPosition); } /// <summary> /// Writes the attached <see cref="HtmlAttributes"/> on the specified <see cref="MarkdownObject"/>. /// </summary> /// <param name="markdownObject">The object.</param> /// <returns></returns> public HtmlRenderer WriteAttributes(MarkdownObject markdownObject) { if (markdownObject == null) ThrowHelper.ArgumentNullException_markdownObject(); return WriteAttributes(markdownObject.TryGetAttributes()); } /// <summary> /// Writes the specified <see cref="HtmlAttributes"/>. /// </summary> /// <param name="attributes">The attributes to render.</param> /// <param name="classFilter">A class filter used to transform a class into another class at writing time</param> /// <returns>This instance</returns> public HtmlRenderer WriteAttributes(HtmlAttributes attributes, Func<string, string> classFilter = null) { if (attributes == null) { return this; } if (attributes.Id != null) { Write(" id=\"").WriteEscape(attributes.Id).Write("\""); } if (attributes.Classes != null && attributes.Classes.Count > 0) { Write(" class=\""); for (int i = 0; i < attributes.Classes.Count; i++) { var cssClass = attributes.Classes[i]; if (i > 0) { Write(" "); } WriteEscape(classFilter != null ? classFilter(cssClass) : cssClass); } Write("\""); } if (attributes.Properties != null && attributes.Properties.Count > 0) { foreach (var property in attributes.Properties) { Write(" ").Write(property.Key); Write("=").Write("\""); WriteEscape(property.Value ?? ""); Write("\""); } } return this; } /// <summary> /// Writes the lines of a <see cref="LeafBlock"/> /// </summary> /// <param name="leafBlock">The leaf block.</param> /// <param name="writeEndOfLines">if set to <c>true</c> write end of lines.</param> /// <param name="escape">if set to <c>true</c> escape the content for HTML</param> /// <param name="softEscape">Only escape &lt; and &amp;</param> /// <returns>This instance</returns> public HtmlRenderer WriteLeafRawLines(LeafBlock leafBlock, bool writeEndOfLines, bool escape, bool softEscape = false) { if (leafBlock == null) ThrowHelper.ArgumentNullException_leafBlock(); if (leafBlock.Lines.Lines != null) { var lines = leafBlock.Lines; var slices = lines.Lines; for (int i = 0; i < lines.Count; i++) { if (!writeEndOfLines && i > 0) { WriteLine(); } if (escape) { WriteEscape(ref slices[i].Slice, softEscape); } else { Write(ref slices[i].Slice); } if (writeEndOfLines) { WriteLine(); } } } return this; } } }
// 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.Reflection; using System.CommandLine; using System.Runtime.InteropServices; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; using Internal.CommandLine; namespace ILCompiler { internal class Program { private Dictionary<string, string> _inputFilePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private Dictionary<string, string> _referenceFilePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private string _outputFilePath; private bool _isCppCodegen; private bool _isWasmCodegen; private bool _isVerbose; private string _dgmlLogFileName; private bool _generateFullDgmlLog; private string _scanDgmlLogFileName; private bool _generateFullScanDgmlLog; private TargetArchitecture _targetArchitecture; private string _targetArchitectureStr; private TargetOS _targetOS; private string _targetOSStr; private OptimizationMode _optimizationMode; private bool _enableDebugInfo; private string _ilDump; private string _systemModuleName = "System.Private.CoreLib"; private bool _multiFile; private bool _useSharedGenerics; private bool _useScanner; private bool _noScanner; private string _mapFileName; private string _metadataLogFileName; private string _singleMethodTypeName; private string _singleMethodName; private IReadOnlyList<string> _singleMethodGenericArgs; private IReadOnlyList<string> _codegenOptions = Array.Empty<string>(); private IReadOnlyList<string> _rdXmlFilePaths = Array.Empty<string>(); private bool _help; private Program() { } private void Help(string helpText) { Console.WriteLine(); Console.Write("Microsoft (R) .NET Native IL Compiler"); Console.Write(" "); Console.Write(typeof(Program).GetTypeInfo().Assembly.GetName().Version); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(helpText); } private void InitializeDefaultOptions() { // We could offer this as a command line option, but then we also need to // load a different RyuJIT, so this is a future nice to have... if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) _targetOS = TargetOS.Windows; else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) _targetOS = TargetOS.Linux; else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) _targetOS = TargetOS.OSX; else throw new NotImplementedException(); switch (RuntimeInformation.ProcessArchitecture) { case Architecture.X86: _targetArchitecture = TargetArchitecture.X86; break; case Architecture.X64: _targetArchitecture = TargetArchitecture.X64; break; case Architecture.Arm: _targetArchitecture = TargetArchitecture.ARM; break; case Architecture.Arm64: _targetArchitecture = TargetArchitecture.ARM64; break; default: throw new NotImplementedException(); } } private ArgumentSyntax ParseCommandLine(string[] args) { IReadOnlyList<string> inputFiles = Array.Empty<string>(); IReadOnlyList<string> referenceFiles = Array.Empty<string>(); bool optimize = false; bool waitForDebugger = false; AssemblyName name = typeof(Program).GetTypeInfo().Assembly.GetName(); ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax => { syntax.ApplicationName = name.Name.ToString(); // HandleHelp writes to error, fails fast with crash dialog and lacks custom formatting. syntax.HandleHelp = false; syntax.HandleErrors = true; syntax.DefineOption("h|help", ref _help, "Help message for ILC"); syntax.DefineOptionList("r|reference", ref referenceFiles, "Reference file(s) for compilation"); syntax.DefineOption("o|out", ref _outputFilePath, "Output file path"); syntax.DefineOption("O", ref optimize, "Enable optimizations"); syntax.DefineOption("g", ref _enableDebugInfo, "Emit debugging information"); syntax.DefineOption("cpp", ref _isCppCodegen, "Compile for C++ code-generation"); syntax.DefineOption("wasm", ref _isWasmCodegen, "Compile for WebAssembly code-generation"); syntax.DefineOption("dgmllog", ref _dgmlLogFileName, "Save result of dependency analysis as DGML"); syntax.DefineOption("fulllog", ref _generateFullDgmlLog, "Save detailed log of dependency analysis"); syntax.DefineOption("scandgmllog", ref _scanDgmlLogFileName, "Save result of scanner dependency analysis as DGML"); syntax.DefineOption("scanfulllog", ref _generateFullScanDgmlLog, "Save detailed log of scanner dependency analysis"); syntax.DefineOption("verbose", ref _isVerbose, "Enable verbose logging"); syntax.DefineOption("systemmodule", ref _systemModuleName, "System module name (default: System.Private.CoreLib)"); syntax.DefineOption("multifile", ref _multiFile, "Compile only input files (do not compile referenced assemblies)"); syntax.DefineOption("waitfordebugger", ref waitForDebugger, "Pause to give opportunity to attach debugger"); syntax.DefineOption("usesharedgenerics", ref _useSharedGenerics, "Enable shared generics"); syntax.DefineOptionList("codegenopt", ref _codegenOptions, "Define a codegen option"); syntax.DefineOptionList("rdxml", ref _rdXmlFilePaths, "RD.XML file(s) for compilation"); syntax.DefineOption("map", ref _mapFileName, "Generate a map file"); syntax.DefineOption("metadatalog", ref _metadataLogFileName, "Generate a metadata log file"); syntax.DefineOption("scan", ref _useScanner, "Use IL scanner to generate optimized code (implied by -O)"); syntax.DefineOption("noscan", ref _noScanner, "Do not use IL scanner to generate optimized code"); syntax.DefineOption("ildump", ref _ilDump, "Dump IL assembly listing for compiler-generated IL"); syntax.DefineOption("targetarch", ref _targetArchitectureStr, "Target architecture for cross compilation"); syntax.DefineOption("targetos", ref _targetOSStr, "Target OS for cross compilation"); syntax.DefineOption("singlemethodtypename", ref _singleMethodTypeName, "Single method compilation: name of the owning type"); syntax.DefineOption("singlemethodname", ref _singleMethodName, "Single method compilation: name of the method"); syntax.DefineOptionList("singlemethodgenericarg", ref _singleMethodGenericArgs, "Single method compilation: generic arguments to the method"); syntax.DefineParameterList("in", ref inputFiles, "Input file(s) to compile"); }); if (waitForDebugger) { Console.WriteLine("Waiting for debugger to attach. Press ENTER to continue"); Console.ReadLine(); } _optimizationMode = optimize ? OptimizationMode.Blended : OptimizationMode.None; foreach (var input in inputFiles) Helpers.AppendExpandedPaths(_inputFilePaths, input, true); foreach (var reference in referenceFiles) Helpers.AppendExpandedPaths(_referenceFilePaths, reference, false); return argSyntax; } private int Run(string[] args) { InitializeDefaultOptions(); ArgumentSyntax syntax = ParseCommandLine(args); if (_help) { Help(syntax.GetHelpText()); return 1; } if (_outputFilePath == null) throw new CommandLineException("Output filename must be specified (/out <file>)"); // // Set target Architecture and OS // if (_targetArchitectureStr != null) { if (_targetArchitectureStr.Equals("x86", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.X86; else if (_targetArchitectureStr.Equals("x64", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.X64; else if (_targetArchitectureStr.Equals("arm", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.ARM; else if (_targetArchitectureStr.Equals("armel", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.ARMEL; else if (_targetArchitectureStr.Equals("arm64", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.ARM64; else throw new CommandLineException("Target architecture is not supported"); } if (_targetOSStr != null) { if (_targetOSStr.Equals("windows", StringComparison.OrdinalIgnoreCase)) _targetOS = TargetOS.Windows; else if (_targetOSStr.Equals("linux", StringComparison.OrdinalIgnoreCase)) _targetOS = TargetOS.Linux; else if (_targetOSStr.Equals("osx", StringComparison.OrdinalIgnoreCase)) _targetOS = TargetOS.OSX; else throw new CommandLineException("Target OS is not supported"); } if (_isWasmCodegen) _targetArchitecture = TargetArchitecture.Wasm32; // // Initialize type system context // SharedGenericsMode genericsMode = _useSharedGenerics || (!_isCppCodegen && !_isWasmCodegen) ? SharedGenericsMode.CanonicalReferenceTypes : SharedGenericsMode.Disabled; // TODO: compiler switch for SIMD support? var simdVectorLength = (_isCppCodegen || _isWasmCodegen) ? SimdVectorLength.None : SimdVectorLength.Vector128Bit; var targetDetails = new TargetDetails(_targetArchitecture, _targetOS, TargetAbi.CoreRT, simdVectorLength); var typeSystemContext = new CompilerTypeSystemContext(targetDetails, genericsMode); // // TODO: To support our pre-compiled test tree, allow input files that aren't managed assemblies since // some tests contain a mixture of both managed and native binaries. // // See: https://github.com/dotnet/corert/issues/2785 // // When we undo this this hack, replace this foreach with // typeSystemContext.InputFilePaths = _inputFilePaths; // Dictionary<string, string> inputFilePaths = new Dictionary<string, string>(); foreach (var inputFile in _inputFilePaths) { try { var module = typeSystemContext.GetModuleFromPath(inputFile.Value); inputFilePaths.Add(inputFile.Key, inputFile.Value); } catch (TypeSystemException.BadImageFormatException) { // Keep calm and carry on. } } typeSystemContext.InputFilePaths = inputFilePaths; typeSystemContext.ReferenceFilePaths = _referenceFilePaths; typeSystemContext.SetSystemModule(typeSystemContext.GetModuleForSimpleName(_systemModuleName)); if (typeSystemContext.InputFilePaths.Count == 0) throw new CommandLineException("No input files specified"); // // Initialize compilation group and compilation roots // // Single method mode? MethodDesc singleMethod = CheckAndParseSingleMethodModeArguments(typeSystemContext); CompilationModuleGroup compilationGroup; List<ICompilationRootProvider> compilationRoots = new List<ICompilationRootProvider>(); if (singleMethod != null) { // Compiling just a single method compilationGroup = new SingleMethodCompilationModuleGroup(singleMethod); compilationRoots.Add(new SingleMethodRootProvider(singleMethod)); } else { // Either single file, or multifile library, or multifile consumption. EcmaModule entrypointModule = null; foreach (var inputFile in typeSystemContext.InputFilePaths) { EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); if (module.PEReader.PEHeaders.IsExe) { if (entrypointModule != null) throw new Exception("Multiple EXE modules"); entrypointModule = module; } // TODO: Wasm fails to compile some of the exported methods due to missing opcodes if (!_isWasmCodegen) { compilationRoots.Add(new ExportedMethodsRootProvider(module)); } } if (entrypointModule != null) { // TODO: Wasm fails to compile some of the library initializers if (!_isWasmCodegen) { LibraryInitializers libraryInitializers = new LibraryInitializers(typeSystemContext, _isCppCodegen); compilationRoots.Add(new MainMethodRootProvider(entrypointModule, libraryInitializers.LibraryInitializerMethods)); } else { compilationRoots.Add(new RawMainMethodRootProvider(entrypointModule)); } } if (_multiFile) { List<EcmaModule> inputModules = new List<EcmaModule>(); foreach (var inputFile in typeSystemContext.InputFilePaths) { EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); if (entrypointModule == null) { // This is a multifile production build - we need to root all methods compilationRoots.Add(new LibraryRootProvider(module)); } inputModules.Add(module); } compilationGroup = new MultiFileSharedCompilationModuleGroup(typeSystemContext, inputModules); } else { if (entrypointModule == null) throw new Exception("No entrypoint module"); // TODO: Wasm fails to compile some of the xported methods due to missing opcodes if (!_isWasmCodegen) { compilationRoots.Add(new ExportedMethodsRootProvider((EcmaModule)typeSystemContext.SystemModule)); } compilationGroup = new SingleFileCompilationModuleGroup(typeSystemContext); } foreach (var rdXmlFilePath in _rdXmlFilePaths) { compilationRoots.Add(new RdXmlRootProvider(typeSystemContext, rdXmlFilePath)); } } // // Compile // CompilationBuilder builder; if (_isWasmCodegen) builder = new WebAssemblyCodegenCompilationBuilder(typeSystemContext, compilationGroup); else if (_isCppCodegen) builder = new CppCodegenCompilationBuilder(typeSystemContext, compilationGroup); else builder = new RyuJitCompilationBuilder(typeSystemContext, compilationGroup); bool useScanner = _useScanner || (_optimizationMode != OptimizationMode.None && !_isCppCodegen && !_isWasmCodegen); useScanner &= !_noScanner; ILScanResults scanResults = null; if (useScanner) { ILScannerBuilder scannerBuilder = builder.GetILScannerBuilder() .UseCompilationRoots(compilationRoots); if (_scanDgmlLogFileName != null) scannerBuilder.UseDependencyTracking(_generateFullScanDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First); IILScanner scanner = scannerBuilder.ToILScanner(); scanResults = scanner.Scan(); } var logger = new Logger(Console.Out, _isVerbose); DebugInformationProvider debugInfoProvider = _enableDebugInfo ? (_ilDump == null ? new DebugInformationProvider() : new ILAssemblyGeneratingMethodDebugInfoProvider(_ilDump, new EcmaOnlyDebugInformationProvider())) : new NullDebugInformationProvider(); DependencyTrackingLevel trackingLevel = _dgmlLogFileName == null ? DependencyTrackingLevel.None : (_generateFullDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First); CompilerGeneratedMetadataManager metadataManager = new CompilerGeneratedMetadataManager(compilationGroup, typeSystemContext, _metadataLogFileName); builder .UseBackendOptions(_codegenOptions) .UseMetadataManager(metadataManager) .UseLogger(logger) .UseDependencyTracking(trackingLevel) .UseCompilationRoots(compilationRoots) .UseOptimizationMode(_optimizationMode) .UseDebugInfoProvider(debugInfoProvider); if (scanResults != null) { // If we have a scanner, feed the vtable analysis results to the compilation. // This could be a command line switch if we really wanted to. builder.UseVTableSliceProvider(scanResults.GetVTableLayoutInfo()); // If we have a scanner, feed the generic dictionary results to the compilation. // This could be a command line switch if we really wanted to. builder.UseGenericDictionaryLayoutProvider(scanResults.GetDictionaryLayoutInfo()); } ICompilation compilation = builder.ToCompilation(); ObjectDumper dumper = _mapFileName != null ? new ObjectDumper(_mapFileName) : null; CompilationResults compilationResults = compilation.Compile(_outputFilePath, dumper); if (_dgmlLogFileName != null) compilationResults.WriteDependencyLog(_dgmlLogFileName); if (scanResults != null) { SimdHelper simdHelper = new SimdHelper(); if (_scanDgmlLogFileName != null) scanResults.WriteDependencyLog(_scanDgmlLogFileName); // If the scanner and compiler don't agree on what to compile, the outputs of the scanner might not actually be usable. // We are going to check this two ways: // 1. The methods and types generated during compilation are a subset of method and types scanned // 2. The methods and types scanned are a subset of methods and types compiled (this has a chance to hold for unoptimized builds only). // Check that methods and types generated during compilation are a subset of method and types scanned bool scanningFail = false; DiffCompilationResults(ref scanningFail, compilationResults.CompiledMethodBodies, scanResults.CompiledMethodBodies, "Methods", "compiled", "scanned", method => !(method.GetTypicalMethodDefinition() is EcmaMethod)); DiffCompilationResults(ref scanningFail, compilationResults.ConstructedEETypes, scanResults.ConstructedEETypes, "EETypes", "compiled", "scanned", type => !(type.GetTypeDefinition() is EcmaType)); // If optimizations are enabled, the results will for sure not match in the other direction due to inlining, etc. // But there's at least some value in checking the scanner doesn't expand the universe too much in debug. if (_optimizationMode == OptimizationMode.None) { // Check that methods and types scanned are a subset of methods and types compiled // If we find diffs here, they're not critical, but still might be causing a Size on Disk regression. bool dummy = false; // We additionally skip methods in SIMD module because there's just too many intrisics to handle and IL scanner // doesn't expand them. They would show up as noisy diffs. DiffCompilationResults(ref dummy, scanResults.CompiledMethodBodies, compilationResults.CompiledMethodBodies, "Methods", "scanned", "compiled", method => !(method.GetTypicalMethodDefinition() is EcmaMethod) || simdHelper.IsInSimdModule(method.OwningType)); DiffCompilationResults(ref dummy, scanResults.ConstructedEETypes, compilationResults.ConstructedEETypes, "EETypes", "scanned", "compiled", type => !(type.GetTypeDefinition() is EcmaType)); } if (scanningFail) throw new Exception("Scanning failure"); } if (debugInfoProvider is IDisposable) ((IDisposable)debugInfoProvider).Dispose(); return 0; } [System.Diagnostics.Conditional("DEBUG")] private void DiffCompilationResults<T>(ref bool result, IEnumerable<T> set1, IEnumerable<T> set2, string prefix, string set1name, string set2name, Predicate<T> filter) { HashSet<T> diff = new HashSet<T>(set1); diff.ExceptWith(set2); // TODO: move ownership of compiler-generated entities to CompilerTypeSystemContext. // https://github.com/dotnet/corert/issues/3873 diff.RemoveWhere(filter); if (diff.Count > 0) { result = true; Console.WriteLine($"*** {prefix} {set1name} but not {set2name}:"); foreach (var d in diff) { Console.WriteLine(d.ToString()); } } } private TypeDesc FindType(CompilerTypeSystemContext context, string typeName) { ModuleDesc systemModule = context.SystemModule; TypeDesc foundType = systemModule.GetTypeByCustomAttributeTypeName(typeName, false, (typeDefName, module, throwIfNotFound) => { return (MetadataType)context.GetCanonType(typeDefName) ?? CustomAttributeTypeNameParser.ResolveCustomAttributeTypeDefinitionName(typeDefName, module, throwIfNotFound); }); if (foundType == null) throw new CommandLineException($"Type '{typeName}' not found"); return foundType; } private MethodDesc CheckAndParseSingleMethodModeArguments(CompilerTypeSystemContext context) { if (_singleMethodName == null && _singleMethodTypeName == null && _singleMethodGenericArgs == null) return null; if (_singleMethodName == null || _singleMethodTypeName == null) throw new CommandLineException("Both method name and type name are required parameters for single method mode"); TypeDesc owningType = FindType(context, _singleMethodTypeName); // TODO: allow specifying signature to distinguish overloads MethodDesc method = owningType.GetMethod(_singleMethodName, null); if (method == null) throw new CommandLineException($"Method '{_singleMethodName}' not found in '{_singleMethodTypeName}'"); if (method.HasInstantiation != (_singleMethodGenericArgs != null) || (method.HasInstantiation && (method.Instantiation.Length != _singleMethodGenericArgs.Count))) { throw new CommandLineException( $"Expected {method.Instantiation.Length} generic arguments for method '{_singleMethodName}' on type '{_singleMethodTypeName}'"); } if (method.HasInstantiation) { List<TypeDesc> genericArguments = new List<TypeDesc>(); foreach (var argString in _singleMethodGenericArgs) genericArguments.Add(FindType(context, argString)); method = method.MakeInstantiatedMethod(genericArguments.ToArray()); } return method; } private static bool DumpReproArguments(CodeGenerationFailedException ex) { Console.WriteLine("To repro, add following arguments to the command line:"); MethodDesc failingMethod = ex.Method; var formatter = new CustomAttributeTypeNameFormatter((IAssemblyDesc)failingMethod.Context.SystemModule); Console.Write($"--singlemethodtypename {formatter.FormatName(failingMethod.OwningType)}"); Console.Write($" --singlemethodname {failingMethod.Name}"); for (int i = 0; i < failingMethod.Instantiation.Length; i++) Console.Write($" --singlemethodgenericarg {formatter.FormatName(failingMethod.Instantiation[i])}"); return false; } private static int Main(string[] args) { #if DEBUG try { return new Program().Run(args); } catch (CodeGenerationFailedException ex) when (DumpReproArguments(ex)) { throw new NotSupportedException(); // Unreachable } #else try { return new Program().Run(args); } catch (Exception e) { Console.Error.WriteLine("Error: " + e.Message); Console.Error.WriteLine(e.ToString()); return 1; } #endif } } }
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. using System; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using System.Runtime.InteropServices; using System.Collections; using System.IO; using Microsoft.Win32; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; using IServiceProvider = System.IServiceProvider; using System.Diagnostics; using System.Xml; using System.Text; using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID; using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID; using Microsoft.VisualStudio.FSharp.LanguageService.Resources; namespace Microsoft.VisualStudio.FSharp.LanguageService { internal class DefaultFieldValue { private string field; private string value; internal DefaultFieldValue(string field, string value) { this.field = field; this.value = value; } internal string Field { get { return this.field; } } internal string Value { get { return this.value; } } } [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public class ExpansionProvider : IDisposable, IVsExpansionClient { IVsTextView view; ISource source; IVsExpansion vsExpansion; IVsExpansionSession expansionSession; bool expansionActive; bool expansionPrepared; bool completorActiveDuringPreExec; ArrayList fieldDefaults; // CDefaultFieldValues string titleToInsert; string pathToInsert; internal ExpansionProvider(ISource src) { if (src == null){ throw new ArgumentNullException("src"); } this.fieldDefaults = new ArrayList(); if (src == null) throw new System.ArgumentNullException(); this.source = src; this.vsExpansion = null; // do we need a Close() method here? // QI for IVsExpansion IVsTextLines buffer = src.GetTextLines(); this.vsExpansion = (IVsExpansion)buffer; if (this.vsExpansion == null) { throw new ArgumentNullException("(IVsExpansion)src.GetTextLines()"); } } ~ExpansionProvider() { #if LANGTRACE Trace.WriteLine("~ExpansionProvider"); #endif } public virtual void Dispose() { EndTemplateEditing(true); this.source = null; this.vsExpansion = null; this.view = null; GC.SuppressFinalize(this); } internal ISource Source { get { return this.source; } } internal IVsTextView TextView { get { return this.view; } } internal IVsExpansion Expansion { get { return this.vsExpansion; } } internal IVsExpansionSession ExpansionSession { get { return this.expansionSession; } } internal virtual bool HandleQueryStatus(ref Guid guidCmdGroup, uint nCmdId, out int hr) { // in case there's something to conditinally support later on... hr = 0; return false; } internal virtual bool InTemplateEditingMode { get { return this.expansionActive; } } internal virtual TextSpan GetExpansionSpan() { if (this.expansionSession == null){ throw new System.InvalidOperationException(SR.GetString(SR.NoExpansionSession)); } TextSpan[] pts = new TextSpan[1]; int hr = this.expansionSession.GetSnippetSpan(pts); if (NativeMethods.Succeeded(hr)) { return pts[0]; } return new TextSpan(); } internal virtual bool HandlePreExec(ref Guid guidCmdGroup, uint nCmdId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (!this.expansionActive || this.expansionSession == null) { return false; } this.completorActiveDuringPreExec = this.IsCompletorActive(this.view); if (guidCmdGroup == typeof(VsCommands2K).GUID) { VsCommands2K cmd = (VsCommands2K)nCmdId; #if TRACE_EXEC Trace.WriteLine(String.Format("ExecCommand: {0}", cmd.ToString())); #endif switch (cmd) { case VsCommands2K.CANCEL: if (this.completorActiveDuringPreExec) return false; EndTemplateEditing(true); return true; case VsCommands2K.RETURN: bool leaveCaret = false; int line = 0, col = 0; if (NativeMethods.Succeeded(this.view.GetCaretPos(out line, out col))) { TextSpan span = GetExpansionSpan(); if (!TextSpanHelper.ContainsExclusive(span, line, col)) { leaveCaret = true; } } if (this.completorActiveDuringPreExec) return false; if (this.completorActiveDuringPreExec) return false; EndTemplateEditing(leaveCaret); if (leaveCaret) return false; return true; case VsCommands2K.BACKTAB: if (this.completorActiveDuringPreExec) return false; this.expansionSession.GoToPreviousExpansionField(); return true; case VsCommands2K.TAB: if (this.completorActiveDuringPreExec) return false; this.expansionSession.GoToNextExpansionField(0); // fCommitIfLast=false return true; #if TRACE_EXEC case VsCommands2K.TYPECHAR: if (pvaIn != IntPtr.Zero) { Variant v = Variant.ToVariant(pvaIn); char ch = v.ToChar(); Trace.WriteLine(String.Format("TYPECHAR: {0}, '{1}', {2}", cmd.ToString(), ch.ToString(), (int)ch)); } return true; #endif } } return false; } internal virtual bool HandlePostExec(ref Guid guidCmdGroup, uint nCmdId, uint nCmdexecopt, bool commit, IntPtr pvaIn, IntPtr pvaOut) { if (guidCmdGroup == typeof(VsCommands2K).GUID) { VsCommands2K cmd = (VsCommands2K)nCmdId; switch (cmd) { case VsCommands2K.RETURN: if (this.completorActiveDuringPreExec && commit) { // if the completor was active during the pre-exec we want to let it handle the command first // so we didn't deal with this in pre-exec. If we now get the command, we want to end // the editing of the expansion. We also return that we handled the command so auto-indenting doesn't happen EndTemplateEditing(false); this.completorActiveDuringPreExec = false; return true; } break; } } this.completorActiveDuringPreExec = false; return false; } internal virtual bool DisplayExpansionBrowser(IVsTextView view, string prompt, string[] types, bool includeNullType, string[] kinds, bool includeNullKind) { if (this.expansionActive) this.EndTemplateEditing(true); if (this.source.IsCompletorActive) { this.source.DismissCompletor(); } this.view = view; IServiceProvider site = this.source.LanguageService.Site; IVsTextManager2 textmgr = site.GetService(typeof(SVsTextManager)) as IVsTextManager2; if (textmgr == null) return false; IVsExpansionManager exmgr; textmgr.GetExpansionManager(out exmgr); Guid languageSID = this.source.LanguageService.GetLanguageServiceGuid(); int hr = 0; if (exmgr != null) { hr = exmgr.InvokeInsertionUI(view, // pView this, // pClient languageSID, // guidLang types, // bstrTypes (types == null) ? 0 : types.Length, // iCountTypes includeNullType ? 1 : 0, // fIncludeNULLType kinds, // bstrKinds (kinds == null) ? 0 : kinds.Length, // iCountKinds includeNullKind ? 1 : 0, // fIncludeNULLKind prompt, // bstrPrefixText ">" //bstrCompletionChar ); if (NativeMethods.Succeeded(hr)) { return true; } } return false; } internal virtual bool InsertSpecificExpansion(IVsTextView view, XmlElement snippet, TextSpan pos, string relativePath) { if (this.expansionActive) this.EndTemplateEditing(true); if (this.source.IsCompletorActive) { this.source.DismissCompletor(); } this.view = view; MSXML.IXMLDOMDocument doc = (MSXML.IXMLDOMDocument)new MSXML.DOMDocumentClass(); if (!doc.loadXML(snippet.OuterXml)) { throw new ArgumentException(doc.parseError.reason); } Guid guidLanguage = this.source.LanguageService.GetLanguageServiceGuid(); int hr = this.vsExpansion.InsertSpecificExpansion(doc, pos, this, guidLanguage, relativePath, out this.expansionSession); if (hr != NativeMethods.S_OK || this.expansionSession == null) { this.EndTemplateEditing(true); } else { this.expansionActive = true; return true; } return false; } bool IsCompletorActive(IVsTextView view){ if (this.source.IsCompletorActive) return true; IVsTextViewEx viewex = view as IVsTextViewEx; if (viewex != null) { return viewex.IsCompletorWindowActive() == Microsoft.VisualStudio.VSConstants.S_OK; } return false; } internal virtual bool InsertNamedExpansion(IVsTextView view, string title, string path, TextSpan pos, bool showDisambiguationUI) { if (this.source.IsCompletorActive) { this.source.DismissCompletor(); } this.view = view; if (this.expansionActive) this.EndTemplateEditing(true); Guid guidLanguage = this.source.LanguageService.GetLanguageServiceGuid(); int hr = this.vsExpansion.InsertNamedExpansion(title, path, pos, this, guidLanguage, showDisambiguationUI ? 1 : 0, out this.expansionSession); if (hr != NativeMethods.S_OK || this.expansionSession == null) { this.EndTemplateEditing(true); return false; } else if (hr == NativeMethods.S_OK) { this.expansionActive = true; return true; } return false; } /// <summary>Returns S_OK if match found, S_FALSE if expansion UI is shown, and error otherwise</summary> internal virtual int FindExpansionByShortcut(IVsTextView view, string shortcut, TextSpan span, bool showDisambiguationUI, out string title, out string path) { if (this.expansionActive) this.EndTemplateEditing(true); this.view = view; title = path = null; LanguageService_DEPRECATED svc = this.source.LanguageService; IVsExpansionManager mgr = svc.Site.GetService(typeof(SVsExpansionManager)) as IVsExpansionManager; if (mgr == null) return NativeMethods.E_FAIL ; Guid guidLanguage = svc.GetLanguageServiceGuid(); TextSpan[] pts = new TextSpan[1]; pts[0] = span; int hr = mgr.GetExpansionByShortcut(this, guidLanguage, shortcut, this.TextView, pts, showDisambiguationUI ? 1 : 0, out path, out title); return hr; } public virtual IVsExpansionFunction GetExpansionFunction(XmlElement xmlFunctionNode, string fieldName) { string functionName = null; ArrayList rgFuncParams = new ArrayList(); // first off, get the function string from the node string function = xmlFunctionNode.InnerText; if (function == null || function.Length == 0) return null; bool inIdent = false; bool inParams = false; int token = 0; // initialize the vars needed for our super-complex function parser :-) for (int i = 0, n = function.Length; i < n; i++) { char ch = function[i]; // ignore and skip whitespace if (!Char.IsWhiteSpace(ch)) { switch (ch) { case ',': if (!inIdent || !inParams) i = n; // terminate loop else { // we've hit a comma, so end this param and move on... string name = function.Substring(token, i - token); rgFuncParams.Add(name); inIdent = false; } break; case '(': if (!inIdent || inParams) i = n; // terminate loop else { // we've hit the (, so we know the token before this is the name of the function functionName = function.Substring(token, i - token); inIdent = false; inParams = true; } break; case ')': if (!inParams) i = n; // terminate loop else { if (inIdent) { // save last param and stop string name = function.Substring(token, i - token); rgFuncParams.Add(name); inIdent = false; } i = n; // terminate loop } break; default: if (!inIdent) { inIdent = true; token = i; } break; } } } if (functionName != null && functionName.Length > 0) { ExpansionFunction func = this.source.LanguageService.CreateExpansionFunction(this, functionName); if (func != null) { func.FieldName = fieldName; func.Arguments = (string[])rgFuncParams.ToArray(typeof(string)); return func; } } return null; } internal virtual void PrepareTemplate(string title, string path) { if (title == null) throw new System.ArgumentNullException("title"); // stash the title and path for when we actually insert the template this.titleToInsert = title; this.pathToInsert = path; this.expansionPrepared = true; } void SetFieldDefault(string field, string value) { if (!this.expansionPrepared) { throw new System.InvalidOperationException(SR.GetString(SR.TemplateNotPrepared)); } if (field == null) throw new System.ArgumentNullException("field"); if (value == null) throw new System.ArgumentNullException("value"); // we have an expansion "prepared" to insert, so we can now save this // field default to set when the expansion is actually inserted this.fieldDefaults.Add(new DefaultFieldValue(field, value)); } internal virtual void BeginTemplateEditing(int line, int col) { if (!this.expansionPrepared) { throw new System.InvalidOperationException(SR.GetString(SR.TemplateNotPrepared)); } TextSpan tsInsert = new TextSpan(); tsInsert.iStartLine = tsInsert.iEndLine = line; tsInsert.iStartIndex = tsInsert.iEndIndex = col; Guid languageSID = this.source.LanguageService.GetType().GUID; int hr = this.vsExpansion.InsertNamedExpansion(this.titleToInsert, this.pathToInsert, tsInsert, (IVsExpansionClient)this, languageSID, 0, // fShowDisambiguationUI, out this.expansionSession); if (hr != NativeMethods.S_OK) { this.EndTemplateEditing(true); } this.pathToInsert = null; this.titleToInsert = null; } internal virtual void EndTemplateEditing(bool leaveCaret) { if (!this.expansionActive || this.expansionSession == null) { this.expansionActive = false; return; } this.expansionSession.EndCurrentExpansion(leaveCaret ? 1 : 0); // fLeaveCaret=true this.expansionSession = null; this.expansionActive = false; } internal virtual bool GetFieldSpan(string field, out TextSpan pts) { if (this.expansionSession == null) { throw new System.InvalidOperationException(SR.GetString(SR.NoExpansionSession)); } if (this.expansionSession != null) { TextSpan[] apt = new TextSpan[1]; this.expansionSession.GetFieldSpan(field, apt); pts = apt[0]; return true; } else { pts = new TextSpan(); return false; } } internal virtual bool GetFieldValue(string field, out string value) { if (this.expansionSession == null) { throw new System.InvalidOperationException(SR.GetString(SR.NoExpansionSession)); } if (this.expansionSession != null) { this.expansionSession.GetFieldValue(field, out value); } else { value = null; } return value != null; } public int EndExpansion() { this.expansionActive = false; this.expansionSession = null; return NativeMethods.S_OK; } public virtual int FormatSpan(IVsTextLines buffer, TextSpan[] ts) { if (this.source.GetTextLines() != buffer) { throw new System.ArgumentException(SR.GetString(SR.UnknownBuffer), "buffer"); } int rc = NativeMethods.E_NOTIMPL; if (ts != null) { for (int i = 0, n = ts.Length; i < n; i++) { if (this.source.LanguageService.Preferences.EnableFormatSelection) { TextSpan span = ts[i]; // We should not merge edits in this case because it might clobber the // $varname$ spans which are markers for yellow boxes. using (EditArray edits = new EditArray(this.source, this.view, false, SR.GetString(SR.FormatSpan))) { this.source.ReformatSpan(edits, span); edits.ApplyEdits(); } rc = NativeMethods.S_OK; } } } return rc; } public virtual int IsValidKind(IVsTextLines buffer, TextSpan[] ts, string bstrKind, out int /*BOOL*/ fIsValid) { fIsValid = 0; if (this.source.GetTextLines() != buffer) { throw new System.ArgumentException(SR.GetString(SR.UnknownBuffer), "buffer"); } fIsValid = 1; return NativeMethods.S_OK; } public virtual int IsValidType(IVsTextLines buffer, TextSpan[] ts, string[] rgTypes, int iCountTypes, out int /*BOOL*/ fIsValid) { fIsValid = 0; if (this.source.GetTextLines() != buffer) { throw new System.ArgumentException(SR.GetString(SR.UnknownBuffer), "buffer"); } fIsValid = 1; return NativeMethods.S_OK; } public virtual int OnItemChosen(string pszTitle, string pszPath) { TextSpan ts; view.GetCaretPos(out ts.iStartLine, out ts.iStartIndex); ts.iEndLine = ts.iStartLine; ts.iEndIndex = ts.iStartIndex; if (this.expansionSession != null) { // previous session should have been ended by now! EndTemplateEditing(true); } Guid languageSID = this.source.LanguageService.GetType().GUID; // insert the expansion int hr = this.vsExpansion.InsertNamedExpansion(pszTitle, pszPath, ts, (IVsExpansionClient)this, languageSID, 0, // fShowDisambiguationUI, (FALSE) out this.expansionSession); return hr; } public virtual int PositionCaretForEditing(IVsTextLines pBuffer, TextSpan[] ts) { // NOP return NativeMethods.S_OK; } public virtual int OnAfterInsertion(IVsExpansionSession session) { return NativeMethods.S_OK; } public virtual int OnBeforeInsertion(IVsExpansionSession session) { if (session == null) return NativeMethods.E_UNEXPECTED; this.expansionPrepared = false; this.expansionActive = true; // stash the expansion session pointer while the expansion is active if (this.expansionSession == null) { this.expansionSession = session; } else { // these better be the same! Debug.Assert(this.expansionSession == session); } // now set any field defaults that we have. foreach (DefaultFieldValue dv in this.fieldDefaults) { this.expansionSession.SetFieldDefault(dv.Field, dv.Value); } this.fieldDefaults.Clear(); return NativeMethods.S_OK; } public virtual int GetExpansionFunction(MSXML.IXMLDOMNode xmlFunctionNode, string fieldName, out IVsExpansionFunction func) { XmlDocument doc = new XmlDocument(); doc.XmlResolver = null; using(StringReader stream = new StringReader(xmlFunctionNode.xml)) using (XmlReader reader = XmlReader.Create(stream, new XmlReaderSettings() { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null })) { doc.Load(reader); func = GetExpansionFunction(doc.DocumentElement, fieldName); } return NativeMethods.S_OK; } } [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public abstract class ExpansionFunction : IVsExpansionFunction { ExpansionProvider provider; string fieldName; string[] args; string[] list; /// <summary>You must construct this object with an ExpansionProvider</summary> private ExpansionFunction() { } internal ExpansionFunction(ExpansionProvider provider) { this.provider = provider; } public ExpansionProvider ExpansionProvider { get { return this.provider; } } public string[] Arguments { get { return this.args; } set { this.args = value; } } public string FieldName { get { return this.fieldName; } set { this.fieldName = value; } } public abstract string GetCurrentValue(); public virtual string GetDefaultValue() { // This must call GetCurrentValue sincs during initialization of the snippet // VS will call GetDefaultValue and not GetCurrentValue. return GetCurrentValue(); } /// <summary>Override this method if you want intellisense drop support on a list of possible values.</summary> public virtual string[] GetIntellisenseList() { return null; } /// <summary> /// Gets the value of the specified argument, resolving any fields referenced in the argument. /// In the substitution, "$$" is replaced with "$" and any floating '$' signs are left unchanged, /// for example "$US 23.45" is returned as is. Only if the two dollar signs enclose a string of /// letters or digits is this considered a field name (e.g. "$foo123$"). If the field is not found /// then the unresolved string "$foo" is returned. /// </summary> public string GetArgument(int index) { if (args == null || args.Length == 0 || index > args.Length) return null; string arg = args[index]; if (arg == null) return null; int i = arg.IndexOf('$'); if (i >= 0) { StringBuilder sb = new StringBuilder(); int len = arg.Length; int start = 0; while (i >= 0 && i + 1 < len) { sb.Append(arg.Substring(start, i - start)); start = i; i++; if (arg[i] == '$') { sb.Append('$'); start = i + 1; // $$ is resolved to $. } else { // parse name of variable. int j = i; for (; j < len; j++) { if (!Char.IsLetterOrDigit(arg[j])) break; } if (j == len) { // terminating '$' not found. sb.Append('$'); start = i; break; } else if (arg[j] == '$') { string name = arg.Substring(i, j - i); string value; if (GetFieldValue(name, out value)) { sb.Append(value); } else { // just return the unresolved variable. sb.Append('$'); sb.Append(name); sb.Append('$'); } start = j + 1; } else { // invalid syntax, e.g. "$US 23.45" or some such thing sb.Append('$'); sb.Append(arg.Substring(i, j - i)); start = j; } } i = arg.IndexOf('$', start); } if (start < len) { sb.Append(arg.Substring(start, len - start)); } arg = sb.ToString(); } // remove quotes around string literals. if (arg.Length > 2 && arg[0] == '"' && arg[arg.Length - 1] == '"') { arg = arg.Substring(1, arg.Length - 2); } else if (arg.Length > 2 && arg[0] == '\'' && arg[arg.Length - 1] == '\'') { arg = arg.Substring(1, arg.Length - 2); } return arg; } public bool GetFieldValue(string name, out string value) { value = null; if (this.provider != null && this.provider.ExpansionSession != null) { int hr = this.provider.ExpansionSession.GetFieldValue(name, out value); return NativeMethods.Succeeded(hr); } return false; } public TextSpan GetSelection() { TextSpan result = new TextSpan(); ExpansionProvider provider = this.ExpansionProvider; if (provider != null && provider.TextView != null) { NativeMethods.ThrowOnFailure(provider.TextView.GetSelection(out result.iStartLine, out result.iStartIndex, out result.iEndLine, out result.iEndIndex)); } return result; } public virtual int FieldChanged(string bstrField, out int fRequeryValue) { // Returns true if we care about this field changing. // We care if the field changes if one of the arguments refers to it. if (this.args != null) { string var = "$" + bstrField + "$"; foreach (string arg in this.args) { if (arg == var) { fRequeryValue = 1; // we care! return NativeMethods.S_OK; } } } fRequeryValue = 0; return NativeMethods.S_OK; } public int GetCurrentValue(out string bstrValue, out int hasDefaultValue) { try { bstrValue = this.GetCurrentValue(); } catch { bstrValue = String.Empty; } hasDefaultValue = (bstrValue == null) ? 0 : 1; return NativeMethods.S_OK; } public int GetDefaultValue(out string bstrValue, out int hasCurrentValue) { try { bstrValue = this.GetDefaultValue(); } catch { bstrValue = String.Empty; } hasCurrentValue = (bstrValue == null) ? 0 : 1; return NativeMethods.S_OK; } public virtual int GetFunctionType(out uint pFuncType) { if (this.list == null) { this.list = this.GetIntellisenseList(); } pFuncType = (this.list == null) ? (uint)_ExpansionFunctionType.eft_Value : (uint)_ExpansionFunctionType.eft_List; return NativeMethods.S_OK; } public virtual int GetListCount(out int iListCount) { if (this.list == null) { this.list = this.GetIntellisenseList(); } if (this.list != null) { iListCount = this.list.Length; } else { iListCount = 0; } return NativeMethods.S_OK; } public virtual int GetListText(int iIndex, out string ppszText) { if (this.list == null) { this.list = this.GetIntellisenseList(); } if (this.list != null) { ppszText = this.list[iIndex]; } else { ppszText = null; } return NativeMethods.S_OK; } public virtual int ReleaseFunction() { this.provider = null; return NativeMethods.S_OK; } } // todo: for some reason VsExpansionManager is wrong. [Guid("4970C2BC-AF33-4a73-A34F-18B0584C40E4")] internal class SVsExpansionManager { } }
/* * ICE.cs - Native method interface for ICE. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace Xsharp.Ice { using System; using System.Runtime.InteropServices; using OpenSystem.Platform; using OpenSystem.Platform.X11; internal sealed unsafe class ICE { [StructLayout(LayoutKind.Explicit)] public struct IcePoAuthProcIncapsulator { [FieldOffset(0)] IcePoAuthProc cb; public IcePoAuthProcIncapsulator(IcePoAuthProc cb) { this.cb = cb; } } [StructLayout(LayoutKind.Explicit)] public struct IcePoProcessMsgProcIncapsulator { [FieldOffset(0)] IcePoProcessMsgProc cb; public IcePoProcessMsgProcIncapsulator(IcePoProcessMsgProc cb) { this.cb = cb; } } [DllImport("ICE")] extern public static Xlib.Xint IceRegisterForProtocolSetup (String protocolName, String vendor, String release, Xlib.Xint versionCount, ref IcePoVersionRec versionRecs, Xlib.Xint authCount, String[] authNames, ref IcePoAuthProcIncapsulator authProcs, IceIOErrorProc ioErrorProc); [DllImport("ICE")] extern public static Xlib.Xint IceRegisterForProtocolReply (String protocolName, String vendor, String release, Xlib.Xint versionCount, ref IcePaVersionRec versionRecs, Xlib.Xint authCount, ref String[] authNames, ref IcePaAuthProc authProcs, IceHostBasedAuthProc hostBasedAuthProc, IceProtocolSetupProc protocolSetupProc, IceProtocolActivateProc protocolActivateProc, IceIOErrorProc ioErrorProc); [DllImport("ICE")] extern public static IceConn *IceOpenConnection (String networkIdsList, IntPtr context, XBool mustAuthenticate, Xlib.Xint majorOpcodeCheck, Xlib.Xint errorLength, byte[] errorStringRet); [DllImport("ICE")] extern public static IntPtr IceGetConnectionContext(IceConn *iceConn); [DllImport("ICE")] extern public static XStatus IceListenForConnections (ref Xlib.Xint countRet, ref IntPtr listenObjsRet, Xlib.Xint errorLength, byte[] errorStringRet); [DllImport("ICE")] extern public static XStatus IceListenForWellKnownConnections (String port, ref Xlib.Xint countRet, ref IntPtr listenObjsRet, Xlib.Xint errorLength, byte[] errorStringRet); [DllImport("ICE")] extern public static Xlib.Xint IceGetListenConnectionNumber (IntPtr listenObj); [DllImport("ICE")] extern public static String IceGetListenConnectionString (IntPtr listenObj); [DllImport("ICE")] extern public static String IceComposeNetworkIdList (Xlib.Xint count, IntPtr listenObjs); [DllImport("ICE")] extern public static void IceFreeListenObjs (Xlib.Xint count, IntPtr listenObjs); [DllImport("ICE")] extern public static void IceSetHostBasedAuthProc (IntPtr listenObj, IceHostBasedAuthProc hostBasedAuthProc); [DllImport("ICE")] extern public static IceConn *IceAcceptConnection (IntPtr listenObj, ref Xlib.Xint statusRet); [DllImport("ICE")] extern public static void IceSetShutdownNegotiation (IceConn *iceConn, XBool negotiate); [DllImport("ICE")] extern public static XBool IceCheckShutdownNegotiation(IceConn *iceConn); [DllImport("ICE")] extern public static Xlib.Xint IceCloseConnection(IceConn *iceConn); [DllImport("ICE")] extern public static XStatus IceAddConnectionWatch (IceWatchProc watchProc, IntPtr clientData); [DllImport("ICE")] extern public static XStatus IceRemoveConnectionWatch (IceWatchProc watchProc, IntPtr clientData); [DllImport("ICE")] extern public static Xlib.Xint IceProtocolSetup (IceConn *iceConn, Xlib.Xint myOpcode, IntPtr clientData, XBool mustAuthenticate, out Xlib.Xint majorVersionRet, out Xlib.Xint minorVersionRet, out IntPtr vendorRet, out IntPtr releaseRet, Xlib.Xint errorLength, byte[] errorStringRet); [DllImport("ICE")] extern public static XStatus IceProtocolShutdown (IceConn *iceConn, Xlib.Xint majorOpcode); [DllImport("ICE")] extern public static Xlib.Xint IceProcessMessages (IceConn *iceConn, ref IceReplyWaitInfo replyWait, ref XBool replyReadyRet); [DllImport("ICE")] extern public static XStatus IcePing (IceConn *iceConn, IcePingReplyProc pingReplyProc, IntPtr clientData); [DllImport("ICE")] extern public static IntPtr IceAllocScratch (IceConn *iceConn, Xlib.Xulong size); [DllImport("ICE")] extern public static Xlib.Xint IceFlush(IceConn *iceConn); [DllImport("ICE")] extern public static Xlib.Xint IceGetOutBufSize(IceConn *iceConn); [DllImport("ICE")] extern public static Xlib.Xint IceGetInBufSize(IceConn *iceConn); [DllImport("ICE")] extern public static Xlib.Xint IceConnectionStatus(IceConn *iceConn); [DllImport("ICE")] extern public static String IceVendor(IceConn *iceConn); [DllImport("ICE")] extern public static String IceRelease(IceConn *iceConn); [DllImport("ICE")] extern public static Xlib.Xint IceProtocolVersion(IceConn *iceConn); [DllImport("ICE")] extern public static Xlib.Xint IceProtocolRevision(IceConn *iceConn); [DllImport("ICE")] extern public static Xlib.Xint IceConnectionNumber(IceConn *iceConn); [DllImport("ICE")] extern public static String IceConnectionString(IceConn *iceConn); [DllImport("ICE")] extern public static Xlib.Xulong IceLastSentSequenceNumber(IceConn *iceConn); [DllImport("ICE")] extern public static Xlib.Xulong IceLastReceivedSequenceNumber (IceConn *iceConn); [DllImport("ICE")] extern public static XBool IceSwapping(IceConn *iceConn); [DllImport("ICE")] extern public static IntPtr IceSetErrorHandler(IceErrorHandler handler); [DllImport("ICE")] extern public static IntPtr IceSetErrorHandler(IntPtr handler); [DllImport("ICE")] extern public static IntPtr IceSetIOErrorHandler(IceIOErrorHandler handler); [DllImport("ICE")] extern public static IntPtr IceSetIOErrorHandler(IntPtr handler); [DllImport("ICE")] extern public static XStatus IceInitThreads(); [DllImport("ICE")] extern public static void IceAppLockConn(IceConn *iceConn); [DllImport("ICE")] extern public static void IceAppUnlockConn(IceConn *iceConn); [DllImport("ICE")] extern public static Xlib.Xint _IcePoMagicCookie1Proc (IntPtr iceConn, IntPtr authStatePtr, XBool cleanUp, XBool swap, Xlib.Xint authDataLen, IntPtr authData, ref Xlib.Xint replyDataLenRet, ref IntPtr replyDataRet, ref IntPtr errorStringRet); [DllImport("ICE")] extern public static Xlib.Xint _IcePaMagicCookie1Proc (IntPtr iceConn, IntPtr authStatePtr, XBool swap, Xlib.Xint authDataLen, IntPtr authData, ref Xlib.Xint replyDataLenRet, ref IntPtr replyDataRet, ref IntPtr errorStringRet); [DllImport("ICE")] extern public static XStatus _IceRead (IceConn *iceConn, Xlib.Xulong nbytes, byte[] ptr); [DllImport("ICE")] extern public static void _IceReadSkip (IceConn *iceConn, Xlib.Xulong nbytes); [DllImport("ICE")] extern public static void _IceWrite (IceConn *iceConn, Xlib.Xulong nbytes, byte[] ptr); [DllImport("ICE")] extern public static void _IceErrorBadMinor (IceConn *iceConn, Xlib.Xint majorOpcode, Xlib.Xint offendingMinor, Xlib.Xint severity); [DllImport("ICE")] extern public static void _IceErrorBadState (IceConn *iceConn, Xlib.Xint majorOpcode, Xlib.Xint offendingMinor, Xlib.Xint severity); [DllImport("ICE")] extern public static void _IceErrorBadLength (IceConn *iceConn, Xlib.Xint majorOpcode, Xlib.Xint offendingMinor, Xlib.Xint severity); [DllImport("ICE")] extern public static void _IceErrorBadValue (IceConn *iceConn, Xlib.Xint majorOpcode, Xlib.Xint offendingMinor, Xlib.Xint offset, Xlib.Xint length, IntPtr value); // Determine if this platform is little-endian. private static int endian = -1; public static bool IsLittleEndian { get { lock(typeof(ICE)) { if(endian == -1) { IntPtr buf = Marshal.AllocHGlobal(2); Marshal.WriteInt16(buf, 0, 0x0102); if(Marshal.ReadByte(buf, 0) == 0x01) { endian = 1; } else { endian = 0; } Marshal.FreeHGlobal(buf); } return (endian == 0); } } } // Send data over an ICE connection. public static void IceSendData(IceConn *iceConn, int nbytes, byte[] data) { IceFlush(iceConn); _IceWrite(iceConn, (Xlib.Xulong)(uint)nbytes, data); } // Read data from an ICE connection. public static bool IceReadData(IceConn *iceConn, int nbytes, byte[] data) { return (_IceRead(iceConn, (Xlib.Xulong)(uint)nbytes, data) != XStatus.Zero); } } // class ICE } // namespace Xsharp.Ice
/* * 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 Apache.Ignite.Core.Tests { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Messaging; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// <see cref="IMessaging"/> tests. /// </summary> public class MessagingTest { /** */ private IIgnite _grid1; /** */ private IIgnite _grid2; /** */ private IIgnite _grid3; /** */ public static int MessageId; /// <summary> /// Executes before each test. /// </summary> [SetUp] public void SetUp() { _grid1 = Ignition.Start(Configuration("config\\compute\\compute-grid1.xml")); _grid2 = Ignition.Start(Configuration("config\\compute\\compute-grid2.xml")); _grid3 = Ignition.Start(Configuration("config\\compute\\compute-grid3.xml")); } /// <summary> /// Executes after each test. /// </summary> [TearDown] public virtual void TearDown() { try { TestUtils.AssertHandleRegistryIsEmpty(1000, _grid1, _grid2, _grid3); MessagingTestHelper.AssertFailures(); } finally { // Stop all grids between tests to drop any hanging messages Ignition.StopAll(true); } } /// <summary> /// Tests LocalListen. /// </summary> [Test] public void TestLocalListen() { TestLocalListen(null); TestLocalListen("string topic"); TestLocalListen(NextId()); } /// <summary> /// Tests LocalListen. /// </summary> [SuppressMessage("ReSharper", "AccessToModifiedClosure")] public void TestLocalListen(object topic) { var messaging = _grid1.GetMessaging(); var listener = MessagingTestHelper.GetListener(); messaging.LocalListen(listener, topic); // Test sending CheckSend(topic); CheckSend(topic, _grid2); CheckSend(topic, _grid3); // Test different topic CheckNoMessage(NextId()); CheckNoMessage(NextId(), _grid2); // Test multiple subscriptions for the same filter messaging.LocalListen(listener, topic); messaging.LocalListen(listener, topic); CheckSend(topic, repeatMultiplier: 3); // expect all messages repeated 3 times messaging.StopLocalListen(listener, topic); CheckSend(topic, repeatMultiplier: 2); // expect all messages repeated 2 times messaging.StopLocalListen(listener, topic); CheckSend(topic); // back to 1 listener // Test message type mismatch var ex = Assert.Throws<IgniteException>(() => messaging.Send(1.1, topic)); Assert.AreEqual("Unable to cast object of type 'System.Double' to type 'System.String'.", ex.Message); // Test end listen MessagingTestHelper.ListenResult = false; CheckSend(topic, single: true); // we'll receive one more and then unsubscribe because of delegate result. CheckNoMessage(topic); // Start again MessagingTestHelper.ListenResult = true; messaging.LocalListen(listener, topic); CheckSend(topic); // Stop messaging.StopLocalListen(listener, topic); CheckNoMessage(topic); } /// <summary> /// Tests LocalListen with projection. /// </summary> [Test] public void TestLocalListenProjection() { TestLocalListenProjection(null); TestLocalListenProjection("prj"); TestLocalListenProjection(NextId()); } /// <summary> /// Tests LocalListen with projection. /// </summary> private void TestLocalListenProjection(object topic) { var grid3GotMessage = false; var grid3Listener = new MessageListener<string>((id, x) => { grid3GotMessage = true; return true; }); _grid3.GetMessaging().LocalListen(grid3Listener, topic); var clusterMessaging = _grid1.GetCluster().ForNodes(_grid1.GetCluster().GetLocalNode(), _grid2.GetCluster().GetLocalNode()).GetMessaging(); var clusterListener = MessagingTestHelper.GetListener(); clusterMessaging.LocalListen(clusterListener, topic); CheckSend(msg: clusterMessaging, topic: topic); Assert.IsFalse(grid3GotMessage, "Grid3 should not get messages"); CheckSend(grid: _grid2, msg: clusterMessaging, topic: topic); Assert.IsFalse(grid3GotMessage, "Grid3 should not get messages"); clusterMessaging.StopLocalListen(clusterListener, topic); _grid3.GetMessaging().StopLocalListen(grid3Listener, topic); } /// <summary> /// Tests LocalListen in multithreaded mode. /// </summary> [Test] [SuppressMessage("ReSharper", "AccessToModifiedClosure")] [Category(TestUtils.CategoryIntensive)] public void TestLocalListenMultithreaded() { const int threadCnt = 20; const int runSeconds = 20; var messaging = _grid1.GetMessaging(); var senders = Task.Factory.StartNew(() => TestUtils.RunMultiThreaded(() => { messaging.Send(NextMessage()); Thread.Sleep(50); }, threadCnt, runSeconds)); var sharedReceived = 0; var sharedListener = new MessageListener<string>((id, x) => { Interlocked.Increment(ref sharedReceived); Thread.MemoryBarrier(); return true; }); TestUtils.RunMultiThreaded(() => { // Check that listen/stop work concurrently messaging.LocalListen(sharedListener); for (int i = 0; i < 100; i++) { messaging.LocalListen(sharedListener); messaging.StopLocalListen(sharedListener); } var localReceived = 0; var stopLocal = 0; var localListener = new MessageListener<string>((id, x) => { Interlocked.Increment(ref localReceived); Thread.MemoryBarrier(); return Thread.VolatileRead(ref stopLocal) == 0; }); messaging.LocalListen(localListener); Thread.Sleep(100); Thread.VolatileWrite(ref stopLocal, 1); Thread.Sleep(1000); var result = Thread.VolatileRead(ref localReceived); Thread.Sleep(100); // Check that unsubscription worked properly Assert.AreEqual(result, Thread.VolatileRead(ref localReceived)); messaging.StopLocalListen(sharedListener); }, threadCnt, runSeconds); senders.Wait(); Thread.Sleep(100); var sharedResult = Thread.VolatileRead(ref sharedReceived); messaging.Send(NextMessage()); Thread.Sleep(MessagingTestHelper.MessageTimeout); // Check that unsubscription worked properly Assert.AreEqual(sharedResult, Thread.VolatileRead(ref sharedReceived)); } /// <summary> /// Tests RemoteListen. /// </summary> [Test] public void TestRemoteListen() { TestRemoteListen(null); TestRemoteListen("string topic"); TestRemoteListen(NextId()); } /// <summary> /// Tests RemoteListen with async mode enabled. /// </summary> [Test] public void TestRemoteListenAsync() { TestRemoteListen(null, true); TestRemoteListen("string topic", true); TestRemoteListen(NextId(), true); } /// <summary> /// Tests RemoteListen. /// </summary> private void TestRemoteListen(object topic, bool async = false) { var messaging =_grid1.GetMessaging(); var listener = MessagingTestHelper.GetListener(); var listenId = async ? messaging.RemoteListenAsync(listener, topic).Result : messaging.RemoteListen(listener, topic); // Test sending CheckSend(topic, msg: messaging, remoteListen: true); // Test different topic CheckNoMessage(NextId()); // Test multiple subscriptions for the same filter var listenId2 = async ? messaging.RemoteListenAsync(listener, topic).Result : messaging.RemoteListen(listener, topic); CheckSend(topic, msg: messaging, remoteListen: true, repeatMultiplier: 2); // expect twice the messages if (async) messaging.StopRemoteListenAsync(listenId2).Wait(); else messaging.StopRemoteListen(listenId2); CheckSend(topic, msg: messaging, remoteListen: true); // back to normal after unsubscription // Test message type mismatch var ex = Assert.Throws<IgniteException>(() => messaging.Send(1.1, topic)); Assert.AreEqual("Unable to cast object of type 'System.Double' to type 'System.String'.", ex.Message); // Test end listen if (async) messaging.StopRemoteListenAsync(listenId).Wait(); else messaging.StopRemoteListen(listenId); CheckNoMessage(topic); } /// <summary> /// Tests RemoteListen with a projection. /// </summary> [Test] public void TestRemoteListenProjection() { TestRemoteListenProjection(null); TestRemoteListenProjection("string topic"); TestRemoteListenProjection(NextId()); } /// <summary> /// Tests RemoteListen with a projection. /// </summary> private void TestRemoteListenProjection(object topic) { var clusterMessaging = _grid1.GetCluster().ForNodes(_grid1.GetCluster().GetLocalNode(), _grid2.GetCluster().GetLocalNode()).GetMessaging(); var clusterListener = MessagingTestHelper.GetListener(); var listenId = clusterMessaging.RemoteListen(clusterListener, topic); CheckSend(msg: clusterMessaging, topic: topic, remoteListen: true); clusterMessaging.StopRemoteListen(listenId); CheckNoMessage(topic); } /// <summary> /// Tests LocalListen in multithreaded mode. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestRemoteListenMultithreaded() { const int threadCnt = 20; const int runSeconds = 20; var messaging = _grid1.GetMessaging(); var senders = Task.Factory.StartNew(() => TestUtils.RunMultiThreaded(() => { MessagingTestHelper.ClearReceived(int.MaxValue); messaging.Send(NextMessage()); Thread.Sleep(50); }, threadCnt, runSeconds)); var sharedListener = MessagingTestHelper.GetListener(); for (int i = 0; i < 100; i++) messaging.RemoteListen(sharedListener); // add some listeners to be stopped by filter result TestUtils.RunMultiThreaded(() => { // Check that listen/stop work concurrently messaging.StopRemoteListen(messaging.RemoteListen(sharedListener)); }, threadCnt, runSeconds / 2); MessagingTestHelper.ListenResult = false; messaging.Send(NextMessage()); // send a message to make filters return false Thread.Sleep(MessagingTestHelper.MessageTimeout); // wait for all to unsubscribe MessagingTestHelper.ListenResult = true; senders.Wait(); // wait for senders to stop MessagingTestHelper.ClearReceived(int.MaxValue); var lastMsg = NextMessage(); messaging.Send(lastMsg); Thread.Sleep(MessagingTestHelper.MessageTimeout); // Check that unsubscription worked properly var sharedResult = MessagingTestHelper.ReceivedMessages.ToArray(); if (sharedResult.Length != 0) { Assert.Fail("Unexpected messages ({0}): {1}; last sent message: {2}", sharedResult.Length, string.Join(",", sharedResult), lastMsg); } } /// <summary> /// Sends messages in various ways and verefies correct receival. /// </summary> /// <param name="topic">Topic.</param> /// <param name="grid">The grid to use.</param> /// <param name="msg">Messaging to use.</param> /// <param name="remoteListen">Whether to expect remote listeners.</param> /// <param name="single">When true, only check one message.</param> /// <param name="repeatMultiplier">Expected message count multiplier.</param> private void CheckSend(object topic = null, IIgnite grid = null, IMessaging msg = null, bool remoteListen = false, bool single = false, int repeatMultiplier = 1) { IClusterGroup cluster; if (msg != null) cluster = msg.ClusterGroup; else { grid = grid ?? _grid1; msg = grid.GetMessaging(); cluster = grid.GetCluster().ForLocal(); } // Messages will repeat due to multiple nodes listening var expectedRepeat = repeatMultiplier * (remoteListen ? cluster.GetNodes().Count : 1); var messages = Enumerable.Range(1, 10).Select(x => NextMessage()).OrderBy(x => x).ToList(); // Single message MessagingTestHelper.ClearReceived(expectedRepeat); msg.Send(messages[0], topic); MessagingTestHelper.VerifyReceive(cluster, messages.Take(1), m => m.ToList(), expectedRepeat); if (single) return; // Multiple messages (receive order is undefined) MessagingTestHelper.ClearReceived(messages.Count * expectedRepeat); msg.SendAll(messages, topic); MessagingTestHelper.VerifyReceive(cluster, messages, m => m.OrderBy(x => x), expectedRepeat); // Multiple messages, ordered MessagingTestHelper.ClearReceived(messages.Count * expectedRepeat); messages.ForEach(x => msg.SendOrdered(x, topic, MessagingTestHelper.MessageTimeout)); if (remoteListen) // in remote scenario messages get mixed up due to different timing on different nodes MessagingTestHelper.VerifyReceive(cluster, messages, m => m.OrderBy(x => x), expectedRepeat); else MessagingTestHelper.VerifyReceive(cluster, messages, m => m.Reverse(), expectedRepeat); } /// <summary> /// Checks that no message has arrived. /// </summary> private void CheckNoMessage(object topic, IIgnite grid = null) { // this will result in an exception in case of a message MessagingTestHelper.ClearReceived(0); (grid ?? _grid1).GetMessaging().SendAll(NextMessage(), topic); Thread.Sleep(MessagingTestHelper.MessageTimeout); MessagingTestHelper.AssertFailures(); } /// <summary> /// Gets the Ignite configuration. /// </summary> private static IgniteConfiguration Configuration(string springConfigUrl) { return new IgniteConfiguration { SpringConfigUrl = springConfigUrl, JvmClasspath = TestUtils.CreateTestClasspath(), JvmOptions = TestUtils.TestJavaOptions() }; } /// <summary> /// Generates next message with sequential ID and current test name. /// </summary> private static string NextMessage() { var id = NextId(); return id + "_" + TestContext.CurrentContext.Test.Name; } /// <summary> /// Generates next sequential ID. /// </summary> private static int NextId() { return Interlocked.Increment(ref MessageId); } } /// <summary> /// Messaging test helper class. /// </summary> [Serializable] public static class MessagingTestHelper { /** */ public static readonly ConcurrentStack<string> ReceivedMessages = new ConcurrentStack<string>(); /** */ public static readonly ConcurrentStack<string> Failures = new ConcurrentStack<string>(); /** */ public static readonly CountdownEvent ReceivedEvent = new CountdownEvent(0); /** */ public static readonly ConcurrentStack<Guid> LastNodeIds = new ConcurrentStack<Guid>(); /** */ public static volatile bool ListenResult = true; /** */ public static readonly TimeSpan MessageTimeout = TimeSpan.FromMilliseconds(700); /// <summary> /// Clears received message information. /// </summary> /// <param name="expectedCount">The expected count of messages to be received.</param> public static void ClearReceived(int expectedCount) { ReceivedMessages.Clear(); ReceivedEvent.Reset(expectedCount); LastNodeIds.Clear(); } /// <summary> /// Verifies received messages against expected messages. /// </summary> /// <param name="cluster">Cluster.</param> /// <param name="expectedMessages">Expected messages.</param> /// <param name="resultFunc">Result transform function.</param> /// <param name="expectedRepeat">Expected repeat count.</param> public static void VerifyReceive(IClusterGroup cluster, IEnumerable<string> expectedMessages, Func<IEnumerable<string>, IEnumerable<string>> resultFunc, int expectedRepeat) { // check if expected message count has been received; Wait returns false if there were none. Assert.IsTrue(ReceivedEvent.Wait(MessageTimeout)); expectedMessages = expectedMessages.SelectMany(x => Enumerable.Repeat(x, expectedRepeat)); Assert.AreEqual(expectedMessages, resultFunc(ReceivedMessages)); // check that all messages came from local node. var localNodeId = cluster.Ignite.GetCluster().GetLocalNode().Id; Assert.AreEqual(localNodeId, LastNodeIds.Distinct().Single()); AssertFailures(); } /// <summary> /// Gets the message listener. /// </summary> /// <returns>New instance of message listener.</returns> public static IMessageListener<string> GetListener() { return new MessageListener<string>(Listen); } /// <summary> /// Combines accumulated failures and throws an assertion, if there are any. /// Clears accumulated failures. /// </summary> public static void AssertFailures() { if (Failures.Any()) Assert.Fail(Failures.Reverse().Aggregate((x, y) => string.Format("{0}\n{1}", x, y))); Failures.Clear(); } /// <summary> /// Listen method. /// </summary> /// <param name="id">Originating node ID.</param> /// <param name="msg">Message.</param> private static bool Listen(Guid id, string msg) { try { LastNodeIds.Push(id); ReceivedMessages.Push(msg); ReceivedEvent.Signal(); return ListenResult; } catch (Exception ex) { // When executed on remote nodes, these exceptions will not go to sender, // so we have to accumulate them. Failures.Push(string.Format("Exception in Listen (msg: {0}, id: {1}): {2}", msg, id, ex)); throw; } } } /// <summary> /// Test message filter. /// </summary> [Serializable] public class MessageListener<T> : IMessageListener<T> { /** */ private readonly Func<Guid, T, bool> _invoke; #pragma warning disable 649 /** Grid. */ [InstanceResource] private IIgnite _grid; #pragma warning restore 649 /// <summary> /// Initializes a new instance of the <see cref="MessageListener{T}"/> class. /// </summary> /// <param name="invoke">The invoke delegate.</param> public MessageListener(Func<Guid, T, bool> invoke) { _invoke = invoke; } /** <inheritdoc /> */ public bool Invoke(Guid nodeId, T message) { Assert.IsNotNull(_grid); return _invoke(nodeId, message); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT License. See LICENSE.txt in the project root for license information. using Microsoft.Graphics.Canvas; using Microsoft.Graphics.Canvas.Geometry; using Microsoft.Graphics.Canvas.Text; using Microsoft.Graphics.Canvas.UI; using Microsoft.Graphics.Canvas.UI.Xaml; using System; using System.Collections.Generic; using System.IO; using System.Numerics; using System.Threading.Tasks; using Windows.Foundation; using Windows.Storage; using Windows.UI; using Windows.UI.Input.Inking; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Media; namespace ExampleGallery { public sealed partial class InkExample : UserControl { CanvasRenderTarget renderTarget; List<Point> selectionPolylinePoints; Rect? selectionBoundingRect; InkSynchronizer inkSynchronizer; CanvasTextFormat textFormat; bool needsClear; bool needsInkSurfaceValidation; bool needToCreateSizeDepdendentResources; bool showTextLabels; public enum DryInkRenderingType { BuiltIn, CustomGeometry } public List<DryInkRenderingType> DryInkRenderingTypes { get { return Utils.GetEnumAsList<DryInkRenderingType>(); } } public DryInkRenderingType SelectedDryInkRenderingType { get; set; } // Since this app uses custom drying, it can't use the built-in stroke container on the ink canvas. InkManager inkManager = new InkManager(); List<InkStroke> strokeList = new List<InkStroke>(); public InkExample() { this.InitializeComponent(); inkCanvas.InkPresenter.InputDeviceTypes = Windows.UI.Core.CoreInputDeviceTypes.Mouse | Windows.UI.Core.CoreInputDeviceTypes.Pen | Windows.UI.Core.CoreInputDeviceTypes.Touch; // By default, pen barrel button or right mouse button is processed for inking // Set the configuration to instead allow processing these input on the UI thread inkCanvas.InkPresenter.InputProcessingConfiguration.RightDragAction = InkInputRightDragAction.LeaveUnprocessed; inkCanvas.InkPresenter.UnprocessedInput.PointerPressed += UnprocessedInput_PointerPressed; inkCanvas.InkPresenter.UnprocessedInput.PointerMoved += UnprocessedInput_PointerMoved; inkCanvas.InkPresenter.UnprocessedInput.PointerReleased += UnprocessedInput_PointerReleased; inkCanvas.InkPresenter.StrokeInput.StrokeStarted += StrokeInput_StrokeStarted; inkCanvas.InkPresenter.StrokesCollected += InkPresenter_StrokesCollected; inkCanvas.InkPresenter.StrokesErased += InkPresenter_StrokesErased; inkSynchronizer = inkCanvas.InkPresenter.ActivateCustomDrying(); textFormat = new CanvasTextFormat(); // Set defaults SelectedDryInkRenderingType = DryInkRenderingType.BuiltIn; SelectColor(color0); showTextLabels = true; needToCreateSizeDepdendentResources = true; } private void InkPresenter_StrokesCollected(InkPresenter sender, InkStrokesCollectedEventArgs args) { strokeList.AddRange(args.Strokes); foreach (var s in args.Strokes) { inkManager.AddStroke(s); } canvasControl.Invalidate(); } private void StrokeInput_StrokeStarted(InkStrokeInput sender, Windows.UI.Core.PointerEventArgs args) { ClearSelection(); canvasControl.Invalidate(); } private void InkPresenter_StrokesErased(InkPresenter sender, InkStrokesErasedEventArgs args) { var removed = args.Strokes; foreach (var s in removed) { strokeList.Remove(s); } inkManager = new InkManager(); foreach (var s in strokeList) { inkManager.AddStroke(s); } ClearSelection(); canvasControl.Invalidate(); } private void UnprocessedInput_PointerPressed(InkUnprocessedInput sender, Windows.UI.Core.PointerEventArgs args) { selectionPolylinePoints = new List<Point>(); selectionPolylinePoints.Add(args.CurrentPoint.RawPosition); canvasControl.Invalidate(); } private void UnprocessedInput_PointerMoved(InkUnprocessedInput sender, Windows.UI.Core.PointerEventArgs args) { selectionPolylinePoints.Add(args.CurrentPoint.RawPosition); canvasControl.Invalidate(); } private void UnprocessedInput_PointerReleased(InkUnprocessedInput sender, Windows.UI.Core.PointerEventArgs args) { selectionPolylinePoints.Add(args.CurrentPoint.RawPosition); selectionBoundingRect = inkManager.SelectWithPolyLine(selectionPolylinePoints); selectionPolylinePoints = null; canvasControl.Invalidate(); } private void ClearSelection() { selectionPolylinePoints = null; selectionBoundingRect = null; } private void CreateSizeDependentResources() { renderTarget = new CanvasRenderTarget(canvasControl, canvasControl.Size); textFormat.FontSize = (float)canvasControl.Size.Width / 10.0f; } private async Task LoadThumbnailResources(CanvasControl sender) { var thumbnailFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/InkThumbnailStrokes.bin")); using (var stream = await thumbnailFile.OpenReadAsync()) { LoadStrokesFromStream(stream.AsStreamForRead()); } } private void canvasControl_CreateResources(CanvasControl sender, Microsoft.Graphics.Canvas.UI.CanvasCreateResourcesEventArgs args) { CreateSizeDependentResources(); if (ThumbnailGenerator.IsDrawingThumbnail) { args.TrackAsyncAction(LoadThumbnailResources(sender).AsAsyncAction()); } needToCreateSizeDepdendentResources = false; if(args.Reason != CanvasCreateResourcesReason.FirstTime) { needsInkSurfaceValidation = true; } } private void DrawSelectionLasso(CanvasControl sender, CanvasDrawingSession ds) { if (selectionPolylinePoints == null) return; if (selectionPolylinePoints.Count == 0) return; CanvasPathBuilder selectionLasso = new CanvasPathBuilder(canvasControl); selectionLasso.BeginFigure(selectionPolylinePoints[0].ToVector2()); for (int i = 1; i < selectionPolylinePoints.Count; ++i) { selectionLasso.AddLine(selectionPolylinePoints[i].ToVector2()); } selectionLasso.EndFigure(CanvasFigureLoop.Open); CanvasGeometry pathGeometry = CanvasGeometry.CreatePath(selectionLasso); ds.DrawGeometry(pathGeometry, Colors.Magenta, 5.0f); } private void DrawSelectionBoundingRect(CanvasDrawingSession ds) { if (selectionBoundingRect == null) return; if ((selectionBoundingRect.Value.Width == 0) || (selectionBoundingRect.Value.Height == 0) || selectionBoundingRect.Value.IsEmpty) { return; } ds.DrawRectangle(selectionBoundingRect.Value, Colors.Magenta); } private void DrawDryInk_CustomGeometryMethod(CanvasDrawingSession ds, IReadOnlyList<InkStroke> strokes) { // // This shows off the fact that apps can use the custom drying path // to render dry ink using Win2D, and not necessarily // rely on the built-in rendering in CanvasDrawingSession.DrawInk. // foreach (var stroke in strokes) { var color = stroke.DrawingAttributes.Color; var inkPoints = stroke.GetInkPoints(); if (inkPoints.Count > 0) { CanvasPathBuilder pathBuilder = new CanvasPathBuilder(canvasControl); pathBuilder.BeginFigure(inkPoints[0].Position.ToVector2()); for (int i = 1; i < inkPoints.Count; i++) { pathBuilder.AddLine(inkPoints[i].Position.ToVector2()); ds.DrawCircle(inkPoints[i].Position.ToVector2(), 3, color); } pathBuilder.EndFigure(CanvasFigureLoop.Open); CanvasGeometry geometry = CanvasGeometry.CreatePath(pathBuilder); ds.DrawGeometry(geometry, color); } } } private void DrawStrokeCollectionToInkSurface(IReadOnlyList<InkStroke> strokes) { using (CanvasDrawingSession ds = renderTarget.CreateDrawingSession()) { if (SelectedDryInkRenderingType == DryInkRenderingType.BuiltIn) { ds.DrawInk(strokes); } else { DrawDryInk_CustomGeometryMethod(ds, strokes); } } } private void DrawBackgroundText(CanvasDrawingSession ds) { if (showTextLabels && !ThumbnailGenerator.IsDrawingThumbnail) { textFormat.VerticalAlignment = CanvasVerticalAlignment.Top; textFormat.HorizontalAlignment = CanvasHorizontalAlignment.Left; ds.DrawText("Dry Ink Background", new Vector2(10, 10), Colors.DarkGray, textFormat); } } private void DrawForegroundText(CanvasDrawingSession ds) { if (showTextLabels && !ThumbnailGenerator.IsDrawingThumbnail) { textFormat.VerticalAlignment = CanvasVerticalAlignment.Bottom; textFormat.HorizontalAlignment = CanvasHorizontalAlignment.Right; ds.DrawText("Dry Ink Foreground", new Vector2((float)canvasControl.Size.Width - 10, (float)canvasControl.Size.Height - 10), Colors.DarkGoldenrod, textFormat); } } private void canvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args) { if(needToCreateSizeDepdendentResources) { CreateSizeDependentResources(); } if(needsClear || needsInkSurfaceValidation) { ClearInkSurface(); } if(needsInkSurfaceValidation) { DrawStrokeCollectionToInkSurface(strokeList); } needToCreateSizeDepdendentResources = false; needsClear = false; needsInkSurfaceValidation = false; DrawBackgroundText(args.DrawingSession); var strokes = inkSynchronizer.BeginDry(); DrawStrokeCollectionToInkSurface(strokes); // Incremental draw only. inkSynchronizer.EndDry(); args.DrawingSession.DrawImage(renderTarget); DrawForegroundText(args.DrawingSession); DrawSelectionBoundingRect(args.DrawingSession); DrawSelectionLasso(sender, args.DrawingSession); } const string saveFileName = "savedFile.bin"; private void DeleteSelected_Clicked(object sender, RoutedEventArgs e) { inkManager.DeleteSelected(); strokeList.Clear(); var strokes = inkManager.GetStrokes(); strokeList.AddRange(strokes); selectionBoundingRect = null; needsInkSurfaceValidation = true; canvasControl.Invalidate(); } private async void LoadStrokesFromStream(Stream stream) { await inkManager.LoadAsync(stream.AsInputStream()); strokeList.Clear(); strokeList.AddRange(inkManager.GetStrokes()); needsInkSurfaceValidation = true; } private async void Load_Clicked(object sender, RoutedEventArgs e) { try { using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(saveFileName)) { LoadStrokesFromStream(stream); } } catch (FileNotFoundException) { MessageDialog dialog = new MessageDialog("No saved data was found."); await dialog.ShowAsync(); } canvasControl.Invalidate(); } private async void Save_Clicked(object sender, RoutedEventArgs e) { using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(saveFileName, CreationCollisionOption.ReplaceExisting)) { await inkManager.SaveAsync(stream.AsOutputStream()); } } void ClearInkSurface() { using (CanvasDrawingSession ds = renderTarget.CreateDrawingSession()) { ds.Clear(Colors.Transparent); } } private void Clear_Clicked(object sender, RoutedEventArgs e) { strokeList.Clear(); inkManager = new InkManager(); needsClear = true; canvasControl.Invalidate(); } void ResetColorSelectors() { Button[] buttons = { color0, color1, color2, color3, color4, color5, color6, color7 }; foreach (Button button in buttons) { button.BorderBrush = null; button.BorderThickness = new Thickness(0); } } void SelectColor(Button button) { ResetColorSelectors(); button.BorderBrush = new SolidColorBrush(Colors.Red); button.BorderThickness = new Thickness(3); InkDrawingAttributes drawingAttributes = inkCanvas.InkPresenter.CopyDefaultDrawingAttributes(); drawingAttributes.Color = ((SolidColorBrush)(button.Background)).Color; inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes); } private void ColorPickerButton_Clicked(object sender, RoutedEventArgs e) { SelectColor((Button)e.OriginalSource); } private void StrokeWidth_ValueChanged(object sender, RangeBaseValueChangedEventArgs e) { if (inkCanvas != null) { InkDrawingAttributes drawingAttributes = inkCanvas.InkPresenter.CopyDefaultDrawingAttributes(); drawingAttributes.Size = new Size(e.NewValue, drawingAttributes.Size.Height); inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes); } } private void StrokeHeight_ValueChanged(object sender, RangeBaseValueChangedEventArgs e) { if (inkCanvas != null) { InkDrawingAttributes drawingAttributes = inkCanvas.InkPresenter.CopyDefaultDrawingAttributes(); drawingAttributes.Size = new Size(drawingAttributes.Size.Width, e.NewValue); inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes); } } private void Rotation_ValueChanged(object sender, RangeBaseValueChangedEventArgs e) { if (inkCanvas != null) { InkDrawingAttributes drawingAttributes = inkCanvas.InkPresenter.CopyDefaultDrawingAttributes(); float radians = Utils.DegreesToRadians((float)e.NewValue); drawingAttributes.PenTipTransform = Matrix3x2.CreateRotation(radians); inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes); } } private void SettingsCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { // // Changing the rendering type will invalidate any ink we've // already drawn, so we need to wipe the intermediate, and re-draw // the strokes that have been collected so far. // needsInkSurfaceValidation = true; canvasControl.Invalidate(); } private void Canvas_SizeChanged(object sender, SizeChangedEventArgs e) { needToCreateSizeDepdendentResources = true; needsInkSurfaceValidation = true; canvasControl.Invalidate(); } void ShowTextLabels_Checked(object sender, RoutedEventArgs e) { showTextLabels = true; if(canvasControl != null) canvasControl.Invalidate(); } void ShowTextLabels_Unchecked(object sender, RoutedEventArgs e) { showTextLabels = false; if (canvasControl != null) canvasControl.Invalidate(); } private void control_Unloaded(object sender, RoutedEventArgs e) { // Explicitly remove references to allow the Win2D controls to get garbage collected canvasControl.RemoveFromVisualTree(); canvasControl = null; // If we don't unregister these events, the control will leak. inkCanvas.InkPresenter.UnprocessedInput.PointerPressed -= UnprocessedInput_PointerPressed; inkCanvas.InkPresenter.UnprocessedInput.PointerMoved -= UnprocessedInput_PointerMoved; inkCanvas.InkPresenter.UnprocessedInput.PointerReleased -= UnprocessedInput_PointerReleased; inkCanvas.InkPresenter.StrokeInput.StrokeStarted -= StrokeInput_StrokeStarted; inkCanvas.InkPresenter.StrokesCollected -= InkPresenter_StrokesCollected; inkCanvas.InkPresenter.StrokesErased -= InkPresenter_StrokesErased; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/audit/audit_log.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Cloud.Audit { /// <summary>Holder for reflection information generated from google/cloud/audit/audit_log.proto</summary> public static partial class AuditLogReflection { #region Descriptor /// <summary>File descriptor for google/cloud/audit/audit_log.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static AuditLogReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiJnb29nbGUvY2xvdWQvYXVkaXQvYXVkaXRfbG9nLnByb3RvEhJnb29nbGUu", "Y2xvdWQuYXVkaXQaHGdvb2dsZS9hcGkvYW5ub3RhdGlvbnMucHJvdG8aGWdv", "b2dsZS9wcm90b2J1Zi9hbnkucHJvdG8aHGdvb2dsZS9wcm90b2J1Zi9zdHJ1", "Y3QucHJvdG8aF2dvb2dsZS9ycGMvc3RhdHVzLnByb3RvItQDCghBdWRpdExv", "ZxIUCgxzZXJ2aWNlX25hbWUYByABKAkSEwoLbWV0aG9kX25hbWUYCCABKAkS", "FQoNcmVzb3VyY2VfbmFtZRgLIAEoCRIaChJudW1fcmVzcG9uc2VfaXRlbXMY", "DCABKAMSIgoGc3RhdHVzGAIgASgLMhIuZ29vZ2xlLnJwYy5TdGF0dXMSQwoT", "YXV0aGVudGljYXRpb25faW5mbxgDIAEoCzImLmdvb2dsZS5jbG91ZC5hdWRp", "dC5BdXRoZW50aWNhdGlvbkluZm8SQQoSYXV0aG9yaXphdGlvbl9pbmZvGAkg", "AygLMiUuZ29vZ2xlLmNsb3VkLmF1ZGl0LkF1dGhvcml6YXRpb25JbmZvEj0K", "EHJlcXVlc3RfbWV0YWRhdGEYBCABKAsyIy5nb29nbGUuY2xvdWQuYXVkaXQu", "UmVxdWVzdE1ldGFkYXRhEigKB3JlcXVlc3QYECABKAsyFy5nb29nbGUucHJv", "dG9idWYuU3RydWN0EikKCHJlc3BvbnNlGBEgASgLMhcuZ29vZ2xlLnByb3Rv", "YnVmLlN0cnVjdBIqCgxzZXJ2aWNlX2RhdGEYDyABKAsyFC5nb29nbGUucHJv", "dG9idWYuQW55Ii0KEkF1dGhlbnRpY2F0aW9uSW5mbxIXCg9wcmluY2lwYWxf", "ZW1haWwYASABKAkiSgoRQXV0aG9yaXphdGlvbkluZm8SEAoIcmVzb3VyY2UY", "ASABKAkSEgoKcGVybWlzc2lvbhgCIAEoCRIPCgdncmFudGVkGAMgASgIIkgK", "D1JlcXVlc3RNZXRhZGF0YRIRCgljYWxsZXJfaXAYASABKAkSIgoaY2FsbGVy", "X3N1cHBsaWVkX3VzZXJfYWdlbnQYAiABKAlCYgoWY29tLmdvb2dsZS5jbG91", "ZC5hdWRpdEINQXVkaXRMb2dQcm90b1ABWjdnb29nbGUuZ29sYW5nLm9yZy9n", "ZW5wcm90by9nb29nbGVhcGlzL2Nsb3VkL2F1ZGl0O2F1ZGl0YgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.AnyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor, global::Google.Rpc.StatusReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Audit.AuditLog), global::Google.Cloud.Audit.AuditLog.Parser, new[]{ "ServiceName", "MethodName", "ResourceName", "NumResponseItems", "Status", "AuthenticationInfo", "AuthorizationInfo", "RequestMetadata", "Request", "Response", "ServiceData" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Audit.AuthenticationInfo), global::Google.Cloud.Audit.AuthenticationInfo.Parser, new[]{ "PrincipalEmail" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Audit.AuthorizationInfo), global::Google.Cloud.Audit.AuthorizationInfo.Parser, new[]{ "Resource", "Permission", "Granted" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Audit.RequestMetadata), global::Google.Cloud.Audit.RequestMetadata.Parser, new[]{ "CallerIp", "CallerSuppliedUserAgent" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// Common audit log format for Google Cloud Platform API operations. /// </summary> public sealed partial class AuditLog : pb::IMessage<AuditLog> { private static readonly pb::MessageParser<AuditLog> _parser = new pb::MessageParser<AuditLog>(() => new AuditLog()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<AuditLog> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Audit.AuditLogReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AuditLog() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AuditLog(AuditLog other) : this() { serviceName_ = other.serviceName_; methodName_ = other.methodName_; resourceName_ = other.resourceName_; numResponseItems_ = other.numResponseItems_; Status = other.status_ != null ? other.Status.Clone() : null; AuthenticationInfo = other.authenticationInfo_ != null ? other.AuthenticationInfo.Clone() : null; authorizationInfo_ = other.authorizationInfo_.Clone(); RequestMetadata = other.requestMetadata_ != null ? other.RequestMetadata.Clone() : null; Request = other.request_ != null ? other.Request.Clone() : null; Response = other.response_ != null ? other.Response.Clone() : null; ServiceData = other.serviceData_ != null ? other.ServiceData.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AuditLog Clone() { return new AuditLog(this); } /// <summary>Field number for the "service_name" field.</summary> public const int ServiceNameFieldNumber = 7; private string serviceName_ = ""; /// <summary> /// The name of the API service performing the operation. For example, /// `"datastore.googleapis.com"`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ServiceName { get { return serviceName_; } set { serviceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "method_name" field.</summary> public const int MethodNameFieldNumber = 8; private string methodName_ = ""; /// <summary> /// The name of the service method or operation. /// For API calls, this should be the name of the API method. /// For example, /// /// "google.datastore.v1.Datastore.RunQuery" /// "google.logging.v1.LoggingService.DeleteLog" /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string MethodName { get { return methodName_; } set { methodName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "resource_name" field.</summary> public const int ResourceNameFieldNumber = 11; private string resourceName_ = ""; /// <summary> /// The resource or collection that is the target of the operation. /// The name is a scheme-less URI, not including the API service name. /// For example: /// /// "shelves/SHELF_ID/books" /// "shelves/SHELF_ID/books/BOOK_ID" /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ResourceName { get { return resourceName_; } set { resourceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "num_response_items" field.</summary> public const int NumResponseItemsFieldNumber = 12; private long numResponseItems_; /// <summary> /// The number of items returned from a List or Query API method, /// if applicable. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long NumResponseItems { get { return numResponseItems_; } set { numResponseItems_ = value; } } /// <summary>Field number for the "status" field.</summary> public const int StatusFieldNumber = 2; private global::Google.Rpc.Status status_; /// <summary> /// The status of the overall operation. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Rpc.Status Status { get { return status_; } set { status_ = value; } } /// <summary>Field number for the "authentication_info" field.</summary> public const int AuthenticationInfoFieldNumber = 3; private global::Google.Cloud.Audit.AuthenticationInfo authenticationInfo_; /// <summary> /// Authentication information. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Audit.AuthenticationInfo AuthenticationInfo { get { return authenticationInfo_; } set { authenticationInfo_ = value; } } /// <summary>Field number for the "authorization_info" field.</summary> public const int AuthorizationInfoFieldNumber = 9; private static readonly pb::FieldCodec<global::Google.Cloud.Audit.AuthorizationInfo> _repeated_authorizationInfo_codec = pb::FieldCodec.ForMessage(74, global::Google.Cloud.Audit.AuthorizationInfo.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Audit.AuthorizationInfo> authorizationInfo_ = new pbc::RepeatedField<global::Google.Cloud.Audit.AuthorizationInfo>(); /// <summary> /// Authorization information. If there are multiple /// resources or permissions involved, then there is /// one AuthorizationInfo element for each {resource, permission} tuple. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Audit.AuthorizationInfo> AuthorizationInfo { get { return authorizationInfo_; } } /// <summary>Field number for the "request_metadata" field.</summary> public const int RequestMetadataFieldNumber = 4; private global::Google.Cloud.Audit.RequestMetadata requestMetadata_; /// <summary> /// Metadata about the operation. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Audit.RequestMetadata RequestMetadata { get { return requestMetadata_; } set { requestMetadata_ = value; } } /// <summary>Field number for the "request" field.</summary> public const int RequestFieldNumber = 16; private global::Google.Protobuf.WellKnownTypes.Struct request_; /// <summary> /// The operation request. This may not include all request parameters, /// such as those that are too large, privacy-sensitive, or duplicated /// elsewhere in the log record. /// It should never include user-generated data, such as file contents. /// When the JSON object represented here has a proto equivalent, the proto /// name will be indicated in the `@type` property. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Struct Request { get { return request_; } set { request_ = value; } } /// <summary>Field number for the "response" field.</summary> public const int ResponseFieldNumber = 17; private global::Google.Protobuf.WellKnownTypes.Struct response_; /// <summary> /// The operation response. This may not include all response elements, /// such as those that are too large, privacy-sensitive, or duplicated /// elsewhere in the log record. /// It should never include user-generated data, such as file contents. /// When the JSON object represented here has a proto equivalent, the proto /// name will be indicated in the `@type` property. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Struct Response { get { return response_; } set { response_ = value; } } /// <summary>Field number for the "service_data" field.</summary> public const int ServiceDataFieldNumber = 15; private global::Google.Protobuf.WellKnownTypes.Any serviceData_; /// <summary> /// Other service-specific data about the request, response, and other /// activities. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Any ServiceData { get { return serviceData_; } set { serviceData_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as AuditLog); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(AuditLog other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ServiceName != other.ServiceName) return false; if (MethodName != other.MethodName) return false; if (ResourceName != other.ResourceName) return false; if (NumResponseItems != other.NumResponseItems) return false; if (!object.Equals(Status, other.Status)) return false; if (!object.Equals(AuthenticationInfo, other.AuthenticationInfo)) return false; if(!authorizationInfo_.Equals(other.authorizationInfo_)) return false; if (!object.Equals(RequestMetadata, other.RequestMetadata)) return false; if (!object.Equals(Request, other.Request)) return false; if (!object.Equals(Response, other.Response)) return false; if (!object.Equals(ServiceData, other.ServiceData)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (ServiceName.Length != 0) hash ^= ServiceName.GetHashCode(); if (MethodName.Length != 0) hash ^= MethodName.GetHashCode(); if (ResourceName.Length != 0) hash ^= ResourceName.GetHashCode(); if (NumResponseItems != 0L) hash ^= NumResponseItems.GetHashCode(); if (status_ != null) hash ^= Status.GetHashCode(); if (authenticationInfo_ != null) hash ^= AuthenticationInfo.GetHashCode(); hash ^= authorizationInfo_.GetHashCode(); if (requestMetadata_ != null) hash ^= RequestMetadata.GetHashCode(); if (request_ != null) hash ^= Request.GetHashCode(); if (response_ != null) hash ^= Response.GetHashCode(); if (serviceData_ != null) hash ^= ServiceData.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (status_ != null) { output.WriteRawTag(18); output.WriteMessage(Status); } if (authenticationInfo_ != null) { output.WriteRawTag(26); output.WriteMessage(AuthenticationInfo); } if (requestMetadata_ != null) { output.WriteRawTag(34); output.WriteMessage(RequestMetadata); } if (ServiceName.Length != 0) { output.WriteRawTag(58); output.WriteString(ServiceName); } if (MethodName.Length != 0) { output.WriteRawTag(66); output.WriteString(MethodName); } authorizationInfo_.WriteTo(output, _repeated_authorizationInfo_codec); if (ResourceName.Length != 0) { output.WriteRawTag(90); output.WriteString(ResourceName); } if (NumResponseItems != 0L) { output.WriteRawTag(96); output.WriteInt64(NumResponseItems); } if (serviceData_ != null) { output.WriteRawTag(122); output.WriteMessage(ServiceData); } if (request_ != null) { output.WriteRawTag(130, 1); output.WriteMessage(Request); } if (response_ != null) { output.WriteRawTag(138, 1); output.WriteMessage(Response); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (ServiceName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ServiceName); } if (MethodName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(MethodName); } if (ResourceName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ResourceName); } if (NumResponseItems != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(NumResponseItems); } if (status_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Status); } if (authenticationInfo_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(AuthenticationInfo); } size += authorizationInfo_.CalculateSize(_repeated_authorizationInfo_codec); if (requestMetadata_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(RequestMetadata); } if (request_ != null) { size += 2 + pb::CodedOutputStream.ComputeMessageSize(Request); } if (response_ != null) { size += 2 + pb::CodedOutputStream.ComputeMessageSize(Response); } if (serviceData_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(ServiceData); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(AuditLog other) { if (other == null) { return; } if (other.ServiceName.Length != 0) { ServiceName = other.ServiceName; } if (other.MethodName.Length != 0) { MethodName = other.MethodName; } if (other.ResourceName.Length != 0) { ResourceName = other.ResourceName; } if (other.NumResponseItems != 0L) { NumResponseItems = other.NumResponseItems; } if (other.status_ != null) { if (status_ == null) { status_ = new global::Google.Rpc.Status(); } Status.MergeFrom(other.Status); } if (other.authenticationInfo_ != null) { if (authenticationInfo_ == null) { authenticationInfo_ = new global::Google.Cloud.Audit.AuthenticationInfo(); } AuthenticationInfo.MergeFrom(other.AuthenticationInfo); } authorizationInfo_.Add(other.authorizationInfo_); if (other.requestMetadata_ != null) { if (requestMetadata_ == null) { requestMetadata_ = new global::Google.Cloud.Audit.RequestMetadata(); } RequestMetadata.MergeFrom(other.RequestMetadata); } if (other.request_ != null) { if (request_ == null) { request_ = new global::Google.Protobuf.WellKnownTypes.Struct(); } Request.MergeFrom(other.Request); } if (other.response_ != null) { if (response_ == null) { response_ = new global::Google.Protobuf.WellKnownTypes.Struct(); } Response.MergeFrom(other.Response); } if (other.serviceData_ != null) { if (serviceData_ == null) { serviceData_ = new global::Google.Protobuf.WellKnownTypes.Any(); } ServiceData.MergeFrom(other.ServiceData); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 18: { if (status_ == null) { status_ = new global::Google.Rpc.Status(); } input.ReadMessage(status_); break; } case 26: { if (authenticationInfo_ == null) { authenticationInfo_ = new global::Google.Cloud.Audit.AuthenticationInfo(); } input.ReadMessage(authenticationInfo_); break; } case 34: { if (requestMetadata_ == null) { requestMetadata_ = new global::Google.Cloud.Audit.RequestMetadata(); } input.ReadMessage(requestMetadata_); break; } case 58: { ServiceName = input.ReadString(); break; } case 66: { MethodName = input.ReadString(); break; } case 74: { authorizationInfo_.AddEntriesFrom(input, _repeated_authorizationInfo_codec); break; } case 90: { ResourceName = input.ReadString(); break; } case 96: { NumResponseItems = input.ReadInt64(); break; } case 122: { if (serviceData_ == null) { serviceData_ = new global::Google.Protobuf.WellKnownTypes.Any(); } input.ReadMessage(serviceData_); break; } case 130: { if (request_ == null) { request_ = new global::Google.Protobuf.WellKnownTypes.Struct(); } input.ReadMessage(request_); break; } case 138: { if (response_ == null) { response_ = new global::Google.Protobuf.WellKnownTypes.Struct(); } input.ReadMessage(response_); break; } } } } } /// <summary> /// Authentication information for the operation. /// </summary> public sealed partial class AuthenticationInfo : pb::IMessage<AuthenticationInfo> { private static readonly pb::MessageParser<AuthenticationInfo> _parser = new pb::MessageParser<AuthenticationInfo>(() => new AuthenticationInfo()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<AuthenticationInfo> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Audit.AuditLogReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AuthenticationInfo() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AuthenticationInfo(AuthenticationInfo other) : this() { principalEmail_ = other.principalEmail_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AuthenticationInfo Clone() { return new AuthenticationInfo(this); } /// <summary>Field number for the "principal_email" field.</summary> public const int PrincipalEmailFieldNumber = 1; private string principalEmail_ = ""; /// <summary> /// The email address of the authenticated user making the request. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string PrincipalEmail { get { return principalEmail_; } set { principalEmail_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as AuthenticationInfo); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(AuthenticationInfo other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (PrincipalEmail != other.PrincipalEmail) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (PrincipalEmail.Length != 0) hash ^= PrincipalEmail.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (PrincipalEmail.Length != 0) { output.WriteRawTag(10); output.WriteString(PrincipalEmail); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (PrincipalEmail.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(PrincipalEmail); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(AuthenticationInfo other) { if (other == null) { return; } if (other.PrincipalEmail.Length != 0) { PrincipalEmail = other.PrincipalEmail; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { PrincipalEmail = input.ReadString(); break; } } } } } /// <summary> /// Authorization information for the operation. /// </summary> public sealed partial class AuthorizationInfo : pb::IMessage<AuthorizationInfo> { private static readonly pb::MessageParser<AuthorizationInfo> _parser = new pb::MessageParser<AuthorizationInfo>(() => new AuthorizationInfo()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<AuthorizationInfo> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Audit.AuditLogReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AuthorizationInfo() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AuthorizationInfo(AuthorizationInfo other) : this() { resource_ = other.resource_; permission_ = other.permission_; granted_ = other.granted_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AuthorizationInfo Clone() { return new AuthorizationInfo(this); } /// <summary>Field number for the "resource" field.</summary> public const int ResourceFieldNumber = 1; private string resource_ = ""; /// <summary> /// The resource being accessed, as a REST-style string. For example: /// /// bigquery.googlapis.com/projects/PROJECTID/datasets/DATASETID /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Resource { get { return resource_; } set { resource_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "permission" field.</summary> public const int PermissionFieldNumber = 2; private string permission_ = ""; /// <summary> /// The required IAM permission. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Permission { get { return permission_; } set { permission_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "granted" field.</summary> public const int GrantedFieldNumber = 3; private bool granted_; /// <summary> /// Whether or not authorization for `resource` and `permission` /// was granted. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Granted { get { return granted_; } set { granted_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as AuthorizationInfo); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(AuthorizationInfo other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Resource != other.Resource) return false; if (Permission != other.Permission) return false; if (Granted != other.Granted) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Resource.Length != 0) hash ^= Resource.GetHashCode(); if (Permission.Length != 0) hash ^= Permission.GetHashCode(); if (Granted != false) hash ^= Granted.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Resource.Length != 0) { output.WriteRawTag(10); output.WriteString(Resource); } if (Permission.Length != 0) { output.WriteRawTag(18); output.WriteString(Permission); } if (Granted != false) { output.WriteRawTag(24); output.WriteBool(Granted); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Resource.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Resource); } if (Permission.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Permission); } if (Granted != false) { size += 1 + 1; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(AuthorizationInfo other) { if (other == null) { return; } if (other.Resource.Length != 0) { Resource = other.Resource; } if (other.Permission.Length != 0) { Permission = other.Permission; } if (other.Granted != false) { Granted = other.Granted; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Resource = input.ReadString(); break; } case 18: { Permission = input.ReadString(); break; } case 24: { Granted = input.ReadBool(); break; } } } } } /// <summary> /// Metadata about the request. /// </summary> public sealed partial class RequestMetadata : pb::IMessage<RequestMetadata> { private static readonly pb::MessageParser<RequestMetadata> _parser = new pb::MessageParser<RequestMetadata>(() => new RequestMetadata()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<RequestMetadata> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Audit.AuditLogReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RequestMetadata() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RequestMetadata(RequestMetadata other) : this() { callerIp_ = other.callerIp_; callerSuppliedUserAgent_ = other.callerSuppliedUserAgent_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RequestMetadata Clone() { return new RequestMetadata(this); } /// <summary>Field number for the "caller_ip" field.</summary> public const int CallerIpFieldNumber = 1; private string callerIp_ = ""; /// <summary> /// The IP address of the caller. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string CallerIp { get { return callerIp_; } set { callerIp_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "caller_supplied_user_agent" field.</summary> public const int CallerSuppliedUserAgentFieldNumber = 2; private string callerSuppliedUserAgent_ = ""; /// <summary> /// The user agent of the caller. /// This information is not authenticated and should be treated accordingly. /// For example: /// /// + `google-api-python-client/1.4.0`: /// The request was made by the Google API client for Python. /// + `Cloud SDK Command Line Tool apitools-client/1.0 gcloud/0.9.62`: /// The request was made by the Google Cloud SDK CLI (gcloud). /// + `AppEngine-Google; (+http://code.google.com/appengine; appid: s~my-project`: /// The request was made from the `my-project` App Engine app. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string CallerSuppliedUserAgent { get { return callerSuppliedUserAgent_; } set { callerSuppliedUserAgent_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as RequestMetadata); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(RequestMetadata other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (CallerIp != other.CallerIp) return false; if (CallerSuppliedUserAgent != other.CallerSuppliedUserAgent) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (CallerIp.Length != 0) hash ^= CallerIp.GetHashCode(); if (CallerSuppliedUserAgent.Length != 0) hash ^= CallerSuppliedUserAgent.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (CallerIp.Length != 0) { output.WriteRawTag(10); output.WriteString(CallerIp); } if (CallerSuppliedUserAgent.Length != 0) { output.WriteRawTag(18); output.WriteString(CallerSuppliedUserAgent); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (CallerIp.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(CallerIp); } if (CallerSuppliedUserAgent.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(CallerSuppliedUserAgent); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(RequestMetadata other) { if (other == null) { return; } if (other.CallerIp.Length != 0) { CallerIp = other.CallerIp; } if (other.CallerSuppliedUserAgent.Length != 0) { CallerSuppliedUserAgent = other.CallerSuppliedUserAgent; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { CallerIp = input.ReadString(); break; } case 18: { CallerSuppliedUserAgent = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
//============================================================================= // System : Sandcastle Help File Builder Utilities // File : TopicFile.cs // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 09/05/2008 // Note : Copyright 2008, Eric Woodruff, All rights reserved // Compiler: Microsoft Visual C# // // This file contains a class representing a conceptual content topic file. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://SHFB.CodePlex.com. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.8.0.0 08/07/2008 EFW Created the code //============================================================================= using System; using System.ComponentModel; using System.Globalization; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Xml; using SandcastleBuilder.Utils; using SandcastleBuilder.Utils.BuildEngine; namespace SandcastleBuilder.Utils.ConceptualContent { /// <summary> /// This class represents a conceptual content topic file /// </summary> public class TopicFile { #region Private data members //===================================================================== private static Regex reMeta = new Regex("\\<meta\\s*name\\s*=" + "\\s*\"(?<Name>\\w*?)\"\\s*content\\s*=\\s*\"(?<Content>.*?)\"", RegexOptions.IgnoreCase | RegexOptions.Singleline); private FileItem fileItem; private DocumentType docType; private string id, errorMessage; private int revision; private bool contentParsed; #endregion #region Properties //===================================================================== /// <summary> /// This is used to get or set the file build item /// </summary> public FileItem FileItem { get { return fileItem; } set { fileItem = value; contentParsed = false; docType = DocumentType.None; } } /// <summary> /// Get the name of the file without the path /// </summary> public string Name { get { return fileItem.Name; } } /// <summary> /// Get the full path to the file /// </summary> public string FullPath { get { return fileItem.FullPath; } } /// <summary> /// This is used to get the unique ID of the topic /// </summary> public string Id { get { this.ParseContent(false); return id; } } /// <summary> /// This is used to get the topic's revision number /// </summary> public int RevisionNumber { get { this.ParseContent(false); return revision; } } /// <summary> /// This read-only property is used to get the document type /// </summary> public DocumentType DocumentType { get { this.ParseContent(false); return docType; } } /// <summary> /// This read-only property is used to return the error message if /// <see cref="DocumentType" /> returns <b>Invalid</b>. /// </summary> public string ErrorMessage { get { return errorMessage; } } #endregion #region Constructor //===================================================================== /// <summary> /// Constructor /// </summary> /// <param name="file">The file build item from the project</param> /// <exception cref="ArgumentNullException">This is thrown if the file /// item is null.</exception> public TopicFile(FileItem file) { if(file == null) throw new ArgumentNullException("file"); fileItem = file; revision = 1; } #endregion #region Parsing methods //===================================================================== /// <summary> /// This will parse the file content and extract the document type, /// unique ID, and revision number. /// </summary> /// <param name="reparse">If false and the file has already been /// parsed, the method just returns. If true, the file is reparsed /// to refresh the information.</param> public void ParseContent(bool reparse) { XmlReaderSettings settings = new XmlReaderSettings(); XmlReader xr = null; string attrValue, ext; int rev; if(!reparse && contentParsed) return; contentParsed = false; docType = DocumentType.None; id = errorMessage = null; revision = 1; if(!File.Exists(fileItem.FullPath)) { docType = DocumentType.NotFound; return; } // Don't bother parsing HTML files but support them for passing // through stuff like title pages which may not need to look like // the API topics. ext = Path.GetExtension(fileItem.FullPath).ToLower( CultureInfo.InvariantCulture); if(ext == ".htm" || ext == ".html" || ext == ".topic") { docType = DocumentType.Html; if(ext != ".topic") { contentParsed = true; this.ParseIdFromHtml(); return; } } try { settings.CloseInput = true; settings.IgnoreComments = true; settings.IgnoreProcessingInstructions = true; settings.IgnoreWhitespace = true; xr = XmlReader.Create(fileItem.FullPath, settings); xr.MoveToContent(); while(!xr.EOF) if(xr.NodeType != XmlNodeType.Element) xr.Read(); else switch(xr.Name) { case "topic": // If a <topic> element is found, parse the ID // and revision number from it. attrValue = xr.GetAttribute("id"); // The ID is required if(attrValue != null && attrValue.Trim().Length != 0) id = attrValue; else throw new XmlException("<topic> element " + "is missing the 'id' attribute"); // This is optional attrValue = xr.GetAttribute("revisionNumber"); if(attrValue != null && Int32.TryParse(attrValue, out rev)) revision = rev; xr.Read(); break; case "developerConceptualDocument": case "developerErrorMessageDocument": case "developerGlossaryDocument": case "developerHowToDocument": case "developerOrientationDocument": case "codeEntityDocument": case "developerReferenceWithSyntaxDocument": case "developerReferenceWithoutSyntaxDocument": case "developerSampleDocument": case "developerSDKTechnologyOverviewArchitectureDocument": case "developerSDKTechnologyOverviewCodeDirectoryDocument": case "developerSDKTechnologyOverviewOrientationDocument": case "developerSDKTechnologyOverviewScenariosDocument": case "developerSDKTechnologyOverviewTechnologySummaryDocument": case "developerTroubleshootingDocument": case "developerUIReferenceDocument": case "developerWalkthroughDocument": case "developerWhitePaperDocument": case "developerXmlReference": docType = (DocumentType)Enum.Parse( typeof(DocumentType), xr.Name, true); xr.Read(); break; default: // Ignore it xr.Skip(); break; } } catch(Exception ex) { docType = DocumentType.Invalid; errorMessage = ex.Message; } finally { if(xr != null) xr.Close(); contentParsed = true; } } /// <summary> /// This is used to parse the ID and revision number from an HTML file /// </summary> private void ParseIdFromHtml() { Encoding enc = Encoding.Default; int rev; string content = BuildProcess.ReadWithEncoding(fileItem.FullPath, ref enc); MatchCollection matches = reMeta.Matches(content); foreach(Match m in matches) if(m.Groups[1].Value == "id") id = m.Groups[2].Value; else if(m.Groups[1].Value == "revisionNumber" && Int32.TryParse(m.Groups[2].Value, out rev)) revision = rev; } #endregion } }
// Copyright 2022 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="ConversionCustomVariableServiceClient"/> instances.</summary> public sealed partial class ConversionCustomVariableServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="ConversionCustomVariableServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="ConversionCustomVariableServiceSettings"/>.</returns> public static ConversionCustomVariableServiceSettings GetDefault() => new ConversionCustomVariableServiceSettings(); /// <summary> /// Constructs a new <see cref="ConversionCustomVariableServiceSettings"/> object with default settings. /// </summary> public ConversionCustomVariableServiceSettings() { } private ConversionCustomVariableServiceSettings(ConversionCustomVariableServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); MutateConversionCustomVariablesSettings = existing.MutateConversionCustomVariablesSettings; OnCopy(existing); } partial void OnCopy(ConversionCustomVariableServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ConversionCustomVariableServiceClient.MutateConversionCustomVariables</c> and /// <c>ConversionCustomVariableServiceClient.MutateConversionCustomVariablesAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateConversionCustomVariablesSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="ConversionCustomVariableServiceSettings"/> object.</returns> public ConversionCustomVariableServiceSettings Clone() => new ConversionCustomVariableServiceSettings(this); } /// <summary> /// Builder class for <see cref="ConversionCustomVariableServiceClient"/> to provide simple configuration of /// credentials, endpoint etc. /// </summary> internal sealed partial class ConversionCustomVariableServiceClientBuilder : gaxgrpc::ClientBuilderBase<ConversionCustomVariableServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public ConversionCustomVariableServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public ConversionCustomVariableServiceClientBuilder() { UseJwtAccessWithScopes = ConversionCustomVariableServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref ConversionCustomVariableServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ConversionCustomVariableServiceClient> task); /// <summary>Builds the resulting client.</summary> public override ConversionCustomVariableServiceClient Build() { ConversionCustomVariableServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<ConversionCustomVariableServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<ConversionCustomVariableServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private ConversionCustomVariableServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return ConversionCustomVariableServiceClient.Create(callInvoker, Settings); } private async stt::Task<ConversionCustomVariableServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return ConversionCustomVariableServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => ConversionCustomVariableServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => ConversionCustomVariableServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => ConversionCustomVariableServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>ConversionCustomVariableService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage conversion custom variables. /// </remarks> public abstract partial class ConversionCustomVariableServiceClient { /// <summary> /// The default endpoint for the ConversionCustomVariableService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default ConversionCustomVariableService scopes.</summary> /// <remarks> /// The default ConversionCustomVariableService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="ConversionCustomVariableServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="ConversionCustomVariableServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="ConversionCustomVariableServiceClient"/>.</returns> public static stt::Task<ConversionCustomVariableServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new ConversionCustomVariableServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="ConversionCustomVariableServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="ConversionCustomVariableServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="ConversionCustomVariableServiceClient"/>.</returns> public static ConversionCustomVariableServiceClient Create() => new ConversionCustomVariableServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="ConversionCustomVariableServiceClient"/> which uses the specified call invoker for /// remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="ConversionCustomVariableServiceSettings"/>.</param> /// <returns>The created <see cref="ConversionCustomVariableServiceClient"/>.</returns> internal static ConversionCustomVariableServiceClient Create(grpccore::CallInvoker callInvoker, ConversionCustomVariableServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } ConversionCustomVariableService.ConversionCustomVariableServiceClient grpcClient = new ConversionCustomVariableService.ConversionCustomVariableServiceClient(callInvoker); return new ConversionCustomVariableServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC ConversionCustomVariableService client</summary> public virtual ConversionCustomVariableService.ConversionCustomVariableServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates or updates conversion custom variables. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [ConversionCustomVariableError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateConversionCustomVariablesResponse MutateConversionCustomVariables(MutateConversionCustomVariablesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates or updates conversion custom variables. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [ConversionCustomVariableError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateConversionCustomVariablesResponse> MutateConversionCustomVariablesAsync(MutateConversionCustomVariablesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates or updates conversion custom variables. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [ConversionCustomVariableError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateConversionCustomVariablesResponse> MutateConversionCustomVariablesAsync(MutateConversionCustomVariablesRequest request, st::CancellationToken cancellationToken) => MutateConversionCustomVariablesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates or updates conversion custom variables. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [ConversionCustomVariableError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose conversion custom variables are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual conversion custom /// variables. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateConversionCustomVariablesResponse MutateConversionCustomVariables(string customerId, scg::IEnumerable<ConversionCustomVariableOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateConversionCustomVariables(new MutateConversionCustomVariablesRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates or updates conversion custom variables. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [ConversionCustomVariableError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose conversion custom variables are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual conversion custom /// variables. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateConversionCustomVariablesResponse> MutateConversionCustomVariablesAsync(string customerId, scg::IEnumerable<ConversionCustomVariableOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateConversionCustomVariablesAsync(new MutateConversionCustomVariablesRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates or updates conversion custom variables. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [ConversionCustomVariableError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose conversion custom variables are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual conversion custom /// variables. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateConversionCustomVariablesResponse> MutateConversionCustomVariablesAsync(string customerId, scg::IEnumerable<ConversionCustomVariableOperation> operations, st::CancellationToken cancellationToken) => MutateConversionCustomVariablesAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>ConversionCustomVariableService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage conversion custom variables. /// </remarks> public sealed partial class ConversionCustomVariableServiceClientImpl : ConversionCustomVariableServiceClient { private readonly gaxgrpc::ApiCall<MutateConversionCustomVariablesRequest, MutateConversionCustomVariablesResponse> _callMutateConversionCustomVariables; /// <summary> /// Constructs a client wrapper for the ConversionCustomVariableService service, with the specified gRPC client /// and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="ConversionCustomVariableServiceSettings"/> used within this client. /// </param> public ConversionCustomVariableServiceClientImpl(ConversionCustomVariableService.ConversionCustomVariableServiceClient grpcClient, ConversionCustomVariableServiceSettings settings) { GrpcClient = grpcClient; ConversionCustomVariableServiceSettings effectiveSettings = settings ?? ConversionCustomVariableServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callMutateConversionCustomVariables = clientHelper.BuildApiCall<MutateConversionCustomVariablesRequest, MutateConversionCustomVariablesResponse>(grpcClient.MutateConversionCustomVariablesAsync, grpcClient.MutateConversionCustomVariables, effectiveSettings.MutateConversionCustomVariablesSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateConversionCustomVariables); Modify_MutateConversionCustomVariablesApiCall(ref _callMutateConversionCustomVariables); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_MutateConversionCustomVariablesApiCall(ref gaxgrpc::ApiCall<MutateConversionCustomVariablesRequest, MutateConversionCustomVariablesResponse> call); partial void OnConstruction(ConversionCustomVariableService.ConversionCustomVariableServiceClient grpcClient, ConversionCustomVariableServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC ConversionCustomVariableService client</summary> public override ConversionCustomVariableService.ConversionCustomVariableServiceClient GrpcClient { get; } partial void Modify_MutateConversionCustomVariablesRequest(ref MutateConversionCustomVariablesRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates or updates conversion custom variables. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [ConversionCustomVariableError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateConversionCustomVariablesResponse MutateConversionCustomVariables(MutateConversionCustomVariablesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateConversionCustomVariablesRequest(ref request, ref callSettings); return _callMutateConversionCustomVariables.Sync(request, callSettings); } /// <summary> /// Creates or updates conversion custom variables. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [ConversionCustomVariableError]() /// [DatabaseError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateConversionCustomVariablesResponse> MutateConversionCustomVariablesAsync(MutateConversionCustomVariablesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateConversionCustomVariablesRequest(ref request, ref callSettings); return _callMutateConversionCustomVariables.Async(request, callSettings); } } }
// // 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. // IMPORTANT: This code was machine generated and then modified by humans. // Updating this file with the machine generated one might overwrite important changes. // Please review and revert unintended changes carefully. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml; using Hyak.Common; using Microsoft.Azure.Insights; using Microsoft.Azure.Insights.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Insights { /// <summary> /// Operations for metric values. /// </summary> internal partial class MetricOperations : IServiceOperations<InsightsClient>, IMetricOperations { /// <summary> /// Initializes a new instance of the MetricOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal MetricOperations(InsightsClient client) { this._client = client; } private InsightsClient _client; /// <summary> /// Gets a reference to the Microsoft.Azure.Insights.InsightsClient. /// </summary> public InsightsClient Client { get { return this._client; } } /// <summary> /// The List Metric operation lists the metric value sets for the /// resource metrics. /// </summary> /// <param name='resourceUri'> /// Required. The resource identifier of the target resource to get /// metrics for. /// </param> /// <param name='filterString'> /// Optional. An OData $filter expression that supports querying by the /// name, startTime, endTime and timeGrain of the metric value sets. /// For example, "(name.value eq 'Percentage CPU') and startTime eq /// 2014-07-02T01:00Z and endTime eq 2014-08-21T01:00:00Z and /// timeGrain eq duration'PT1H'". In the expression, startTime, /// endTime and timeGrain are required. Name is optional. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Metric values operation response. /// </returns> public async Task<MetricListResponse> GetMetricsInternalAsync(string resourceUri, string filterString, CancellationToken cancellationToken) { // Validate if (resourceUri == null) { throw new ArgumentNullException("resourceUri"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("filterString", filterString); TracingAdapter.Enter(invocationId, this, "GetMetricsAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; url = url + resourceUri; url = url + "/metrics"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); List<string> odataFilter = new List<string>(); if (filterString != null) { odataFilter.Add(Uri.EscapeDataString(filterString)); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(null, odataFilter)); } if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-04-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result MetricListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new MetricListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { MetricCollection metricCollectionInstance = new MetricCollection(); result.MetricCollection = metricCollectionInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Metric metricInstance = new Metric(); metricCollectionInstance.Value.Add(metricInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { LocalizableString nameInstance = new LocalizableString(); metricInstance.Name = nameInstance; JToken valueValue2 = nameValue["value"]; if (valueValue2 != null && valueValue2.Type != JTokenType.Null) { string valueInstance = ((string)valueValue2); nameInstance.Value = valueInstance; } JToken localizedValueValue = nameValue["localizedValue"]; if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null) { string localizedValueInstance = ((string)localizedValueValue); nameInstance.LocalizedValue = localizedValueInstance; } } JToken unitValue = valueValue["unit"]; if (unitValue != null && unitValue.Type != JTokenType.Null) { Unit unitInstance = ((Unit)Enum.Parse(typeof(Unit), ((string)unitValue), true)); metricInstance.Unit = unitInstance; } JToken timeGrainValue = valueValue["timeGrain"]; if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null) { TimeSpan timeGrainInstance = XmlConvert.ToTimeSpan(((string)timeGrainValue)); metricInstance.TimeGrain = timeGrainInstance; } JToken startTimeValue = valueValue["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTime startTimeInstance = ((DateTime)startTimeValue); metricInstance.StartTime = startTimeInstance; } JToken endTimeValue = valueValue["endTime"]; if (endTimeValue != null && endTimeValue.Type != JTokenType.Null) { DateTime endTimeInstance = ((DateTime)endTimeValue); metricInstance.EndTime = endTimeInstance; } JToken metricValuesArray = valueValue["metricValues"]; if (metricValuesArray != null && metricValuesArray.Type != JTokenType.Null) { foreach (JToken metricValuesValue in ((JArray)metricValuesArray)) { MetricValue metricValueInstance = new MetricValue(); metricInstance.MetricValues.Add(metricValueInstance); JToken timestampValue = metricValuesValue["timestamp"]; if (timestampValue != null && timestampValue.Type != JTokenType.Null) { DateTime timestampInstance = ((DateTime)timestampValue); metricValueInstance.Timestamp = timestampInstance; } JToken averageValue = metricValuesValue["average"]; if (averageValue != null && averageValue.Type != JTokenType.Null) { double averageInstance = ((double)averageValue); metricValueInstance.Average = averageInstance; } JToken minimumValue = metricValuesValue["minimum"]; if (minimumValue != null && minimumValue.Type != JTokenType.Null) { double minimumInstance = ((double)minimumValue); metricValueInstance.Minimum = minimumInstance; } JToken maximumValue = metricValuesValue["maximum"]; if (maximumValue != null && maximumValue.Type != JTokenType.Null) { double maximumInstance = ((double)maximumValue); metricValueInstance.Maximum = maximumInstance; } JToken totalValue = metricValuesValue["total"]; if (totalValue != null && totalValue.Type != JTokenType.Null) { double totalInstance = ((double)totalValue); metricValueInstance.Total = totalInstance; } JToken countValue = metricValuesValue["count"]; if (countValue != null && countValue.Type != JTokenType.Null) { long countInstance = ((long)countValue); metricValueInstance.Count = countInstance; } JToken lastValue = metricValuesValue["last"]; if (lastValue != null && lastValue.Type != JTokenType.Null) { double lastInstance = ((double)lastValue); metricValueInstance.Last = lastInstance; } JToken propertiesSequenceElement = ((JToken)metricValuesValue["properties"]); if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in propertiesSequenceElement) { string propertiesKey = ((string)property.Name); string propertiesValue = ((string)property.Value); metricValueInstance.Properties.Add(propertiesKey, propertiesValue); } } } } JToken resourceIdValue = valueValue["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { string resourceIdInstance = ((string)resourceIdValue); metricInstance.ResourceId = resourceIdInstance; } JToken propertiesSequenceElement2 = ((JToken)valueValue["properties"]); if (propertiesSequenceElement2 != null && propertiesSequenceElement2.Type != JTokenType.Null) { foreach (JProperty property2 in propertiesSequenceElement2) { string propertiesKey2 = ((string)property2.Name); string propertiesValue2 = ((string)property2.Value); metricInstance.Properties.Add(propertiesKey2, propertiesValue2); } } JToken dimensionNameValue = valueValue["dimensionName"]; if (dimensionNameValue != null && dimensionNameValue.Type != JTokenType.Null) { LocalizableString dimensionNameInstance = new LocalizableString(); metricInstance.DimensionName = dimensionNameInstance; JToken valueValue3 = dimensionNameValue["value"]; if (valueValue3 != null && valueValue3.Type != JTokenType.Null) { string valueInstance2 = ((string)valueValue3); dimensionNameInstance.Value = valueInstance2; } JToken localizedValueValue2 = dimensionNameValue["localizedValue"]; if (localizedValueValue2 != null && localizedValueValue2.Type != JTokenType.Null) { string localizedValueInstance2 = ((string)localizedValueValue2); dimensionNameInstance.LocalizedValue = localizedValueInstance2; } } JToken dimensionValueValue = valueValue["dimensionValue"]; if (dimensionValueValue != null && dimensionValueValue.Type != JTokenType.Null) { LocalizableString dimensionValueInstance = new LocalizableString(); metricInstance.DimensionValue = dimensionValueInstance; JToken valueValue4 = dimensionValueValue["value"]; if (valueValue4 != null && valueValue4.Type != JTokenType.Null) { string valueInstance3 = ((string)valueValue4); dimensionValueInstance.Value = valueInstance3; } JToken localizedValueValue3 = dimensionValueValue["localizedValue"]; if (localizedValueValue3 != null && localizedValueValue3.Type != JTokenType.Null) { string localizedValueInstance3 = ((string)localizedValueValue3); dimensionValueInstance.LocalizedValue = localizedValueInstance3; } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Data; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Runtime.Serialization; namespace DDay.iCal { /// <summary> /// A class that contains time zone information, and is usually accessed /// from an iCalendar object using the <see cref="DDay.iCal.iCalendar.GetTimeZone"/> method. /// </summary> #if !SILVERLIGHT [Serializable] #endif public class iCalTimeZoneInfo : CalendarComponent, ITimeZoneInfo { #region Private Fields TimeZoneInfoEvaluator m_Evaluator; DateTime m_End; #endregion #region Constructors public iCalTimeZoneInfo() : base() { // FIXME: how do we ensure SEQUENCE doesn't get serialized? //base.Sequence = null; // iCalTimeZoneInfo does not allow sequence numbers // Perhaps we should have a custom serializer that fixes this? Initialize(); } public iCalTimeZoneInfo(string name) : this() { this.Name = name; } void Initialize() { m_Evaluator = new TimeZoneInfoEvaluator(this); SetService(m_Evaluator); } #endregion #region Overrides protected override void OnDeserializing(StreamingContext context) { base.OnDeserializing(context); Initialize(); } public override bool Equals(object obj) { iCalTimeZoneInfo tzi = obj as iCalTimeZoneInfo; if (tzi != null) { return object.Equals(TimeZoneName, tzi.TimeZoneName) && object.Equals(OffsetFrom, tzi.OffsetFrom) && object.Equals(OffsetTo, tzi.OffsetTo); } return base.Equals(obj); } #endregion #region ITimeZoneInfo Members virtual public string TZID { get { ITimeZone tz = Parent as ITimeZone; if (tz != null) return tz.TZID; return null; } } private bool _timeZoneNameSet; private string _timeZoneName; /// <summary> /// Returns the name of the current Time Zone. /// <example> /// The following are examples: /// <list type="bullet"> /// <item>EST</item> /// <item>EDT</item> /// <item>MST</item> /// <item>MDT</item> /// </list> /// </example> /// </summary> virtual public string TimeZoneName { get { if (_timeZoneNameSet) return _timeZoneName; var names = TimeZoneNames; if (names.Count > 0) { _timeZoneName = names[0]; _timeZoneNameSet = true; } return _timeZoneName; } set { TimeZoneNames.Clear(); TimeZoneNames.Add(value); _timeZoneName = null; _timeZoneNameSet = false; } } virtual public IUTCOffset TZOffsetFrom { get { return OffsetFrom; } set { OffsetFrom = value; } } virtual public IUTCOffset OffsetFrom { get { return Properties.Get<IUTCOffset>("TZOFFSETFROM"); } set { Properties.Set("TZOFFSETFROM", value); } } virtual public IUTCOffset OffsetTo { get { return Properties.Get<IUTCOffset>("TZOFFSETTO"); } set { Properties.Set("TZOFFSETTO", value); } } virtual public IUTCOffset TZOffsetTo { get { return OffsetTo; } set { OffsetTo = value; } } virtual public IList<string> TimeZoneNames { get { return Properties.GetMany<string>("TZNAME"); } set { Properties.Set("TZNAME", value); } } virtual public TimeZoneObservance? GetObservance(IDateTime dt) { if (Parent == null) throw new Exception("Cannot call GetObservance() on a TimeZoneInfo whose Parent property is null."); if (string.Equals(dt.TZID, TZID)) { // Normalize date/time values within this time zone to a local value. DateTime normalizedDt = dt.Value; // Let's evaluate our time zone observances to find the // observance that applies to this date/time value. IEvaluator parentEval = Parent.GetService(typeof(IEvaluator)) as IEvaluator; if (parentEval != null) { // Evaluate the date/time in question. parentEval.Evaluate(Start, DateUtil.GetSimpleDateTimeData(Start), normalizedDt, true); // NOTE: We avoid using period.Contains here, because we want to avoid // doing an inadvertent time zone lookup with it. var period = m_Evaluator .Periods .FirstOrDefault(p => p.StartTime.Value <= normalizedDt && (p.EndTime == null || p.EndTime.Value > normalizedDt) ); if (period != null) { return new TimeZoneObservance(period, this); } } } return null; } virtual public bool Contains(IDateTime dt) { TimeZoneObservance? retval = GetObservance(dt); return (retval != null && retval.HasValue); } #endregion #region IRecurrable Members virtual public IDateTime DTStart { get { return Start; } set { Start = value; } } virtual public IDateTime Start { get { return Properties.Get<IDateTime>("DTSTART"); } set { Properties.Set("DTSTART", value); } } virtual public IList<IPeriodList> ExceptionDates { get { return Properties.GetMany<IPeriodList>("EXDATE"); } set { Properties.Set("EXDATE", value); } } virtual public IList<IRecurrencePattern> ExceptionRules { get { return Properties.GetMany<IRecurrencePattern>("EXRULE"); } set { Properties.Set("EXRULE", value); } } virtual public IList<IPeriodList> RecurrenceDates { get { return Properties.GetMany<IPeriodList>("RDATE"); } set { Properties.Set("RDATE", value); } } virtual public IList<IRecurrencePattern> RecurrenceRules { get { return Properties.GetMany<IRecurrencePattern>("RRULE"); } set { Properties.Set("RRULE", value); } } virtual public IDateTime RecurrenceID { get { return Properties.Get<IDateTime>("RECURRENCE-ID"); } set { Properties.Set("RECURRENCE-ID", value); } } #endregion #region IRecurrable Members virtual public void ClearEvaluation() { RecurrenceUtil.ClearEvaluation(this); } virtual public IList<Occurrence> GetOccurrences(IDateTime dt) { return RecurrenceUtil.GetOccurrences(this, dt, true); } virtual public IList<Occurrence> GetOccurrences(DateTime dt) { return RecurrenceUtil.GetOccurrences(this, new iCalDateTime(dt), true); } virtual public IList<Occurrence> GetOccurrences(IDateTime startTime, IDateTime endTime) { return RecurrenceUtil.GetOccurrences(this, startTime, endTime, true); } virtual public IList<Occurrence> GetOccurrences(DateTime startTime, DateTime endTime) { return RecurrenceUtil.GetOccurrences(this, new iCalDateTime(startTime), new iCalDateTime(endTime), true); } #endregion } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// EnvelopeTransferRuleInformation /// </summary> [DataContract] public partial class EnvelopeTransferRuleInformation : IEquatable<EnvelopeTransferRuleInformation>, IValidatableObject { public EnvelopeTransferRuleInformation() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="EnvelopeTransferRuleInformation" /> class. /// </summary> /// <param name="EndPosition">The last position in the result set. .</param> /// <param name="EnvelopeTransferRules">EnvelopeTransferRules.</param> /// <param name="NextUri">The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. .</param> /// <param name="PreviousUri">The postal code for the billing address..</param> /// <param name="ResultSetSize">The number of results returned in this response. .</param> /// <param name="StartPosition">Starting position of the current result set..</param> /// <param name="TotalSetSize">The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response..</param> public EnvelopeTransferRuleInformation(string EndPosition = default(string), List<EnvelopeTransferRule> EnvelopeTransferRules = default(List<EnvelopeTransferRule>), string NextUri = default(string), string PreviousUri = default(string), string ResultSetSize = default(string), string StartPosition = default(string), string TotalSetSize = default(string)) { this.EndPosition = EndPosition; this.EnvelopeTransferRules = EnvelopeTransferRules; this.NextUri = NextUri; this.PreviousUri = PreviousUri; this.ResultSetSize = ResultSetSize; this.StartPosition = StartPosition; this.TotalSetSize = TotalSetSize; } /// <summary> /// The last position in the result set. /// </summary> /// <value>The last position in the result set. </value> [DataMember(Name="endPosition", EmitDefaultValue=false)] public string EndPosition { get; set; } /// <summary> /// Gets or Sets EnvelopeTransferRules /// </summary> [DataMember(Name="envelopeTransferRules", EmitDefaultValue=false)] public List<EnvelopeTransferRule> EnvelopeTransferRules { get; set; } /// <summary> /// The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. /// </summary> /// <value>The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. </value> [DataMember(Name="nextUri", EmitDefaultValue=false)] public string NextUri { get; set; } /// <summary> /// The postal code for the billing address. /// </summary> /// <value>The postal code for the billing address.</value> [DataMember(Name="previousUri", EmitDefaultValue=false)] public string PreviousUri { get; set; } /// <summary> /// The number of results returned in this response. /// </summary> /// <value>The number of results returned in this response. </value> [DataMember(Name="resultSetSize", EmitDefaultValue=false)] public string ResultSetSize { get; set; } /// <summary> /// Starting position of the current result set. /// </summary> /// <value>Starting position of the current result set.</value> [DataMember(Name="startPosition", EmitDefaultValue=false)] public string StartPosition { get; set; } /// <summary> /// The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response. /// </summary> /// <value>The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.</value> [DataMember(Name="totalSetSize", EmitDefaultValue=false)] public string TotalSetSize { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class EnvelopeTransferRuleInformation {\n"); sb.Append(" EndPosition: ").Append(EndPosition).Append("\n"); sb.Append(" EnvelopeTransferRules: ").Append(EnvelopeTransferRules).Append("\n"); sb.Append(" NextUri: ").Append(NextUri).Append("\n"); sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n"); sb.Append(" ResultSetSize: ").Append(ResultSetSize).Append("\n"); sb.Append(" StartPosition: ").Append(StartPosition).Append("\n"); sb.Append(" TotalSetSize: ").Append(TotalSetSize).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as EnvelopeTransferRuleInformation); } /// <summary> /// Returns true if EnvelopeTransferRuleInformation instances are equal /// </summary> /// <param name="other">Instance of EnvelopeTransferRuleInformation to be compared</param> /// <returns>Boolean</returns> public bool Equals(EnvelopeTransferRuleInformation other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.EndPosition == other.EndPosition || this.EndPosition != null && this.EndPosition.Equals(other.EndPosition) ) && ( this.EnvelopeTransferRules == other.EnvelopeTransferRules || this.EnvelopeTransferRules != null && this.EnvelopeTransferRules.SequenceEqual(other.EnvelopeTransferRules) ) && ( this.NextUri == other.NextUri || this.NextUri != null && this.NextUri.Equals(other.NextUri) ) && ( this.PreviousUri == other.PreviousUri || this.PreviousUri != null && this.PreviousUri.Equals(other.PreviousUri) ) && ( this.ResultSetSize == other.ResultSetSize || this.ResultSetSize != null && this.ResultSetSize.Equals(other.ResultSetSize) ) && ( this.StartPosition == other.StartPosition || this.StartPosition != null && this.StartPosition.Equals(other.StartPosition) ) && ( this.TotalSetSize == other.TotalSetSize || this.TotalSetSize != null && this.TotalSetSize.Equals(other.TotalSetSize) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.EndPosition != null) hash = hash * 59 + this.EndPosition.GetHashCode(); if (this.EnvelopeTransferRules != null) hash = hash * 59 + this.EnvelopeTransferRules.GetHashCode(); if (this.NextUri != null) hash = hash * 59 + this.NextUri.GetHashCode(); if (this.PreviousUri != null) hash = hash * 59 + this.PreviousUri.GetHashCode(); if (this.ResultSetSize != null) hash = hash * 59 + this.ResultSetSize.GetHashCode(); if (this.StartPosition != null) hash = hash * 59 + this.StartPosition.GetHashCode(); if (this.TotalSetSize != null) hash = hash * 59 + this.TotalSetSize.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// // GtkBaseClient.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007 Novell, 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 System.IO; using Mono.Addins; using Hyena; using Banshee.Base; using Banshee.Metrics; using Banshee.Database; using Banshee.ServiceStack; using Banshee.Gui.Dialogs; namespace Banshee.Gui { public abstract class GtkBaseClient : Client { static GtkBaseClient () { Application.InitializePaths (); user_gtkrc = Path.Combine (Paths.ApplicationData, "gtkrc"); } private static Type client_type; private static string user_gtkrc; public static void Startup<T> (string [] args) where T : GtkBaseClient { Hyena.Log.InformationFormat ("Running Banshee {0}: [{1}]", Application.Version, Application.BuildDisplayInfo); // This could go into GtkBaseClient, but it's probably something we // should really only support at each client level if (File.Exists (user_gtkrc) && !ApplicationContext.CommandLine.Contains ("no-gtkrc")) { Gtk.Rc.AddDefaultFile (user_gtkrc); } // Boot the client Banshee.Gui.GtkBaseClient.Startup<T> (); } public static void Startup<T> () where T : GtkBaseClient { if (client_type != null) { throw new ApplicationException ("Only a single GtkBaseClient can be initialized through Entry<T>"); } client_type = typeof (T); Hyena.Gui.CleanRoomStartup.Startup (Startup); } private static void Startup () { ((GtkBaseClient)Activator.CreateInstance (client_type)).Run (); } private string default_icon_name; protected GtkBaseClient () : this (true, Application.IconName) { } protected GtkBaseClient (bool initializeDefault, string defaultIconName) { this.default_icon_name = defaultIconName; if (initializeDefault) { Initialize (true); } } protected virtual void PreInitializeGtk () { } protected virtual void InitializeGtk () { Log.Debug ("Initializing GTK"); if (!GLib.Thread.Supported) { GLib.Thread.Init (); } Gtk.Application.Init (); if (ApplicationContext.CommandLine.Contains ("debug-gtkrc")) { Log.Information ("Note: gtkrc files will be checked for reload every 5 seconds!"); GLib.Timeout.Add (5000, delegate { if (Gtk.Rc.ReparseAll ()) { Gtk.Rc.ResetStyles (Gtk.Settings.Default); Log.Information ("gtkrc has been reloaded"); } return true; }); } } protected virtual void PostInitializeGtk () { Log.Debug ("Post-Initializing GTK"); foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes ("/Banshee/ThickClient/GtkBaseClient/PostInitializeGtk")) { try { node.CreateInstance (); } catch (Exception e) { Log.Exception ("PostInitializeGtk extension failed to run", e); } } } protected void Initialize (bool registerCommonServices) { // Set the process name so system process listings and commands are pretty ApplicationContext.TrySetProcessName (Application.InternalName); PreInitializeGtk (); InitializeGtk (); Application.Initialize (); PostInitializeGtk (); Gtk.Window.DefaultIconName = default_icon_name; ThreadAssist.InitializeMainThread (); ThreadAssist.ProxyToMainHandler = Banshee.ServiceStack.Application.Invoke; Gdk.Global.ProgramClass = Application.InternalName; GLib.Global.ApplicationName = "Banshee"; // TODO: Set this to "video" when we're playing a video. PulseAudio doesn't treat it differently // than "music" for now, but it would be more correct. Environment.SetEnvironmentVariable ("PULSE_PROP_media.role", "music"); if (ApplicationContext.Debugging) { GLib.Log.SetLogHandler ("Gtk", GLib.LogLevelFlags.Critical, GLib.Log.PrintTraceLogFunction); Gdk.Window.DebugUpdates = !String.IsNullOrEmpty (Environment.GetEnvironmentVariable ("GDK_DEBUG_UPDATES")); } ServiceManager.ServiceStarted += OnServiceStarted; // Register specific services this client will care about if (registerCommonServices) { Banshee.Gui.CommonServices.Register (); } OnRegisterServices (); Application.ShutdownPromptHandler = OnShutdownPrompt; Application.TimeoutHandler = RunTimeout; Application.IdleHandler = RunIdle; Application.IdleTimeoutRemoveHandler = IdleTimeoutRemove; BansheeMetrics.Started += OnMetricsStarted; // Start the core boot process Application.PushClient (this); Application.Run (); if (!Banshee.Configuration.DefaultApplicationHelper.NeverAsk && Banshee.Configuration.DefaultApplicationHelper.HaveHelper) { Application.ClientStarted += delegate { Banshee.Gui.Dialogs.DefaultApplicationHelperDialog.RunIfAppropriate (); }; } Log.Notify += OnLogNotify; } private void OnMetricsStarted () { var metrics = BansheeMetrics.Instance; var screen = Gdk.Screen.Default; metrics.Add ("Display/NScreens", Gdk.Display.Default.NScreens); metrics.Add ("Screen/Height", screen.Height); metrics.Add ("Screen/Width", screen.Width); metrics.Add ("Screen/IsComposited", screen.IsComposited); metrics.Add ("Screen/NMonitors", screen.NMonitors); } public virtual void Run () { RunIdle (delegate { OnStarted (); return false; }); Log.Debug ("Starting GTK main loop"); Gtk.Application.Run (); } protected virtual void OnRegisterServices () { } private void OnServiceStarted (ServiceStartedArgs args) { if (args.Service is BansheeDbConnection) { ServiceManager.ServiceStarted -= OnServiceStarted; BansheeDbFormatMigrator migrator = ((BansheeDbConnection)args.Service).Migrator; if (migrator != null) { migrator.Started += OnMigratorStarted; migrator.Finished += OnMigratorFinished; } } } private void OnMigratorStarted (object o, EventArgs args) { BansheeDbFormatMigrator migrator = (BansheeDbFormatMigrator)o; new BansheeDbFormatMigratorMonitor (migrator); } private void OnMigratorFinished (object o, EventArgs args) { BansheeDbFormatMigrator migrator = (BansheeDbFormatMigrator)o; migrator.Started -= OnMigratorStarted; migrator.Finished -= OnMigratorFinished; } private void OnLogNotify (LogNotifyArgs args) { RunIdle (delegate { ShowLogCoreEntry (args.Entry); return false; }); } private void ShowLogCoreEntry (LogEntry entry) { Gtk.Window window = null; Gtk.MessageType mtype; if (ServiceManager.Contains<GtkElementsService> ()) { window = ServiceManager.Get<GtkElementsService> ().PrimaryWindow; } switch (entry.Type) { case LogEntryType.Warning: mtype = Gtk.MessageType.Warning; break; case LogEntryType.Information: mtype = Gtk.MessageType.Info; break; case LogEntryType.Error: default: mtype = Gtk.MessageType.Error; break; } Hyena.Widgets.HigMessageDialog dialog = new Hyena.Widgets.HigMessageDialog ( window, Gtk.DialogFlags.Modal, mtype, Gtk.ButtonsType.Close, entry.Message, entry.Details); dialog.Title = String.Empty; dialog.Run (); dialog.Destroy (); } private bool OnShutdownPrompt () { ConfirmShutdownDialog dialog = new ConfirmShutdownDialog (); try { return dialog.Run () != Gtk.ResponseType.Cancel; } finally { dialog.Destroy (); } } protected uint RunTimeout (uint milliseconds, TimeoutHandler handler) { return GLib.Timeout.Add (milliseconds, delegate { return handler (); }); } protected uint RunIdle (IdleHandler handler) { return GLib.Idle.Add (delegate { return handler (); }); } protected bool IdleTimeoutRemove (uint id) { return GLib.Source.Remove (id); } } }
using System; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Threading; using System.Collections; using System.Collections.Generic; using System.Text; namespace SunnyChen.Common.Servers { /// <summary> /// The base class for concurrency servers. /// </summary> /// <remarks> /// All the SOCKET-based concurrency server implementations should inherit from this ConcurrencyServerBase class. /// Concurrency servers are very suitable for small-scaled server application implementation, however for large /// mission critical server applications it is not recommend use the concurrency servers. For more information about /// concurrency servers and server implementations please refer to POSA volume 2, "Patterns for Concurrency and Network Objects". /// </remarks> /// <example> /// Following code illustrates an implementation of the file server. /// <code> /// public class FileServer : ConcurrencyServerBase /// { /// public FileServer(int _port) /// : base(_port, Assembly.GetExecutingAssembly()) /// { /// /// } /// /// public FileServer(int _port, Assembly _assembly) /// : base(_port, _assembly) /// { /// /// } /// /// public override int Start() /// { /// // Put server starting code here. /// return 0; /// } /// /// public override int Stop() /// { /// // Put server stopping code here. /// return 0; /// } /// /// protected override void WorkerThread(object parameters) /// { /// // Put worker thread processing logic here. /// } /// /// protected override ThreadPriority WorkerThreadPriority /// { /// get { return ThreadPriority.Normal; } /// } /// } /// </code> /// </example> public abstract class ConcurrencyServerBase : IServer, IDisposable { #region Private Fields private bool alreadyDisposed__ = false; private Hashtable serverCommands__ = new Hashtable(); private IList<Socket> connectedClients__ = new List<Socket>(); private IList<Thread> workerThreads__ = new List<Thread>(); private Thread serverThread__; private IPEndPoint endpoint__; private TcpListener listener__; private Assembly commandAssembly__; #endregion #region Constructors /// <summary> /// Initializes the concurrency server by specified TCP connection port and the /// assembly that contains the definition for the server commands. /// </summary> /// <param name="_port">The TCP connection port to which the server listens.</param> /// <param name="_commandAssembly">The assembly that contains the definition for the server commands.</param> public ConcurrencyServerBase(int _port, Assembly _commandAssembly) { //endpoint__ = new IPEndPoint(Dns.GetHostAddresses("localhost")[0], _port); endpoint__ = new IPEndPoint(IPAddress.Any, _port); listener__ = new TcpListener(endpoint__); commandAssembly__ = _commandAssembly; } /// <summary> /// Destructor which disposes the concurrency server. /// </summary> ~ConcurrencyServerBase() { Dispose(true); } #endregion #region Protected Properties /// <summary> /// Gets the registered server commands. /// </summary> protected Hashtable ServerCommands { get { return serverCommands__; } } /// <summary> /// Gets the connected clients. /// </summary> protected IList<Socket> ConnectedClients { get { return connectedClients__; } } /// <summary> /// Gets the worker thread pool. /// </summary> protected IList<Thread> WorkerThreads { get { return workerThreads__; } } /// <summary> /// Gets the running server thread. /// </summary> protected Thread ServerThread { get { return serverThread__; } } /// <summary> /// Gets the server end point /// </summary> protected IPEndPoint ServerEndPoint { get { return endpoint__; } } /// <summary> /// Gets the listener. /// </summary> protected TcpListener ServerListener { get { return listener__; } } /// <summary> /// Gets the assembly that holds the server commands. /// </summary> protected Assembly CommandAssembly { get { return commandAssembly__; } } /// <summary> /// Gets the priority of the worker thread. /// </summary> protected abstract ThreadPriority WorkerThreadPriority { get;} #endregion #region Delegates and Events /// <summary> /// Occurs before the server starts. /// </summary> public event EventHandler BeforeStart; /// <summary> /// Occurs after the server has started. /// </summary> public event EventHandler AfterStart; /// <summary> /// Occurs before the server stops. /// </summary> public event EventHandler BeforeStop; /// <summary> /// Occurs after the server has stopped. /// </summary> public event EventHandler AfterStop; #endregion #region Private Methods /// <summary> /// Register all the server commands existing in the specified assembly. /// </summary> private void RegisterServerCommands() { // Clear the registered command for it // will raise exception if we are going // to register the command more than once. serverCommands__.Clear(); // Finds all the commands in the specified assembly // and registers them in the hashtable. foreach (Type type in commandAssembly__.GetTypes()) { if (type.IsClass && type.GetInterface("SunnyChen.Common.Servers.IServerCommand") != null) { IServerCommand command = (IServerCommand)Activator.CreateInstance(type); serverCommands__.Add(command.CommandIdentifier, command); } } } /// <summary> /// Main server thread. /// </summary> private void ServerThreadProc() { try { ParameterizedThreadStart threadStart = new ParameterizedThreadStart(WorkerThread); listener__.Start(); while (true) { // Accept the client socket Socket clientSocket = listener__.AcceptSocket(); //clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); //clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true); // Registers the connected client socket in the pool connectedClients__.Add(clientSocket); // Starts the worker thread for further processing // and registers the thread in the list Thread thread = new Thread(threadStart); workerThreads__.Add(thread); thread.Priority = this.WorkerThreadPriority; thread.Start(clientSocket); } } catch (Exception ex) { throw ex; } } #endregion #region Protected Methods /// <summary> /// Worker thread to do the further processing on the connection (abstract). /// </summary> /// <param name="parameters">The parameter, always the type of <see cref="System.Sockets.Socket"/>.</param> protected abstract void WorkerThread(object parameters); /// <summary> /// The disposing procedure that stops the running server and releases the resources. /// </summary> /// <param name="isDisposing">true to release both managed and unmanaged resources; false to release only /// unmanaged resources.</param> protected virtual void Dispose(bool isDisposing) { if (alreadyDisposed__) return; if (isDisposing) { this.Stop(); } alreadyDisposed__ = true; } #region Protected Event Handlers /// <summary> /// Called before the server starts. /// </summary> /// <param name="e">The event argument.</param> protected virtual void OnBeforeStart(System.EventArgs e) { if (BeforeStart != null) { this.BeforeStart(this, e); } } /// <summary> /// Called after the server has started. /// </summary> /// <param name="e">The event argument.</param> protected virtual void OnAfterStart(System.EventArgs e) { if (AfterStart != null) { this.AfterStart(this, e); } } /// <summary> /// Called before the server stops. /// </summary> /// <param name="e">The event argument.</param> protected virtual void OnBeforeStop(System.EventArgs e) { if (BeforeStop != null) { this.BeforeStop(this, e); } } /// <summary> /// Called after the server has stopped. /// </summary> /// <param name="e">The event argument.</param> protected virtual void OnAfterStop(System.EventArgs e) { if (AfterStop != null) { this.AfterStop(this, e); } } #endregion #endregion #region Public Static Methods /// <summary> /// Gets the identifier of the command. /// </summary> /// <param name="_commandString">The command string.</param> /// <returns>Identifier of the command.</returns> public static int GetCommandIdentifier(string _commandString) { try { return Convert.ToInt32(_commandString.Split(' ')[0]); } catch { return -1; } } /// <summary> /// Formats a command with the identifier and its parts. /// </summary> /// <param name="_commandIdentifier">Command identifier.</param> /// <param name="_commandParts">Command parts.</param> /// <returns>The formatted command string.</returns> public static string FormatCommand(int _commandIdentifier, params string[] _commandParts) { StringBuilder sb = new StringBuilder(); foreach (string commandPart in _commandParts) { sb.Append(" "); sb.Append(commandPart); } return string.Format("{0}{1}", _commandIdentifier, sb.ToString()); } /// <summary> /// Formats a command with the identifier and its body. /// </summary> /// <param name="_commandIdentifier">Command identifier.</param> /// <param name="_commandString">Command body.</param> /// <returns>The formatted command string.</returns> public static string FormatCommand(int _commandIdentifier, string _commandString) { return string.Format("{0} {1}", _commandIdentifier, _commandString); } #endregion #region IServer Members /// <summary> /// Starts the server thread. /// </summary> /// <returns>Zero if it starts successfully, otherwise, false.</returns> public virtual int Start() { try { this.OnBeforeStart(System.EventArgs.Empty); this.RegisterServerCommands(); serverThread__ = new Thread(ServerThreadProc); serverThread__.Start(); this.OnAfterStart(System.EventArgs.Empty); return 0; } catch (Exception ex) { throw ex; } } /// <summary> /// Pauses the running server thread. /// </summary> /// <returns>Zero if the server has been paused successfully, otherwise, false.</returns> [Obsolete("Do not use the Pause method on the server, it has not been implemented yet.", true)] public virtual int Pause() { serverThread__.Suspend(); return 0; } /// <summary> /// Stops the running server thread. /// </summary> /// <returns>Zero if the server stops normally, otherwise, false.</returns> public virtual int Stop() { try { this.OnBeforeStop(System.EventArgs.Empty); for (int i = 0; i < connectedClients__.Count; i++) { Socket socket = connectedClients__[i]; if (socket != null) { if (socket.Connected) { socket.Shutdown(SocketShutdown.Both); socket.Disconnect(true); } socket.Close(); socket = null; } } for (int i = 0; i < workerThreads__.Count; i++) { Thread workerThread = workerThreads__[i]; if (workerThread != null) { if (workerThread.ThreadState != ThreadState.Aborted && workerThread.ThreadState != ThreadState.AbortRequested && workerThread.ThreadState != ThreadState.Unstarted) { workerThread.Abort(); } workerThread = null; } } if (serverThread__ != null) { serverThread__.Abort(); serverThread__ = null; } connectedClients__.Clear(); workerThreads__.Clear(); listener__.Stop(); this.OnAfterStop(System.EventArgs.Empty); return 0; } catch (Exception ex) { throw ex; } } /// <summary> /// Resumes the running server thread. /// </summary> /// <returns>Zero if the server has been resumed successfully, otherwise, false.</returns> [Obsolete("Do not use the Resume method on the server, it has not been implemented yet.", true)] public virtual int Resume() { serverThread__.Resume(); return 0; } #endregion #region IDisposable Members /// <summary> /// Dispose /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } #endregion } }
// Copyright 2008-2011. This work is licensed under the BSD license, available at // http://www.movesinstitute.org/licenses // // Orignal authors: DMcG, Jason Nelson // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace OpenDis.Enumerations.Radio.Transmitter { /// <summary> /// Enumeration values for RadioSignalEncoding (radio.tx.encoding, Radio signal encoding, /// section 9.1.8 - 9.1.9) /// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was /// obtained from http://discussions.sisostds.org/default.asp?action=10&amp;fd=31 /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Serializable] public struct RadioSignalEncoding { /// <summary> /// Encoding type /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Encoding type")] public enum EncodingTypeValue : uint { /// <summary> /// 8-bit mu-law /// </summary> _8BitMuLaw = 1, /// <summary> /// CVSD per MIL-STD-188-113 /// </summary> CVSDPerMILSTD188113 = 2, /// <summary> /// ADPCM per CCITT G.721 /// </summary> ADPCMPerCCITTG721 = 3, /// <summary> /// 16-bit linear PCM /// </summary> _16BitLinearPCM = 4, /// <summary> /// 8-bit linear PCM /// </summary> _8BitLinearPCM = 5, /// <summary> /// VQ (Vector Quantization) /// </summary> VQVectorQuantization = 6 } /// <summary> /// Encoding class /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Encoding class")] public enum EncodingClassValue : uint { /// <summary> /// Encoded audio /// </summary> EncodedAudio = 0, /// <summary> /// Raw Binary Data /// </summary> RawBinaryData = 1, /// <summary> /// Application-Specific Data /// </summary> ApplicationSpecificData = 2, /// <summary> /// Database index /// </summary> DatabaseIndex = 3 } private RadioSignalEncoding.EncodingTypeValue encodingType; private RadioSignalEncoding.EncodingClassValue encodingClass; /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(RadioSignalEncoding left, RadioSignalEncoding right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(RadioSignalEncoding left, RadioSignalEncoding right) { if (object.ReferenceEquals(left, right)) { return true; } // If parameters are null return false (cast to object to prevent recursive loop!) if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } /// <summary> /// Performs an explicit conversion from <see cref="OpenDis.Enumerations.Radio.Transmitter.RadioSignalEncoding"/> to <see cref="System.UInt16"/>. /// </summary> /// <param name="obj">The <see cref="OpenDis.Enumerations.Radio.Transmitter.RadioSignalEncoding"/> scheme instance.</param> /// <returns>The result of the conversion.</returns> public static explicit operator ushort(RadioSignalEncoding obj) { return obj.ToUInt16(); } /// <summary> /// Performs an explicit conversion from <see cref="System.UInt16"/> to <see cref="OpenDis.Enumerations.Radio.Transmitter.RadioSignalEncoding"/>. /// </summary> /// <param name="value">The ushort value.</param> /// <returns>The result of the conversion.</returns> public static explicit operator RadioSignalEncoding(ushort value) { return RadioSignalEncoding.FromUInt16(value); } /// <summary> /// Creates the <see cref="OpenDis.Enumerations.Radio.Transmitter.RadioSignalEncoding"/> instance from the byte array. /// </summary> /// <param name="array">The array which holds the values for the <see cref="OpenDis.Enumerations.Radio.Transmitter.RadioSignalEncoding"/>.</param> /// <param name="index">The starting position within value.</param> /// <returns>The <see cref="OpenDis.Enumerations.Radio.Transmitter.RadioSignalEncoding"/> instance, represented by a byte array.</returns> /// <exception cref="ArgumentNullException">if the <c>array</c> is null.</exception> /// <exception cref="IndexOutOfRangeException">if the <c>index</c> is lower than 0 or greater or equal than number of elements in array.</exception> public static RadioSignalEncoding FromByteArray(byte[] array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (index < 0 || index > array.Length - 1 || index + 2 > array.Length - 1) { throw new IndexOutOfRangeException(); } return FromUInt16(BitConverter.ToUInt16(array, index)); } /// <summary> /// Creates the <see cref="OpenDis.Enumerations.Radio.Transmitter.RadioSignalEncoding"/> instance from the ushort value. /// </summary> /// <param name="value">The ushort value which represents the <see cref="OpenDis.Enumerations.Radio.Transmitter.RadioSignalEncoding"/> instance.</param> /// <returns>The <see cref="OpenDis.Enumerations.Radio.Transmitter.RadioSignalEncoding"/> instance, represented by the ushort value.</returns> public static RadioSignalEncoding FromUInt16(ushort value) { RadioSignalEncoding ps = new RadioSignalEncoding(); uint mask0 = 0x3fff; byte shift0 = 0; uint newValue0 = value & mask0 >> shift0; ps.EncodingType = (RadioSignalEncoding.EncodingTypeValue)newValue0; uint mask1 = 0xc000; byte shift1 = 14; uint newValue1 = value & mask1 >> shift1; ps.EncodingClass = (RadioSignalEncoding.EncodingClassValue)newValue1; return ps; } /// <summary> /// Gets or sets the encodingtype. /// </summary> /// <value>The encodingtype.</value> public RadioSignalEncoding.EncodingTypeValue EncodingType { get { return this.encodingType; } set { this.encodingType = value; } } /// <summary> /// Gets or sets the encodingclass. /// </summary> /// <value>The encodingclass.</value> public RadioSignalEncoding.EncodingClassValue EncodingClass { get { return this.encodingClass; } set { this.encodingClass = value; } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { if (obj == null) { return false; } if (!(obj is RadioSignalEncoding)) { return false; } return this.Equals((RadioSignalEncoding)obj); } /// <summary> /// Determines whether the specified <see cref="OpenDis.Enumerations.Radio.Transmitter.RadioSignalEncoding"/> instance is equal to this instance. /// </summary> /// <param name="other">The <see cref="OpenDis.Enumerations.Radio.Transmitter.RadioSignalEncoding"/> instance to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="OpenDis.Enumerations.Radio.Transmitter.RadioSignalEncoding"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(RadioSignalEncoding other) { // If parameter is null return false (cast to object to prevent recursive loop!) if ((object)other == null) { return false; } return this.EncodingType == other.EncodingType && this.EncodingClass == other.EncodingClass; } /// <summary> /// Converts the instance of <see cref="OpenDis.Enumerations.Radio.Transmitter.RadioSignalEncoding"/> to the byte array. /// </summary> /// <returns>The byte array representing the current <see cref="OpenDis.Enumerations.Radio.Transmitter.RadioSignalEncoding"/> instance.</returns> public byte[] ToByteArray() { return BitConverter.GetBytes(this.ToUInt16()); } /// <summary> /// Converts the instance of <see cref="OpenDis.Enumerations.Radio.Transmitter.RadioSignalEncoding"/> to the ushort value. /// </summary> /// <returns>The ushort value representing the current <see cref="OpenDis.Enumerations.Radio.Transmitter.RadioSignalEncoding"/> instance.</returns> public ushort ToUInt16() { ushort val = 0; val |= (ushort)((uint)this.EncodingType << 0); val |= (ushort)((uint)this.EncodingClass << 14); return val; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { int hash = 17; // Overflow is fine, just wrap unchecked { hash = (hash * 29) + this.EncodingType.GetHashCode(); hash = (hash * 29) + this.EncodingClass.GetHashCode(); } return hash; } } }
// Copyright 2006 - Morten Nielsen (www.iter.dk) // // This file is part of SharpMap. // SharpMap 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 2 of the License, or // (at your option) any later version. // // SharpMap 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 SharpMap; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using System.Drawing; using System.Drawing.Drawing2D; namespace SharpMap.Rendering.Thematics { /// <summary> /// Defines arrays of colors and positions used for interpolating color blending in a multicolor gradient. /// </summary> /// <seealso cref="SharpMap.Rendering.Thematics.GradientTheme"/> [Serializable] public class ColorBlend { private Color[] _colors; private float[] _positions; private float _maximum = float.NaN; private float _minimum = float.NaN; internal ColorBlend() { } /// <summary> /// Initializes a new instance of the ColorBlend class. /// </summary> /// <param name="colors">An array of Color structures that represents the colors to use at corresponding positions along a gradient.</param> /// <param name="positions">An array of values that specify percentages of distance along the gradient line.</param> public ColorBlend(Color[] colors, float[] positions) { _colors = colors; Positions = positions; } /// <summary> /// Gets or sets an array of colors that represents the colors to use at corresponding positions along a gradient. /// </summary> /// <value>An array of <see cref="System.Drawing.Color"/> structures that represents the colors to use at corresponding positions along a gradient.</value> /// <remarks> /// This property is an array of <see cref="System.Drawing.Color"/> structures that represents the colors to use at corresponding positions /// along a gradient. Along with the Positions property, this property defines a multicolor gradient. /// </remarks> public Color[] Colors { get { return _colors; } set { _colors = value; } } /// <summary> /// Gets or sets the positions along a gradient line. /// </summary> /// <value>An array of values that specify percentages of distance along the gradient line.</value> /// <remarks> /// <para>The elements of this array specify percentages of distance along the gradient line. /// For example, an element value of 0.2f specifies that this point is 20 percent of the total /// distance from the starting point. The elements in this array are represented by float /// values between 0.0f and 1.0f, and the first element of the array must be 0.0f and the /// last element must be 1.0f.</para> /// <pre>Along with the Colors property, this property defines a multicolor gradient.</pre> /// </remarks> public float[] Positions { get { return _positions; } set { _positions = value; if ( value == null ) _minimum = _maximum = float.NaN; else { _minimum = value[0]; _maximum = value[value.GetUpperBound(0)]; } } } /// <summary> /// Gets the color from the scale at position 'pos'. /// </summary> /// <remarks>If the position is outside the scale [0..1] only the fractional part /// is used (in other words the scale restarts for each integer-part).</remarks> /// <param name="pos">Position on scale between 0.0f and 1.0f</param> /// <returns>Color on scale</returns> public Color GetColor(float pos) { if (float.IsNaN(_minimum)) throw (new ArgumentException("Positions not set")); if (_colors.Length != _positions.Length) throw (new ArgumentException("Colors and Positions arrays must be of equal length")); if (_colors.Length < 2) throw (new ArgumentException("At least two colors must be defined in the ColorBlend")); /* if (_Positions[0] != 0f) throw (new ArgumentException("First position value must be 0.0f")); if (_Positions[_Positions.Length - 1] != 1f) throw (new ArgumentException("Last position value must be 1.0f")); if (pos > 1 || pos < 0) pos -= (float) Math.Floor(pos); */ int i = 1; while (i < _positions.Length && _positions[i] < pos) i++; float frac = (pos - _positions[i - 1])/(_positions[i] - _positions[i - 1]); frac = Math.Max(frac, 0.0f); frac = Math.Min(frac, 1.0f); int R = (int) Math.Round((_colors[i - 1].R*(1 - frac) + _colors[i].R*frac)); int G = (int) Math.Round((_colors[i - 1].G*(1 - frac) + _colors[i].G*frac)); int B = (int) Math.Round((_colors[i - 1].B*(1 - frac) + _colors[i].B*frac)); int A = (int) Math.Round((_colors[i - 1].A*(1 - frac) + _colors[i].A*frac)); return Color.FromArgb(A, R, G, B); } /// <summary> /// Converts the color blend to a gradient brush /// </summary> /// <param name="rectangle"></param> /// <param name="angle"></param> /// <returns></returns> public LinearGradientBrush ToBrush(Rectangle rectangle, float angle) { LinearGradientBrush br = new LinearGradientBrush(rectangle, Color.Black, Color.Black, angle, true); System.Drawing.Drawing2D.ColorBlend cb = new System.Drawing.Drawing2D.ColorBlend(); cb.Colors = _colors; //scale and translate positions to range[0.0, 1.0] float[] positions = new float[_positions.Length]; float range = _maximum - _minimum; for (int i = 0; i < _positions.Length; i++) positions[i] = (_positions[i] - _minimum) / range; cb.Positions = positions; br.InterpolationColors = cb; return br; } #region Predefined color scales /// <summary> /// Gets a linear gradient scale with nine colours making a RAINBOW like used in MOHID. /// </summary> /// <remarks> /// Colors pass from Dark Blue over Green , Yellow to Dark Red /// </remarks> public static ColorBlend RainbowMOHID { get { return new ColorBlend( new Color[] {Color.FromArgb(0,0,127), Color.FromArgb(0,0,255), Color.FromArgb(0,255,255), Color.FromArgb(0,255,0), Color.FromArgb(127,255,0), Color.FromArgb(255,255,0), Color.FromArgb(255,127,0), Color.FromArgb(255,0,0), Color.FromArgb(127,0,0)}, new float[] { 0f, 0.125f, 0.25f, 0.375f, 0.5f, 0.625f, 0.75f, 0.875f, 1f }); } } /// <summary> /// Gets a linear gradient scale with nine colours making a INVERSE RAINBOW like used in MOHID. /// </summary> /// <remarks> /// Colors pass from Dark Red, over Yellow and Green to Dark Blue /// </remarks> public static ColorBlend InverseRainbowMOHID { get { return new ColorBlend( new Color[] {Color.FromArgb(127,0,0), Color.FromArgb(255,0,0), Color.FromArgb(255,127,0), Color.FromArgb(255,255,0), Color.FromArgb(127,255,0), Color.FromArgb(0,255,0), Color.FromArgb(0,255,255), Color.FromArgb(0,0,255), Color.FromArgb(0,0,127)}, new float[] { 0f, 0.125f, 0.25f, 0.375f, 0.5f, 0.625f, 0.75f, 0.875f, 1f }); } } /// <summary> /// Gets a linear gradient scale with nine colours making a DTM like used in MOHID. /// </summary> /// <remarks> /// Colors pass from Dark Blue over Green , Yellow to Dark Red /// </remarks> public static ColorBlend DigitalTerrainModelMOHID { get { return new ColorBlend( new Color[] {Color.FromArgb(16, 56, 0), Color.FromArgb(38, 127, 0), Color.FromArgb(58, 193, 0), Color.FromArgb(255, 247, 176), Color.FromArgb(244, 170, 81), Color.FromArgb(239, 139, 2), Color.FromArgb(205, 112, 9), Color.FromArgb(148, 82, 17), Color.FromArgb(99, 66, 3)}, new float[] { 0f, 0.125f, 0.25f, 0.375f, 0.5f, 0.625f, 0.75f, 0.875f, 1f }); } } /// <summary> /// Gets a linear gradient scale with six colours making a Bathymetry like used in MOHID. /// </summary> /// <remarks> /// Colors pass from Dark Blue over Green , Yellow to Dark Red /// </remarks> public static ColorBlend BathymetryMOHID { get { return new ColorBlend( new Color[] {Color.FromArgb(254, 255, 255), Color.FromArgb(223, 241, 251), Color.FromArgb(187, 228, 246), Color.FromArgb(133,208, 239), Color.FromArgb(63,189, 237), Color.FromArgb(87, 153, 203)}, new float[] { 0f, 0.2f, 0.4f, 0.6f, 0.8f, 1.0f }); } } /// <summary> /// Gets a linear gradient scale with seven colours making a rainbow from red to violet. /// </summary> /// <remarks> /// Colors span the following with an interval of 1/6: /// { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Violet } /// </remarks> public static ColorBlend Rainbow7 { get { return new ColorBlend( new[] { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Violet }, new[] { 0f, 0.1667f, 0.3333f, 0.5f, 0.6667f, 0.8333f, 1 }); } } /// <summary> /// Gets a linear gradient scale with five colours making a rainbow from red to blue. /// </summary> /// <remarks> /// Colors span the following with an interval of 0.25: /// { Color.Red, Color.Yellow, Color.Green, Color.Cyan, Color.Blue } /// </remarks> public static ColorBlend Rainbow5 { get { return new ColorBlend( new[] {Color.Red, Color.Yellow, Color.Green, Color.Cyan, Color.Blue}, new[] {0f, 0.25f, 0.5f, 0.75f, 1f}); } } /// <summary> /// Gets a linear gradient scale from black to white /// </summary> public static ColorBlend BlackToWhite { get { return new ColorBlend(new[] {Color.Black, Color.White}, new[] {0f, 1f}); } } /// <summary> /// Gets a linear gradient scale from white to black /// </summary> public static ColorBlend WhiteToBlack { get { return new ColorBlend(new[] {Color.White, Color.Black}, new[] {0f, 1f}); } } /// <summary> /// Gets a linear gradient scale from red to green /// </summary> public static ColorBlend RedToGreen { get { return new ColorBlend(new[] {Color.Red, Color.Green}, new[] {0f, 1f}); } } /// <summary> /// Gets a linear gradient scale from green to red /// </summary> public static ColorBlend GreenToRed { get { return new ColorBlend(new[] {Color.Green, Color.Red}, new[] {0f, 1f}); } } /// <summary> /// Gets a linear gradient scale from blue to green /// </summary> public static ColorBlend BlueToGreen { get { return new ColorBlend(new[] {Color.Blue, Color.Green}, new[] {0f, 1f}); } } /// <summary> /// Gets a linear gradient scale from green to blue /// </summary> public static ColorBlend GreenToBlue { get { return new ColorBlend(new[] {Color.Green, Color.Blue}, new[] {0f, 1f}); } } /// <summary> /// Gets a linear gradient scale from red to blue /// </summary> public static ColorBlend RedToBlue { get { return new ColorBlend(new[] {Color.Red, Color.Blue}, new[] {0f, 1f}); } } /// <summary> /// Gets a linear gradient scale from blue to red /// </summary> public static ColorBlend BlueToRed { get { return new ColorBlend(new[] {Color.Blue, Color.Red}, new[] {0f, 1f}); } } #endregion #region Constructor helpers /// <summary> /// Creates a linear gradient scale from two colors /// </summary> /// <param name="fromColor"></param> /// <param name="toColor"></param> /// <returns></returns> public static ColorBlend TwoColors(Color fromColor, Color toColor) { return new ColorBlend(new[] {fromColor, toColor}, new[] {0f, 1f}); } /// <summary> /// Creates a linear gradient scale from three colors /// </summary> public static ColorBlend ThreeColors(Color fromColor, Color middleColor, Color toColor) { return new ColorBlend(new[] {fromColor, middleColor, toColor}, new[] {0f, 0.5f, 1f}); } #endregion } }
// ------------------------------------------------------------------------------------ // 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 Amqp; using Amqp.Types; #if !(NETMF || COMPACT_FRAMEWORK) using Microsoft.VisualStudio.TestTools.UnitTesting; #endif namespace Test.Amqp { #if !(NETMF || COMPACT_FRAMEWORK) [TestClass] #endif public class UtilityTests { #if !(NETMF || COMPACT_FRAMEWORK) [TestMethod] #endif public void TestMethod_Address() { Address address = new Address("amqps://broker1"); Assert.AreEqual("amqps", address.Scheme); Assert.AreEqual(true, address.UseSsl); Assert.AreEqual(null, address.User); Assert.AreEqual(null, address.Password); Assert.AreEqual("broker1", address.Host); Assert.AreEqual(5671, address.Port); Assert.AreEqual("/", address.Path); address = new Address("amqp://broker1:12345"); Assert.AreEqual("amqp", address.Scheme); Assert.AreEqual(false, address.UseSsl); Assert.AreEqual(null, address.User); Assert.AreEqual(null, address.Password); Assert.AreEqual("broker1", address.Host); Assert.AreEqual(12345, address.Port); Assert.AreEqual("/", address.Path); address = new Address("amqp://guest:@broker1"); Assert.AreEqual("amqp", address.Scheme); Assert.AreEqual(false, address.UseSsl); Assert.AreEqual("guest", address.User); Assert.AreEqual(string.Empty, address.Password); Assert.AreEqual("broker1", address.Host); Assert.AreEqual(5672, address.Port); Assert.AreEqual("/", address.Path); address = new Address("amqp://:abc@broker1"); Assert.AreEqual("amqp", address.Scheme); Assert.AreEqual(false, address.UseSsl); Assert.AreEqual(string.Empty, address.User); Assert.AreEqual("abc", address.Password); Assert.AreEqual("broker1", address.Host); Assert.AreEqual(5672, address.Port); Assert.AreEqual("/", address.Path); address = new Address("amqps://:@broker1"); Assert.AreEqual("amqps", address.Scheme); Assert.AreEqual(true, address.UseSsl); Assert.AreEqual(string.Empty, address.User); Assert.AreEqual(string.Empty, address.Password); Assert.AreEqual("broker1", address.Host); Assert.AreEqual(5671, address.Port); Assert.AreEqual("/", address.Path); address = new Address("amqps://guest:pass1@broker1"); Assert.AreEqual("amqps", address.Scheme); Assert.AreEqual(true, address.UseSsl); Assert.AreEqual("guest", address.User); Assert.AreEqual("pass1", address.Password); Assert.AreEqual("broker1", address.Host); Assert.AreEqual(5671, address.Port); Assert.AreEqual("/", address.Path); address = new Address("amqp://me:secret@my.contoso.com:1234/foo/bar"); Assert.AreEqual("amqp", address.Scheme); Assert.AreEqual(false, address.UseSsl); Assert.AreEqual("me", address.User); Assert.AreEqual("secret", address.Password); Assert.AreEqual("my.contoso.com", address.Host); Assert.AreEqual(1234, address.Port); Assert.AreEqual("/foo/bar", address.Path); address = new Address("amqp://broker1/foo"); Assert.AreEqual("amqp", address.Scheme); Assert.AreEqual(false, address.UseSsl); Assert.AreEqual(null, address.User); Assert.AreEqual(null, address.Password); Assert.AreEqual("broker1", address.Host); Assert.AreEqual(5672, address.Port); Assert.AreEqual("/foo", address.Path); address = new Address("amqps://broker1:5555/foo"); Assert.AreEqual("amqps", address.Scheme); Assert.AreEqual(true, address.UseSsl); Assert.AreEqual(null, address.User); Assert.AreEqual(null, address.Password); Assert.AreEqual("broker1", address.Host); Assert.AreEqual(5555, address.Port); Assert.AreEqual("/foo", address.Path); address = new Address("amqps://me:@broker1/foo"); Assert.AreEqual("amqps", address.Scheme); Assert.AreEqual(true, address.UseSsl); Assert.AreEqual("me", address.User); Assert.AreEqual(string.Empty, address.Password); Assert.AreEqual("broker1", address.Host); Assert.AreEqual(5671, address.Port); Assert.AreEqual("/foo", address.Path); address = new Address("amqps://m%2fe%2f:s%21e%25c%26r%2ae%2bt%2f@my.contoso.com:1234/foo/bar"); Assert.AreEqual("amqps", address.Scheme); Assert.AreEqual(true, address.UseSsl); Assert.AreEqual("m/e/", address.User); Assert.AreEqual("s!e%c&r*e+t/", address.Password); Assert.AreEqual("my.contoso.com", address.Host); Assert.AreEqual(1234, address.Port); Assert.AreEqual("/foo/bar", address.Path); address = new Address("myhost", 1234, "myuser/", "secret/", "/foo/bar", "amqps"); Assert.AreEqual("amqps", address.Scheme); Assert.AreEqual(true, address.UseSsl); Assert.AreEqual("myuser/", address.User); Assert.AreEqual("secret/", address.Password); Assert.AreEqual("myhost", address.Host); Assert.AreEqual(1234, address.Port); Assert.AreEqual("/foo/bar", address.Path); } #if !(NETMF || COMPACT_FRAMEWORK) [TestMethod] #endif public void TestMethod_AmqpBitConverter() { ByteBuffer buffer = new ByteBuffer(128, true); AmqpBitConverter.WriteByte(buffer, 0x22); AmqpBitConverter.WriteByte(buffer, -0x22); AmqpBitConverter.WriteUByte(buffer, 0x22); AmqpBitConverter.WriteUByte(buffer, 0xB2); AmqpBitConverter.WriteShort(buffer, 0x22B7); AmqpBitConverter.WriteShort(buffer, -0x22B7); AmqpBitConverter.WriteUShort(buffer, 0x22B7); AmqpBitConverter.WriteUShort(buffer, 0xC2B7); AmqpBitConverter.WriteInt(buffer, 0x340da287); AmqpBitConverter.WriteInt(buffer, -0x340da287); AmqpBitConverter.WriteUInt(buffer, 0x340da287); AmqpBitConverter.WriteUInt(buffer, 0xF40da287); AmqpBitConverter.WriteLong(buffer, 0x5d00BB9A340da287); AmqpBitConverter.WriteLong(buffer, -0x5d00BB9A340da287); AmqpBitConverter.WriteULong(buffer, 0x5d00BB9A340da287); AmqpBitConverter.WriteULong(buffer, 0xad00BB9A340da287); AmqpBitConverter.WriteFloat(buffer, 12344.4434F); AmqpBitConverter.WriteFloat(buffer, -12344.4434F); AmqpBitConverter.WriteDouble(buffer, 39432123244.44352334); AmqpBitConverter.WriteDouble(buffer, -39432123244.44352334); Guid uuid = Guid.NewGuid(); AmqpBitConverter.WriteUuid(buffer, uuid); sbyte b = AmqpBitConverter.ReadByte(buffer); sbyte b2 = AmqpBitConverter.ReadByte(buffer); byte ub = AmqpBitConverter.ReadUByte(buffer); byte ub2 = AmqpBitConverter.ReadUByte(buffer); short s = AmqpBitConverter.ReadShort(buffer); short s2 = AmqpBitConverter.ReadShort(buffer); ushort us = AmqpBitConverter.ReadUShort(buffer); ushort us2 = AmqpBitConverter.ReadUShort(buffer); int i = AmqpBitConverter.ReadInt(buffer); int i2 = AmqpBitConverter.ReadInt(buffer); uint ui = AmqpBitConverter.ReadUInt(buffer); uint ui2 = AmqpBitConverter.ReadUInt(buffer); long l = AmqpBitConverter.ReadLong(buffer); long l2 = AmqpBitConverter.ReadLong(buffer); ulong ul = AmqpBitConverter.ReadULong(buffer); ulong ul2 = AmqpBitConverter.ReadULong(buffer); float f = AmqpBitConverter.ReadFloat(buffer); float f2 = AmqpBitConverter.ReadFloat(buffer); double d = AmqpBitConverter.ReadDouble(buffer); double d2 = AmqpBitConverter.ReadDouble(buffer); Guid uuid2 = AmqpBitConverter.ReadUuid(buffer); } #if !(NETMF || COMPACT_FRAMEWORK) [TestMethod] #endif public void TestMethod_EncoderTest() { byte[] payload = new byte[] { 0x40, 0x56, 0x01, 0x56, 0x00, 0x41, 0x42, 0x50, 0x12, 0x50, 0xab, 0x60, 0x12, 0xab, 0x60, 0xab, 0x12, 0x70, 0x12, 0xab, 0xcd, 0x89, 0x70, 0xab, 0x12, 0x89, 0xcd, 0x52, 0x12, 0x52, 0xab, 0x43, 0x80, 0x12, 0xab, 0xcd, 0x89, 0x12, 0xab, 0xcd, 0x89, 0x80, 0xab, 0x12, 0x89, 0xcd, 0xab, 0x12, 0x89, 0xcd, 0x53, 0x12, 0x53, 0xab, 0x44, 0x51, 0x12, 0x51, 0xab, 0x61, 0x12, 0xab, 0x61, 0xab, 0x12, 0x71, 0x12, 0xab, 0xcd, 0x89, 0x71, 0xab, 0x12, 0x89, 0xcd, 0x54, 0x12, 0x54, 0xab, 0x81, 0x12, 0xab, 0xcd, 0x89, 0x12, 0xab, 0xcd, 0x89, 0x81, 0xab, 0x12, 0x89, 0xcd, 0xab, 0x12, 0x89, 0xcd, 0x55, 0x12, 0x55, 0xab, 0x72, 0x12, 0xab, 0xcd, 0x89, 0x72, 0xab, 0x12, 0x89, 0xcd, 0x82, 0x12, 0xab, 0xcd, 0x89, 0x12, 0xab, 0xcd, 0x89, 0x82, 0xab, 0x12, 0x89, 0xcd, 0xab, 0x12, 0x89, 0xcd, 0x73, 0x00, 0x00, 0x00, 0x51, 0x83, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xe8, 0x83, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x18, 0x98, 0x57, 0xad, 0x04, 0xe0, 0x99, 0x94, 0x4a, 0x2d, 0xac, 0xd6, 0x64, 0x61, 0xa5, 0x19, 0xcd, 0xb9 }; #if NETMF DateTime dt1 = new DateTime(116444736000000000 + 10000000, DateTimeKind.Utc); // 1970, 1, 1, 0, 0, 1; DateTime dt2 = new DateTime(116444736000000000 - 10000000, DateTimeKind.Utc); // 1969, 12, 31, 23, 59, 59; #else DateTime dt1 = new DateTime(1970, 1, 1, 0, 0, 1, DateTimeKind.Utc); DateTime dt2 = new DateTime(1969, 12, 31, 23, 59, 59, DateTimeKind.Utc); #endif #if COMPACT_FRAMEWORK Guid uuid = new Guid(0x57ad04e0, unchecked((short)0x9994), 0x4a2d, 0xac, 0xd6, 0x64, 0x61, 0xa5, 0x19, 0xcd, 0xb9); #else Guid uuid = new Guid(0x57ad04e0, 0x9994, 0x4a2d, 0xac, 0xd6, 0x64, 0x61, 0xa5, 0x19, 0xcd, 0xb9); #endif ByteBuffer buffer = new ByteBuffer(payload.Length, false); Encoder.WriteObject(buffer, null); Encoder.WriteBoolean(buffer, true, false); Encoder.WriteBoolean(buffer, false, false); Encoder.WriteBoolean(buffer, true, true); Encoder.WriteBoolean(buffer, false, true); Encoder.WriteUByte(buffer, 0x12); Encoder.WriteUByte(buffer, 0xab); Encoder.WriteUShort(buffer, 0x12ab); Encoder.WriteUShort(buffer, 0xab12); Encoder.WriteUInt(buffer, (uint)0x12abcd89, false); Encoder.WriteUInt(buffer, (uint)0xab1289cd, false); Encoder.WriteUInt(buffer, (uint)0x12, true); Encoder.WriteUInt(buffer, (uint)0xab, true); Encoder.WriteUInt(buffer, (uint)0, true); Encoder.WriteULong(buffer, (ulong)0x12abcd8912abcd89, false); Encoder.WriteULong(buffer, (ulong)0xab1289cdab1289cd, false); Encoder.WriteULong(buffer, (ulong)0x12, true); Encoder.WriteULong(buffer, (ulong)0xab, true); Encoder.WriteULong(buffer, (ulong)0, true); Encoder.WriteByte(buffer, 0x12); Encoder.WriteByte(buffer, unchecked((sbyte)0xab)); Encoder.WriteShort(buffer, 0x12ab); Encoder.WriteShort(buffer, unchecked((short)0xab12)); Encoder.WriteInt(buffer, 0x12abcd89, false); Encoder.WriteInt(buffer, unchecked((int)0xab1289cd), false); Encoder.WriteInt(buffer, 0x12, true); Encoder.WriteInt(buffer, unchecked((sbyte)0xab), true); Encoder.WriteLong(buffer, 0x12abcd8912abcd89, false); Encoder.WriteLong(buffer, unchecked((long)0xab1289cdab1289cd), false); Encoder.WriteLong(buffer, 0x12, true); Encoder.WriteLong(buffer, unchecked((sbyte)0xab), true); Encoder.WriteFloat(buffer, 1.08422855E-27F); Encoder.WriteFloat(buffer, -5.20608567E-13F); Encoder.WriteDouble(buffer, 9.8451612575257768E-219); Encoder.WriteDouble(buffer, -3.3107870105667015E-101); Encoder.WriteChar(buffer, 'Q'); Encoder.WriteTimestamp(buffer, dt1); Encoder.WriteTimestamp(buffer, dt2); Encoder.WriteUuid(buffer, uuid); Fx.Assert(payload.Length == buffer.Length, "size not equal"); for (int i = 0; i < payload.Length; i++) { Fx.Assert(payload[i] == buffer.Buffer[i], Fx.Format("the {0} byte is different: {1} <-> {2}", i, payload[i], buffer.Buffer[i])); } Fx.Assert(Encoder.ReadObject(buffer) == null, "null"); Fx.Assert(Encoder.ReadObject(buffer).Equals(true), "true"); Fx.Assert(Encoder.ReadObject(buffer).Equals(false), "false"); Fx.Assert(Encoder.ReadObject(buffer).Equals(true), "true"); Fx.Assert(Encoder.ReadObject(buffer).Equals(false), "false"); Fx.Assert(Encoder.ReadObject(buffer).Equals((byte)0x12), "byte1"); Fx.Assert(Encoder.ReadObject(buffer).Equals((byte)0xab), "byte2"); Fx.Assert(Encoder.ReadObject(buffer).Equals((ushort)0x12ab), "ushort1"); Fx.Assert(Encoder.ReadObject(buffer).Equals((ushort)0xab12), "ushort2"); Fx.Assert(Encoder.ReadObject(buffer).Equals((uint)0x12abcd89), "uint1"); Fx.Assert(Encoder.ReadObject(buffer).Equals((uint)0xab1289cd), "uint2"); Fx.Assert(Encoder.ReadObject(buffer).Equals((uint)0x12), "uint3"); Fx.Assert(Encoder.ReadObject(buffer).Equals((uint)0xab), "uint4"); Fx.Assert(Encoder.ReadObject(buffer).Equals((uint)0), "uint0"); Fx.Assert(Encoder.ReadObject(buffer).Equals((ulong)0x12abcd8912abcd89), "ulong1"); Fx.Assert(Encoder.ReadObject(buffer).Equals((ulong)0xab1289cdab1289cd), "ulong2"); Fx.Assert(Encoder.ReadObject(buffer).Equals((ulong)0x12), "ulong3"); Fx.Assert(Encoder.ReadObject(buffer).Equals((ulong)0xab), "ulong4"); Fx.Assert(Encoder.ReadObject(buffer).Equals((ulong)0), "ulong0"); Fx.Assert(Encoder.ReadObject(buffer).Equals((sbyte)0x12), "sbyte1"); Fx.Assert(Encoder.ReadObject(buffer).Equals(unchecked((sbyte)0xab)), "sbyte2"); Fx.Assert(Encoder.ReadObject(buffer).Equals((short)0x12ab), "short1"); Fx.Assert(Encoder.ReadObject(buffer).Equals(unchecked((short)0xab12)), "short2"); Fx.Assert(Encoder.ReadObject(buffer).Equals((int)0x12abcd89), "int1"); Fx.Assert(Encoder.ReadObject(buffer).Equals(unchecked((int)0xab1289cd)), "int2"); Fx.Assert(Encoder.ReadObject(buffer).Equals((int)0x12), "int3"); Fx.Assert(Encoder.ReadObject(buffer).Equals((int)unchecked((sbyte)0xab)), "int4"); Fx.Assert(Encoder.ReadObject(buffer).Equals((long)0x12abcd8912abcd89), "long1"); Fx.Assert(Encoder.ReadObject(buffer).Equals(unchecked((long)0xab1289cdab1289cd)), "long2"); Fx.Assert(Encoder.ReadObject(buffer).Equals((long)0x12), "long3"); Fx.Assert(Encoder.ReadObject(buffer).Equals((long)unchecked((sbyte)0xab)), "long4"); Fx.Assert(Encoder.ReadObject(buffer).Equals(1.08422855E-27F), "float1"); Fx.Assert(Encoder.ReadObject(buffer).Equals(-5.20608567E-13F), "flaot2"); Fx.Assert(Encoder.ReadObject(buffer).Equals(9.8451612575257768E-219), "double1"); Fx.Assert(Encoder.ReadObject(buffer).Equals(-3.3107870105667015E-101), "double2"); Fx.Assert(Encoder.ReadObject(buffer).Equals('Q'), "char"); Fx.Assert(Encoder.ReadObject(buffer).Equals(dt1), "timestamp1"); Fx.Assert(Encoder.ReadObject(buffer).Equals(dt2), "timestamp2"); Fx.Assert(Encoder.ReadObject(buffer).Equals(uuid), "uuid"); } } }
//#define USE_GENERICS using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans; using Orleans.Runtime; using Orleans.Streams; using UnitTests.GrainInterfaces; using UnitTests.StreamingTests; namespace UnitTests.Grains { [Serializable] public class StreamReliabilityTestGrainState { // For producer and consumer // -- only need to store because of how we run our unit tests against multiple providers public string StreamProviderName { get; set; } // For producer only. #if USE_GENERICS public IAsyncStream<T> Stream { get; set; } #else public IAsyncStream<int> Stream { get; set; } #endif public bool IsProducer { get; set; } // For consumer only. #if USE_GENERICS public HashSet<StreamSubscriptionHandle<T>> ConsumerSubscriptionHandles { get; set; } public StreamReliabilityTestGrainState() { ConsumerSubscriptionHandles = new HashSet<StreamSubscriptionHandle<T>>(); } #else public HashSet<StreamSubscriptionHandle<int>> ConsumerSubscriptionHandles { get; set; } public StreamReliabilityTestGrainState() { ConsumerSubscriptionHandles = new HashSet<StreamSubscriptionHandle<int>>(); } #endif } [Orleans.Providers.StorageProvider(ProviderName = "AzureStore")] #if USE_GENERICS public class StreamReliabilityTestGrain<T> : Grain<IStreamReliabilityTestGrainState>, IStreamReliabilityTestGrain<T> #else public class StreamReliabilityTestGrain : Grain<StreamReliabilityTestGrainState>, IStreamReliabilityTestGrain #endif { [NonSerialized] private ILogger logger; #if USE_GENERICS private IAsyncStream<T> Stream { get; set; } private IAsyncObserver<T> Producer { get; set; } private Dictionary<StreamSubscriptionHandle<T>, MyStreamObserver<T>> Observers { get; set; } #else private IAsyncStream<int> Stream { get { return State.Stream; } } private IAsyncObserver<int> Producer { get; set; } private Dictionary<StreamSubscriptionHandle<int>, MyStreamObserver<int>> Observers { get; set; } #endif private const string StreamNamespace = StreamTestsConstants.StreamReliabilityNamespace; public StreamReliabilityTestGrain(ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}"); } public override async Task OnActivateAsync() { logger.Info(String.Format("OnActivateAsync IsProducer = {0}, IsConsumer = {1}.", State.IsProducer, State.ConsumerSubscriptionHandles != null && State.ConsumerSubscriptionHandles.Count > 0)); if (Observers == null) #if USE_GENERICS Observers = new Dictionary<StreamSubscriptionHandle<T>, MyStreamObserver<T>>(); #else Observers = new Dictionary<StreamSubscriptionHandle<int>, MyStreamObserver<int>>(); #endif if (State.Stream != null && State.StreamProviderName != null) { //TryInitStream(State.Stream, State.StreamProviderName); if (State.ConsumerSubscriptionHandles.Count > 0) { var handles = State.ConsumerSubscriptionHandles.ToArray(); State.ConsumerSubscriptionHandles.Clear(); await ReconnectConsumerHandles(handles); } if (State.IsProducer) { //await BecomeProducer(State.StreamId, State.StreamProviderName); Producer = Stream; State.IsProducer = true; await WriteStateAsync(); } } else { logger.Info("No stream yet."); } } public override Task OnDeactivateAsync() { logger.Info("OnDeactivateAsync"); return base.OnDeactivateAsync(); } public Task<int> GetConsumerCount() { int numConsumers = State.ConsumerSubscriptionHandles.Count; logger.Info("ConsumerCount={0}", numConsumers); return Task.FromResult(numConsumers); } public Task<int> GetReceivedCount() { int numReceived = Observers.Sum(o => o.Value.NumItems); logger.Info("ReceivedCount={0}", numReceived); return Task.FromResult(numReceived); } public Task<int> GetErrorsCount() { int numErrors = Observers.Sum(o => o.Value.NumErrors); logger.Info("ErrorsCount={0}", numErrors); return Task.FromResult(numErrors); } public Task Ping() { logger.Info("Ping"); return Task.CompletedTask; } #if USE_GENERICS public async Task<StreamSubscriptionHandle<T>> AddConsumer(Guid streamId, string providerName) #else public async Task<StreamSubscriptionHandle<int>> AddConsumer(Guid streamId, string providerName) #endif { logger.Info("AddConsumer StreamId={0} StreamProvider={1} Grain={2}", streamId, providerName, this.AsReference<IStreamReliabilityTestGrain>()); TryInitStream(streamId, providerName); #if USE_GENERICS var observer = new MyStreamObserver<T>(); #else var observer = new MyStreamObserver<int>(logger); #endif var subsHandle = await Stream.SubscribeAsync(observer); Observers.Add(subsHandle, observer); State.ConsumerSubscriptionHandles.Add(subsHandle); await WriteStateAsync(); return subsHandle; } #if USE_GENERICS public async Task RemoveConsumer(Guid streamId, string providerName, StreamSubscriptionHandle<T> subsHandle) #else public async Task RemoveConsumer(Guid streamId, string providerName, StreamSubscriptionHandle<int> subsHandle) #endif { logger.Info("RemoveConsumer StreamId={0} StreamProvider={1}", streamId, providerName); if (State.ConsumerSubscriptionHandles.Count == 0) throw new InvalidOperationException("Not a Consumer"); await subsHandle.UnsubscribeAsync(); Observers.Remove(subsHandle); State.ConsumerSubscriptionHandles.Remove(subsHandle); await WriteStateAsync(); } public async Task RemoveAllConsumers() { logger.Info("RemoveAllConsumers: State.ConsumerSubscriptionHandles.Count={0}", State.ConsumerSubscriptionHandles.Count); if (State.ConsumerSubscriptionHandles.Count == 0) throw new InvalidOperationException("Not a Consumer"); var handles = State.ConsumerSubscriptionHandles.ToArray(); foreach (var handle in handles) { await handle.UnsubscribeAsync(); } //Observers.Remove(subsHandle); State.ConsumerSubscriptionHandles.Clear(); await WriteStateAsync(); } public async Task BecomeProducer(Guid streamId, string providerName) { logger.Info("BecomeProducer StreamId={0} StreamProvider={1}", streamId, providerName); TryInitStream(streamId, providerName); Producer = Stream; State.IsProducer = true; await WriteStateAsync(); } public async Task RemoveProducer(Guid streamId, string providerName) { logger.Info("RemoveProducer StreamId={0} StreamProvider={1}", streamId, providerName); if (!State.IsProducer) throw new InvalidOperationException("Not a Producer"); Producer = null; State.IsProducer = false; await WriteStateAsync(); } public async Task ClearGrain() { logger.Info("ClearGrain."); State.ConsumerSubscriptionHandles.Clear(); State.IsProducer = false; Observers.Clear(); State.Stream = null; await ClearStateAsync(); } public Task<bool> IsConsumer() { bool isConsumer = State.ConsumerSubscriptionHandles.Count > 0; logger.Info("IsConsumer={0}", isConsumer); return Task.FromResult(isConsumer); } public Task<bool> IsProducer() { bool isProducer = State.IsProducer; logger.Info("IsProducer={0}", isProducer); return Task.FromResult(isProducer); } public Task<int> GetConsumerHandlesCount() { return Task.FromResult(State.ConsumerSubscriptionHandles.Count); } public async Task<int> GetConsumerObserversCount() { #if USE_GENERICS var consumer = (StreamConsumer<T>)Stream; #else var consumer = (StreamConsumer<int>)Stream; #endif return await consumer.DiagGetConsumerObserversCount(); } #if USE_GENERICS public async Task SendItem(T item) #else public async Task SendItem(int item) #endif { logger.Info("SendItem Item={0}", item); await Producer.OnNextAsync(item); } public Task<SiloAddress> GetLocation() { SiloAddress siloAddress = Data.Address.Silo; logger.Info("GetLocation SiloAddress={0}", siloAddress); return Task.FromResult(siloAddress); } private void TryInitStream(Guid streamId, string providerName) { if (providerName == null) throw new ArgumentNullException(nameof(providerName)); State.StreamProviderName = providerName; if (State.Stream == null) { logger.Info("InitStream StreamId={0} StreamProvider={1}", streamId, providerName); IStreamProvider streamProvider = GetStreamProvider(providerName); #if USE_GENERICS State.Stream = streamProvider.GetStream<T>(streamId); #else State.Stream = streamProvider.GetStream<int>(streamId, StreamNamespace); #endif } } #if USE_GENERICS private async Task ReconnectConsumerHandles(StreamSubscriptionHandle<T>[] subscriptionHandles) #else private async Task ReconnectConsumerHandles(StreamSubscriptionHandle<int>[] subscriptionHandles) #endif { logger.Info("ReconnectConsumerHandles SubscriptionHandles={0} Grain={1}", Utils.EnumerableToString(subscriptionHandles), this.AsReference<IStreamReliabilityTestGrain>()); foreach (var subHandle in subscriptionHandles) { #if USE_GENERICS // var stream = GetStreamProvider(State.StreamProviderName).GetStream<T>(subHandle.StreamId); var stream = subHandle.Stream; var observer = new MyStreamObserver<T>(); #else var observer = new MyStreamObserver<int>(logger); #endif var subsHandle = await subHandle.ResumeAsync(observer); Observers.Add(subsHandle, observer); State.ConsumerSubscriptionHandles.Add(subsHandle); } await WriteStateAsync(); } } //[Serializable] //public class MyStreamObserver<T> : IAsyncObserver<T> //{ // internal int NumItems { get; private set; } // internal int NumErrors { get; private set; } // private readonly Logger logger; // internal MyStreamObserver(Logger logger) // { // this.logger = logger; // } // public Task OnNextAsync(T item, StreamSequenceToken token) // { // NumItems++; // if (logger.IsVerbose) // logger.Verbose("Received OnNextAsync - Item={0} - Total Items={1} Errors={2}", item, NumItems, NumErrors); // return Task.CompletedTask; // } // public Task OnCompletedAsync() // { // logger.Info("Receive OnCompletedAsync - Total Items={0} Errors={1}", NumItems, NumErrors); // return Task.CompletedTask; // } // public Task OnErrorAsync(Exception ex) // { // NumErrors++; // logger.Warn(1, "Received OnErrorAsync - Exception={0} - Total Items={1} Errors={2}", ex, NumItems, NumErrors); // return Task.CompletedTask; // } //} [Orleans.Providers.StorageProvider(ProviderName = "AzureStore")] public class StreamUnsubscribeTestGrain : Grain<StreamReliabilityTestGrainState>, IStreamUnsubscribeTestGrain { [NonSerialized] private ILogger logger; private const string StreamNamespace = StreamTestsConstants.StreamReliabilityNamespace; public StreamUnsubscribeTestGrain(ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}"); } public override Task OnActivateAsync() { logger.Info(String.Format("OnActivateAsync IsProducer = {0}, IsConsumer = {1}.", State.IsProducer, State.ConsumerSubscriptionHandles != null && State.ConsumerSubscriptionHandles.Count > 0)); return Task.CompletedTask; } public async Task Subscribe(Guid streamId, string providerName) { logger.Info("Subscribe StreamId={0} StreamProvider={1} Grain={2}", streamId, providerName, this.AsReference<IStreamUnsubscribeTestGrain>()); State.StreamProviderName = providerName; if (State.Stream == null) { logger.Info("InitStream StreamId={0} StreamProvider={1}", streamId, providerName); IStreamProvider streamProvider = GetStreamProvider(providerName); State.Stream = streamProvider.GetStream<int>(streamId, StreamNamespace); } var observer = new MyStreamObserver<int>(logger); var consumer = State.Stream; var subsHandle = await consumer.SubscribeAsync(observer); State.ConsumerSubscriptionHandles.Add(subsHandle); await WriteStateAsync(); } public async Task UnSubscribeFromAllStreams() { logger.Info("UnSubscribeFromAllStreams: State.ConsumerSubscriptionHandles.Count={0}", State.ConsumerSubscriptionHandles.Count); if (State.ConsumerSubscriptionHandles.Count == 0) throw new InvalidOperationException("Not a Consumer"); var handles = State.ConsumerSubscriptionHandles.ToArray(); foreach (var handle in handles) { await handle.UnsubscribeAsync(); } State.ConsumerSubscriptionHandles.Clear(); await WriteStateAsync(); } } }
// 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.Threading; using System.Diagnostics; using System.Collections.Generic; namespace System.Reflection.TypeLoading { internal sealed class GetTypeCoreCache { private volatile Container _container; private readonly object _lock; public GetTypeCoreCache() { _lock = new object(); _container = new Container(this); } public bool TryGet(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, int hashCode, out RoDefinitionType type) { return _container.TryGetValue(ns, name, hashCode, out type); } public RoDefinitionType GetOrAdd(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, int hashCode, RoDefinitionType type) { bool found = _container.TryGetValue(ns, name, hashCode, out RoDefinitionType prior); if (found) return prior; Monitor.Enter(_lock); try { if (_container.TryGetValue(ns, name, hashCode, out RoDefinitionType winner)) return winner; if (!_container.HasCapacity) _container.Resize(); // This overwrites the _container field. _container.Add(hashCode, type); return type; } finally { Monitor.Exit(_lock); } } public static int ComputeHashCode(ReadOnlySpan<byte> name) { int hashCode = 0x38723781; for (int i = 0; i < name.Length; i++) { hashCode = (hashCode << 8) ^ name[i]; } return hashCode; } private sealed class Container { public Container(GetTypeCoreCache owner) { // Note: This could be done by calling Resize()'s logic but we cannot safely do that as this code path is reached // during class construction time and Resize() pulls in enough stuff that we get cyclic cctor warnings from the build. _buckets = new int[_initialCapacity]; for (int i = 0; i < _initialCapacity; i++) _buckets[i] = -1; _entries = new Entry[_initialCapacity]; _nextFreeEntry = 0; _owner = owner; } private Container(GetTypeCoreCache owner, int[] buckets, Entry[] entries, int nextFreeEntry) { _buckets = buckets; _entries = entries; _nextFreeEntry = nextFreeEntry; _owner = owner; } public bool TryGetValue(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, int hashCode, out RoDefinitionType value) { // Lock acquistion NOT required. int bucket = ComputeBucket(hashCode, _buckets.Length); int i = Volatile.Read(ref _buckets[bucket]); while (i != -1) { if (hashCode == _entries[i]._hashCode) { RoDefinitionType actualValue = _entries[i]._value; if (actualValue.IsTypeNameEqual(ns, name)) { value = actualValue; return true; } } i = _entries[i]._next; } value = default; return false; } public void Add(int hashCode, RoDefinitionType value) { int bucket = ComputeBucket(hashCode, _buckets.Length); int newEntryIdx = _nextFreeEntry; _entries[newEntryIdx]._value = value; _entries[newEntryIdx]._hashCode = hashCode; _entries[newEntryIdx]._next = _buckets[bucket]; _nextFreeEntry++; // The line that atomically adds the new key/value pair. If the thread is killed before this line executes but after // we've incremented _nextFreeEntry, this entry is harmlessly leaked until the next resize. Volatile.Write(ref _buckets[bucket], newEntryIdx); VerifyUnifierConsistency(); } public bool HasCapacity => _nextFreeEntry != _entries.Length; public void Resize() { int newSize = HashHelpers.GetPrime(_buckets.Length * 2); #if DEBUG newSize = _buckets.Length + 3; #endif if (newSize <= _nextFreeEntry) throw new OutOfMemoryException(); Entry[] newEntries = new Entry[newSize]; int[] newBuckets = new int[newSize]; for (int i = 0; i < newSize; i++) newBuckets[i] = -1; // Note that we walk the bucket chains rather than iterating over _entries. This is because we allow for the possibility // of abandoned entries (with undefined contents) if a thread is killed between allocating an entry and linking it onto the // bucket chain. int newNextFreeEntry = 0; for (int bucket = 0; bucket < _buckets.Length; bucket++) { for (int entry = _buckets[bucket]; entry != -1; entry = _entries[entry]._next) { newEntries[newNextFreeEntry]._value = _entries[entry]._value; newEntries[newNextFreeEntry]._hashCode = _entries[entry]._hashCode; int newBucket = ComputeBucket(newEntries[newNextFreeEntry]._hashCode, newSize); newEntries[newNextFreeEntry]._next = newBuckets[newBucket]; newBuckets[newBucket] = newNextFreeEntry; newNextFreeEntry++; } } // The assertion is "<=" rather than "==" because we allow an entry to "leak" until the next resize if // a thread died between the time between we allocated the entry and the time we link it into the bucket stack. Debug.Assert(newNextFreeEntry <= _nextFreeEntry); // The line that atomically installs the resize. If this thread is killed before this point, // the table remains full and the next guy attempting an add will have to redo the resize. _owner._container = new Container(_owner, newBuckets, newEntries, newNextFreeEntry); _owner._container.VerifyUnifierConsistency(); } private static int ComputeBucket(int hashCode, int numBuckets) { int bucket = (hashCode & 0x7fffffff) % numBuckets; return bucket; } [Conditional("DEBUG")] public void VerifyUnifierConsistency() { #if DEBUG // There's a point at which this check becomes gluttonous, even by checked build standards... if (_nextFreeEntry >= 5000 && (0 != (_nextFreeEntry % 100))) return; Debug.Assert(_nextFreeEntry >= 0 && _nextFreeEntry <= _entries.Length); int numEntriesEncountered = 0; for (int bucket = 0; bucket < _buckets.Length; bucket++) { int walk1 = _buckets[bucket]; int walk2 = _buckets[bucket]; // walk2 advances two elements at a time - if walk1 ever meets walk2, we've detected a cycle. while (walk1 != -1) { numEntriesEncountered++; Debug.Assert(walk1 >= 0 && walk1 < _nextFreeEntry); Debug.Assert(walk2 >= -1 && walk2 < _nextFreeEntry); int storedBucket = ComputeBucket(_entries[walk1]._hashCode, _buckets.Length); Debug.Assert(storedBucket == bucket); walk1 = _entries[walk1]._next; if (walk2 != -1) walk2 = _entries[walk2]._next; if (walk2 != -1) walk2 = _entries[walk2]._next; if (walk1 == walk2 && walk2 != -1) Debug.Fail("Bucket " + bucket + " has a cycle in its linked list."); } } // The assertion is "<=" rather than "==" because we allow an entry to "leak" until the next resize if // a thread died between the time between we allocated the entry and the time we link it into the bucket stack. Debug.Assert(numEntriesEncountered <= _nextFreeEntry); #endif //DEBUG } private readonly int[] _buckets; private readonly Entry[] _entries; private int _nextFreeEntry; private readonly GetTypeCoreCache _owner; private const int _initialCapacity = 5; private const double _growThreshold = 0.75; } private struct Entry { public RoDefinitionType _value; public int _hashCode; public int _next; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; [System.Serializable] [AddComponentMenu("NGUI/NData/PopupList Binding")] public class NguiPopupListSourceBinding : NguiItemsSourceBinding { /* private UIPopupList _uiPopupList = null; public override void Awake() { base.Awake(); _uiPopupList = GetComponent<UIPopupList>(); if (_uiPopupList != null) { _uiPopupList.onChange.Add(new EventDelegate(OnSelectionChange)); } } protected override void Bind() { base.Bind(); if (_uiPopupList == null) return; OnItemsClear(); if (_collection == null) return; for (var i = 0; i < _collection.ItemsCount; ++i) { _uiPopupList.items.Add(GetItemDisplayValue(i)); } _uiPopupList.value = GetItemDisplayValue(_collection.SelectedIndex); } protected override void OnItemInsert(int position, EZData.Context item) { base.OnItemInsert(position, item); _uiPopupList.items.Insert(position, GetDisplayValueProperty(item).GetValue()); _uiPopupList.value = GetItemDisplayValue(_collection.SelectedIndex); } protected override void OnItemRemove(int position) { if (_collection == null || _uiPopupList == null) return; _displayValuesCache.Remove(_collection.GetBaseItem(position)); base.OnItemRemove(position); _uiPopupList.items.RemoveAt(position); if (_uiPopupList.items.Count == 0) _uiPopupList.value = string.Empty; else _uiPopupList.value = GetItemDisplayValue(_collection.SelectedIndex); } protected override void OnItemsClear() { _displayValuesCache.Clear(); _uiPopupList.items.Clear(); _uiPopupList.value = string.Empty; } private EZData.Property<string> GetDisplayValueProperty(EZData.Context item) { if (item == null) return null; EZData.Property<string> property = null; if (_displayValuesCache.TryGetValue(item, out property)) return property; property = item.FindProperty<string>(DisplayValuePath, this); if (property != null) _displayValuesCache.Add(item, property); return property; } private string GetItemDisplayValue(int index) { if (_collection == null) return string.Empty; var property = GetDisplayValueProperty(_collection.GetBaseItem(index)); if (property == null) return string.Empty; return property.GetValue(); } public void OnSelectionChange() { var selectedItem = _uiPopupList.value; if (_collection != null && !_isCollectionSelecting) { _isCollectionSelecting = true; for (var i = 0; i < _collection.ItemsCount; ++i) { if (GetItemDisplayValue(i) == selectedItem) { _collection.SelectItem(i); break; } } _isCollectionSelecting = false; } } protected override void OnCollectionSelectionChange() { if (_uiPopupList == null || _collection == null) return; var selectedValue = GetItemDisplayValue(_collection.SelectedIndex); _uiPopupList.value = selectedValue; } */ public string DisplayValuePath; private readonly Dictionary<EZData.Context, EZData.Property<string>> _displayValuesCache = new Dictionary<EZData.Context, EZData.Property<string>>(); private UIPopupList _uiPopupList = null; #if NGUI_2 private GameObject _nativeEventReceiver; private string _nativeFunctionName; #endif private void AssignValue(string value) { #if NGUI_2 _uiPopupList.selection = value; #else _uiPopupList.value = value; #endif } public override void Awake() { base.Awake(); _uiPopupList = GetComponent<UIPopupList>(); if (_uiPopupList != null) { #if NGUI_2 _nativeEventReceiver = _uiPopupList.eventReceiver; _nativeFunctionName = _uiPopupList.functionName; _uiPopupList.eventReceiver = gameObject; _uiPopupList.functionName = "OnSelectionChange"; #else _uiPopupList.onChange.Add(new EventDelegate(OnSelectionChange1)); #endif } } protected override void Bind() { base.Bind(); if (_uiPopupList == null) return; OnItemsClear(); if (_collection == null) return; for (var i = 0; i < _collection.ItemsCount; ++i) { _uiPopupList.items.Add(GetItemDisplayValue(i)); } AssignValue(GetItemDisplayValue(_collection.SelectedIndex)); } protected override void OnItemInsert(int position, EZData.Context item) { base.OnItemInsert(position, item); _uiPopupList.items.Insert(position, GetDisplayValueProperty(item).GetValue()); AssignValue(GetItemDisplayValue(_collection.SelectedIndex)); } protected override void OnItemRemove(int position) { if (_collection == null || _uiPopupList == null) return; _displayValuesCache.Remove(_collection.GetBaseItem(position)); base.OnItemRemove(position); _uiPopupList.items.RemoveAt(position); if (_uiPopupList.items.Count == 0) AssignValue(string.Empty); else AssignValue(GetItemDisplayValue(_collection.SelectedIndex)); } protected override void OnItemsClear() { _displayValuesCache.Clear(); _uiPopupList.items.Clear(); AssignValue(string.Empty); } private EZData.Property<string> GetDisplayValueProperty(EZData.Context item) { if (item == null) return null; EZData.Property<string> property = null; if (_displayValuesCache.TryGetValue(item, out property)) return property; property = item.FindProperty<string>(DisplayValuePath, this); if (property != null) _displayValuesCache.Add(item, property); return property; } private string GetItemDisplayValue(int index) { if (_collection == null) return string.Empty; var property = GetDisplayValueProperty(_collection.GetBaseItem(index)); if (property == null) return string.Empty; return property.GetValue(); } #if !NGUI_2 public void OnSelectionChange1() { OnSelectionChange(_uiPopupList.value); } #endif public void OnSelectionChange(string selectedItem) { if (_collection != null && !_isCollectionSelecting) { _isCollectionSelecting = true; for (var i = 0; i < _collection.ItemsCount; ++i) { if (GetItemDisplayValue(i) == selectedItem) { _collection.SelectItem(i); break; } } _isCollectionSelecting = false; } #if NGUI_2 if (_nativeEventReceiver != null) { if (_nativeEventReceiver != gameObject || _nativeFunctionName != "OnSelectionChange") { _nativeEventReceiver.SendMessage(_nativeFunctionName, selectedItem, SendMessageOptions.DontRequireReceiver); } } #endif } protected override void OnCollectionSelectionChange() { if (_uiPopupList == null || _collection == null) return; var selectedValue = GetItemDisplayValue(_collection.SelectedIndex); AssignValue(selectedValue); } }
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * API Version: 2006-03-01 * */ using System; using System.Net; using Amazon.S3.Model; using Amazon.S3.Util; using Amazon.Util; namespace Amazon.S3 { /// <summary> /// Configuration for Amazon S3 Client. /// </summary> public partial class AmazonS3Config { #region Private Members private RegionEndpoint regionEndpoint; private string serviceURL = S3Constants.S3DefaultEndpoint; private string userAgent = Amazon.Util.AWSSDKUtils.SDKUserAgent; private string proxyHost; private int proxyPort = -1; private string proxyUsername; private string proxyPassword; private int maxErrorRetry = 3; private Protocol protocol = Protocol.HTTPS; private bool fUseSecureString = true; private int bufferSize = S3Constants.DefaultBufferSize; private int? connectionLimit; private ICredentials proxyCredentials; #endregion /// <summary> /// Gets and sets the RegionEndpoint property. /// This value is the region constant that /// determines the service endpoint to use. If this value is not set, /// then the client will use the value of ServiceURL. /// </summary> public RegionEndpoint RegionEndpoint { get { return regionEndpoint; } set { this.regionEndpoint = value; } } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> internal string RegionEndpointServiceName { get { return "s3"; } } /// <summary> /// Gets and sets the ServiceURL property. /// This value specifies the endpoint to access with the client. /// ServiceURL is ignored if RegionEndpoint is set. /// This is an optional property; change it /// only if you want to try a different service /// endpoint or want to switch between https and http. /// </summary> public string ServiceURL { get { return this.serviceURL; } set { this.serviceURL = value; } } /// <summary> /// Sets the ServiceURL property /// </summary> /// <param name="serviceURL">ServiceURL property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonS3Config WithServiceURL(string serviceURL) { this.serviceURL = serviceURL; return this; } /// <summary> /// Checks if ServiceURL property is set /// </summary> /// <returns>true if ServiceURL property is set</returns> internal bool IsSetServiceURL() { return !System.String.IsNullOrEmpty(this.serviceURL); } /// <summary> /// Gets and sets the UserAgent property. /// </summary> public string UserAgent { get { return this.userAgent; } set { this.userAgent = value; } } /// <summary> /// Sets the UserAgent property /// </summary> /// <param name="userAgent">UserAgent property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonS3Config WithUserAgent(string userAgent) { this.userAgent = userAgent; return this; } /// <summary> /// Checks if UserAgent property is set /// </summary> /// <returns>true if UserAgent property is set</returns> internal bool IsSetUserAgent() { return !System.String.IsNullOrEmpty(this.userAgent); } /// <summary> /// Gets and sets the ProxyHost property. /// </summary> public string ProxyHost { get { return this.proxyHost; } set { this.proxyHost = value; } } /// <summary> /// Sets the ProxyHost property /// </summary> /// <param name="proxyHost">ProxyHost property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonS3Config WithProxyHost(string proxyHost) { this.proxyHost = proxyHost; return this; } /// <summary> /// Checks if ProxyHost property is set /// </summary> /// <returns>true if ProxyHost property is set</returns> internal bool IsSetProxyHost() { return !System.String.IsNullOrEmpty(this.proxyHost); } /// <summary> /// Gets and sets the ProxyPort property. /// </summary> public int ProxyPort { get { return this.proxyPort; } set { this.proxyPort = value; } } /// <summary> /// Sets the ProxyPort property /// </summary> /// <param name="proxyPort">ProxyPort property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonS3Config WithProxyPort(int proxyPort) { this.proxyPort = proxyPort; return this; } /// <summary> /// Checks if ProxyPort property is set /// </summary> /// <returns>true if ProxyPort property is set</returns> internal bool IsSetProxyPort() { return (ProxyPort > -1 && ProxyPort <= 65535); } /// <summary> /// Gets and sets the ProxyUsername property. /// Used in conjunction with the ProxyPassword /// property to authenticate requests with the /// specified Proxy server. /// </summary> [Obsolete("Use ProxyCredentials instead")] public string ProxyUsername { get { return this.proxyUsername; } set { this.proxyUsername = value; } } /// <summary> /// Sets the ProxyUsername property /// </summary> /// <param name="userName">Value for the ProxyUsername property</param> /// <returns>this instance</returns> [Obsolete("Use WithProxyCredentials instead")] public AmazonS3Config WithProxyUsername(string userName) { this.proxyUsername = userName; return this; } /// <summary> /// Checks if ProxyUsername property is set /// </summary> /// <returns>true if ProxyUsername property is set</returns> internal bool IsSetProxyUsername() { return !System.String.IsNullOrEmpty(this.proxyUsername); } /// <summary> /// Gets and sets the ProxyPassword property. /// Used in conjunction with the ProxyUsername /// property to authenticate requests with the /// specified Proxy server. /// </summary> /// <remarks> /// If this property isn't set, String.Empty is used as /// the proxy password. This property isn't /// used if ProxyUsername is null or empty. /// </remarks> [Obsolete("Use ProxyCredentials instead")] public string ProxyPassword { get { return this.proxyPassword; } set { this.proxyPassword = value; } } /// <summary> /// Sets the ProxyPassword property. /// Used in conjunction with the ProxyUsername /// property to authenticate requests with the /// specified Proxy server. /// </summary> /// <remarks> /// If this property isn't set, String.Empty is used as /// the proxy password. This property isn't /// used if ProxyUsername is null or empty. /// </remarks> /// <param name="password">ProxyPassword property</param> /// <returns>this instance</returns> [Obsolete("Use WithProxyCredentials instead")] public AmazonS3Config WithProxyPassword(string password) { this.proxyPassword = password; return this; } /// <summary> /// Checks if ProxyPassword property is set /// </summary> /// <returns>true if ProxyPassword property is set</returns> internal bool IsSetProxyPassword() { return !System.String.IsNullOrEmpty(this.proxyPassword); } /// <summary> /// Credentials to use with a proxy. /// </summary> public ICredentials ProxyCredentials { get { ICredentials credentials = this.proxyCredentials; if (credentials == null && this.IsSetProxyUsername()) { credentials = new NetworkCredential(this.proxyUsername, this.proxyPassword ?? String.Empty); } return credentials; } set { this.proxyCredentials = value; } } /// <summary> /// Sets the ProxyCredentials property. /// </summary> /// <param name="proxyCredentials">ProxyCredentials property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonS3Config WithProxyCredentials(ICredentials proxyCredentials) { this.proxyCredentials = proxyCredentials; return this; } /// <summary> /// Checks if ProxyCredentials property is set /// </summary> /// <returns>true if ProxyCredentials property is set</returns> internal bool IsSetProxyCredentials() { return (this.ProxyCredentials != null); } /// <summary> /// Gets and sets the MaxErrorRetry property. /// </summary> public int MaxErrorRetry { get { return this.maxErrorRetry; } set { this.maxErrorRetry = value; } } /// <summary> /// Sets the MaxErrorRetry property /// </summary> /// <param name="maxErrorRetry">MaxErrorRetry property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonS3Config WithMaxErrorRetry(int maxErrorRetry) { this.maxErrorRetry = maxErrorRetry; return this; } /// <summary> /// Checks if MaxErrorRetry property is set /// </summary> /// <returns>true if MaxErrorRetry property is set</returns> internal bool IsSetMaxErrorRetry() { return MaxErrorRetry > -1; } /// <summary> /// Gets and Sets the property that determines whether /// the HTTP or HTTPS protocol is used to make requests to the /// S3 service. By default Protocol.HTTPS is used to /// communicate with S3. /// </summary> public Protocol CommunicationProtocol { get { return this.protocol; } set { this.protocol = value; } } /// <summary> /// Sets the Protocol property. Valid values are Protocol.HTTP /// and Protocol.HTTPS. Default is Protocol.HTTPS. /// </summary> /// <param name="protocol">The protocol to use</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonS3Config WithCommunicationProtocol(Protocol protocol) { this.protocol = protocol; return this; } /// <summary> /// Gets and Sets the UseSecureString property. /// By default, the AWS Secret Access Key is stored /// in a SecureString (true) - this is one of the secure /// ways to store a secret provided by the .NET Framework. /// But, the use of SecureStrings is not supported in Medium /// Trust Windows Hosting environments. If you are building an /// ASP.NET application that needs to run with Medium Trust, /// set this property to false, and the client will /// not save your AWS Secret Key in a secure string. Changing /// the default to false can result in the Secret Key being /// vulnerable; please use this property judiciously. /// </summary> /// <remarks>Storing the AWS Secret Access Key is not /// recommended unless absolutely necessary. /// </remarks> /// <seealso cref="T:System.Security.SecureString"/> public bool UseSecureStringForAwsSecretKey { get { return this.fUseSecureString; } set { this.fUseSecureString = value; } } /// <summary> /// Sets the UseSecureString property. /// By default, the AWS Secret Access Key is stored /// in a SecureString (true) - this is one of the secure /// ways to store a secret provided by the .NET Framework. /// But, the use of SecureStrings is not supported in Medium /// Trust Windows Hosting environments. If you are building an /// ASP.NET application that needs to run with Medium Trust, /// set this property to false, and the client will /// not save your AWS Secret Key in a secure string. Changing /// the default to false can result in the Secret Key being /// vulnerable; please use this property judiciously. /// </summary> /// <param name="fSecure"> /// Whether a secure string should be used or not. /// </param> /// <returns>The Config object with the property set</returns> /// <remarks>Storing the AWS Secret Access Key is not /// recommended unless absolutely necessary. /// </remarks> /// <seealso cref="T:System.Security.SecureString"/> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonS3Config WithUseSecureStringForAwsSecretKey(bool fSecure) { fUseSecureString = fSecure; return this; } /// <summary> /// Gets and Sets the BufferSize property. /// The BufferSize controls the buffer used to read in from input streams and write /// out to the request. /// </summary> public int BufferSize { get { return this.bufferSize; } set { this.bufferSize = value; } } /// <summary> /// Gets and sets the connection limit set on the ServicePoint for the WebRequest. /// Default value is 50 connections unless ServicePointManager.DefaultConnectionLimit is set in /// which case ServicePointManager.DefaultConnectionLimit will be used as the default. /// </summary> public int ConnectionLimit { get { return AWSSDKUtils.GetConnectionLimit(this.connectionLimit); } set { this.connectionLimit = value; } } } }
using System.Drawing; using GuiLabs.Canvas.DrawStyle; using GuiLabs.Canvas.Renderer; namespace GuiLabs.Editor.CSharp { public class CSharpStyleFactory : StyleFactory { public CSharpStyleFactory() { #region Colors Color lightGray = Color.FromArgb(250, 250, 250); lightGray = Color.FromArgb(230, 230, 230); //lightGray = Color.FromArgb(255, 255, 230); Color niceGray = Color.FromArgb(246, 243, 243); Color classBack = lightGray; Color methodBack = lightGray; Color memberBack = Color.GhostWhite; Color namespaceBack = lightGray; Color propertyBack = lightGray; Color grayFrame = Color.Black;// Color.Gainsboro; Color deselectedFrame = Color.Transparent; //deselectedFrame = lightGray; //deselectedFrame = Color.Gainsboro; //Color controlStructure = Color.White; //Color controlStructure = Color.FromArgb(250, 250, 250); Color controlStructure = lightGray; Color typeName = Color.FromArgb(43, 145, 175); #endregion Color secondGradient = Color.White; Color namespaceGradient = Color.FromArgb(255, 220, 255); IFillStyleInfo namespaceBackground = RendererSingleton.StyleFactory.ProduceNewFillStyleInfo( namespaceGradient, secondGradient, FillMode.HorizontalGradient); IFillStyleInfo namespaceBackgroundSelected = RendererSingleton.StyleFactory.ProduceNewFillStyleInfo( namespaceGradient, secondGradient, FillMode.HorizontalGradient); Color typeGradient = Color.FromArgb(230, 230, 255); IFillStyleInfo typeBackground = RendererSingleton.StyleFactory.ProduceNewFillStyleInfo( typeGradient, secondGradient, FillMode.HorizontalGradient); IFillStyleInfo typeBackgroundSelected = RendererSingleton.StyleFactory.ProduceNewFillStyleInfo( typeGradient, secondGradient, FillMode.HorizontalGradient); Color memberGradient = Color.FromArgb(230, 255, 200); IFillStyleInfo memberBackground = RendererSingleton.StyleFactory.ProduceNewFillStyleInfo( memberGradient, secondGradient, FillMode.HorizontalGradient); IFillStyleInfo memberBackgroundSelected = RendererSingleton.StyleFactory.ProduceNewFillStyleInfo( memberGradient, secondGradient, FillMode.HorizontalGradient); Color fieldGradient = Color.FromArgb(230, 235, 255); IFillStyleInfo fieldBackground = RendererSingleton.StyleFactory.ProduceNewFillStyleInfo( fieldGradient, secondGradient, FillMode.HorizontalGradient); IFillStyleInfo fieldBackgroundSelected = RendererSingleton.StyleFactory.ProduceNewFillStyleInfo( fieldGradient, secondGradient, FillMode.HorizontalGradient); Color controlStructureGradient = Color.FromArgb(255, 240, 200); IFillStyleInfo controlStructureBackground = RendererSingleton.StyleFactory.ProduceNewFillStyleInfo( controlStructureGradient, secondGradient, FillMode.HorizontalGradient); IFillStyleInfo controlStructureBackgroundSelected = RendererSingleton.StyleFactory.ProduceNewFillStyleInfo( controlStructureGradient, secondGradient, FillMode.HorizontalGradient); AddStyle(StyleNames.Transparent, Color.Transparent, Color.Transparent); AddAlias(StyleNames.TransparentSel, StyleNames.Transparent); AddAliasAndSelected("Control", StyleNames.Transparent); #region Types AddStyle( StyleNames.TypeName, Color.Transparent, Color.Transparent, typeName//, "Consolas", 11, FontStyle.Regular ); AddAlias( StyleNames.TypeNameSel, StyleNames.TypeName); AddStyle("ClassBlock", deselectedFrame, typeBackground); AddStyle("ClassBlock_selected", grayFrame, typeBackgroundSelected); AddAliasAndSelected("StructBlock", "ClassBlock"); AddAliasAndSelected("InterfaceBlock", "ClassBlock"); AddAliasAndSelected("EnumBlock", "ClassBlock"); #endregion #region Namespace AddStyle("NamespaceBlock", deselectedFrame, namespaceBackground); AddStyle("NamespaceBlock_selected", grayFrame, namespaceBackgroundSelected); AddAliasAndSelected("UsingBlock", "NamespaceBlock"); #endregion #region Members AddStyle("MethodBlock", deselectedFrame, memberBackground); AddStyle("MethodBlock_selected", grayFrame, memberBackgroundSelected); AddStyle("FieldBlock", Color.Transparent, Color.Transparent); AddStyle("FieldBlock_selected", grayFrame, fieldBackgroundSelected); AddAliasAndSelected("PropertyBlock", "MethodBlock"); AddAliasAndSelected("PropertyAccessorBlock", "MethodBlock"); AddAliasAndSelected("InterfaceAccessorsBlock", "FieldBlock"); #endregion AddAliasAndSelected("DelegateBlock", "FieldBlock"); #region Method AddStyle("ControlStructureBlock", deselectedFrame, controlStructureBackground); AddStyle("ControlStructureBlock_selected", grayFrame, controlStructureBackgroundSelected); #endregion #region Text //ShapeStyle s = new ShapeStyle(); //s.Name = "GuiLabs.Editor.CSharp.ModifierLabelBlock_selected"; //s.FontStyleInfo = // GuiLabs.Canvas.Renderer.RendererSingleton.StyleFactory.ProduceNewFontStyleInfo( // "Lucida Console", // 14, // FontStyle.Regular); //s.LineColor = Color.BlueViolet; //Add(s); AddStyle("MemberNameBlock", Color.Transparent, Color.Transparent, Color.Black, FontStyle.Bold); AddStyle("MemberNameBlock_selected", Color.PaleGoldenrod, Color.LightYellow, Color.Black, FontStyle.Bold); AddStyle("CommentBlock", //Color.MintCream, //Color.MintCream, Color.Transparent, Color.Transparent, Color.Transparent, FillMode.HorizontalGradient); AddStyle("CommentBlock_selected", Color.Green, Color.MintCream, secondGradient, FillMode.HorizontalGradient); AddStyle("CommentLine", Color.Transparent, Color.Transparent, Color.Green, "Arial", 8, FontStyle.Regular); AddStyle("CommentLine_selected", Color.Transparent, Color.Transparent, Color.Green, "Arial", 8, FontStyle.Regular); AddStyle("ButtonBlock", Color.DarkRed, Color.Linen, Color.PeachPuff, FillMode.VerticalGradient); AddStyle("ButtonBlock_selected", Color.DarkRed, Color.Linen, Color.SandyBrown, FillMode.VerticalGradient); AddStyle("SpaceBlock", Color.Transparent, Color.Transparent); AddStyle("SpaceBlock_selected", Color.DarkBlue, Color.LightCyan); AddStyle("StatementLine", Color.Transparent, Color.Transparent); AddStyle("StatementLine_selected", Color.LightGray, Color.LightYellow); AddStyle("KeywordLabel", Color.Transparent, Color.Transparent, Color.Blue); AddStyle("KeywordLabel_selected", Color.Blue, Color.LightCyan, Color.Blue); AddStyle("AttributeBlock", Color.Yellow, Color.LightYellow); AddStyle("AttributeBlock_selected", Color.DarkKhaki, Color.Yellow); AddStyle("OneWordStatement", Color.Transparent, Color.Transparent, Color.Blue); AddStyle("OneWordStatement_selected", Color.Gray, Color.Yellow, Color.Black); AddStyle("TextBox", Color.Transparent, Color.Transparent); AddStyle("TextBox_selected", Color.Transparent, Color.Transparent); AddAliasAndSelected("Label", "TextBox"); AddAliasAndSelected("TextLine", "TextBox"); AddAliasAndSelected("ExpressionBlock", "TextLine"); #endregion #region Modifiers AddAliasAndSelected("ModifierSelectionBlock", "KeywordLabel"); AddAliasAndSelected("ModifierSeparatorBlock", "KeywordLabel"); AddStyle("TypeSelection", Color.Transparent, Color.Transparent, typeName); AddStyle("TypeSelection_selected", Color.Blue, Color.LightCyan, typeName); AddAliasAndSelected("InterfacePropertyAccessor", "ModifierSelectionBlock"); #endregion } } }
using System.Collections.Generic; using System.Data; using FluentMigrator.Expressions; using FluentMigrator.Model; using FluentMigrator.Runner.Generators.Postgres; using NUnit.Framework; using NUnit.Should; namespace FluentMigrator.Tests.Unit.Generators.Postgres { [TestFixture] public class PostgresGeneratorTests { protected PostgresGenerator Generator; [SetUp] public void Setup() { Generator = new PostgresGenerator(); } [Test] public void CanCreateTableWithDateTimeOffsetColumn() { var tableName = "TestTable1"; var expression = new CreateTableExpression { TableName = tableName }; expression.Columns.Add(new ColumnDefinition { TableName = tableName, Name = "TestColumn1", Type = DbType.DateTimeOffset }); expression.Columns.Add(new ColumnDefinition { TableName = tableName, Name = "TestColumn2", Type = DbType.DateTime2 }); expression.Columns.Add(new ColumnDefinition { TableName = tableName, Name = "TestColumn3", Type = DbType.Date }); expression.Columns.Add(new ColumnDefinition { TableName = tableName, Name = "TestColumn4", Type = DbType.Time }); var result = Generator.Generate(expression); result.ShouldBe(string.Format("CREATE TABLE \"public\".\"{0}\" (\"TestColumn1\" timestamptz NOT NULL, \"TestColumn2\" timestamp NOT NULL, \"TestColumn3\" date NOT NULL, \"TestColumn4\" time NOT NULL);", tableName)); } [Test] public void CanCreateAutoIncrementColumnForInt64() { var expression = GeneratorTestHelper.GetCreateTableWithAutoIncrementExpression(); expression.Columns[0].Type = DbType.Int64; var result = Generator.Generate(expression); result.ShouldBe("CREATE TABLE \"public\".\"TestTable1\" (\"TestColumn1\" bigserial NOT NULL, \"TestColumn2\" integer NOT NULL);"); } [Test] public void CanCreateTableWithBinaryColumnWithSize() { var expression = GeneratorTestHelper.GetCreateTableExpression(); expression.Columns[0].Type = DbType.Binary; expression.Columns[0].Size = 10000; var result = Generator.Generate(expression); result.ShouldBe("CREATE TABLE \"public\".\"TestTable1\" (\"TestColumn1\" bytea NOT NULL, \"TestColumn2\" integer NOT NULL);"); // PostgreSQL does not actually use the configured size } [Test] public void CanCreateTableWithBoolDefaultValue() { var expression = GeneratorTestHelper.GetCreateTableExpression(); expression.Columns[0].DefaultValue = true; var result = Generator.Generate(expression); result.ShouldBe("CREATE TABLE \"public\".\"TestTable1\" (\"TestColumn1\" text NOT NULL DEFAULT true, \"TestColumn2\" integer NOT NULL);"); } [Test] public void CanUseSystemMethodCurrentUserAsADefaultValueForAColumn() { const string tableName = "NewTable"; var columnDefinition = new ColumnDefinition { Name = "NewColumn", Size = 15, Type = DbType.String, DefaultValue = SystemMethods.CurrentUser }; var expression = new CreateColumnExpression { Column = columnDefinition, TableName = tableName }; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE \"public\".\"NewTable\" ADD \"NewColumn\" varchar(15) NOT NULL DEFAULT current_user;"); } [Test] public void CanUseSystemMethodCurrentUTCDateTimeAsADefaultValueForAColumn() { const string tableName = "NewTable"; var columnDefinition = new ColumnDefinition { Name = "NewColumn", Size = 5, Type = DbType.String, DefaultValue = SystemMethods.CurrentUTCDateTime }; var expression = new CreateColumnExpression { Column = columnDefinition, TableName = tableName }; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE \"public\".\"NewTable\" ADD \"NewColumn\" varchar(5) NOT NULL DEFAULT (now() at time zone 'UTC');"); } [Test] public void ExplicitUnicodeStringIgnoredForNonSqlServer() { var expression = new InsertDataExpression {TableName = "TestTable"}; expression.Rows.Add(new InsertionDataDefinition { new KeyValuePair<string, object>("NormalString", "Just'in"), new KeyValuePair<string, object>("UnicodeString", new ExplicitUnicodeString("codethinked'.com")) }); var result = Generator.Generate(expression); result.ShouldBe("INSERT INTO \"public\".\"TestTable\" (\"NormalString\",\"UnicodeString\") VALUES ('Just''in','codethinked''.com');"); } [Test] public void CanAlterColumnAndSetAsNullable() { var expression = new AlterColumnExpression { Column = new ColumnDefinition { Type = DbType.String, Name = "TestColumn1", IsNullable = true }, SchemaName = "TestSchema", TableName = "TestTable1" }; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" TYPE text, ALTER \"TestColumn1\" DROP NOT NULL;"); } [Test] public void CanAlterColumnAndSetAsNotNullable() { var expression = new AlterColumnExpression { Column = new ColumnDefinition { Type = DbType.String, Name = "TestColumn1", IsNullable = false }, SchemaName = "TestSchema", TableName = "TestTable1" }; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" TYPE text, ALTER \"TestColumn1\" SET NOT NULL;"); } [Test] public void CanAlterDefaultConstraintToNewGuid() { var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression(); expression.DefaultValue = SystemMethods.NewGuid; expression.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" DROP DEFAULT, ALTER \"TestColumn1\" SET DEFAULT uuid_generate_v4();"); } [Test] public void CanDeleteDefaultConstraint() { var expression = new DeleteDefaultConstraintExpression { ColumnName = "TestColumn1", SchemaName = "TestSchema", TableName = "TestTable1" }; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" DROP DEFAULT;"); } [Test] public void CanAlterDefaultConstraintToCurrentUser() { var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression(); expression.DefaultValue = SystemMethods.CurrentUser; expression.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" DROP DEFAULT, ALTER \"TestColumn1\" SET DEFAULT current_user;"); } [Test] public void CanAlterDefaultConstraintToCurrentDate() { var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression(); expression.DefaultValue = SystemMethods.CurrentDateTime; expression.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" DROP DEFAULT, ALTER \"TestColumn1\" SET DEFAULT now();"); } [Test] public void CanAlterDefaultConstraintToCurrentUtcDateTime() { var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression(); expression.DefaultValue = SystemMethods.CurrentUTCDateTime; expression.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" DROP DEFAULT, ALTER \"TestColumn1\" SET DEFAULT (now() at time zone 'UTC');"); } [Test] public void CanAlterColumnAndOnlySetTypeIfIsNullableNotSet() { var expression = new AlterColumnExpression { Column = new ColumnDefinition { Type = DbType.String, Name = "TestColumn1", IsNullable = null }, SchemaName = "TestSchema", TableName = "TestTable1" }; var result = Generator.Generate(expression); result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" TYPE text;"); } } }
/* * 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. */ using System; using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; using Common.Logging; using Quartz; using Quartz.Simpl; using Quartz.Xml; using Spring.Collections; using Spring.Context; using Spring.Core.IO; using Spring.Transaction; using Spring.Transaction.Support; namespace Spring.Scheduling.Quartz { /// <summary> /// Common base class for accessing a Quartz Scheduler, i.e. for registering jobs, /// triggers and listeners on a <see cref="IScheduler" /> instance. /// </summary> /// <remarks> /// For concrete usage, check out the <see cref="SchedulerFactoryObject" /> and /// <see cref="SchedulerAccessorObject" /> classes. ///</remarks> /// <author>Juergen Hoeller</author> /// <author>Marko Lahma (.NET)</author> public abstract class SchedulerAccessor : IResourceLoaderAware { /// <summary> /// Logger instance. /// </summary> private readonly ILog logger; private bool overwriteExistingJobs; private string[] jobSchedulingDataLocations; private IList<IJobDetail> jobDetails; private IDictionary calendars; private IList triggers; private ISchedulerListener[] schedulerListeners; private IJobListener[] globalJobListeners; private IJobListener[] jobListeners; private ITriggerListener[] globalTriggerListeners; private ITriggerListener[] triggerListeners; private IPlatformTransactionManager transactionManager; /// <summary> /// Resource loader instance for sub-classes /// </summary> private IResourceLoader resourceLoader; /// <summary> /// Initializes a new instance of the <see cref="SchedulerAccessor"/> class. /// </summary> protected SchedulerAccessor() { logger = LogManager.GetLogger(GetType()); } /// <summary> /// Set whether any jobs defined on this SchedulerFactoryObject should overwrite /// existing job definitions. Default is "false", to not overwrite already /// registered jobs that have been read in from a persistent job store. /// </summary> public virtual bool OverwriteExistingJobs { set => overwriteExistingJobs = value; } /// <summary> /// Set the locations of Quartz job definition XML files that follow the /// "job_scheduling_data_1_5" XSD. Can be specified to automatically /// register jobs that are defined in such files, possibly in addition /// to jobs defined directly on this SchedulerFactoryObject. /// </summary> /// <seealso cref="XMLSchedulingDataProcessor" /> public virtual string[] JobSchedulingDataLocations { set => jobSchedulingDataLocations = value; } /// <summary> /// Set the location of a Quartz job definition XML file that follows the /// "job_scheduling_data" XSD. Can be specified to automatically /// register jobs that are defined in such a file, possibly in addition /// to jobs defined directly on this SchedulerFactoryObject. /// </summary> /// <seealso cref="XMLSchedulingDataProcessor" /> public virtual string JobSchedulingDataLocation { set => jobSchedulingDataLocations = new string[] {value}; } /// <summary> /// Register a list of JobDetail objects with the Scheduler that /// this FactoryObject creates, to be referenced by Triggers. /// This is not necessary when a Trigger determines the JobDetail /// itself: In this case, the JobDetail will be implicitly registered /// in combination with the Trigger. /// </summary> /// <seealso cref="Triggers" /> /// <seealso cref="IJobDetail" /> /// <seealso cref="JobDetailObject" /> /// <seealso cref="IJobDetailAwareTrigger" /> /// <seealso cref="ITrigger.JobKey" /> public virtual IJobDetail[] JobDetails { set => jobDetails = new List<IJobDetail>(value); } /// <summary> /// Register a list of Quartz ICalendar objects with the Scheduler /// that this FactoryObject creates, to be referenced by Triggers. /// </summary> /// <value>Map with calendar names as keys as Calendar objects as values</value> /// <seealso cref="ICalendar" /> /// <seealso cref="ITrigger.CalendarName" /> public virtual IDictionary Calendars { set => calendars = value; } /// <summary> /// Register a list of Trigger objects with the Scheduler that /// this FactoryObject creates. /// </summary> /// <remarks> /// If the Trigger determines the corresponding JobDetail itself, /// the job will be automatically registered with the Scheduler. /// Else, the respective JobDetail needs to be registered via the /// "jobDetails" property of this FactoryObject. /// </remarks> /// <seealso cref="JobDetails" /> /// <seealso cref="IJobDetail" /> /// <seealso cref="IJobDetailAwareTrigger" /> /// <seealso cref="CronTriggerObject" /> /// <seealso cref="SimpleTriggerObject" /> public virtual ITrigger[] Triggers { set => triggers = new ArrayList(value); } /// <summary> /// Specify Quartz SchedulerListeners to be registered with the Scheduler. /// </summary> public virtual ISchedulerListener[] SchedulerListeners { set => schedulerListeners = value; } /// <summary> /// Specify global Quartz JobListeners to be registered with the Scheduler. /// Such JobListeners will apply to all Jobs in the Scheduler. /// </summary> public virtual IJobListener[] GlobalJobListeners { set => globalJobListeners = value; } /// <summary> /// Specify named Quartz JobListeners to be registered with the Scheduler. /// Such JobListeners will only apply to Jobs that explicitly activate /// them via their name. /// </summary> /// <seealso cref="IJobListener.Name" /> public virtual IJobListener[] JobListeners { set => jobListeners = value; } /// <summary> /// Specify global Quartz TriggerListeners to be registered with the Scheduler. /// Such TriggerListeners will apply to all Triggers in the Scheduler. /// </summary> public virtual ITriggerListener[] GlobalTriggerListeners { set => globalTriggerListeners = value; } /// <summary> /// Specify named Quartz TriggerListeners to be registered with the Scheduler. /// Such TriggerListeners will only apply to Triggers that explicitly activate /// them via their name. /// </summary> /// <seealso cref="ITriggerListener.Name" /> public virtual ITriggerListener[] TriggerListeners { set => triggerListeners = value; } /// <summary> /// Set the transaction manager to be used for registering jobs and triggers /// that are defined by this SchedulerFactoryObject. Default is none; setting /// this only makes sense when specifying a DataSource for the Scheduler. /// </summary> public virtual IPlatformTransactionManager TransactionManager { set => transactionManager = value; } /// <summary> /// Sets the <see cref="Spring.Core.IO.IResourceLoader"/> /// that this object runs in. /// </summary> /// <value></value> /// <remarks> /// Invoked <b>after</b> population of normal objects properties but /// before an init callback such as /// <see cref="Spring.Objects.Factory.IInitializingObject"/>'s /// <see cref="Spring.Objects.Factory.IInitializingObject.AfterPropertiesSet()"/> /// or a custom init-method. Invoked <b>before</b> setting /// <see cref="Spring.Context.IApplicationContextAware"/>'s /// <see cref="Spring.Context.IApplicationContextAware.ApplicationContext"/> /// property. /// </remarks> public virtual IResourceLoader ResourceLoader { set { resourceLoader = value; } protected get { return resourceLoader; } } /// <summary> /// Logger instance. /// </summary> protected ILog Logger => logger; /// <summary> /// Register jobs and triggers (within a transaction, if possible). /// </summary> protected virtual async Task RegisterJobsAndTriggers() { ITransactionStatus transactionStatus = null; if (transactionManager != null) { transactionStatus = transactionManager.GetTransaction(new DefaultTransactionDefinition()); } try { if (jobSchedulingDataLocations != null) { var dataProcessor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); dataProcessor.OverWriteExistingData = overwriteExistingJobs; foreach (string location in jobSchedulingDataLocations) { await dataProcessor.ProcessFileAndScheduleJobs(location, GetScheduler()).ConfigureAwait(false); } } // Register JobDetails. if (jobDetails != null) { foreach (IJobDetail jobDetail in jobDetails) { await AddJobToScheduler(jobDetail).ConfigureAwait(false); } } else { // Create empty list for easier checks when registering triggers. jobDetails = new List<IJobDetail>(); } // Register Calendars. if (calendars != null) { foreach (DictionaryEntry entry in calendars) { string calendarName = (string) entry.Key; ICalendar calendar = (ICalendar) entry.Value; await GetScheduler().AddCalendar(calendarName, calendar, true, true).ConfigureAwait(false); } } // Register Triggers. if (triggers != null) { foreach (ITrigger trigger in triggers) { await AddTriggerToScheduler(trigger).ConfigureAwait(false); } } } catch (Exception ex) { if (transactionStatus != null) { try { transactionManager.Rollback(transactionStatus); } catch (TransactionException) { logger.Error("Job registration exception overridden by rollback exception", ex); throw; } } if (ex is SchedulerException) { throw; } throw new SchedulerException("Registration of jobs and triggers failed: " + ex.Message); } if (transactionStatus != null) { transactionManager.Commit(transactionStatus); } } /// <summary> /// Add the given job to the Scheduler, if it doesn't already exist. /// Overwrites the job in any case if "overwriteExistingJobs" is set. /// </summary> /// <param name="jobDetail">the job to add</param> /// <returns><code>true</code> if the job was actually added, <code>false</code> if it already existed before</returns> private async Task<bool> AddJobToScheduler(IJobDetail jobDetail) { if (overwriteExistingJobs || await GetScheduler().GetJobDetail(jobDetail.Key).ConfigureAwait(false) == null) { await GetScheduler().AddJob(jobDetail, true, true).ConfigureAwait(false); return true; } return false; } /// <summary> /// Add the given trigger to the Scheduler, if it doesn't already exist. /// Overwrites the trigger in any case if "overwriteExistingJobs" is set. /// </summary> /// <param name="trigger">the trigger to add</param> /// <returns><code>true</code> if the trigger was actually added, <code>false</code> if it already existed before</returns> private async Task<bool> AddTriggerToScheduler(ITrigger trigger) { bool triggerExists = await GetScheduler().GetTrigger(trigger.Key).ConfigureAwait(false) != null; if (!triggerExists || overwriteExistingJobs) { // Check if the Trigger is aware of an associated JobDetail. if (trigger is IJobDetailAwareTrigger awareTrigger) { IJobDetail jobDetail = awareTrigger.JobDetail; // Automatically register the JobDetail too. if (!jobDetails.Contains(jobDetail) && await AddJobToScheduler(jobDetail).ConfigureAwait(false)) { jobDetails.Add(jobDetail); } } if (!triggerExists) { try { await GetScheduler().ScheduleJob(trigger).ConfigureAwait(false); } catch (ObjectAlreadyExistsException ex) { if (logger.IsDebugEnabled) { logger.Debug( $"Unexpectedly found existing trigger, assumably due to cluster race condition: {ex.Message} - can safely be ignored"); } if (overwriteExistingJobs) { await GetScheduler().RescheduleJob(trigger.Key, trigger).ConfigureAwait(false); } } } else { await GetScheduler().RescheduleJob(trigger.Key, trigger).ConfigureAwait(false); } return true; } else { return false; } } /// <summary> /// Register all specified listeners with the Scheduler. /// </summary> protected virtual void RegisterListeners() { if (schedulerListeners != null) { for (int i = 0; i < schedulerListeners.Length; i++) { GetScheduler().ListenerManager.AddSchedulerListener(schedulerListeners[i]); } } if (globalJobListeners != null) { foreach (IJobListener jobListener in globalJobListeners) { GetScheduler().ListenerManager.AddJobListener(jobListener); } } if (jobListeners != null && jobListeners.Length > 0) { throw new InvalidOperationException("Non-global JobListeners not supported on Quartz 2 - " + "manually register a Matcher against the Quartz ListenerManager instead"); } if (globalTriggerListeners != null) { foreach (ITriggerListener triggerListener in globalTriggerListeners) { GetScheduler().ListenerManager.AddTriggerListener(triggerListener); } } if (triggerListeners != null && triggerListeners.Length > 0) { throw new InvalidOperationException("Non-global TriggerListeners not supported on Quartz 2 - " + "manually register a Matcher against the Quartz ListenerManager instead"); } } /// <summary> /// Template method that determines the Scheduler to operate on. /// To be implemented by subclasses. /// </summary> /// <returns></returns> protected abstract IScheduler GetScheduler(); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace MyCustomWebService.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
//======= Copyright (c) Valve Corporation, All rights reserved. =============== // // Purpose: Prompt developers to use settings most compatible with SteamVR. // //============================================================================= using UnityEngine; using UnityEditor; using System.IO; [InitializeOnLoad] public class SteamVR_Settings : EditorWindow { const bool forceShow = false; // Set to true to get the dialog to show back up in the case you clicked Ignore All. const string ignore = "ignore."; const string useRecommended = "Use recommended ({0})"; const string currentValue = " (current = {0})"; const string buildTarget = "Build Target"; const string showUnitySplashScreen = "Show Unity Splashscreen"; const string defaultIsFullScreen = "Default is Fullscreen"; const string defaultScreenSize = "Default Screen Size"; const string runInBackground = "Run In Background"; const string displayResolutionDialog = "Display Resolution Dialog"; const string resizableWindow = "Resizable Window"; const string fullscreenMode = "D3D11 Fullscreen Mode"; const string visibleInBackground = "Visible In Background"; const string renderingPath = "Rendering Path"; const string colorSpace = "Color Space"; const string gpuSkinning = "GPU Skinning"; #if false // skyboxes are currently broken const string singlePassStereoRendering = "Single-Pass Stereo Rendering"; #endif const BuildTarget recommended_BuildTarget = BuildTarget.StandaloneWindows64; const bool recommended_ShowUnitySplashScreen = false; const bool recommended_DefaultIsFullScreen = false; const int recommended_DefaultScreenWidth = 1024; const int recommended_DefaultScreenHeight = 768; const bool recommended_RunInBackground = true; const ResolutionDialogSetting recommended_DisplayResolutionDialog = ResolutionDialogSetting.HiddenByDefault; const bool recommended_ResizableWindow = true; const D3D11FullscreenMode recommended_FullscreenMode = D3D11FullscreenMode.FullscreenWindow; const bool recommended_VisibleInBackground = true; const RenderingPath recommended_RenderPath = RenderingPath.Forward; const ColorSpace recommended_ColorSpace = ColorSpace.Linear; const bool recommended_GpuSkinning = true; #if false const bool recommended_SinglePassStereoRendering = true; #endif static SteamVR_Settings window; static SteamVR_Settings() { EditorApplication.update += Update; } static void Update() { bool show = (!EditorPrefs.HasKey(ignore + buildTarget) && EditorUserBuildSettings.activeBuildTarget != recommended_BuildTarget) || (!EditorPrefs.HasKey(ignore + showUnitySplashScreen) && PlayerSettings.showUnitySplashScreen != recommended_ShowUnitySplashScreen) || (!EditorPrefs.HasKey(ignore + defaultIsFullScreen) && PlayerSettings.defaultIsFullScreen != recommended_DefaultIsFullScreen) || (!EditorPrefs.HasKey(ignore + defaultScreenSize) && (PlayerSettings.defaultScreenWidth != recommended_DefaultScreenWidth || PlayerSettings.defaultScreenHeight != recommended_DefaultScreenHeight)) || (!EditorPrefs.HasKey(ignore + runInBackground) && PlayerSettings.runInBackground != recommended_RunInBackground) || (!EditorPrefs.HasKey(ignore + displayResolutionDialog) && PlayerSettings.displayResolutionDialog != recommended_DisplayResolutionDialog) || (!EditorPrefs.HasKey(ignore + resizableWindow) && PlayerSettings.resizableWindow != recommended_ResizableWindow) || (!EditorPrefs.HasKey(ignore + fullscreenMode) && PlayerSettings.d3d11FullscreenMode != recommended_FullscreenMode) || (!EditorPrefs.HasKey(ignore + visibleInBackground) && PlayerSettings.visibleInBackground != recommended_VisibleInBackground) || (!EditorPrefs.HasKey(ignore + renderingPath) && PlayerSettings.renderingPath != recommended_RenderPath) || (!EditorPrefs.HasKey(ignore + colorSpace) && PlayerSettings.colorSpace != recommended_ColorSpace) || (!EditorPrefs.HasKey(ignore + gpuSkinning) && PlayerSettings.gpuSkinning != recommended_GpuSkinning) || #if false (!EditorPrefs.HasKey(ignore + singlePassStereoRendering) && PlayerSettings.singlePassStereoRendering != recommended_SinglePassStereoRendering) || #endif forceShow; if (show) { window = GetWindow<SteamVR_Settings>(true); window.minSize = new Vector2(320, 440); //window.title = "SteamVR"; } // Switch to native OpenVR support. var updated = false; if (!PlayerSettings.virtualRealitySupported) { PlayerSettings.virtualRealitySupported = true; updated = true; } var devices = UnityEditorInternal.VR.VREditor.GetVREnabledDevices(BuildTargetGroup.Standalone); var hasOpenVR = false; foreach (var device in devices) if (device.ToLower() == "openvr") hasOpenVR = true; if (!hasOpenVR) { string[] newDevices; if (updated) { newDevices = new string[] { "OpenVR" }; } else { newDevices = new string[devices.Length + 1]; for (int i = 0; i < devices.Length; i++) newDevices[i] = devices[i]; newDevices[devices.Length] = "OpenVR"; updated = true; } UnityEditorInternal.VR.VREditor.SetVREnabledDevices(BuildTargetGroup.Standalone, newDevices); } if (updated) Debug.Log("Switching to native OpenVR support."); var dlls = new string[] { "Plugins/x86/openvr_api.dll", "Plugins/x86_64/openvr_api.dll" }; foreach (var path in dlls) { if (!File.Exists(Application.dataPath + "/" + path)) continue; if (AssetDatabase.DeleteAsset("Assets/" + path)) Debug.Log("Deleting " + path); else { Debug.Log(path + " in use; cannot delete. Please restart Unity to complete upgrade."); } } EditorApplication.update -= Update; } Vector2 scrollPosition; bool toggleState; string GetResourcePath() { var ms = MonoScript.FromScriptableObject(this); var path = AssetDatabase.GetAssetPath(ms); path = Path.GetDirectoryName(path); return path.Substring(0, path.Length - "Editor".Length) + "Textures/"; } public void OnGUI() { var resourcePath = GetResourcePath(); var logo = AssetDatabase.LoadAssetAtPath<Texture2D>(resourcePath + "logo.png"); var rect = GUILayoutUtility.GetRect(position.width, 150, GUI.skin.box); if (logo) GUI.DrawTexture(rect, logo, ScaleMode.ScaleToFit); EditorGUILayout.HelpBox("Recommended project settings for SteamVR:", MessageType.Warning); scrollPosition = GUILayout.BeginScrollView(scrollPosition); int numItems = 0; if (!EditorPrefs.HasKey(ignore + buildTarget) && EditorUserBuildSettings.activeBuildTarget != recommended_BuildTarget) { ++numItems; GUILayout.Label(buildTarget + string.Format(currentValue, EditorUserBuildSettings.activeBuildTarget)); GUILayout.BeginHorizontal(); if (GUILayout.Button(string.Format(useRecommended, recommended_BuildTarget))) { EditorUserBuildSettings.SwitchActiveBuildTarget(recommended_BuildTarget); } GUILayout.FlexibleSpace(); if (GUILayout.Button("Ignore")) { EditorPrefs.SetBool(ignore + buildTarget, true); } GUILayout.EndHorizontal(); } if (!EditorPrefs.HasKey(ignore + showUnitySplashScreen) && PlayerSettings.showUnitySplashScreen != recommended_ShowUnitySplashScreen) { ++numItems; GUILayout.Label(showUnitySplashScreen + string.Format(currentValue, PlayerSettings.showUnitySplashScreen)); GUILayout.BeginHorizontal(); if (GUILayout.Button(string.Format(useRecommended, recommended_ShowUnitySplashScreen))) { PlayerSettings.showUnitySplashScreen = recommended_ShowUnitySplashScreen; } GUILayout.FlexibleSpace(); if (GUILayout.Button("Ignore")) { EditorPrefs.SetBool(ignore + showUnitySplashScreen, true); } GUILayout.EndHorizontal(); } if (!EditorPrefs.HasKey(ignore + defaultIsFullScreen) && PlayerSettings.defaultIsFullScreen != recommended_DefaultIsFullScreen) { ++numItems; GUILayout.Label(defaultIsFullScreen + string.Format(currentValue, PlayerSettings.defaultIsFullScreen)); GUILayout.BeginHorizontal(); if (GUILayout.Button(string.Format(useRecommended, recommended_DefaultIsFullScreen))) { PlayerSettings.defaultIsFullScreen = recommended_DefaultIsFullScreen; } GUILayout.FlexibleSpace(); if (GUILayout.Button("Ignore")) { EditorPrefs.SetBool(ignore + defaultIsFullScreen, true); } GUILayout.EndHorizontal(); } if (!EditorPrefs.HasKey(ignore + defaultScreenSize) && (PlayerSettings.defaultScreenWidth != recommended_DefaultScreenWidth || PlayerSettings.defaultScreenHeight != recommended_DefaultScreenHeight)) { ++numItems; GUILayout.Label(defaultScreenSize + string.Format(" ({0}x{1})", PlayerSettings.defaultScreenWidth, PlayerSettings.defaultScreenHeight)); GUILayout.BeginHorizontal(); if (GUILayout.Button(string.Format("Use recommended ({0}x{1})", recommended_DefaultScreenWidth, recommended_DefaultScreenHeight))) { PlayerSettings.defaultScreenWidth = recommended_DefaultScreenWidth; PlayerSettings.defaultScreenHeight = recommended_DefaultScreenHeight; } GUILayout.FlexibleSpace(); if (GUILayout.Button("Ignore")) { EditorPrefs.SetBool(ignore + defaultScreenSize, true); } GUILayout.EndHorizontal(); } if (!EditorPrefs.HasKey(ignore + runInBackground) && PlayerSettings.runInBackground != recommended_RunInBackground) { ++numItems; GUILayout.Label(runInBackground + string.Format(currentValue, PlayerSettings.runInBackground)); GUILayout.BeginHorizontal(); if (GUILayout.Button(string.Format(useRecommended, recommended_RunInBackground))) { PlayerSettings.runInBackground = recommended_RunInBackground; } GUILayout.FlexibleSpace(); if (GUILayout.Button("Ignore")) { EditorPrefs.SetBool(ignore + runInBackground, true); } GUILayout.EndHorizontal(); } if (!EditorPrefs.HasKey(ignore + displayResolutionDialog) && PlayerSettings.displayResolutionDialog != recommended_DisplayResolutionDialog) { ++numItems; GUILayout.Label(displayResolutionDialog + string.Format(currentValue, PlayerSettings.displayResolutionDialog)); GUILayout.BeginHorizontal(); if (GUILayout.Button(string.Format(useRecommended, recommended_DisplayResolutionDialog))) { PlayerSettings.displayResolutionDialog = recommended_DisplayResolutionDialog; } GUILayout.FlexibleSpace(); if (GUILayout.Button("Ignore")) { EditorPrefs.SetBool(ignore + displayResolutionDialog, true); } GUILayout.EndHorizontal(); } if (!EditorPrefs.HasKey(ignore + resizableWindow) && PlayerSettings.resizableWindow != recommended_ResizableWindow) { ++numItems; GUILayout.Label(resizableWindow + string.Format(currentValue, PlayerSettings.resizableWindow)); GUILayout.BeginHorizontal(); if (GUILayout.Button(string.Format(useRecommended, recommended_ResizableWindow))) { PlayerSettings.resizableWindow = recommended_ResizableWindow; } GUILayout.FlexibleSpace(); if (GUILayout.Button("Ignore")) { EditorPrefs.SetBool(ignore + resizableWindow, true); } GUILayout.EndHorizontal(); } if (!EditorPrefs.HasKey(ignore + fullscreenMode) && PlayerSettings.d3d11FullscreenMode != recommended_FullscreenMode) { ++numItems; GUILayout.Label(fullscreenMode + string.Format(currentValue, PlayerSettings.d3d11FullscreenMode)); GUILayout.BeginHorizontal(); if (GUILayout.Button(string.Format(useRecommended, recommended_FullscreenMode))) { PlayerSettings.d3d11FullscreenMode = recommended_FullscreenMode; } GUILayout.FlexibleSpace(); if (GUILayout.Button("Ignore")) { EditorPrefs.SetBool(ignore + fullscreenMode, true); } GUILayout.EndHorizontal(); } if (!EditorPrefs.HasKey(ignore + visibleInBackground) && PlayerSettings.visibleInBackground != recommended_VisibleInBackground) { ++numItems; GUILayout.Label(visibleInBackground + string.Format(currentValue, PlayerSettings.visibleInBackground)); GUILayout.BeginHorizontal(); if (GUILayout.Button(string.Format(useRecommended, recommended_VisibleInBackground))) { PlayerSettings.visibleInBackground = recommended_VisibleInBackground; } GUILayout.FlexibleSpace(); if (GUILayout.Button("Ignore")) { EditorPrefs.SetBool(ignore + visibleInBackground, true); } GUILayout.EndHorizontal(); } if (!EditorPrefs.HasKey(ignore + renderingPath) && PlayerSettings.renderingPath != recommended_RenderPath) { ++numItems; GUILayout.Label(renderingPath + string.Format(currentValue, PlayerSettings.renderingPath)); GUILayout.BeginHorizontal(); if (GUILayout.Button(string.Format(useRecommended, recommended_RenderPath) + " - required for MSAA")) { PlayerSettings.renderingPath = recommended_RenderPath; } GUILayout.FlexibleSpace(); if (GUILayout.Button("Ignore")) { EditorPrefs.SetBool(ignore + renderingPath, true); } GUILayout.EndHorizontal(); } if (!EditorPrefs.HasKey(ignore + colorSpace) && PlayerSettings.colorSpace != recommended_ColorSpace) { ++numItems; GUILayout.Label(colorSpace + string.Format(currentValue, PlayerSettings.colorSpace)); GUILayout.BeginHorizontal(); if (GUILayout.Button(string.Format(useRecommended, recommended_ColorSpace) + " - requires reloading scene")) { PlayerSettings.colorSpace = recommended_ColorSpace; } GUILayout.FlexibleSpace(); if (GUILayout.Button("Ignore")) { EditorPrefs.SetBool(ignore + colorSpace, true); } GUILayout.EndHorizontal(); } if (!EditorPrefs.HasKey(ignore + gpuSkinning) && PlayerSettings.gpuSkinning != recommended_GpuSkinning) { ++numItems; GUILayout.Label(gpuSkinning + string.Format(currentValue, PlayerSettings.gpuSkinning)); GUILayout.BeginHorizontal(); if (GUILayout.Button(string.Format(useRecommended, recommended_GpuSkinning))) { PlayerSettings.gpuSkinning = recommended_GpuSkinning; } GUILayout.FlexibleSpace(); if (GUILayout.Button("Ignore")) { EditorPrefs.SetBool(ignore + gpuSkinning, true); } GUILayout.EndHorizontal(); } #if false if (!EditorPrefs.HasKey(ignore + singlePassStereoRendering) && PlayerSettings.singlePassStereoRendering != recommended_SinglePassStereoRendering) { ++numItems; GUILayout.Label(singlePassStereoRendering + string.Format(currentValue, PlayerSettings.singlePassStereoRendering)); GUILayout.BeginHorizontal(); if (GUILayout.Button(string.Format(useRecommended, recommended_SinglePassStereoRendering))) { PlayerSettings.singlePassStereoRendering = recommended_SinglePassStereoRendering; } GUILayout.FlexibleSpace(); if (GUILayout.Button("Ignore")) { EditorPrefs.SetBool(ignore + singlePassStereoRendering, true); } GUILayout.EndHorizontal(); } #endif GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Clear All Ignores")) { EditorPrefs.DeleteKey(ignore + buildTarget); EditorPrefs.DeleteKey(ignore + showUnitySplashScreen); EditorPrefs.DeleteKey(ignore + defaultIsFullScreen); EditorPrefs.DeleteKey(ignore + defaultScreenSize); EditorPrefs.DeleteKey(ignore + runInBackground); EditorPrefs.DeleteKey(ignore + displayResolutionDialog); EditorPrefs.DeleteKey(ignore + resizableWindow); EditorPrefs.DeleteKey(ignore + fullscreenMode); EditorPrefs.DeleteKey(ignore + visibleInBackground); EditorPrefs.DeleteKey(ignore + renderingPath); EditorPrefs.DeleteKey(ignore + colorSpace); EditorPrefs.DeleteKey(ignore + gpuSkinning); #if false EditorPrefs.DeleteKey(ignore + singlePassStereoRendering); #endif } GUILayout.EndHorizontal(); GUILayout.EndScrollView(); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); if (numItems > 0) { if (GUILayout.Button("Accept All")) { // Only set those that have not been explicitly ignored. if (!EditorPrefs.HasKey(ignore + buildTarget)) EditorUserBuildSettings.SwitchActiveBuildTarget(recommended_BuildTarget); if (!EditorPrefs.HasKey(ignore + showUnitySplashScreen)) PlayerSettings.showUnitySplashScreen = recommended_ShowUnitySplashScreen; if (!EditorPrefs.HasKey(ignore + defaultIsFullScreen)) PlayerSettings.defaultIsFullScreen = recommended_DefaultIsFullScreen; if (!EditorPrefs.HasKey(ignore + defaultScreenSize)) { PlayerSettings.defaultScreenWidth = recommended_DefaultScreenWidth; PlayerSettings.defaultScreenHeight = recommended_DefaultScreenHeight; } if (!EditorPrefs.HasKey(ignore + runInBackground)) PlayerSettings.runInBackground = recommended_RunInBackground; if (!EditorPrefs.HasKey(ignore + displayResolutionDialog)) PlayerSettings.displayResolutionDialog = recommended_DisplayResolutionDialog; if (!EditorPrefs.HasKey(ignore + resizableWindow)) PlayerSettings.resizableWindow = recommended_ResizableWindow; if (!EditorPrefs.HasKey(ignore + fullscreenMode)) PlayerSettings.d3d11FullscreenMode = recommended_FullscreenMode; if (!EditorPrefs.HasKey(ignore + visibleInBackground)) PlayerSettings.visibleInBackground = recommended_VisibleInBackground; if (!EditorPrefs.HasKey(ignore + renderingPath)) PlayerSettings.renderingPath = recommended_RenderPath; if (!EditorPrefs.HasKey(ignore + colorSpace)) PlayerSettings.colorSpace = recommended_ColorSpace; if (!EditorPrefs.HasKey(ignore + gpuSkinning)) PlayerSettings.gpuSkinning = recommended_GpuSkinning; #if false if (!EditorPrefs.HasKey(ignore + singlePassStereoRendering)) PlayerSettings.singlePassStereoRendering = recommended_SinglePassStereoRendering; #endif EditorUtility.DisplayDialog("Accept All", "You made the right choice!", "Ok"); Close(); } if (GUILayout.Button("Ignore All")) { if (EditorUtility.DisplayDialog("Ignore All", "Are you sure?", "Yes, Ignore All", "Cancel")) { // Only ignore those that do not currently match our recommended settings. if (EditorUserBuildSettings.activeBuildTarget != recommended_BuildTarget) EditorPrefs.SetBool(ignore + buildTarget, true); if (PlayerSettings.showUnitySplashScreen != recommended_ShowUnitySplashScreen) EditorPrefs.SetBool(ignore + showUnitySplashScreen, true); if (PlayerSettings.defaultIsFullScreen != recommended_DefaultIsFullScreen) EditorPrefs.SetBool(ignore + defaultIsFullScreen, true); if (PlayerSettings.defaultScreenWidth != recommended_DefaultScreenWidth || PlayerSettings.defaultScreenHeight != recommended_DefaultScreenHeight) EditorPrefs.SetBool(ignore + defaultScreenSize, true); if (PlayerSettings.runInBackground != recommended_RunInBackground) EditorPrefs.SetBool(ignore + runInBackground, true); if (PlayerSettings.displayResolutionDialog != recommended_DisplayResolutionDialog) EditorPrefs.SetBool(ignore + displayResolutionDialog, true); if (PlayerSettings.resizableWindow != recommended_ResizableWindow) EditorPrefs.SetBool(ignore + resizableWindow, true); if (PlayerSettings.d3d11FullscreenMode != recommended_FullscreenMode) EditorPrefs.SetBool(ignore + fullscreenMode, true); if (PlayerSettings.visibleInBackground != recommended_VisibleInBackground) EditorPrefs.SetBool(ignore + visibleInBackground, true); if (PlayerSettings.renderingPath != recommended_RenderPath) EditorPrefs.SetBool(ignore + renderingPath, true); if (PlayerSettings.colorSpace != recommended_ColorSpace) EditorPrefs.SetBool(ignore + colorSpace, true); if (PlayerSettings.gpuSkinning != recommended_GpuSkinning) EditorPrefs.SetBool(ignore + gpuSkinning, true); #if false if (PlayerSettings.singlePassStereoRendering != recommended_SinglePassStereoRendering) EditorPrefs.SetBool(ignore + singlePassStereoRendering, true); #endif Close(); } } } else if (GUILayout.Button("Close")) { Close(); } GUILayout.EndHorizontal(); } }
using System.Collections.Generic; namespace System.Collections { /// <summary> /// TableSchema /// </summary> //: should this inherit from a dictionary. [CodeVersion(CodeVersionKind.Instinct, "1.0")] public class TableSchema : ICollectionIndexer<string, TableColumn> { protected Dictionary<string, TableColumn> _hash = new Dictionary<string, TableColumn>(); /// <summary> /// private member variable access to the underlying List&lt;string&gt; instance containing the /// primary keys for this table. /// </summary> private List<string> _commitExpressionList; /// <summary> /// private member variable access to the underlying List&lt;string&gt; instance containing the /// primary keys for this table. /// </summary> private List<string> _primaryKeys; /// <summary> /// private member variable access to the underlying List&lt;string&gt; instance containing the /// rowversion keys for this table. /// </summary> private List<string> _rowVersions; /// <summary> /// Initializes a new instance of the <see cref="TableSchema"/> class. /// </summary> public TableSchema() { } /// <summary> /// Gets or sets the <see cref="Instinct.TableColumn"/> with the specified key. /// </summary> /// <value></value> public TableColumn this[string key] { get { if (key == null) throw new ArgumentNullException("key"); TableColumn tableColumn; if (!_hash.TryGetValue(key, out tableColumn)) { // create tableColumn = new TableColumn(); _hash.Add(key, tableColumn); } return tableColumn; } set { if (key == null) throw new ArgumentNullException("key"); _hash[key] = value; } } /// <summary> /// Clears this instance. /// </summary> public void Clear() { _hash.Clear(); // if (m_commitExpressionList != null) // m_commitExpressionList.Clear(); // if (m_primaryKeyList != null) // m_primaryKeyList.Clear(); // if (m_rowVersionList != null) // m_rowVersionList.Clear(); _commitExpressionList = null; _primaryKeys = null; _rowVersions = null; } /// <summary> /// Gets the commit expression list. /// </summary> /// <value>The commit expression list.</value> public List<string> CommitExpressionList { get { return _commitExpressionList; } } /// <summary> /// Gets the count of the items in collection. /// </summary> /// <value>The count.</value> public int Count { get { return _hash.Count; } } /// <summary> /// Defines the column. /// </summary> /// <param name="key">The key.</param> /// <param name="typeCode">The type code.</param> public void DefineColumn(string key, TypeCode typeCode) { DefineColumn(key, new TableColumn(typeCode)); } /// <summary> /// Defines the column. /// </summary> /// <param name="key">The key.</param> /// <param name="tableColumn">The table column.</param> public void DefineColumn(string key, TableColumn tableColumn) { if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key"); if (_hash.ContainsKey(key)) throw new ArgumentException("Core_.Local.RedefineTableColumn", "key"); _hash.Add(key, tableColumn); } /// <summary> /// Sets the underlying List instance containing the list of storeValueIsExpression keys to the string array provided. /// </summary> /// <param name="commitExpressionArray">The row version array.</param> public void DefineCommitExpression(params string[] commitExpressions) { DefineCommitExpression(new List<string>(commitExpressions)); } /// <summary> /// Sets the underlying List instance containing the list of storeValueIsExpression keys to the string array provided. /// </summary> /// <param name="commitExpressionList">The row version list.</param> public void DefineCommitExpression(List<string> commitExpressions) { if (_commitExpressionList == null) _commitExpressionList = commitExpressions; else _commitExpressionList.AddRange(commitExpressions); //if (_commitExpressionList != null) // throw new ArgumentException(Core_.Local.RedefineCalculatedValue, "commitExpressionList"); _commitExpressionList = commitExpressions; foreach (string commitExpression in commitExpressions) this[commitExpression].ColumnFlag |= TableColumnFlag.CommitExpression; } /// <summary> /// Sets the underlying List instance containing the list of primary keys to the string array provided. /// </summary> /// <param name="primaryKeyArray">The primary key array.</param> public void DefinePrimaryKey(params string[] primaryKeys) { // parse primarykeyarray Dictionary<string, TableColumnFlag> primaryKeyHash = null; List<string> primaryKeyList = new List<string>(primaryKeys); for (int primaryKeyIndex = 0; primaryKeyIndex < primaryKeyList.Count; primaryKeyIndex++) { string value; string primaryKey = primaryKeyList[primaryKeyIndex].ParseBoundedPrefix("[]", out value); if (value.Length > 0) { var columnFlag = (TableColumnFlag)Enum.Parse(typeof(TableColumnFlag), value); primaryKeyList[primaryKeyIndex] = primaryKey; if (primaryKeyHash == null) primaryKeyHash = new Dictionary<string, TableColumnFlag>(1); primaryKeyHash.Add(primaryKey, columnFlag); } } DefinePrimaryKey(primaryKeyList); // apply primaryKeyHash hash if (primaryKeyHash != null) foreach (string primaryKey in primaryKeyHash.Keys) this[primaryKey].ColumnFlag |= primaryKeyHash[primaryKey]; } /// <summary> /// Sets the underlying List instance containing the list of primary keys to the string array provided. /// </summary> /// <param name="primaryKeyList">The primary key list.</param> public void DefinePrimaryKey(List<string> primaryKeys) { if (_primaryKeys != null) throw new ArgumentException("Core_.Local.RedefinePrimaryKey", "primaryKeyList"); _primaryKeys = primaryKeys; foreach (string primaryKey in _primaryKeys) this[primaryKey].ColumnFlag |= TableColumnFlag.PrimaryKey; } /// <summary> /// Sets the underlying List instance containing the list of rowverison keys to the string array provided. /// </summary> /// <param name="rowVersionArray">The row version array.</param> public void DefineRowVersion(params string[] rowVersions) { DefineRowVersion(new List<string>(rowVersions)); } /// <summary> /// Sets the underlying List instance containing the list of row version keys to the string array provided. /// </summary> /// <param name="rowVersionList">The row version list.</param> public void DefineRowVersion(List<string> rowVersions) { if (_rowVersions != null) throw new ArgumentException("Core_.Local.RedefineRowVersion", "rowVersionList"); _rowVersions = rowVersions; foreach (string rowVersion in _rowVersions) this[rowVersion].ColumnFlag |= TableColumnFlag.RowVersion; } /// <summary> /// Determines whether the item in collection with specified key exists. /// </summary> /// <param name="key">The key to check.</param> /// <returns> /// <c>true</c> if the specified item exists; otherwise, <c>false</c>. /// </returns> public bool ContainsKey(string key) { return _hash.ContainsKey(key); } /// <summary> /// Resets the underlying primary key hash instance. /// </summary> public void PreUpdate() { //+ create default primary key if none specified if ((_primaryKeys == null) || (_primaryKeys.Count == 0)) { List<string> primaryKeys = new List<string>(1); primaryKeys.Add("Key"); DefinePrimaryKey(primaryKeys); this["Key"].ColumnFlag |= TableColumnFlag.IdentityPrimaryKey; } } /// <summary> /// Gets the primary key list. /// </summary> /// <value>The primary key list.</value> public List<string> PrimaryKeys { get { return _primaryKeys; } } /// <summary> /// Removes the item with the specified key. /// </summary> /// <param name="key">The key to use.</param> /// <returns></returns> public bool Remove(string key) { return _hash.Remove(key); } /// <summary> /// Gets the row version list. /// </summary> /// <value>The row version list.</value> public List<string> RowVersions { get { return _rowVersions; } } /// <summary> /// Return an instance of <see cref="System.Collections.Generic.ICollection{string}"/> representing the collection of /// keys in the indexed collection. /// </summary> /// <value> /// The <see cref="System.Collections.Generic.ICollection{string}"/> instance containing the collection of keys. /// </value> public ICollection<string> Keys { get { return _hash.Keys; } } /// <summary> /// Return an instance of <see cref="System.Collections.Generic.ICollection{TableField}"/> representing the collection of /// values in the indexed collection. /// </summary> /// <value> /// The <see cref="System.Collections.Generic.ICollection{TableField}"/> instance containing the collection of values. /// </value> public ICollection<TableColumn> Values { get { return _hash.Values; } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Orleans; using Orleans.Runtime; using TestExtensions; using TestGrainInterfaces; using UnitTests.GrainInterfaces; using Xunit; namespace DefaultCluster.Tests.General { /// <summary> /// Unit tests for grains implementing generic interfaces /// </summary> public class GenericGrainTests : HostedTestClusterEnsureDefaultStarted { private static int grainId = 0; public GenericGrainTests(DefaultClusterFixture fixture) : base(fixture) { } public TGrainInterface GetGrain<TGrainInterface>(long i) where TGrainInterface : IGrainWithIntegerKey { return this.GrainFactory.GetGrain<TGrainInterface>(i); } public TGrainInterface GetGrain<TGrainInterface>() where TGrainInterface : IGrainWithIntegerKey { return this.GrainFactory.GetGrain<TGrainInterface>(GetRandomGrainId()); } /// Can instantiate multiple concrete grain types that implement /// different specializations of the same generic interface [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_ConcreteGrainWithGenericInterfaceGetGrain() { var grainOfIntFloat1 = GetGrain<IGenericGrain<int, float>>(); var grainOfIntFloat2 = GetGrain<IGenericGrain<int, float>>(); var grainOfFloatString = GetGrain<IGenericGrain<float, string>>(); await grainOfIntFloat1.SetT(123); await grainOfIntFloat2.SetT(456); await grainOfFloatString.SetT(789.0f); var floatResult1 = await grainOfIntFloat1.MapT2U(); var floatResult2 = await grainOfIntFloat2.MapT2U(); var stringResult = await grainOfFloatString.MapT2U(); Assert.Equal(123f, floatResult1); Assert.Equal(456f, floatResult2); Assert.Equal("789", stringResult); } /// Multiple GetGrain requests with the same id return the same concrete grain [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_ConcreteGrainWithGenericInterfaceMultiplicity() { var grainId = GetRandomGrainId(); var grainRef1 = GetGrain<IGenericGrain<int, float>>(grainId); await grainRef1.SetT(123); var grainRef2 = GetGrain<IGenericGrain<int, float>>(grainId); var floatResult = await grainRef2.MapT2U(); Assert.Equal(123f, floatResult); } /// Can instantiate generic grain specializations [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_SimpleGenericGrainGetGrain() { var grainOfFloat1 = GetGrain<ISimpleGenericGrain<float>>(); var grainOfFloat2 = GetGrain<ISimpleGenericGrain<float>>(); var grainOfString = GetGrain<ISimpleGenericGrain<string>>(); await grainOfFloat1.Set(1.2f); await grainOfFloat2.Set(3.4f); await grainOfString.Set("5.6"); // generic grain implementation does not change the set value: await grainOfFloat1.Transform(); await grainOfFloat2.Transform(); await grainOfString.Transform(); var floatResult1 = await grainOfFloat1.Get(); var floatResult2 = await grainOfFloat2.Get(); var stringResult = await grainOfString.Get(); Assert.Equal(1.2f, floatResult1); Assert.Equal(3.4f, floatResult2); Assert.Equal("5.6", stringResult); } /// Can instantiate grains that implement generic interfaces with generic type parameters [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_GenericInterfaceWithGenericParametersGetGrain() { var grain = GetGrain<ISimpleGenericGrain<List<float>>>(); var list = new List<float>(); list.Add(0.1f); await grain.Set(list); var result = await grain.Get(); Assert.Single(result); Assert.Equal(0.1f, result[0]); } /// Multiple GetGrain requests with the same id return the same generic grain specialization [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_SimpleGenericGrainMultiplicity() { var grainId = GetRandomGrainId(); var grainRef1 = GetGrain<ISimpleGenericGrain<float>>(grainId); await grainRef1.Set(1.2f); await grainRef1.Transform(); // NOP for generic grain class var grainRef2 = GetGrain<ISimpleGenericGrain<float>>(grainId); var floatResult = await grainRef2.Get(); Assert.Equal(1.2f, floatResult); } /// If both a concrete implementation and a generic implementation of a /// generic interface exist, prefer the concrete implementation. [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_PreferConcreteGrainImplementationOfGenericInterface() { var grainOfDouble1 = GetGrain<ISimpleGenericGrain<double>>(); var grainOfDouble2 = GetGrain<ISimpleGenericGrain<double>>(); await grainOfDouble1.Set(1.0); await grainOfDouble2.Set(2.0); // concrete implementation (SpecializedSimpleGenericGrain) doubles the set value: await grainOfDouble1.Transform(); await grainOfDouble2.Transform(); var result1 = await grainOfDouble1.Get(); var result2 = await grainOfDouble2.Get(); Assert.Equal(2.0, result1); Assert.Equal(4.0, result2); } /// Multiple GetGrain requests with the same id return the same concrete grain implementation [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_PreferConcreteGrainImplementationOfGenericInterfaceMultiplicity() { var grainId = GetRandomGrainId(); var grainRef1 = GetGrain<ISimpleGenericGrain<double>>(grainId); await grainRef1.Set(1.0); await grainRef1.Transform(); // SpecializedSimpleGenericGrain doubles the value for generic grain class // a second reference with the same id points to the same grain: var grainRef2 = GetGrain<ISimpleGenericGrain<double>>(grainId); await grainRef2.Transform(); var floatResult = await grainRef2.Get(); Assert.Equal(4.0f, floatResult); } /// Can instantiate concrete grains that implement multiple generic interfaces [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_ConcreteGrainWithMultipleGenericInterfacesGetGrain() { var grain1 = GetGrain<ISimpleGenericGrain<int>>(); var grain2 = GetGrain<ISimpleGenericGrain<int>>(); await grain1.Set(1); await grain2.Set(2); // ConcreteGrainWith2GenericInterfaces multiplies the set value by 10: await grain1.Transform(); await grain2.Transform(); var result1 = await grain1.Get(); var result2 = await grain2.Get(); Assert.Equal(10, result1); Assert.Equal(20, result2); } /// Multiple GetGrain requests with the same id and interface return the same concrete grain implementation [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_ConcreteGrainWithMultipleGenericInterfacesMultiplicity1() { var grainId = GetRandomGrainId(); var grainRef1 = GetGrain<ISimpleGenericGrain<int>>(grainId); await grainRef1.Set(1); // ConcreteGrainWith2GenericInterfaces multiplies the set value by 10: await grainRef1.Transform(); //A second reference to the interface will point to the same grain var grainRef2 = GetGrain<ISimpleGenericGrain<int>>(grainId); await grainRef2.Transform(); var floatResult = await grainRef2.Get(); Assert.Equal(100, floatResult); } /// Multiple GetGrain requests with the same id and different interfaces return the same concrete grain implementation [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_ConcreteGrainWithMultipleGenericInterfacesMultiplicity2() { var grainId = GetRandomGrainId(); var grainRef1 = GetGrain<ISimpleGenericGrain<int>>(grainId); await grainRef1.Set(1); await grainRef1.Transform(); // ConcreteGrainWith2GenericInterfaces multiplies the set value by 10: // A second reference to a different interface implemented by ConcreteGrainWith2GenericInterfaces // will reference the same grain: var grainRef2 = GetGrain<IGenericGrain<int, string>>(grainId); // ConcreteGrainWith2GenericInterfaces returns a string representation of the current value multiplied by 10: var floatResult = await grainRef2.MapT2U(); Assert.Equal("100", floatResult); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainTests_UseGenericFactoryInsideGrain() { var grainId = GetRandomGrainId(); var grainRef1 = GetGrain<ISimpleGenericGrain<string>>(grainId); await grainRef1.Set("JustString"); await grainRef1.CompareGrainReferences(grainRef1); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_SimpleGrain_GetGrain() { var grain = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++); await grain.GetA(); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_SimpleGrainControlFlow() { var a = random.Next(100); var b = a + 1; var expected = a + "x" + b; var grain = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++); await grain.SetA(a); await grain.SetB(b); Task<string> stringPromise = grain.GetAxB(); Assert.Equal(expected, stringPromise.Result); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public void Generic_SimpleGrainControlFlow_Blocking() { var a = random.Next(100); var b = a + 1; var expected = a + "x" + b; var grain = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++); // explicitly use .Wait() and .Result to make sure the client does not deadlock in these cases. grain.SetA(a).Wait(); grain.SetB(b).Wait(); Task<string> stringPromise = grain.GetAxB(); Assert.Equal(expected, stringPromise.Result); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_SimpleGrainDataFlow() { var a = random.Next(100); var b = a + 1; var expected = a + "x" + b; var grain = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++); var setAPromise = grain.SetA(a); var setBPromise = grain.SetB(b); var stringPromise = Task.WhenAll(setAPromise, setBPromise).ContinueWith((_) => grain.GetAxB()).Unwrap(); var x = await stringPromise; Assert.Equal(expected, x); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_SimpleGrain2_GetGrain() { var g1 = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++); var g2 = this.GrainFactory.GetGrain<ISimpleGenericGrainU<int>>(grainId++); var g3 = this.GrainFactory.GetGrain<ISimpleGenericGrain2<int, int>>(grainId++); await g1.GetA(); await g2.GetA(); await g3.GetA(); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_SimpleGrainGenericParameterWithMultipleArguments_GetGrain() { var g1 = this.GrainFactory.GetGrain<ISimpleGenericGrain1<Dictionary<int, int>>>(GetRandomGrainId()); await g1.GetA(); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_SimpleGrainControlFlow2_GetAB() { var a = random.Next(100); var b = a + 1; var expected = a + "x" + b; var g1 = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++); var g2 = this.GrainFactory.GetGrain<ISimpleGenericGrainU<int>>(grainId++); var g3 = this.GrainFactory.GetGrain<ISimpleGenericGrain2<int, int>>(grainId++); string r1 = await g1.GetAxB(a, b); string r2 = await g2.GetAxB(a, b); string r3 = await g3.GetAxB(a, b); Assert.Equal(expected, r1); Assert.Equal(expected, r2); Assert.Equal(expected, r3); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_SimpleGrainControlFlow3() { ISimpleGenericGrain2<int, float> g = this.GrainFactory.GetGrain<ISimpleGenericGrain2<int, float>>(grainId++); await g.SetA(3); await g.SetB(1.25f); Assert.Equal("3x1.25", await g.GetAxB()); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_BasicGrainControlFlow() { IBasicGenericGrain<int, float> g = this.GrainFactory.GetGrain<IBasicGenericGrain<int, float>>(0); await g.SetA(3); await g.SetB(1.25f); Assert.Equal("3x1.25", await g.GetAxB()); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GrainWithListFields() { string a = random.Next(100).ToString(CultureInfo.InvariantCulture); string b = random.Next(100).ToString(CultureInfo.InvariantCulture); var g1 = this.GrainFactory.GetGrain<IGrainWithListFields>(grainId++); var p1 = g1.AddItem(a); var p2 = g1.AddItem(b); await Task.WhenAll(p1, p2); var r1 = await g1.GetItems(); Assert.True( (a == r1[0] && b == r1[1]) || (b == r1[0] && a == r1[1]), // Message ordering was not necessarily preserved. string.Format("Result: r[0]={0}, r[1]={1}", r1[0], r1[1])); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_GrainWithListFields() { int a = random.Next(100); int b = random.Next(100); var g1 = this.GrainFactory.GetGrain<IGenericGrainWithListFields<int>>(grainId++); var p1 = g1.AddItem(a); var p2 = g1.AddItem(b); await Task.WhenAll(p1, p2); var r1 = await g1.GetItems(); Assert.True( (a == r1[0] && b == r1[1]) || (b == r1[0] && a == r1[1]), // Message ordering was not necessarily preserved. string.Format("Result: r[0]={0}, r[1]={1}", r1[0], r1[1])); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_GrainWithNoProperties_ControlFlow() { int a = random.Next(100); int b = random.Next(100); string expected = a + "x" + b; var g1 = this.GrainFactory.GetGrain<IGenericGrainWithNoProperties<int>>(grainId++); string r1 = await g1.GetAxB(a, b); Assert.Equal(expected, r1); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GrainWithNoProperties_ControlFlow() { int a = random.Next(100); int b = random.Next(100); string expected = a + "x" + b; long grainId = GetRandomGrainId(); var g1 = this.GrainFactory.GetGrain<IGrainWithNoProperties>(grainId); string r1 = await g1.GetAxB(a, b); Assert.Equal(expected, r1); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_ReaderWriterGrain1() { int a = random.Next(100); var g = this.GrainFactory.GetGrain<IGenericReaderWriterGrain1<int>>(grainId++); await g.SetValue(a); var res = await g.GetValue(); Assert.Equal(a, res); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_ReaderWriterGrain2() { int a = random.Next(100); string b = "bbbbb"; var g = this.GrainFactory.GetGrain<IGenericReaderWriterGrain2<int, string>>(grainId++); await g.SetValue1(a); await g.SetValue2(b); var r1 = await g.GetValue1(); Assert.Equal(a, r1); var r2 = await g.GetValue2(); Assert.Equal(b, r2); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_ReaderWriterGrain3() { int a = random.Next(100); string b = "bbbbb"; double c = 3.145; var g = this.GrainFactory.GetGrain<IGenericReaderWriterGrain3<int, string, double>>(grainId++); await g.SetValue1(a); await g.SetValue2(b); await g.SetValue3(c); var r1 = await g.GetValue1(); Assert.Equal(a, r1); var r2 = await g.GetValue2(); Assert.Equal(b, r2); var r3 = await g.GetValue3(); Assert.Equal(c, r3); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_Non_Primitive_Type_Argument() { IEchoHubGrain<Guid, string> g1 = this.GrainFactory.GetGrain<IEchoHubGrain<Guid, string>>(1); IEchoHubGrain<Guid, int> g2 = this.GrainFactory.GetGrain<IEchoHubGrain<Guid, int>>(1); IEchoHubGrain<Guid, byte[]> g3 = this.GrainFactory.GetGrain<IEchoHubGrain<Guid, byte[]>>(1); Assert.NotEqual((GrainReference)g1, (GrainReference)g2); Assert.NotEqual((GrainReference)g1, (GrainReference)g3); Assert.NotEqual((GrainReference)g2, (GrainReference)g3); await g1.Foo(Guid.Empty, "", 1); await g2.Foo(Guid.Empty, 0, 2); await g3.Foo(Guid.Empty, new byte[] { }, 3); Assert.Equal(1, await g1.GetX()); Assert.Equal(2, await g2.GetX()); Assert.Equal(3m, await g3.GetX()); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_Echo_Chain_1() { const string msg1 = "Hello from EchoGenericChainGrain-1"; IEchoGenericChainGrain<string> g1 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId()); string received = await g1.Echo(msg1); Assert.Equal(msg1, received); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_Echo_Chain_2() { const string msg2 = "Hello from EchoGenericChainGrain-2"; IEchoGenericChainGrain<string> g2 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId()); string received = await g2.Echo2(msg2); Assert.Equal(msg2, received); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_Echo_Chain_3() { const string msg3 = "Hello from EchoGenericChainGrain-3"; IEchoGenericChainGrain<string> g3 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId()); string received = await g3.Echo3(msg3); Assert.Equal(msg3, received); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_Echo_Chain_4() { const string msg4 = "Hello from EchoGenericChainGrain-4"; var g4 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId()); string received = await g4.Echo4(msg4); Assert.Equal(msg4, received); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_Echo_Chain_5() { const string msg5 = "Hello from EchoGenericChainGrain-5"; var g5 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId()); string received = await g5.Echo5(msg5); Assert.Equal(msg5, received); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_Echo_Chain_6() { const string msg6 = "Hello from EchoGenericChainGrain-6"; var g6 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId()); string received = await g6.Echo6(msg6); Assert.Equal(msg6, received); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_1Argument_GenericCallOnly() { var grain = this.GrainFactory.GetGrain<IGeneric1Argument<string>>(Guid.NewGuid(), "UnitTests.Grains.Generic1ArgumentGrain"); var s1 = Guid.NewGuid().ToString(); var s2 = await grain.Ping(s1); Assert.Equal(s1, s2); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_1Argument_NonGenericCallFirst() { var id = Guid.NewGuid(); var nonGenericFacet = this.GrainFactory.GetGrain<INonGenericBase>(id, "UnitTests.Grains.Generic1ArgumentGrain"); await Assert.ThrowsAsync<OrleansException>(async () => { try { await nonGenericFacet.Ping(); } catch (AggregateException exc) { throw exc.GetBaseException(); } }); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_1Argument_GenericCallFirst() { var id = Guid.NewGuid(); var grain = this.GrainFactory.GetGrain<IGeneric1Argument<string>>(id, "UnitTests.Grains.Generic1ArgumentGrain"); var s1 = Guid.NewGuid().ToString(); var s2 = await grain.Ping(s1); Assert.Equal(s1, s2); var nonGenericFacet = this.GrainFactory.GetGrain<INonGenericBase>(id, "UnitTests.Grains.Generic1ArgumentGrain"); await Assert.ThrowsAsync<OrleansException>(async () => { try { await nonGenericFacet.Ping(); } catch (AggregateException exc) { throw exc.GetBaseException(); } }); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task DifferentTypeArgsProduceIndependentActivations() { var grain1 = this.GrainFactory.GetGrain<IDbGrain<int>>(0); await grain1.SetValue(123); var grain2 = this.GrainFactory.GetGrain<IDbGrain<string>>(0); var v = await grain2.GetValue(); Assert.Null(v); } [Fact, TestCategory("BVT"), TestCategory("Generics"), TestCategory("Echo")] public async Task Generic_PingSelf() { var id = Guid.NewGuid(); var grain = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(id); var s1 = Guid.NewGuid().ToString(); var s2 = await grain.PingSelf(s1); Assert.Equal(s1, s2); } [Fact, TestCategory("BVT"), TestCategory("Generics"), TestCategory("Echo")] public async Task Generic_PingOther() { var id = Guid.NewGuid(); var targetId = Guid.NewGuid(); var grain = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(id); var target = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId); var s1 = Guid.NewGuid().ToString(); var s2 = await grain.PingOther(target, s1); Assert.Equal(s1, s2); } [Fact, TestCategory("BVT"), TestCategory("Generics"), TestCategory("Echo")] public async Task Generic_PingSelfThroughOther() { var id = Guid.NewGuid(); var targetId = Guid.NewGuid(); var grain = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(id); var target = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId); var s1 = Guid.NewGuid().ToString(); var s2 = await grain.PingSelfThroughOther(target, s1); Assert.Equal(s1, s2); } [Fact, TestCategory("BVT"), TestCategory("Generics"), TestCategory("ActivateDeactivate")] public async Task Generic_ScheduleDelayedPingAndDeactivate() { var id = Guid.NewGuid(); var targetId = Guid.NewGuid(); var grain = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(id); var target = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId); var s1 = Guid.NewGuid().ToString(); await grain.ScheduleDelayedPingToSelfAndDeactivate(target, s1, TimeSpan.FromSeconds(5)); await Task.Delay(TimeSpan.FromSeconds(6)); var s2 = await grain.GetLastValue(); Assert.Equal(s1, s2); } [Fact, TestCategory("BVT"), TestCategory("Generics"), TestCategory("Serialization")] public async Task SerializationTests_Generic_CircularReferenceTest() { var grainId = Guid.NewGuid(); var grain = this.GrainFactory.GetGrain<ICircularStateTestGrain>(primaryKey: grainId, keyExtension: grainId.ToString("N")); var c1 = await grain.GetState(); } [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task Generic_GrainWithTypeConstraints() { var grainId = Guid.NewGuid().ToString(); var grain = this.GrainFactory.GetGrain<IGenericGrainWithConstraints<List<int>, int, string>>(grainId); var result = await grain.GetCount(); Assert.Equal(0, result); await grain.Add(42); result = await grain.GetCount(); Assert.Equal(1, result); } [Fact, TestCategory("BVT"), TestCategory("Persistence")] public async Task Generic_GrainWithValueTypeState() { Guid id = Guid.NewGuid(); var grain = this.GrainFactory.GetGrain<IValueTypeTestGrain>(id); var initial = await grain.GetStateData(); Assert.Equal(new ValueTypeTestData(0), initial); var expectedValue = new ValueTypeTestData(42); await grain.SetStateData(expectedValue); Assert.Equal(expectedValue, await grain.GetStateData()); } [Fact(Skip = "https://github.com/dotnet/orleans/issues/1655 Casting from non-generic to generic interface fails with an obscure error message"), TestCategory("Functional"), TestCategory("Cast"), TestCategory("Generics")] public async Task Generic_CastToGenericInterfaceAfterActivation() { var grain = this.GrainFactory.GetGrain<INonGenericCastableGrain>(Guid.NewGuid()); await grain.DoSomething(); //activates original grain type here var castRef = grain.AsReference<ISomeGenericGrain<string>>(); var result = await castRef.Hello(); Assert.Equal("Hello!", result); } [Fact(Skip= "https://github.com/dotnet/orleans/issues/1655 Casting from non-generic to generic interface fails with an obscure error message"), TestCategory("Functional"), TestCategory("Cast"), TestCategory("Generics")] public async Task Generic_CastToDifferentlyConcretizedGenericInterfaceBeforeActivation() { var grain = this.GrainFactory.GetGrain<INonGenericCastableGrain>(Guid.NewGuid()); var castRef = grain.AsReference<IIndependentlyConcretizedGenericGrain<string>>(); var result = await castRef.Hello(); Assert.Equal("Hello!", result); } [Fact, TestCategory("BVT"), TestCategory("Cast")] public async Task Generic_CastToDifferentlyConcretizedInterfaceBeforeActivation() { var grain = this.GrainFactory.GetGrain<INonGenericCastableGrain>(Guid.NewGuid()); var castRef = grain.AsReference<IIndependentlyConcretizedGrain>(); var result = await castRef.Hello(); Assert.Equal("Hello!", result); } [Fact, TestCategory("BVT"), TestCategory("Cast"), TestCategory("Generics")] public async Task Generic_CastGenericInterfaceToNonGenericInterfaceBeforeActivation() { var grain = this.GrainFactory.GetGrain<IGenericCastableGrain<string>>(Guid.NewGuid()); var castRef = grain.AsReference<INonGenericCastGrain>(); var result = await castRef.Hello(); Assert.Equal("Hello!", result); } /// <summary> /// Tests that generic grains can have generic state and that the parameters to the Grain{TState} /// class do not have to match the parameters to the grain class itself. /// </summary> /// <returns></returns> [Fact, TestCategory("BVT"), TestCategory("Generics")] public async Task GenericGrainStateParameterMismatchTest() { var grain = this.GrainFactory.GetGrain<IGenericGrainWithGenericState<int, List<Guid>, string>>(Guid.NewGuid()); var result = await grain.GetStateType(); Assert.Equal(typeof(List<Guid>), result); } } namespace Generic.EdgeCases { using UnitTests.GrainInterfaces.Generic.EdgeCases; public class GenericEdgeCaseTests : HostedTestClusterEnsureDefaultStarted { public GenericEdgeCaseTests(DefaultClusterFixture fixture) : base(fixture) { } static async Task<Type[]> GetConcreteGenArgs(IBasicGrain @this) { var genArgTypeNames = await @this.ConcreteGenArgTypeNames(); return genArgTypeNames.Select(n => Type.GetType(n)) .ToArray(); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_PartiallySpecifyingGenericGrainFulfilsInterface() { var grain = this.GrainFactory.GetGrain<IGrainWithTwoGenArgs<string, int>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(new[] { typeof(int) }) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_GenericGrainCanReuseOwnGenArgRepeatedly() { //resolves correctly but can't be activated: too many gen args supplied for concrete class var grain = this.GrainFactory.GetGrain<IGrainReceivingRepeatedGenArgs<int, int>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(new[] { typeof(int) }) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_PartiallySpecifyingGenericInterfaceIsCastable() { var grain = this.GrainFactory.GetGrain<IPartiallySpecifyingInterface<string>>(Guid.NewGuid()); await grain.Hello(); var castRef = grain.AsReference<IGrainWithTwoGenArgs<string, int>>(); var response = await castRef.Hello(); Assert.Equal("Hello!", response); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_PartiallySpecifyingGenericInterfaceIsCastable_Activating() { var grain = this.GrainFactory.GetGrain<IPartiallySpecifyingInterface<string>>(Guid.NewGuid()); var castRef = grain.AsReference<IGrainWithTwoGenArgs<string, int>>(); var response = await castRef.Hello(); Assert.Equal("Hello!", response); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RepeatedRearrangedGenArgsResolved() { //again resolves to the correct generic type definition, but fails on activation as too many args //gen args aren't being properly inferred from matched concrete type var grain = this.GrainFactory.GetGrain<IReceivingRepeatedGenArgsAmongstOthers<int, string, int>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(new[] { typeof(string), typeof(int) }) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RepeatedGenArgsWorkAmongstInterfacesInTypeResolution() { var grain = this.GrainFactory.GetGrain<IReceivingRepeatedGenArgsFromOtherInterface<bool, bool, bool>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(Enumerable.Empty<Type>()) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RepeatedGenArgsWorkAmongstInterfacesInCasting() { var grain = this.GrainFactory.GetGrain<IReceivingRepeatedGenArgsFromOtherInterface<bool, bool, bool>>(Guid.NewGuid()); await grain.Hello(); var castRef = grain.AsReference<ISpecifyingGenArgsRepeatedlyToParentInterface<bool>>(); var response = await castRef.Hello(); Assert.Equal("Hello!", response); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RepeatedGenArgsWorkAmongstInterfacesInCasting_Activating() { //Only errors on invocation: wrong arity again var grain = this.GrainFactory.GetGrain<IReceivingRepeatedGenArgsFromOtherInterface<bool, bool, bool>>(Guid.NewGuid()); var castRef = grain.AsReference<ISpecifyingGenArgsRepeatedlyToParentInterface<bool>>(); var response = await castRef.Hello(); Assert.Equal("Hello!", response); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RearrangedGenArgsOfCorrectArityAreResolved() { var grain = this.GrainFactory.GetGrain<IReceivingRearrangedGenArgs<int, long>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(new[] { typeof(long), typeof(int) }) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RearrangedGenArgsOfCorrectNumberAreCastable() { var grain = this.GrainFactory.GetGrain<ISpecifyingRearrangedGenArgsToParentInterface<int, long>>(Guid.NewGuid()); await grain.Hello(); var castRef = grain.AsReference<IReceivingRearrangedGenArgsViaCast<long, int>>(); var response = await castRef.Hello(); Assert.Equal("Hello!", response); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_RearrangedGenArgsOfCorrectNumberAreCastable_Activating() { var grain = this.GrainFactory.GetGrain<ISpecifyingRearrangedGenArgsToParentInterface<int, long>>(Guid.NewGuid()); var castRef = grain.AsReference<IReceivingRearrangedGenArgsViaCast<long, int>>(); var response = await castRef.Hello(); Assert.Equal("Hello!", response); } //************************************************************************************************************** //************************************************************************************************************** //Below must be commented out, as supplying multiple fully-specified generic interfaces //to a class causes the codegen to fall over, stopping all other tests from working. //See new test here of the bit causing the issue - type info conflation: //UnitTests.CodeGeneration.CodeGeneratorTests.CodeGen_EncounteredFullySpecifiedInterfacesAreEncodedDistinctly() //public interface IFullySpecifiedGenericInterface<T> : IBasicGrain //{ } //public interface IDerivedFromMultipleSpecializationsOfSameInterface : IFullySpecifiedGenericInterface<int>, IFullySpecifiedGenericInterface<long> //{ } //public class GrainFulfillingMultipleSpecializationsOfSameInterfaceViaIntermediate : BasicGrain, IDerivedFromMultipleSpecializationsOfSameInterface //{ } //[Fact, TestCategory("Generics")] //public async Task CastingBetweenFullySpecifiedGenericInterfaces() //{ // //Is this legitimate? Solely in the realm of virtual grain interfaces - no special knowledge of implementation implicated, only of interface hierarchy // //codegen falling over: duplicate key when both specializations are matched to same concrete type // var grain = this.GrainFactory.GetGrain<IDerivedFromMultipleSpecializationsOfSameInterface>(Guid.NewGuid()); // await grain.Hello(); // var castRef = grain.AsReference<IFullySpecifiedGenericInterface<int>>(); // await castRef.Hello(); // var castRef2 = castRef.AsReference<IFullySpecifiedGenericInterface<long>>(); // await castRef2.Hello(); //} //******************************************************************************************************* [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_CanCastToFullySpecifiedInterfaceUnrelatedToConcreteGenArgs() { var grain = this.GrainFactory.GetGrain<IArbitraryInterface<int, long>>(Guid.NewGuid()); await grain.Hello(); var castRef = grain.AsReference<IInterfaceUnrelatedToConcreteGenArgs<float>>(); var response = await grain.Hello(); Assert.Equal("Hello!", response); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_CanCastToFullySpecifiedInterfaceUnrelatedToConcreteGenArgs_Activating() { var grain = this.GrainFactory.GetGrain<IArbitraryInterface<int, long>>(Guid.NewGuid()); var castRef = grain.AsReference<IInterfaceUnrelatedToConcreteGenArgs<float>>(); var response = await grain.Hello(); Assert.Equal("Hello!", response); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_GenArgsCanBeFurtherSpecialized() { var grain = this.GrainFactory.GetGrain<IInterfaceTakingFurtherSpecializedGenArg<List<int>>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(new[] { typeof(int) }) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_GenArgsCanBeFurtherSpecializedIntoArrays() { var grain = this.GrainFactory.GetGrain<IInterfaceTakingFurtherSpecializedGenArg<long[]>>(Guid.NewGuid()); var concreteGenArgs = await GetConcreteGenArgs(grain); Assert.True( concreteGenArgs.SequenceEqual(new[] { typeof(long) }) ); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_CanCastBetweenInterfacesWithFurtherSpecializedGenArgs() { var grain = this.GrainFactory.GetGrain<IAnotherReceivingFurtherSpecializedGenArg<List<int>>>(Guid.NewGuid()); await grain.Hello(); var castRef = grain.AsReference<IYetOneMoreReceivingFurtherSpecializedGenArg<int[]>>(); var response = await grain.Hello(); Assert.Equal("Hello!", response); } [Fact(Skip = "Currently unsupported"), TestCategory("Generics")] public async Task Generic_CanCastBetweenInterfacesWithFurtherSpecializedGenArgs_Activating() { var grain = this.GrainFactory.GetGrain<IAnotherReceivingFurtherSpecializedGenArg<List<int>>>(Guid.NewGuid()); var castRef = grain.AsReference<IYetOneMoreReceivingFurtherSpecializedGenArg<int[]>>(); var response = await grain.Hello(); Assert.Equal("Hello!", response); } } } }
#if UNITY_EDITOR using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Text; using TNRD.Automatron.Editor.Core; using UnityEditor; using UnityEngine; namespace TNRD.Automatron.Generation { public class WizardData { public Type Type; public string Name; public Dictionary<FieldInfo, bool> Fields; public Dictionary<PropertyInfo, bool> Properties; public Dictionary<MethodInfo, bool> Methods; } public class GenerationData { public Type Type; public List<MethodInfo> Methods; public List<PropertyInfo> Properties; public List<FieldInfo> Fields; } public static class DictExt { public static Dictionary<T, T2> AddRange<T, T2>( this Dictionary<T, T2> dict, IEnumerable<KeyValuePair<T, T2>> values ) { foreach ( var item in values ) { dict.Add( item.Key, item.Value ); } return dict; } } public class GeneratorWizard : ScriptableWizard { public static void Init( List<WizardData> datas ) { var wiz = DisplayWizard<GeneratorWizard>( "Select Members", "Generate", "Cancel" ); wiz.minSize = new Vector2( 720, 480 ); wiz.datas = datas; wiz.Folds(); } private List<WizardData> datas; private int index = 0; private bool foldFields = true; private bool foldProperties = true; private bool foldMethods = true; private Vector2 fieldScroll = new Vector2(); private Vector2 propertyScroll = new Vector2(); private Vector2 methodScroll = new Vector2(); private void Folds() { foldFields = datas[index].Fields.Count > 0; foldProperties = datas[index].Properties.Count > 0; foldMethods = datas[index].Methods.Count > 0; } protected override bool DrawWizardGUI() { if ( GUILayout.Button( "Generate All" ) ) { foreach ( var item in datas ) { { var keys = item.Fields.Keys; for ( int i = keys.Count() - 1; i >= 0; i-- ) { var key = keys.ElementAt( i ); item.Fields[key] = true; } } { var keys = item.Properties.Keys; for ( int i = keys.Count() - 1; i >= 0; i-- ) { var key = keys.ElementAt( i ); item.Properties[key] = true; } } { var keys = item.Methods.Keys; for ( int i = keys.Count() - 1; i >= 0; i-- ) { var key = keys.ElementAt( i ); item.Methods[key] = true; } } } OnWizardCreate(); Close(); } EditorGUILayout.Space(); EditorGUILayout.Space(); var data = datas[index]; EditorGUILayout.LabelField( string.Format( "[{0}/{1}] {2}", index + 1, datas.Count, data.Name ) ); var fieldHeight = position.height; var propertyHeight = position.height; var methodHeight = position.height; var allOpen = foldFields && foldProperties && foldMethods; if ( allOpen ) { fieldHeight /= 3; propertyHeight /= 3; methodHeight /= 3; } else { if ( foldFields ) { if ( foldMethods || foldProperties ) { fieldHeight /= 2; } } if ( foldProperties ) { if ( foldFields || foldMethods ) { propertyHeight /= 2; } } if ( foldMethods ) { if ( foldFields || foldProperties ) { methodHeight /= 2; } } } foldFields = EditorGUILayout.Foldout( foldFields, "Fields" ); if ( foldFields ) { if ( GUILayout.Button( "Toggle" ) ) { var fs = new Dictionary<FieldInfo, bool>( data.Fields ); foreach ( var item in data.Fields ) { var k = item.Key; var v = item.Value; fs[k] = !v; } data.Fields = fs; } fieldScroll = EditorGUILayout.BeginScrollView( fieldScroll, ExtendedGUI.DarkNoneWindowStyle, GUILayout.MinHeight( 16 ), GUILayout.MaxHeight( fieldHeight ), GUILayout.ExpandHeight( true ) ); EditorGUI.indentLevel++; var fields = new Dictionary<FieldInfo, bool>( data.Fields ); foreach ( var item in data.Fields ) { var k = item.Key; var v = item.Value; v = EditorGUILayout.ToggleLeft( string.Format( "[{0}]\t{1} {2}", k.IsStatic ? "Static" : "Instance", Utils.GetTypeName( k.FieldType, false ), k.Name ), v ); fields[k] = v; } data.Fields = fields; EditorGUI.indentLevel--; EditorGUILayout.EndScrollView(); } foldProperties = EditorGUILayout.Foldout( foldProperties, "Properties" ); if ( foldProperties ) { if ( GUILayout.Button( "Toggle" ) ) { var ps = new Dictionary<PropertyInfo, bool>( data.Properties ); foreach ( var item in data.Properties ) { var k = item.Key; var v = item.Value; ps[k] = !v; } data.Properties = ps; } propertyScroll = EditorGUILayout.BeginScrollView( propertyScroll, ExtendedGUI.DarkNoneWindowStyle, GUILayout.MinHeight( 16 ), GUILayout.MaxHeight( propertyHeight ), GUILayout.ExpandHeight( true ) ); var props = new Dictionary<PropertyInfo, bool>( data.Properties ); foreach ( var item in data.Properties ) { var k = item.Key; var v = item.Value; var s = false; try { k.GetValue( null, null ); s = true; } catch ( Exception ) { } v = EditorGUILayout.ToggleLeft( string.Format( "[{0}]\t{1} {2}", s ? "Static" : "Instance", Utils.GetTypeName( k.PropertyType, false ), k.Name ), v ); props[k] = v; } data.Properties = props; EditorGUILayout.EndScrollView(); } foldMethods = EditorGUILayout.Foldout( foldMethods, "Methods" ); if ( foldMethods ) { if ( GUILayout.Button( "Toggle" ) ) { var ms = new Dictionary<MethodInfo, bool>( data.Methods ); foreach ( var item in data.Methods ) { var k = item.Key; var v = item.Value; ms[k] = !v; } data.Methods = ms; } methodScroll = EditorGUILayout.BeginScrollView( methodScroll, ExtendedGUI.DarkNoneWindowStyle, GUILayout.MinHeight( 16 ), GUILayout.MaxHeight( methodHeight ), GUILayout.ExpandHeight( true ) ); var methods = new Dictionary<MethodInfo, bool>( data.Methods ); foreach ( var item in data.Methods ) { var k = item.Key; var v = item.Value; var n = string.Format( "[{0}]\t{1} {2}(", k.IsStatic ? "Static" : "Instance", Utils.GetTypeName( k.ReturnType, false ), k.Name ); var ps = k.GetParameters(); for ( int i = 0; i < ps.Length; i++ ) { var p = ps[i]; n += string.Format( "{0} {1}", Utils.GetTypeName( p.ParameterType, false ), p.Name ); if ( i < ps.Length - 1 ) n += ","; } n += ")"; v = EditorGUILayout.ToggleLeft( n, v ); methods[k] = v; } data.Methods = methods; EditorGUILayout.EndScrollView(); } var r = EditorGUILayout.GetControlRect(); if ( GUI.Button( new Rect( r.x, r.y, r.width / 2, r.height ), "<" ) ) { index = Mathf.Max( 0, index - 1 ); Folds(); } if ( GUI.Button( new Rect( r.x + r.width / 2, r.y, r.width / 2, r.height ), ">" ) ) { index = Math.Min( index + 1, datas.Count - 1 ); Folds(); } return true; } private void OnWizardOtherButton() { Close(); } void OnWizardCreate() { Generator.Generate( datas.Select( d => new GenerationData() { Type = d.Type, Fields = d.Fields.Where( f => f.Value ).Select( f => f.Key ).ToList(), Properties = d.Properties.Where( p => p.Value ).Select( f => f.Key ).ToList(), Methods = d.Methods.Where( m => m.Value ).Select( f => f.Key ).ToList(), } ).ToList() ); } } public class Generator : EditorWindow { public static void CreateMe() { var inst = GetWindow<Generator>( "Generator" ); inst.minSize = new Vector2( 400, 700 ); inst.maxSize = new Vector2( 700, 1000 ); inst.Show(); } #region Generation public static void Generate( List<GenerationData> dataTypes ) { EditorCoroutine.Start( GenerateAsync( dataTypes ) ); } private static IEnumerator GenerateAsync( List<GenerationData> dataTypes ) { var amountDone = 0; foreach ( var typeData in dataTypes ) { var type = typeData.Type; var methods = typeData.Methods; var properties = typeData.Properties; var fields = typeData.Fields; for ( int i = methods.Count - 1; i >= 0; i-- ) { try { var p = methods[i].GetParameters(); Utils.GetTypeName( methods[i].ReturnType ); foreach ( var item in p ) { Utils.GetTypeName( item.ParameterType ); } } catch ( Exception ) { methods.RemoveAt( i ); } } var skip = true; if ( methods.Count > 0 ) { skip = false; } if ( properties.Count > 0 ) { skip = false; } if ( fields.Count > 0 ) { skip = false; } if ( skip ) { Debug.LogFormat( "Skipping {0}", type.Name ); continue; } var builder = new StringBuilder(); builder.AppendLine( "#if UNITY_EDITOR" ); builder.AppendLine( "using System.Collections;" ); builder.AppendLine( "using TNRD.Automatron;" ); builder.AppendLine( "using TNRD.Automatron.Editor.Serialization;" ); builder.AppendLine(); builder.AppendLine( "#pragma warning disable 0649" ); builder.AppendLine(); WriteFields( type, fields, builder ); WriteProperties( type, properties, builder ); WriteMethods( type, methods, builder ); builder.AppendLine(); builder.AppendLine( "#pragma warning restore 0649" ); builder.AppendLine( "#endif" ); if ( !Directory.Exists( AutomatronSettings.AutomationFolder ) ) Directory.CreateDirectory( AutomatronSettings.AutomationFolder ); var path = Path.Combine( AutomatronSettings.AutomationFolder, type.Name + "Automations.cs" ); Debug.LogFormat( "Writing {0}", type.Name ); File.WriteAllText( path, builder.ToString() ); amountDone++; yield return null; } Debug.Log( "Finished generating" ); AssetDatabase.Refresh(); yield break; } private static void WriteMethods( Type type, List<MethodInfo> methods, StringBuilder builder ) { for ( int i = 0; i < methods.Count; i++ ) { var m = methods[i]; var isConditional = m.ReturnType == typeof( bool ); if ( m.GetParameters().Length == 0 ) { builder.AppendLine( string.Format( "\t[Automation( \"{0}/{1}()\" )]", ObjectNames.NicifyVariableName( type.Name ), ObjectNames.NicifyVariableName( m.Name ) ) ); } else { builder.AppendLine( string.Format( "\t[Automation( \"{0}/{1}({2})\" )]", ObjectNames.NicifyVariableName( type.Name ), ObjectNames.NicifyVariableName( m.Name ), m.GetParameters().Select( p => Utils.GetTypeName( p.ParameterType, false ) ).Aggregate( ( a1, a2 ) => a1 + "," + a2 ) ) ); } if ( isConditional ) { builder.AppendLine( string.Format( "\tpublic class {2}{0}{1} : ConditionalAutomation ", m.Name, i, type.Name ) + "{" ); } else { builder.AppendLine( string.Format( "\tpublic class {2}{0}{1} : Automation ", m.Name, i, type.Name ) + "{" ); } builder.AppendLine(); if ( !m.IsStatic ) { builder.AppendLine( string.Format( "\t\tpublic {0} Instance;", Utils.GetTypeName( type ) ) ); } var parameters = m.GetParameters(); foreach ( var item in parameters ) { if ( item.ParameterType == typeof( Type ) ) { builder.AppendLine( "\t\t[TypeLimit()]" ); } var attrs = item.ParameterType.GetCustomAttributes( typeof( DefaultValueAttribute ), false ); if ( attrs.Length == 1 ) { var val = (attrs[0] as DefaultValueAttribute).Value; if ( val != null && val.GetType().IsEnum ) { builder.AppendLine( string.Format( "\t\tpublic {0} {1} = {2}.{3};", Utils.GetTypeName( item.ParameterType ), item.Name, Utils.GetTypeName( item.ParameterType ), ToString( val ) ) ); } else { builder.AppendLine( string.Format( "\t\tpublic {0} {1} = {2};", Utils.GetTypeName( item.ParameterType ), item.Name, ToString( val ) ) ); } } else { builder.AppendLine( string.Format( "\t\tpublic {0} {1};", Utils.GetTypeName( item.ParameterType ), item.Name ) ); } } if ( m.ReturnType != typeof( void ) ) { builder.AppendLine( "\t\t[ReadOnly]\r\n\t\t[IgnoreSerialization]" ); builder.AppendLine( string.Format( "\t\tpublic {0} Result;", Utils.GetTypeName( m.ReturnType ) ) ); } builder.AppendLine(); builder.AppendLine( "\t\tpublic override IEnumerator Execute() {" ); if ( m.ReturnType != typeof( void ) ) { builder.Append( "\t\t\tResult = " ); } else { builder.Append( "\t\t\t" ); } if ( m.IsStatic ) { builder.AppendFormat( "{0}.{1}(", Utils.GetTypeName( type ), m.Name ); } else { builder.AppendFormat( "Instance.{0}(", m.Name ); } for ( int j = 0; j < parameters.Length; j++ ) { var p = parameters[j]; if ( p.ParameterType.IsByRef && !p.IsOut ) { builder.Append( "ref " ); } if ( p.IsOut ) { builder.Append( "out " ); } builder.Append( p.Name ); if ( j < parameters.Length - 1 ) { builder.AppendFormat( "," ); } } builder.AppendLine( ");" ); builder.AppendLine( "\t\t\tyield break;" ); builder.AppendLine( "\t\t}" ); builder.AppendLine(); if ( isConditional ) { builder.AppendLine( "\t\tpublic override bool GetConditionalResult() {" ); builder.AppendLine( "\t\t\treturn Result;" ); builder.AppendLine( "\t\t}" ); } builder.AppendLine( "\t}" ); builder.AppendLine(); } } private static void WriteProperties( Type type, List<PropertyInfo> properties, StringBuilder builder ) { for ( int i = 0; i < properties.Count; i++ ) { var p = properties[i]; var isStatic = false; var isBool = p.PropertyType == typeof( bool ); try { p.GetValue( null, null ); isStatic = true; } catch ( Exception ) { } if ( p.CanRead ) { builder.AppendLine( string.Format( "\t[Automation( \"{0}/Get {1}\" )]", ObjectNames.NicifyVariableName( type.Name ), ObjectNames.NicifyVariableName( p.Name ) ) ); if ( isBool ) { builder.AppendLine( string.Format( "\tpublic class {2}{0}Get{1} : ConditionalAutomation ", p.Name, i, type.Name ) + "{" ); } else { builder.AppendLine( string.Format( "\tpublic class {2}{0}Get{1} : Automation ", p.Name, i, type.Name ) + "{" ); } builder.AppendLine(); if ( !isStatic ) { builder.AppendLine( string.Format( "\t\tpublic {0} Instance;", Utils.GetTypeName( type ) ) ); } builder.AppendLine( "\t\t[ReadOnly]\r\n\t\t[IgnoreSerialization]" ); builder.AppendLine( string.Format( "\t\tpublic {0} Result;", Utils.GetTypeName( p.PropertyType ) ) ); builder.AppendLine(); builder.AppendLine( "\t\tpublic override IEnumerator Execute() {" ); builder.Append( "\t\t\tResult = " ); if ( isStatic ) { builder.AppendFormat( "{0}.{1}", Utils.GetTypeName( type ), p.Name ); } else { builder.AppendFormat( "Instance.{0}", p.Name ); } builder.AppendLine( ";" ); builder.AppendLine( "\t\t\tyield break;" ); builder.AppendLine( "\t\t}" ); builder.AppendLine(); if ( isBool ) { builder.AppendLine( "\t\tpublic override bool GetConditionalResult() {" ); builder.AppendLine( "\t\t\treturn Result;" ); builder.AppendLine( "\t\t}" ); } builder.AppendLine( "\t}" ); builder.AppendLine(); } /////////////////////////////// SET if ( !p.CanWrite ) continue; builder.AppendLine( string.Format( "\t[Automation( \"{0}/Set {1}\" )]", ObjectNames.NicifyVariableName( type.Name ), ObjectNames.NicifyVariableName( p.Name ) ) ); builder.AppendLine( string.Format( "\tpublic class {2}{0}Set{1} : Automation ", p.Name, i, type.Name ) + "{" ); builder.AppendLine(); if ( !isStatic ) { builder.AppendLine( string.Format( "\t\tpublic {0} Instance;", Utils.GetTypeName( type ) ) ); } builder.AppendLine( string.Format( "\t\tpublic {0} Value;", Utils.GetTypeName( p.PropertyType ) ) ); builder.AppendLine(); builder.AppendLine( "\t\tpublic override IEnumerator Execute() {" ); if ( isStatic ) { builder.AppendFormat( "\t\t\t{0}.{1}", Utils.GetTypeName( type ), p.Name ); } else { builder.AppendFormat( "\t\t\tInstance.{0}", p.Name ); } builder.AppendLine( " = Value;" ); builder.AppendLine( "\t\t\tyield break;" ); builder.AppendLine( "\t\t}" ); builder.AppendLine(); builder.AppendLine( "\t}" ); builder.AppendLine(); } } private static void WriteFields( Type type, List<FieldInfo> fields, StringBuilder builder ) { for ( int i = 0; i < fields.Count; i++ ) { var f = fields[i]; var isBool = f.FieldType == typeof( bool ); builder.AppendLine( string.Format( "\t[Automation( \"{0}/Get {1}\" )]", ObjectNames.NicifyVariableName( type.Name ), ObjectNames.NicifyVariableName( f.Name ) ) ); if ( isBool ) { builder.AppendLine( string.Format( "\tpublic class {2}{0}Get{1} : ConditionalAutomation ", f.Name, i, type.Name ) + "{" ); } else { builder.AppendLine( string.Format( "\tpublic class {2}{0}Get{1} : Automation ", f.Name, i, type.Name ) + "{" ); } builder.AppendLine(); if ( !f.IsStatic ) { builder.AppendLine( string.Format( "\t\tpublic {0} Instance;", Utils.GetTypeName( type ) ) ); } builder.AppendLine( "\t\t[ReadOnly]\r\n\t\t[IgnoreSerialization]" ); builder.AppendLine( string.Format( "\t\tpublic {0} Result;", Utils.GetTypeName( f.FieldType ) ) ); builder.AppendLine(); builder.AppendLine( "\t\tpublic override IEnumerator Execute() {" ); builder.Append( "\t\t\tResult = " ); if ( f.IsStatic ) { builder.AppendFormat( "{0}.{1}", Utils.GetTypeName( type ), f.Name ); } else { builder.AppendFormat( "Instance.{0}", f.Name ); } builder.AppendLine( ";" ); builder.AppendLine( "\t\t\tyield break;" ); builder.AppendLine( "\t\t}" ); builder.AppendLine(); if ( isBool ) { builder.AppendLine( "\t\tpublic override bool GetConditionalResult() {" ); builder.AppendLine( "\t\t\treturn Result;" ); builder.AppendLine( "\t\t}" ); } builder.AppendLine( "\t}" ); builder.AppendLine(); if ( f.IsInitOnly ) continue; /////////////////////////////// SET builder.AppendLine( string.Format( "\t[Automation( \"{0}/Set {1}\" )]", ObjectNames.NicifyVariableName( type.Name ), ObjectNames.NicifyVariableName( f.Name ) ) ); builder.AppendLine( string.Format( "\tclass {2}{0}Set{1} : Automation ", f.Name, i, type.Name ) + "{" ); builder.AppendLine(); if ( !f.IsStatic ) { builder.AppendLine( string.Format( "\t\tpublic {0} Instance;", Utils.GetTypeName( type ) ) ); } builder.AppendLine( string.Format( "\t\tpublic {0} Value;", Utils.GetTypeName( f.FieldType ) ) ); builder.AppendLine(); builder.AppendLine( "\t\tpublic override IEnumerator Execute() {" ); if ( f.IsStatic ) { builder.AppendFormat( "\t\t\t{0}.{1}", Utils.GetTypeName( type ), f.Name ); } else { builder.AppendFormat( "\t\t\tInstance.{0}", f.Name ); } builder.AppendLine( " = Value;" ); builder.AppendLine( "\t\t\tyield break;" ); builder.AppendLine( "\t\t}" ); builder.AppendLine(); builder.AppendLine( "\t}" ); builder.AppendLine(); } } private static string ToString( object value ) { if ( value == null ) return "null"; if ( !value.GetType().IsValueType ) return "null"; if ( value is bool ) { return ((bool)value) ? "true" : "false"; } else if ( value is float ) { return value.ToString() + "f"; } else if ( value is double ) { return value.ToString() + "d"; } else if ( value is Vector2 ) { var v = (Vector2)value; return string.Format( "new Vector2({0}f,{1}f)", v.x, v.y ); } else if ( value is Vector3 ) { var v = (Vector3)value; return string.Format( "new Vector3({0}f,{1}f,{2}f)", v.x, v.y, v.z ); } else if ( value is Vector4 ) { var v = (Vector4)value; return string.Format( "new Vector4({0}f,{1}f,{2}f,{3}f)", v.x, v.y, v.z, v.w ); } else if ( value is Quaternion ) { var v = (Quaternion)value; return string.Format( "new Quaternion({0}f,{1}f,{2}f,{3}f)", v.x, v.y, v.z, v.w ); } else if ( value is Bounds ) { var v = (Bounds)value; return string.Format( "new Bounds({0},{1})", ToString( v.center ), ToString( v.size ) ); } else if ( value is Rect ) { var v = (Rect)value; return string.Format( "new Rect({0},{1})", ToString( v.position ), ToString( v.size ) ); } else if ( value.GetType().IsEnum ) { var enumValues = Enum.GetValues( value.GetType() ); if ( enumValues.Length == 0 ) { Debug.Log( "We have nothing" ); return ""; } else { return enumValues.GetValue( 0 ).ToString(); } //return ((int)Enum.GetValues( value.GetType() ).GetValue( 0 )).ToString(); } return "undefined"; } #endregion #region GUI private object initializer = null; private bool isBusy = false; private Dictionary<Type, bool> typeStates = new Dictionary<Type, bool>(); private Vector2 typeScroll = new Vector2(); private Vector2 libraryScroll = Vector2.zero; private List<AssemblyInfo> infos = new List<AssemblyInfo>(); private List<Type> allTypes = new List<Type>(); private List<Type> filteredTypes = new List<Type>(); [SerializeField] private string typeFilter = ""; private int page = 0; [Serializable] private class AssemblyInfo { public Assembly Assembly; public string FullName; public string Name; public bool State; public List<Type> Types; public List<bool> States; public AssemblyInfo() { } public AssemblyInfo( Assembly assembly ) { Assembly = assembly; FullName = assembly.FullName; Name = assembly.GetName().Name; State = false; States = new List<bool>(); Types = new List<Type>(); } public IEnumerator LoadTypes() { var types = Assembly.GetTypes(); int count = 0; foreach ( var item in types ) { if ( item.Name.StartsWith( "<" ) || item.Name.StartsWith( "$" ) ) continue; if ( !item.IsPublic ) continue; if ( item.IsSpecialName ) continue; if ( item.GetCustomAttributes( typeof( ObsoleteAttribute ), false ).Length > 0 ) continue; if ( item.ContainsGenericParameters ) continue; if ( item.IsEnum ) continue; if ( item.GetMembers( BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public ).Length == 0 ) continue; Types.Add( item ); count++; if ( count > 10 ) { count = 0; yield return null; } } yield break; } } private IEnumerator LoadTypes() { isBusy = true; var routines = new List<EditorCoroutine>(); foreach ( var item in infos ) { routines.Add( EditorCoroutine.Start( item.LoadTypes() ) ); } while ( true ) { var anyRunning = false; foreach ( var item in routines ) { if ( item.IsRunning ) { anyRunning = true; break; } } if ( !anyRunning ) break; yield return null; } isBusy = false; Repaint(); yield break; } private IEnumerator SelectTypes() { isBusy = true; allTypes.Clear(); int count = 0; foreach ( var info in infos ) { if ( !info.State ) continue; foreach ( var item in info.Types ) { allTypes.Add( item ); count++; if ( count == 10 ) { count = 0; yield return null; } } yield return null; } isBusy = false; Repaint(); yield break; } private IEnumerator FilterTypes() { isBusy = true; page = 0; if ( string.IsNullOrEmpty( typeFilter ) ) { filteredTypes = new List<Type>( allTypes ); } var type = ""; var label = ""; if ( typeFilter.StartsWith( "t:" ) ) { var end = typeFilter.IndexOf( ' ' ); end = end == -1 ? typeFilter.Length : end; type = typeFilter.Substring( 0, end ).Replace( "t:", "" ).Trim(); label = typeFilter.Remove( 0, end ).Trim(); } else { label = typeFilter; } Type baseType = null; if ( !string.IsNullOrEmpty( type ) ) { baseType = Type.GetType( type ); } filteredTypes.Clear(); int count = 0; foreach ( var item in allTypes ) { if ( baseType != null && !item.IsSubclassOf( baseType ) ) continue; if ( !item.Name.ToLower().Contains( label.ToLower() ) ) continue; filteredTypes.Add( item ); count++; if ( count > 20 ) { count = 0; yield return null; } } isBusy = false; Repaint(); yield break; } void OnGUI() { if ( initializer == null ) { var assmblies = AppDomain.CurrentDomain.GetAssemblies().Where( a => a.FullName.StartsWith( "Unity" ) || a.FullName.StartsWith( "Assembly-CSharp" ) ); assmblies = assmblies.Concat( new[] { typeof( string ).Assembly } ).OrderBy( a => a.FullName ); infos.Clear(); foreach ( var item in assmblies ) { infos.Add( new AssemblyInfo( item ) ); } EditorCoroutine.StartMultiple( LoadTypes(), SelectTypes(), FilterTypes() ); initializer = new object(); } EditorGUI.BeginDisabledGroup( isBusy ); EditorGUILayout.Space(); EditorGUILayout.LabelField( "Libraries", EditorStyles.boldLabel ); EditorGUI.indentLevel++; EditorGUI.BeginChangeCheck(); var w = position.size.x - 200; EditorGUIUtility.labelWidth += w; libraryScroll = EditorGUILayout.BeginScrollView( libraryScroll, GUILayout.Height( 200 ) ); foreach ( var item in infos ) { item.State = EditorGUILayout.Toggle( item.Name, item.State ); } EditorGUILayout.EndScrollView(); EditorGUIUtility.labelWidth -= w; if ( EditorGUI.EndChangeCheck() ) { EditorCoroutine.StartMultiple( SelectTypes(), FilterTypes() ); } EditorGUI.indentLevel--; EditorGUILayout.Space(); EditorGUILayout.LabelField( "Filter", EditorStyles.boldLabel ); EditorGUI.indentLevel++; EditorGUI.BeginChangeCheck(); EditorGUILayout.LabelField( "Prefix with t: for a base type" ); EditorGUILayout.LabelField( "Example: t:Component" ); EditorGUILayout.LabelField( "Combined example: t:Component Collider" ); typeFilter = EditorGUILayout.DelayedTextField( typeFilter ); if ( EditorGUI.EndChangeCheck() ) { EditorCoroutine.Start( FilterTypes() ); } EditorGUI.indentLevel--; EditorGUILayout.Space(); EditorGUILayout.LabelField( "Types", EditorStyles.boldLabel ); int pageOffset = page * 100; var rect = EditorGUILayout.GetControlRect(); EditorGUI.BeginDisabledGroup( page == 0 ); if ( GUI.Button( new Rect( rect.x, rect.y, rect.width / 2, rect.height ), "<" ) ) { if ( page > 0 ) { page--; typeScroll = Vector2.zero; } } EditorGUI.EndDisabledGroup(); EditorGUI.BeginDisabledGroup( pageOffset + 100 >= filteredTypes.Count ); if ( GUI.Button( new Rect( rect.x + (rect.width / 2), rect.y, rect.width / 2, rect.height ), ">" ) ) { page++; typeScroll = Vector2.zero; } EditorGUI.EndDisabledGroup(); if ( GUILayout.Button( "Toggle Page" ) ) { for ( int i = pageOffset; i < pageOffset + 100; i++ ) { if ( i < filteredTypes.Count ) { var t = filteredTypes[i]; if ( !typeStates.ContainsKey( t ) ) { typeStates.Add( t, false ); } typeStates[t] = !typeStates[t]; } else { break; } } } typeScroll = EditorGUILayout.BeginScrollView( typeScroll ); EditorGUI.indentLevel++; for ( int i = pageOffset; i < pageOffset + 100; i++ ) { if ( i < filteredTypes.Count ) { var t = filteredTypes[i]; if ( !typeStates.ContainsKey( t ) ) { typeStates.Add( t, false ); } typeStates[t] = EditorGUILayout.ToggleLeft( string.Format( "{0} ({1})", t.Name, t.Assembly.GetName().Name ), typeStates[t] ); } else { break; } } EditorGUI.indentLevel--; EditorGUILayout.EndScrollView(); if ( GUILayout.Button( "Generate" ) ) { var types = typeStates.Where( t => t.Value ) .Select( t => t.Key ).Select( t => new WizardData() { Type = t, Name = Utils.GetTypeName( t ), Fields = new Dictionary<FieldInfo, bool>().AddRange( GetFields( t ).Select( f => new KeyValuePair<FieldInfo, bool>( f, false ) ) ), Properties = new Dictionary<PropertyInfo, bool>().AddRange( GetProperties( t ).Select( p => new KeyValuePair<PropertyInfo, bool>( p, false ) ) ), Methods = new Dictionary<MethodInfo, bool>().AddRange( GetMethods( t ).Select( m => new KeyValuePair<MethodInfo, bool>( m, false ) ) ), } ).ToList(); GeneratorWizard.Init( types ); } if ( GUILayout.Button( "Generate All" ) ) { var types = typeStates.Where( t => t.Value ) .Select( t => t.Key ).Select( t => new WizardData() { Type = t, Name = Utils.GetTypeName( t ), Fields = new Dictionary<FieldInfo, bool>().AddRange( GetFields( t ).Select( f => new KeyValuePair<FieldInfo, bool>( f, false ) ) ), Properties = new Dictionary<PropertyInfo, bool>().AddRange( GetProperties( t ).Select( p => new KeyValuePair<PropertyInfo, bool>( p, false ) ) ), Methods = new Dictionary<MethodInfo, bool>().AddRange( GetMethods( t ).Select( m => new KeyValuePair<MethodInfo, bool>( m, false ) ) ), } ).ToList(); foreach ( var item in types ) { { var keys = item.Fields.Keys; for ( int i = keys.Count() - 1; i >= 0; i-- ) { var key = keys.ElementAt( i ); item.Fields[key] = true; } } { var keys = item.Properties.Keys; for ( int i = keys.Count() - 1; i >= 0; i-- ) { var key = keys.ElementAt( i ); item.Properties[key] = true; } } { var keys = item.Methods.Keys; for ( int i = keys.Count() - 1; i >= 0; i-- ) { var key = keys.ElementAt( i ); item.Methods[key] = true; } } } Generate( types.Select( d => new GenerationData() { Type = d.Type, Fields = d.Fields.Where( f => f.Value ).Select( f => f.Key ).ToList(), Properties = d.Properties.Where( p => p.Value ).Select( f => f.Key ).ToList(), Methods = d.Methods.Where( m => m.Value ).Select( f => f.Key ).ToList(), } ).ToList() ); } EditorGUI.EndDisabledGroup(); } private List<MethodInfo> GetMethods( Type type ) { var flags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public; return type.GetMethods( flags ) .Where( m => !m.Name.StartsWith( "get_" ) && !m.Name.StartsWith( "set_" ) && !m.Name.StartsWith( "op_" ) && !m.Name.StartsWith( "add_" ) && !m.Name.StartsWith( "remove_" ) ) .Where( m => m.GetCustomAttributes( typeof( ObsoleteAttribute ), false ).Length == 0 ) .Where( m => m.GetGenericArguments().Length == 0 ).ToList(); } private List<PropertyInfo> GetProperties( Type type ) { var flags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public; return type.GetProperties( flags ) .Where( p => p.GetCustomAttributes( typeof( ObsoleteAttribute ), false ).Length == 0 ) .Where( p => p.CanRead ).ToList(); } private List<FieldInfo> GetFields( Type type ) { var flags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public; return type.GetFields( flags ) .Where( f => f.GetCustomAttributes( typeof( ObsoleteAttribute ), false ).Length == 0 ) .Where( f => !f.IsLiteral ).ToList(); } #endregion } } #endif
using System; using System.Linq; using System.Collections.Generic; using Microsoft.EntityFrameworkCore; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using hihapi.Models; using hihapi.Utilities; using hihapi.Exceptions; using Microsoft.AspNetCore.OData.Routing.Controllers; using Microsoft.AspNetCore.OData.Query; using Microsoft.AspNetCore.OData.Formatter; namespace hihapi.Controllers { [Authorize] public class FinanceAccountCategoriesController : ODataController { private readonly hihDataContext _context; public FinanceAccountCategoriesController(hihDataContext context) { _context = context; } /// GET: /FinanceAccountCategories [EnableQuery] [HttpGet] public IActionResult Get() { String usrName = String.Empty; try { usrName = HIHAPIUtility.GetUserID(this); } catch { // Do nothing usrName = String.Empty; } if (String.IsNullOrEmpty(usrName)) return Ok(_context.FinAccountCategories.Where(p => p.HomeID == null)); var rst0 = from acntctgy in _context.FinAccountCategories where acntctgy.HomeID == null select acntctgy; var rst1 = from hmem in _context.HomeMembers where hmem.User == usrName select new { HomeID = hmem.HomeID } into hids join acntctgy in _context.FinAccountCategories on hids.HomeID equals acntctgy.HomeID select acntctgy; return Ok(rst0.Union(rst1)); } /// GET: /FinanceAccountCategories(:id) [EnableQuery] [HttpGet] public FinanceAccountCategory Get([FromODataUri] int key) { String usrName = String.Empty; try { usrName = HIHAPIUtility.GetUserID(this); } catch { // Do nothing usrName = String.Empty; } if (String.IsNullOrEmpty(usrName)) return _context.FinAccountCategories.Where(p => p.ID == key && p.HomeID == null).SingleOrDefault(); return (from ctgy in _context.FinAccountCategories join hmem in _context.HomeMembers on ctgy.HomeID equals hmem.HomeID into hmem2 from nhmem in hmem2.DefaultIfEmpty() where ctgy.ID == key && (nhmem == null || nhmem.User == usrName) select ctgy).SingleOrDefault(); //var hids = (from hmem in _context.HomeMembers // where hmem.User == usrName // select hmem.HomeID).Distinct(); //var result = (from ctgy in _context.FinAccountCategories // where ctgy.ID == key && ctgy.HomeID == null // select ctgy).SingleOrDefault(); //if (result == null) //{ //} //else // return result; // //.Where(p => p.User == usrName) //return (from hmem in _context.HomeMembers.Where(p => p.User == usrName) // from acntctgy in _context.FinAccountCategories.Where(p => p.ID == key && (p.HomeID == null || p.HomeID == hmem.HomeID)) // select acntctgy).SingleOrDefault(); } [HttpPost] public async Task<IActionResult> Post([FromBody] FinanceAccountCategory ctgy) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } // Check if (!ctgy.IsValid(this._context) || !ctgy.HomeID.HasValue) { throw new BadRequestException("Inputted object IsValid failed"); } // User String usrName = String.Empty; try { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) { throw new UnauthorizedAccessException(); } } catch { throw new UnauthorizedAccessException(); } // Check whether User assigned with specified Home ID var hms = _context.HomeMembers.Where(p => p.HomeID == ctgy.HomeID.Value && p.User == usrName).Count(); if (hms <= 0) { throw new UnauthorizedAccessException(); } if (!ctgy.IsValid(this._context)) return BadRequest(); ctgy.Createdby = usrName; ctgy.CreatedAt = DateTime.Now; _context.FinAccountCategories.Add(ctgy); await _context.SaveChangesAsync(); return Created(ctgy); } [HttpPut] public async Task<IActionResult> Put([FromODataUri] int key, [FromBody] FinanceAccountCategory update) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } if (key != update.ID) { throw new BadRequestException("ID mismatched"); } // User String usrName = String.Empty; try { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) { throw new UnauthorizedAccessException(); } } catch { throw new UnauthorizedAccessException(); } // Check whether User assigned with specified Home ID var hms = _context.HomeMembers.Where(p => p.HomeID == update.HomeID && p.User == usrName).Count(); if (hms <= 0) { throw new UnauthorizedAccessException(); } if (!update.IsValid(this._context)) return BadRequest(); update.UpdatedAt = DateTime.Now; update.Updatedby = usrName; _context.Entry(update).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException exp) { if (!_context.FinAccountCategories.Any(p => p.ID == key)) { return NotFound(); } else { throw new DBOperationException(exp.Message); } } return Updated(update); } [HttpDelete] public async Task<IActionResult> Delete([FromODataUri] int key) { var cc = await _context.FinAccountCategories.FindAsync(key); if (cc == null) { return NotFound(); } // User String usrName = String.Empty; try { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) { throw new UnauthorizedAccessException(); } } catch { throw new UnauthorizedAccessException(); } // Check whether User assigned with specified Home ID var hms = _context.HomeMembers.Where(p => p.HomeID == cc.HomeID && p.User == usrName).Count(); if (hms <= 0) { throw new UnauthorizedAccessException(); } if (!cc.IsDeleteAllowed(this._context)) return BadRequest(); _context.FinAccountCategories.Remove(cc); await _context.SaveChangesAsync(); return StatusCode(204); // HttpStatusCode.NoContent } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using Xunit; #if NET35PLUS using System.Threading.Tasks; #endif namespace System.Collections.Immutable.Test { #if !NET45PLUS extern alias rax; using rax::System.Collections; using rax::System.Collections.Generic; #if !NET40PLUS using rax::System.Diagnostics.Contracts; #endif #endif public class ImmutableArrayTest : SimpleElementImmutablesTestBase { private static readonly ImmutableArray<int> s_emptyDefault; private static readonly ImmutableArray<int> s_empty = ImmutableArray.Create<int>(); private static readonly ImmutableArray<int> s_oneElement = ImmutableArray.Create(1); private static readonly ImmutableArray<int> s_manyElements = ImmutableArray.Create(1, 2, 3); private static readonly ImmutableArray<GenericParameterHelper> s_oneElementRefType = ImmutableArray.Create(new GenericParameterHelper(1)); private static readonly ImmutableArray<string> s_twoElementRefTypeWithNull = ImmutableArray.Create("1", null); [Fact] public void CreateEmpty() { Assert.Equal(ImmutableArray.Create<int>(), ImmutableArray<int>.Empty); } [Fact] public void CreateFromEnumerable() { Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange((IEnumerable<int>)null)); IEnumerable<int> source = new[] { 1, 2, 3 }; var array = ImmutableArray.CreateRange(source); Assert.Equal(3, array.Length); } [Fact] public void CreateFromEmptyEnumerableReturnsSingleton() { IEnumerable<int> emptySource1 = new int[0]; var immutable = ImmutableArray.CreateRange(emptySource1); // This equality check returns true if the underlying arrays are the same instance. Assert.Equal(s_empty, immutable); } [Fact] public void CreateRangeFromImmutableArrayWithSelector() { var array = ImmutableArray.Create(4, 5, 6, 7); var copy1 = ImmutableArray.CreateRange(array, i => i + 0.5); Assert.Equal(new[] { 4.5, 5.5, 6.5, 7.5 }, copy1); var copy2 = ImmutableArray.CreateRange(array, i => i + 1); Assert.Equal(new[] { 5, 6, 7, 8 }, copy2); Assert.Equal(new int[] { }, ImmutableArray.CreateRange(s_empty, i => i)); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange(array, (Func<int, int>)null)); } [Fact] public void CreateRangeFromImmutableArrayWithSelectorAndArgument() { var array = ImmutableArray.Create(4, 5, 6, 7); var copy1 = ImmutableArray.CreateRange(array, (i, j) => i + j, 0.5); Assert.Equal(new[] { 4.5, 5.5, 6.5, 7.5 }, copy1); var copy2 = ImmutableArray.CreateRange(array, (i, j) => i + j, 1); Assert.Equal(new[] { 5, 6, 7, 8 }, copy2); var copy3 = ImmutableArray.CreateRange(array, (int i, object j) => i, null); Assert.Equal(new[] { 4, 5, 6, 7 }, copy3); Assert.Equal(new int[] { }, ImmutableArray.CreateRange(s_empty, (i, j) => i + j, 0)); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange(array, (Func<int, int, int>)null, 0)); } [Fact] public void CreateRangeSliceFromImmutableArrayWithSelector() { var array = ImmutableArray.Create(4, 5, 6, 7); var copy1 = ImmutableArray.CreateRange(array, 0, 0, i => i + 0.5); Assert.Equal(new double[] { }, copy1); var copy2 = ImmutableArray.CreateRange(array, 0, 0, i => i); Assert.Equal(new int[] { }, copy2); var copy3 = ImmutableArray.CreateRange(array, 0, 1, i => i * 2); Assert.Equal(new int[] { 8 }, copy3); var copy4 = ImmutableArray.CreateRange(array, 0, 2, i => i + 1); Assert.Equal(new int[] { 5, 6 }, copy4); var copy5 = ImmutableArray.CreateRange(array, 0, 4, i => i); Assert.Equal(new int[] { 4, 5, 6, 7 }, copy5); var copy6 = ImmutableArray.CreateRange(array, 3, 1, i => i); Assert.Equal(new int[] { 7 }, copy6); var copy7 = ImmutableArray.CreateRange(array, 3, 0, i => i); Assert.Equal(new int[] { }, copy7); var copy8 = ImmutableArray.CreateRange(array, 4, 0, i => i); Assert.Equal(new int[] { }, copy8); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange(array, 0, 0, (Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange(s_empty, 0, 0, (Func<int, int>)null)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, -1, 1, (Func<int, int>)null)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, -1, 1, i => i)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 0, 5, i => i)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 4, 1, i => i)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 3, 2, i => i)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 1, -1, i => i)); } [Fact] public void CreateRangeSliceFromImmutableArrayWithSelectorAndArgument() { var array = ImmutableArray.Create(4, 5, 6, 7); var copy1 = ImmutableArray.CreateRange(array, 0, 0, (i, j) => i + j, 0.5); Assert.Equal(new double[] { }, copy1); var copy2 = ImmutableArray.CreateRange(array, 0, 0, (i, j) => i + j, 0); Assert.Equal(new int[] { }, copy2); var copy3 = ImmutableArray.CreateRange(array, 0, 1, (i, j) => i * j, 2); Assert.Equal(new int[] { 8 }, copy3); var copy4 = ImmutableArray.CreateRange(array, 0, 2, (i, j) => i + j, 1); Assert.Equal(new int[] { 5, 6 }, copy4); var copy5 = ImmutableArray.CreateRange(array, 0, 4, (i, j) => i + j, 0); Assert.Equal(new int[] { 4, 5, 6, 7 }, copy5); var copy6 = ImmutableArray.CreateRange(array, 3, 1, (i, j) => i + j, 0); Assert.Equal(new int[] { 7 }, copy6); var copy7 = ImmutableArray.CreateRange(array, 3, 0, (i, j) => i + j, 0); Assert.Equal(new int[] { }, copy7); var copy8 = ImmutableArray.CreateRange(array, 4, 0, (i, j) => i + j, 0); Assert.Equal(new int[] { }, copy8); var copy9 = ImmutableArray.CreateRange(array, 0, 1, (int i, object j) => i, null); Assert.Equal(new int[] { 4 }, copy9); Assert.Equal(new int[] { }, ImmutableArray.CreateRange(s_empty, 0, 0, (i, j) => i + j, 0)); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange(array, 0, 0, (Func<int, int, int>)null, 0)); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange(s_empty, 0, 0, (Func<int, int, int>)null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(s_empty, -1, 1, (Func<int, int, int>)null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, -1, 1, (i, j) => i + j, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 0, 5, (i, j) => i + j, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 4, 1, (i, j) => i + j, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 3, 2, (i, j) => i + j, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 1, -1, (i, j) => i + j, 0)); } [Fact] public void CreateFromSliceOfImmutableArray() { var array = ImmutableArray.Create(4, 5, 6, 7); Assert.Equal(new[] { 4, 5 }, ImmutableArray.Create(array, 0, 2)); Assert.Equal(new[] { 5, 6 }, ImmutableArray.Create(array, 1, 2)); Assert.Equal(new[] { 6, 7 }, ImmutableArray.Create(array, 2, 2)); Assert.Equal(new[] { 7 }, ImmutableArray.Create(array, 3, 1)); Assert.Equal(new int[0], ImmutableArray.Create(array, 4, 0)); Assert.Equal(new int[] { }, ImmutableArray.Create(s_empty, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(s_empty, 0, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, 0, array.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, 1, array.Length)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, array.Length + 1, 0)); } [Fact] public void CreateFromSliceOfImmutableArrayOptimizations() { var array = ImmutableArray.Create(4, 5, 6, 7); var slice = ImmutableArray.Create(array, 0, array.Length); Assert.Equal(array, slice); // array instance actually shared between the two } [Fact] public void CreateFromSliceOfImmutableArrayEmptyReturnsSingleton() { var array = ImmutableArray.Create(4, 5, 6, 7); var slice = ImmutableArray.Create(array, 1, 0); Assert.Equal(s_empty, slice); } [Fact] public void CreateFromSliceOfArray() { var array = new int[] { 4, 5, 6, 7 }; Assert.Equal(new[] { 4, 5 }, ImmutableArray.Create(array, 0, 2)); Assert.Equal(new[] { 5, 6 }, ImmutableArray.Create(array, 1, 2)); Assert.Equal(new[] { 6, 7 }, ImmutableArray.Create(array, 2, 2)); Assert.Equal(new[] { 7 }, ImmutableArray.Create(array, 3, 1)); Assert.Equal(new int[0], ImmutableArray.Create(array, 4, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, 0, array.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, 1, array.Length)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, array.Length + 1, 0)); } [Fact] public void CreateFromSliceOfArrayEmptyReturnsSingleton() { var array = new int[] { 4, 5, 6, 7 }; var slice = ImmutableArray.Create(array, 1, 0); Assert.Equal(s_empty, slice); slice = ImmutableArray.Create(array, array.Length, 0); Assert.Equal(s_empty, slice); } [Fact] public void CreateFromArray() { var source = new[] { 1, 2, 3 }; var immutable = ImmutableArray.Create(source); Assert.Equal(source, immutable); } [Fact] public void CreateFromNullArray() { int[] nullArray = null; ImmutableArray<int> immutable = ImmutableArray.Create(nullArray); Assert.False(immutable.IsDefault); Assert.Equal(0, immutable.Length); } [Fact] public void Covariance() { ImmutableArray<string> derivedImmutable = ImmutableArray.Create("a", "b", "c"); ImmutableArray<object> baseImmutable = derivedImmutable.As<object>(); Assert.False(baseImmutable.IsDefault); #if NET40PLUS Assert.Equal(derivedImmutable, baseImmutable); #else Assert.Equal(derivedImmutable.Cast<object>(), baseImmutable); #endif // Make sure we can reverse that, as a means to verify the underlying array is the same instance. ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>(); Assert.False(derivedImmutable2.IsDefault); Assert.Equal(derivedImmutable, derivedImmutable2); // Try a cast that would fail. Assert.True(baseImmutable.As<Encoder>().IsDefault); } [Fact] public void DowncastOfDefaultStructs() { ImmutableArray<string> derivedImmutable = default(ImmutableArray<string>); ImmutableArray<object> baseImmutable = derivedImmutable.As<object>(); Assert.True(baseImmutable.IsDefault); Assert.True(derivedImmutable.IsDefault); // Make sure we can reverse that, as a means to verify the underlying array is the same instance. ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>(); Assert.True(derivedImmutable2.IsDefault); Assert.True(derivedImmutable == derivedImmutable2); } /// <summary> /// Verifies that using an ordinary Create factory method is smart enough to reuse /// an underlying array when possible. /// </summary> [Fact] public void CovarianceImplicit() { ImmutableArray<string> derivedImmutable = ImmutableArray.Create("a", "b", "c"); #if NET40PLUS ImmutableArray<object> baseImmutable = ImmutableArray.CreateRange<object>(derivedImmutable); Assert.Equal(derivedImmutable, baseImmutable); #else ImmutableArray<object> baseImmutable = ImmutableArray.CreateRange<object>(derivedImmutable.CastArray<object>()); Assert.Equal(derivedImmutable.Cast<object>(), baseImmutable); #endif // Make sure we can reverse that, as a means to verify the underlying array is the same instance. ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>(); Assert.Equal(derivedImmutable, derivedImmutable2); } [Fact] public void CastUpReference() { ImmutableArray<string> derivedImmutable = ImmutableArray.Create("a", "b", "c"); ImmutableArray<object> baseImmutable = ImmutableArray<object>.CastUp(derivedImmutable); #if NET40PLUS Assert.Equal(derivedImmutable, baseImmutable); #else Assert.Equal(derivedImmutable.Cast<object>(), baseImmutable); #endif // Make sure we can reverse that, as a means to verify the underlying array is the same instance. Assert.Equal(derivedImmutable, baseImmutable.As<string>()); Assert.Equal(derivedImmutable, baseImmutable.CastArray<string>()); } [Fact] public void CastUpReferenceDefaultValue() { ImmutableArray<string> derivedImmutable = default(ImmutableArray<string>); ImmutableArray<object> baseImmutable = ImmutableArray<object>.CastUp(derivedImmutable); Assert.True(baseImmutable.IsDefault); Assert.True(derivedImmutable.IsDefault); // Make sure we can reverse that, as a means to verify the underlying array is the same instance. ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>(); Assert.True(derivedImmutable2.IsDefault); Assert.True(derivedImmutable == derivedImmutable2); } [Fact] public void CastUpRefToInterface() { var stringArray = ImmutableArray.Create("a", "b"); var enumArray = ImmutableArray<IEnumerable>.CastUp(stringArray); Assert.Equal(2, enumArray.Length); Assert.Equal(stringArray, enumArray.CastArray<string>()); Assert.Equal(stringArray, enumArray.As<string>()); } [Fact] public void CastUpInterfaceToInterface() { var genericEnumArray = ImmutableArray.Create<IEnumerable<int>>(new List<int>(), new List<int>()); var legacyEnumArray = ImmutableArray<IEnumerable>.CastUp(genericEnumArray); Assert.Equal(2, legacyEnumArray.Length); Assert.Equal(genericEnumArray, legacyEnumArray.As<IEnumerable<int>>()); Assert.Equal(genericEnumArray, legacyEnumArray.CastArray<IEnumerable<int>>()); } [Fact] public void CastUpArrayToSystemArray() { var arrayArray = ImmutableArray.Create(new int[] { 1, 2 }, new int[] { 3, 4 }); var sysArray = ImmutableArray<Array>.CastUp(arrayArray); Assert.Equal(2, sysArray.Length); Assert.Equal(arrayArray, sysArray.As<int[]>()); Assert.Equal(arrayArray, sysArray.CastArray<int[]>()); } [Fact] public void CastUpArrayToObject() { var arrayArray = ImmutableArray.Create(new int[] { 1, 2 }, new int[] { 3, 4 }); var objArray = ImmutableArray<object>.CastUp(arrayArray); Assert.Equal(2, objArray.Length); Assert.Equal(arrayArray, objArray.As<int[]>()); Assert.Equal(arrayArray, objArray.CastArray<int[]>()); } [Fact] public void CastUpDelegateToSystemDelegate() { var delArray = ImmutableArray.Create<Action>(() => { }, () => { }); var sysDelArray = ImmutableArray<Delegate>.CastUp(delArray); Assert.Equal(2, sysDelArray.Length); Assert.Equal(delArray, sysDelArray.As<Action>()); Assert.Equal(delArray, sysDelArray.CastArray<Action>()); } [Fact] public void CastArrayUnrelatedInterface() { var strArray = ImmutableArray.Create<string>("cat", "dog"); var compArray = ImmutableArray<IComparable>.CastUp(strArray); var enumArray = compArray.CastArray<IEnumerable>(); Assert.Equal(2, enumArray.Length); Assert.Equal(strArray, enumArray.As<string>()); Assert.Equal(strArray, enumArray.CastArray<string>()); } [Fact] public void CastArrayBadInterface() { var formattableArray = ImmutableArray.Create<IFormattable>(1, 2); Assert.Throws(typeof(InvalidCastException), () => formattableArray.CastArray<IComparable>()); } [Fact] public void CastArrayBadRef() { var objArray = ImmutableArray.Create<object>("cat", "dog"); Assert.Throws(typeof(InvalidCastException), () => objArray.CastArray<string>()); } [Fact] public void ToImmutableArray() { IEnumerable<int> source = new[] { 1, 2, 3 }; ImmutableArray<int> immutable = source.ToImmutableArray(); Assert.Equal(source, immutable); ImmutableArray<int> immutable2 = immutable.ToImmutableArray(); Assert.Equal(immutable, immutable2); // this will compare array reference equality. } [Fact] public void Count() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.Length); Assert.Throws<InvalidOperationException>(() => ((ICollection)s_emptyDefault).Count); Assert.Throws<InvalidOperationException>(() => ((ICollection<int>)s_emptyDefault).Count); Assert.Throws<InvalidOperationException>(() => ((IReadOnlyCollection<int>)s_emptyDefault).Count); Assert.Equal(0, s_empty.Length); Assert.Equal(0, ((ICollection)s_empty).Count); Assert.Equal(0, ((ICollection<int>)s_empty).Count); Assert.Equal(0, ((IReadOnlyCollection<int>)s_empty).Count); Assert.Equal(1, s_oneElement.Length); Assert.Equal(1, ((ICollection)s_oneElement).Count); Assert.Equal(1, ((ICollection<int>)s_oneElement).Count); Assert.Equal(1, ((IReadOnlyCollection<int>)s_oneElement).Count); } [Fact] public void IsEmpty() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.IsEmpty); Assert.True(s_empty.IsEmpty); Assert.False(s_oneElement.IsEmpty); } [Fact] public void IndexOfDefault() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.IndexOf(5)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.IndexOf(5, 0)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.IndexOf(5, 0, 0)); } [Fact] public void LastIndexOfDefault() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.LastIndexOf(5)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.LastIndexOf(5, 0)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.LastIndexOf(5, 0, 0)); } [Fact] public void IndexOf() { IndexOfTests.IndexOfTest( seq => ImmutableArray.CreateRange(seq), (b, v) => b.IndexOf(v), (b, v, i) => b.IndexOf(v, i), (b, v, i, c) => b.IndexOf(v, i, c), (b, v, i, c, eq) => b.IndexOf(v, i, c, eq)); } [Fact] public void LastIndexOf() { IndexOfTests.LastIndexOfTest( seq => ImmutableArray.CreateRange(seq), (b, v) => b.LastIndexOf(v), (b, v, eq) => b.LastIndexOf(v, eq), (b, v, i) => b.LastIndexOf(v, i), (b, v, i, c) => b.LastIndexOf(v, i, c), (b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq)); } [Fact] public void Contains() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.Contains(0)); Assert.False(s_empty.Contains(0)); Assert.True(s_oneElement.Contains(1)); Assert.False(s_oneElement.Contains(2)); Assert.True(s_manyElements.Contains(3)); Assert.False(s_oneElementRefType.Contains(null)); Assert.True(s_twoElementRefTypeWithNull.Contains(null)); } [Fact] public void ContainsEqualityComparer() { var array = ImmutableArray.Create("a", "B"); Assert.False(array.Contains("A", StringComparer.Ordinal)); Assert.True(array.Contains("A", StringComparer.OrdinalIgnoreCase)); Assert.False(array.Contains("b", StringComparer.Ordinal)); Assert.True(array.Contains("b", StringComparer.OrdinalIgnoreCase)); } [Fact] public void Enumerator() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.GetEnumerator()); ImmutableArray<int>.Enumerator enumerator = default(ImmutableArray<int>.Enumerator); Assert.Throws<NullReferenceException>(() => enumerator.Current); Assert.Throws<NullReferenceException>(() => enumerator.MoveNext()); enumerator = s_empty.GetEnumerator(); Assert.Throws<IndexOutOfRangeException>(() => enumerator.Current); Assert.False(enumerator.MoveNext()); enumerator = s_manyElements.GetEnumerator(); Assert.Throws<IndexOutOfRangeException>(() => enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(1, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(2, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(3, enumerator.Current); Assert.False(enumerator.MoveNext()); Assert.Throws<IndexOutOfRangeException>(() => enumerator.Current); } [Fact] public void ObjectEnumerator() { Assert.Throws<InvalidOperationException>(() => ((IEnumerable<int>)s_emptyDefault).GetEnumerator()); IEnumerator<int> enumerator = ((IEnumerable<int>)s_empty).GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.False(enumerator.MoveNext()); enumerator = ((IEnumerable<int>)s_manyElements).GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(1, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(2, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(3, enumerator.Current); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); } [Fact] public void EnumeratorWithNullValues() { var enumerationResult = System.Linq.Enumerable.ToArray(s_twoElementRefTypeWithNull); Assert.Equal("1", enumerationResult[0]); Assert.Null(enumerationResult[1]); } [Fact] public void EqualityCheckComparesInternalArrayByReference() { var immutable1 = ImmutableArray.Create(1); var immutable2 = ImmutableArray.Create(1); Assert.NotEqual(immutable1, immutable2); Assert.True(immutable1.Equals(immutable1)); Assert.True(immutable1.Equals((object)immutable1)); } [Fact] public void EqualsObjectNull() { Assert.False(s_empty.Equals((object)null)); } [Fact] public void OperatorsAndEquality() { Assert.True(s_empty.Equals(s_empty)); var emptySame = s_empty; Assert.True(s_empty == emptySame); Assert.False(s_empty != emptySame); // empty and default should not be seen as equal Assert.False(s_empty.Equals(s_emptyDefault)); Assert.False(s_empty == s_emptyDefault); Assert.True(s_empty != s_emptyDefault); Assert.False(s_emptyDefault == s_empty); Assert.True(s_emptyDefault != s_empty); Assert.False(s_empty.Equals(s_oneElement)); Assert.False(s_empty == s_oneElement); Assert.True(s_empty != s_oneElement); Assert.False(s_oneElement == s_empty); Assert.True(s_oneElement != s_empty); } [Fact] public void NullableOperators() { ImmutableArray<int>? nullArray = null; ImmutableArray<int>? nonNullDefault = s_emptyDefault; ImmutableArray<int>? nonNullEmpty = s_empty; Assert.True(nullArray == nonNullDefault); Assert.False(nullArray != nonNullDefault); Assert.True(nonNullDefault == nullArray); Assert.False(nonNullDefault != nullArray); Assert.False(nullArray == nonNullEmpty); Assert.True(nullArray != nonNullEmpty); Assert.False(nonNullEmpty == nullArray); Assert.True(nonNullEmpty != nullArray); } [Fact] public void GetHashCodeTest() { Assert.Equal(0, s_emptyDefault.GetHashCode()); Assert.NotEqual(0, s_empty.GetHashCode()); Assert.NotEqual(0, s_oneElement.GetHashCode()); } [Fact] public void Add() { var source = new[] { 1, 2 }; var array1 = ImmutableArray.Create(source); var array2 = array1.Add(3); Assert.Equal(source, array1); Assert.Equal(new[] { 1, 2, 3 }, array2); Assert.Equal(new[] { 1 }, s_empty.Add(1)); } [Fact] public void AddRange() { var nothingToEmpty = s_empty.AddRange(Enumerable.Empty<int>()); Assert.False(nothingToEmpty.IsDefault); Assert.True(nothingToEmpty.IsEmpty); Assert.Equal(new[] { 1, 2 }, s_empty.AddRange(Enumerable.Range(1, 2))); Assert.Equal(new[] { 1, 2 }, s_empty.AddRange(new[] { 1, 2 })); Assert.Equal(new[] { 1, 2, 3, 4 }, s_manyElements.AddRange(new[] { 4 })); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, s_manyElements.AddRange(new[] { 4, 5 })); } [Fact] public void AddRangeDefaultEnumerable() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(Enumerable.Empty<int>())); Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(Enumerable.Range(1, 2))); Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(new[] { 1, 2 })); } [Fact] public void AddRangeDefaultStruct() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(s_empty)); Assert.Throws<NullReferenceException>(() => s_empty.AddRange(s_emptyDefault)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(s_oneElement)); Assert.Throws<NullReferenceException>(() => s_oneElement.AddRange(s_emptyDefault)); IEnumerable<int> emptyBoxed = s_empty; IEnumerable<int> emptyDefaultBoxed = s_emptyDefault; IEnumerable<int> oneElementBoxed = s_oneElement; Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(emptyBoxed)); Assert.Throws<InvalidOperationException>(() => s_empty.AddRange(emptyDefaultBoxed)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(oneElementBoxed)); Assert.Throws<InvalidOperationException>(() => s_oneElement.AddRange(emptyDefaultBoxed)); } [Fact] public void AddRangeNoOpIdentity() { Assert.Equal(s_empty, s_empty.AddRange(s_empty)); Assert.Equal(s_oneElement, s_empty.AddRange(s_oneElement)); // struct overload Assert.Equal(s_oneElement, s_empty.AddRange((IEnumerable<int>)s_oneElement)); // enumerable overload Assert.Equal(s_oneElement, s_oneElement.AddRange(s_empty)); } [Fact] public void Insert() { var array1 = ImmutableArray.Create<char>(); Assert.Throws<ArgumentOutOfRangeException>(() => array1.Insert(-1, 'a')); Assert.Throws<ArgumentOutOfRangeException>(() => array1.Insert(1, 'a')); var insertFirst = array1.Insert(0, 'c'); Assert.Equal(new[] { 'c' }, insertFirst); var insertLeft = insertFirst.Insert(0, 'a'); Assert.Equal(new[] { 'a', 'c' }, insertLeft); var insertRight = insertFirst.Insert(1, 'e'); Assert.Equal(new[] { 'c', 'e' }, insertRight); var insertBetween = insertLeft.Insert(1, 'b'); Assert.Equal(new[] { 'a', 'b', 'c' }, insertBetween); } [Fact] public void InsertDefault() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.Insert(-1, 10)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.Insert(1, 10)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.Insert(0, 10)); } [Fact] public void InsertRangeNoOpIdentity() { Assert.Equal(s_empty, s_empty.InsertRange(0, s_empty)); Assert.Equal(s_oneElement, s_empty.InsertRange(0, s_oneElement)); // struct overload Assert.Equal(s_oneElement, s_empty.InsertRange(0, (IEnumerable<int>)s_oneElement)); // enumerable overload Assert.Equal(s_oneElement, s_oneElement.InsertRange(0, s_empty)); } [Fact] public void InsertRangeEmpty() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.Insert(-1, 10)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.Insert(1, 10)); Assert.Equal(new int[0], s_empty.InsertRange(0, Enumerable.Empty<int>())); Assert.Equal(s_empty, s_empty.InsertRange(0, Enumerable.Empty<int>())); Assert.Equal(new[] { 1 }, s_empty.InsertRange(0, new[] { 1 })); Assert.Equal(new[] { 2, 3, 4 }, s_empty.InsertRange(0, new[] { 2, 3, 4 })); Assert.Equal(new[] { 2, 3, 4 }, s_empty.InsertRange(0, Enumerable.Range(2, 3))); Assert.Equal(s_manyElements, s_manyElements.InsertRange(0, Enumerable.Empty<int>())); Assert.Throws<ArgumentOutOfRangeException>(() => s_empty.InsertRange(1, s_oneElement)); Assert.Throws<ArgumentOutOfRangeException>(() => s_empty.InsertRange(-1, s_oneElement)); } [Fact] public void InsertRangeDefault() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(1, Enumerable.Empty<int>())); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(-1, Enumerable.Empty<int>())); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, Enumerable.Empty<int>())); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, new[] { 1 })); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, new[] { 2, 3, 4 })); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, Enumerable.Range(2, 3))); } /// <summary> /// Validates that a fixed bug in the inappropriate adding of the /// Empty singleton enumerator to the reusable instances bag does not regress. /// </summary> [Fact] public void EmptyEnumeratorReuseRegressionTest() { IEnumerable<int> oneElementBoxed = s_oneElement; IEnumerable<int> emptyBoxed = s_empty; IEnumerable<int> emptyDefaultBoxed = s_emptyDefault; Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(emptyBoxed)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(emptyDefaultBoxed)); Assert.Throws<InvalidOperationException>(() => s_empty.RemoveRange(emptyDefaultBoxed)); Assert.Equal(oneElementBoxed, oneElementBoxed); } [Fact] public void InsertRangeDefaultStruct() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, s_empty)); Assert.Throws<NullReferenceException>(() => s_empty.InsertRange(0, s_emptyDefault)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, s_oneElement)); Assert.Throws<NullReferenceException>(() => s_oneElement.InsertRange(0, s_emptyDefault)); IEnumerable<int> emptyBoxed = s_empty; IEnumerable<int> emptyDefaultBoxed = s_emptyDefault; IEnumerable<int> oneElementBoxed = s_oneElement; Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, emptyBoxed)); Assert.Throws<InvalidOperationException>(() => s_empty.InsertRange(0, emptyDefaultBoxed)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, oneElementBoxed)); Assert.Throws<InvalidOperationException>(() => s_oneElement.InsertRange(0, emptyDefaultBoxed)); } [Fact] public void InsertRangeLeft() { Assert.Equal(new[] { 7, 1, 2, 3 }, s_manyElements.InsertRange(0, new[] { 7 })); Assert.Equal(new[] { 7, 8, 1, 2, 3 }, s_manyElements.InsertRange(0, new[] { 7, 8 })); } [Fact] public void InsertRangeMid() { Assert.Equal(new[] { 1, 7, 2, 3 }, s_manyElements.InsertRange(1, new[] { 7 })); Assert.Equal(new[] { 1, 7, 8, 2, 3 }, s_manyElements.InsertRange(1, new[] { 7, 8 })); } [Fact] public void InsertRangeRight() { Assert.Equal(new[] { 1, 2, 3, 7 }, s_manyElements.InsertRange(3, new[] { 7 })); Assert.Equal(new[] { 1, 2, 3, 7, 8 }, s_manyElements.InsertRange(3, new[] { 7, 8 })); } [Fact] public void RemoveAt() { Assert.Throws<ArgumentOutOfRangeException>(() => s_empty.RemoveAt(0)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveAt(0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_oneElement.RemoveAt(1)); Assert.Throws<ArgumentOutOfRangeException>(() => s_empty.RemoveAt(-1)); Assert.Equal(new int[0], s_oneElement.RemoveAt(0)); Assert.Equal(new[] { 2, 3 }, s_manyElements.RemoveAt(0)); Assert.Equal(new[] { 1, 3 }, s_manyElements.RemoveAt(1)); Assert.Equal(new[] { 1, 2 }, s_manyElements.RemoveAt(2)); } [Fact] public void Remove() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.Remove(5)); Assert.False(s_empty.Remove(5).IsDefault); Assert.True(s_oneElement.Remove(1).IsEmpty); Assert.Equal(new[] { 2, 3 }, s_manyElements.Remove(1)); Assert.Equal(new[] { 1, 3 }, s_manyElements.Remove(2)); Assert.Equal(new[] { 1, 2 }, s_manyElements.Remove(3)); } [Fact] public void RemoveRange() { Assert.Throws<ArgumentOutOfRangeException>(() => s_empty.RemoveRange(0, 0)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_oneElement.RemoveRange(1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_empty.RemoveRange(-1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_oneElement.RemoveRange(0, 2)); Assert.Throws<ArgumentOutOfRangeException>(() => s_oneElement.RemoveRange(0, -1)); var fourElements = ImmutableArray.Create(1, 2, 3, 4); Assert.Equal(new int[0], s_oneElement.RemoveRange(0, 1)); Assert.Equal(s_oneElement.ToArray(), s_oneElement.RemoveRange(0, 0)); Assert.Equal(new[] { 3, 4 }, fourElements.RemoveRange(0, 2)); Assert.Equal(new[] { 1, 4 }, fourElements.RemoveRange(1, 2)); Assert.Equal(new[] { 1, 2 }, fourElements.RemoveRange(2, 2)); } [Fact] public void RemoveRangeDefaultStruct() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(s_empty)); Assert.Throws<ArgumentNullException>(() => Assert.Equal(s_empty, s_empty.RemoveRange(s_emptyDefault))); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(s_oneElement)); Assert.Throws<ArgumentNullException>(() => Assert.Equal(s_oneElement, s_oneElement.RemoveRange(s_emptyDefault))); IEnumerable<int> emptyBoxed = s_empty; IEnumerable<int> emptyDefaultBoxed = s_emptyDefault; IEnumerable<int> oneElementBoxed = s_oneElement; Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(emptyBoxed)); Assert.Throws<InvalidOperationException>(() => s_empty.RemoveRange(emptyDefaultBoxed)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(oneElementBoxed)); Assert.Throws<InvalidOperationException>(() => s_oneElement.RemoveRange(emptyDefaultBoxed)); } [Fact] public void RemoveRangeNoOpIdentity() { Assert.Equal(s_empty, s_empty.RemoveRange(s_empty)); Assert.Equal(s_empty, s_empty.RemoveRange(s_oneElement)); // struct overload Assert.Equal(s_empty, s_empty.RemoveRange((IEnumerable<int>)s_oneElement)); // enumerable overload Assert.Equal(s_oneElement, s_oneElement.RemoveRange(s_empty)); } [Fact] public void RemoveAll() { Assert.Throws<ArgumentNullException>(() => s_oneElement.RemoveAll(null)); var array = ImmutableArray.CreateRange(Enumerable.Range(1, 10)); var removedEvens = array.RemoveAll(n => n % 2 == 0); var removedOdds = array.RemoveAll(n => n % 2 == 1); var removedAll = array.RemoveAll(n => true); var removedNone = array.RemoveAll(n => false); Assert.Equal(new[] { 1, 3, 5, 7, 9 }, removedEvens); Assert.Equal(new[] { 2, 4, 6, 8, 10 }, removedOdds); Assert.True(removedAll.IsEmpty); Assert.Equal(Enumerable.Range(1, 10), removedNone); Assert.False(s_empty.RemoveAll(n => false).IsDefault); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveAll(n => false)); } [Fact] public void RemoveRangeEnumerableTest() { var list = ImmutableArray.Create(1, 2, 3); Assert.Throws<ArgumentNullException>(() => list.RemoveRange(null)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(new int[0]).IsDefault); Assert.False(s_empty.RemoveRange(new int[0]).IsDefault); ImmutableArray<int> removed2 = list.RemoveRange(new[] { 2 }); Assert.Equal(2, removed2.Length); Assert.Equal(new[] { 1, 3 }, removed2); ImmutableArray<int> removed13 = list.RemoveRange(new[] { 1, 3, 5 }); Assert.Equal(1, removed13.Length); Assert.Equal(new[] { 2 }, removed13); Assert.Equal(new[] { 1, 3, 6, 8, 9 }, ImmutableArray.CreateRange(Enumerable.Range(1, 10)).RemoveRange(new[] { 2, 4, 5, 7, 10 })); Assert.Equal(new[] { 3, 6, 8, 9 }, ImmutableArray.CreateRange(Enumerable.Range(1, 10)).RemoveRange(new[] { 1, 2, 4, 5, 7, 10 })); Assert.Equal(list, list.RemoveRange(new[] { 5 })); Assert.Equal(ImmutableArray.Create<int>(), ImmutableArray.Create<int>().RemoveRange(new[] { 1 })); var listWithDuplicates = ImmutableArray.Create(1, 2, 2, 3); Assert.Equal(new[] { 1, 2, 3 }, listWithDuplicates.RemoveRange(new[] { 2 })); Assert.Equal(new[] { 1, 3 }, listWithDuplicates.RemoveRange(new[] { 2, 2 })); Assert.Equal(new[] { 1, 3 }, listWithDuplicates.RemoveRange(new[] { 2, 2, 2 })); } [Fact] public void Replace() { Assert.Equal(new[] { 5 }, s_oneElement.Replace(1, 5)); Assert.Equal(new[] { 6, 2, 3 }, s_manyElements.Replace(1, 6)); Assert.Equal(new[] { 1, 6, 3 }, s_manyElements.Replace(2, 6)); Assert.Equal(new[] { 1, 2, 6 }, s_manyElements.Replace(3, 6)); Assert.Equal(new[] { 1, 2, 3, 4 }, ImmutableArray.Create(1, 3, 3, 4).Replace(3, 2)); } [Fact] public void ReplaceMissingThrowsTest() { Assert.Throws<ArgumentException>(() => s_empty.Replace(5, 3)); } [Fact] public void SetItem() { Assert.Throws<ArgumentOutOfRangeException>(() => s_empty.SetItem(0, 10)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.SetItem(0, 10)); Assert.Throws<ArgumentOutOfRangeException>(() => s_oneElement.SetItem(1, 10)); Assert.Throws<ArgumentOutOfRangeException>(() => s_empty.SetItem(-1, 10)); Assert.Equal(new[] { 12345 }, s_oneElement.SetItem(0, 12345)); Assert.Equal(new[] { 12345, 2, 3 }, s_manyElements.SetItem(0, 12345)); Assert.Equal(new[] { 1, 12345, 3 }, s_manyElements.SetItem(1, 12345)); Assert.Equal(new[] { 1, 2, 12345 }, s_manyElements.SetItem(2, 12345)); } [Fact] public void CopyToArray() { { var target = new int[s_manyElements.Length]; s_manyElements.CopyTo(target); Assert.Equal(target, s_manyElements); } { var target = new int[0]; Assert.Throws<NullReferenceException>(() => s_emptyDefault.CopyTo(target)); } } [Fact] public void CopyToIntArrayIntInt() { var source = ImmutableArray.Create(1, 2, 3); var target = new int[4]; source.CopyTo(1, target, 3, 1); Assert.Equal(new[] { 0, 0, 0, 2 }, target); } [Fact] public void Concat() { var array1 = ImmutableArray.Create(1, 2, 3); var array2 = ImmutableArray.Create(4, 5, 6); var concat = array1.Concat(array2); Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, concat); } /// <summary> /// Verifies reuse of the original array when concatenated to an empty array. /// </summary> [Fact] public void ConcatEdgeCases() { // empty arrays Assert.Equal(s_manyElements, s_manyElements.Concat(s_empty)); Assert.Equal(s_manyElements, s_empty.Concat(s_manyElements)); // default arrays s_manyElements.Concat(s_emptyDefault); Assert.Throws<InvalidOperationException>(() => s_manyElements.Concat(s_emptyDefault).Count()); Assert.Throws<InvalidOperationException>(() => s_emptyDefault.Concat(s_manyElements).Count()); } [Fact] public void IsDefault() { Assert.True(s_emptyDefault.IsDefault); Assert.False(s_empty.IsDefault); Assert.False(s_oneElement.IsDefault); } [Fact] public void IsDefaultOrEmpty() { Assert.True(s_empty.IsDefaultOrEmpty); Assert.True(s_emptyDefault.IsDefaultOrEmpty); Assert.False(s_oneElement.IsDefaultOrEmpty); } [Fact] public void IndexGetter() { Assert.Equal(1, s_oneElement[0]); Assert.Equal(1, ((IList)s_oneElement)[0]); Assert.Equal(1, ((IList<int>)s_oneElement)[0]); Assert.Equal(1, ((IReadOnlyList<int>)s_oneElement)[0]); Assert.Throws<IndexOutOfRangeException>(() => s_oneElement[1]); Assert.Throws<IndexOutOfRangeException>(() => s_oneElement[-1]); Assert.Throws<NullReferenceException>(() => s_emptyDefault[0]); Assert.Throws<InvalidOperationException>(() => ((IList)s_emptyDefault)[0]); Assert.Throws<InvalidOperationException>(() => ((IList<int>)s_emptyDefault)[0]); Assert.Throws<InvalidOperationException>(() => ((IReadOnlyList<int>)s_emptyDefault)[0]); } [Fact] public void ExplicitMethods() { IList<int> c = s_oneElement; Assert.Throws<NotSupportedException>(() => c.Add(3)); Assert.Throws<NotSupportedException>(() => c.Clear()); Assert.Throws<NotSupportedException>(() => c.Remove(3)); Assert.True(c.IsReadOnly); Assert.Throws<NotSupportedException>(() => c.Insert(0, 2)); Assert.Throws<NotSupportedException>(() => c.RemoveAt(0)); Assert.Equal(s_oneElement[0], c[0]); Assert.Throws<NotSupportedException>(() => c[0] = 8); var enumerator = c.GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.Equal(s_oneElement[0], enumerator.Current); Assert.False(enumerator.MoveNext()); } [Fact] public void Sort() { var array = ImmutableArray.Create(2, 4, 1, 3); Assert.Equal(new[] { 1, 2, 3, 4 }, array.Sort()); Assert.Equal(new[] { 2, 4, 1, 3 }, array); // original array unaffected. } [Fact] public void SortNullComparer() { var array = ImmutableArray.Create(2, 4, 1, 3); Assert.Equal(new[] { 1, 2, 3, 4 }, array.Sort(null)); Assert.Equal(new[] { 2, 4, 1, 3 }, array); // original array unaffected. } [Fact] public void SortRange() { var array = ImmutableArray.Create(2, 4, 1, 3); Assert.Throws<ArgumentOutOfRangeException>(() => array.Sort(-1, 2, Comparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => array.Sort(1, 4, Comparer<int>.Default)); Assert.Equal(new int[] { 2, 4, 1, 3 }, array.Sort(array.Length, 0, Comparer<int>.Default)); Assert.Equal(new[] { 2, 1, 4, 3 }, array.Sort(1, 2, Comparer<int>.Default)); } [Fact] public void SortComparer() { var array = ImmutableArray.Create("c", "B", "a"); Assert.Equal(new[] { "a", "B", "c" }, array.Sort(StringComparer.OrdinalIgnoreCase)); Assert.Equal(new[] { "B", "a", "c" }, array.Sort(StringComparer.Ordinal)); } [Fact] public void SortPreservesArrayWhenAlreadySorted() { var sortedArray = ImmutableArray.Create(1, 2, 3, 4); Assert.Equal(sortedArray, sortedArray.Sort()); var mostlySorted = ImmutableArray.Create(1, 2, 3, 4, 6, 5, 7, 8, 9, 10); Assert.Equal(mostlySorted, mostlySorted.Sort(0, 5, Comparer<int>.Default)); Assert.Equal(mostlySorted, mostlySorted.Sort(5, 5, Comparer<int>.Default)); Assert.Equal(Enumerable.Range(1, 10), mostlySorted.Sort(4, 2, Comparer<int>.Default)); } [Fact] public void ToBuilder() { Assert.Equal(0, s_empty.ToBuilder().Count); Assert.Throws<NullReferenceException>(() => s_emptyDefault.ToBuilder().Count); var builder = s_oneElement.ToBuilder(); Assert.Equal(s_oneElement.ToArray(), builder); builder = s_manyElements.ToBuilder(); Assert.Equal(s_manyElements.ToArray(), builder); // Make sure that changing the builder doesn't change the original immutable array. int expected = s_manyElements[0]; builder[0] = expected + 1; Assert.Equal(expected, s_manyElements[0]); Assert.Equal(expected + 1, builder[0]); } [Fact] public void StructuralEquatableEqualsDefault() { IStructuralEquatable eq = s_emptyDefault; Assert.True(eq.Equals(s_emptyDefault, EqualityComparer<int>.Default)); Assert.False(eq.Equals(s_empty, EqualityComparer<int>.Default)); Assert.False(eq.Equals(s_oneElement, EqualityComparer<int>.Default)); } [Fact] public void StructuralEquatableEquals() { IStructuralEquatable array = new int[3] { 1, 2, 3 }.AsStructuralEquatable(); IStructuralEquatable immArray = ImmutableArray.Create(1, 2, 3); var otherArray = new object[] { 1, 2, 3 }; var otherImmArray = ImmutableArray.Create(otherArray); var unequalArray = new int[] { 1, 2, 4 }; var unequalImmArray = ImmutableArray.Create(unequalArray); var unrelatedArray = new string[3]; var unrelatedImmArray = ImmutableArray.Create(unrelatedArray); var otherList = new List<int> { 1, 2, 3 }; Assert.Equal(array.Equals(otherArray, EqualityComparer<int>.Default), immArray.Equals(otherImmArray, EqualityComparer<int>.Default)); Assert.Equal(array.Equals(otherList, EqualityComparer<int>.Default), immArray.Equals(otherList, EqualityComparer<int>.Default)); Assert.Equal(array.Equals(unrelatedArray, EverythingEqual<object>.Default), immArray.Equals(unrelatedImmArray, EverythingEqual<object>.Default)); Assert.Equal(array.Equals(new object(), EqualityComparer<int>.Default), immArray.Equals(new object(), EqualityComparer<int>.Default)); Assert.Equal(array.Equals(null, EqualityComparer<int>.Default), immArray.Equals(null, EqualityComparer<int>.Default)); Assert.Equal(array.Equals(unequalArray, EqualityComparer<int>.Default), immArray.Equals(unequalImmArray, EqualityComparer<int>.Default)); } [Fact] public void StructuralEquatableEqualsArrayInterop() { IStructuralEquatable array = new int[3] { 1, 2, 3 }.AsStructuralEquatable(); IStructuralEquatable immArray = ImmutableArray.Create(1, 2, 3); var unequalArray = new int[] { 1, 2, 4 }; Assert.True(immArray.Equals(array, EqualityComparer<int>.Default)); Assert.False(immArray.Equals(unequalArray, EqualityComparer<int>.Default)); } [Fact] public void StructuralEquatableGetHashCodeDefault() { IStructuralEquatable defaultImmArray = s_emptyDefault; Assert.Equal(0, defaultImmArray.GetHashCode(EqualityComparer<int>.Default)); } [Fact] public void StructuralEquatableGetHashCode() { IStructuralEquatable emptyArray = new int[0].AsStructuralEquatable(); IStructuralEquatable emptyImmArray = s_empty; IStructuralEquatable array = new int[3] { 1, 2, 3 }.AsStructuralEquatable(); IStructuralEquatable immArray = ImmutableArray.Create(1, 2, 3); Assert.Equal(emptyArray.GetHashCode(EqualityComparer<int>.Default), emptyImmArray.GetHashCode(EqualityComparer<int>.Default)); Assert.Equal(array.GetHashCode(EqualityComparer<int>.Default), immArray.GetHashCode(EqualityComparer<int>.Default)); Assert.Equal(array.GetHashCode(EverythingEqual<int>.Default), immArray.GetHashCode(EverythingEqual<int>.Default)); } [Fact] public void StructuralComparableDefault() { IStructuralComparable def = s_emptyDefault; IStructuralComparable mt = s_empty; // default to default is fine, and should be seen as equal. Assert.Equal(0, def.CompareTo(s_emptyDefault, Comparer<int>.Default)); // default to empty and vice versa should throw, on the basis that // arrays compared that are of different lengths throw. Empty vs. default aren't really compatible. Assert.Throws<ArgumentException>(() => def.CompareTo(s_empty, Comparer<int>.Default)); Assert.Throws<ArgumentException>(() => mt.CompareTo(s_emptyDefault, Comparer<int>.Default)); } [Fact] public void StructuralComparable() { IStructuralComparable array = new int[3] { 1, 2, 3 }.AsStructuralComparable(); IStructuralComparable equalArray = new int[3] { 1, 2, 3 }.AsStructuralComparable(); IStructuralComparable immArray = ImmutableArray.Create(array.CastAsArray<int>()); IStructuralComparable equalImmArray = ImmutableArray.Create(equalArray.CastAsArray<int>()); IStructuralComparable longerArray = new int[] { 1, 2, 3, 4 }.AsStructuralComparable(); IStructuralComparable longerImmArray = ImmutableArray.Create(longerArray.CastAsArray<int>()); Assert.Equal(array.CompareTo(equalArray, Comparer<int>.Default), immArray.CompareTo(equalImmArray, Comparer<int>.Default)); Assert.Throws<ArgumentException>(() => array.CompareTo(longerArray, Comparer<int>.Default)); Assert.Throws<ArgumentException>(() => immArray.CompareTo(longerImmArray, Comparer<int>.Default)); var list = new List<int> { 1, 2, 3 }; Assert.Throws<ArgumentException>(() => array.CompareTo(list, Comparer<int>.Default)); Assert.Throws<ArgumentException>(() => immArray.CompareTo(list, Comparer<int>.Default)); } [Fact] public void StructuralComparableArrayInterop() { IStructuralComparable array = new int[3] { 1, 2, 3 }.AsStructuralComparable(); IStructuralComparable equalArray = new int[3] { 1, 2, 3 }.AsStructuralComparable(); IStructuralComparable immArray = ImmutableArray.Create(array.CastAsArray<int>()); IStructuralComparable equalImmArray = ImmutableArray.Create(equalArray.CastAsArray<int>()); Assert.Equal(array.CompareTo(equalArray, Comparer<int>.Default), immArray.CompareTo(equalArray, Comparer<int>.Default)); } [Fact] public void BinarySearch() { Assert.Throws<ArgumentNullException>(() => Assert.Equal(Array.BinarySearch(new int[0], 5), ImmutableArray.BinarySearch(default(ImmutableArray<int>), 5))); Assert.Equal(Array.BinarySearch(new int[0], 5), ImmutableArray.BinarySearch(ImmutableArray.Create<int>(), 5)); Assert.Equal(Array.BinarySearch(new int[] { 3 }, 5), ImmutableArray.BinarySearch(ImmutableArray.Create(3), 5)); Assert.Equal(Array.BinarySearch(new int[] { 5 }, 5), ImmutableArray.BinarySearch(ImmutableArray.Create(5), 5)); } [Fact] public void OfType() { Assert.Equal(0, s_emptyDefault.OfType<int>().Count()); Assert.Equal(0, s_empty.OfType<int>().Count()); Assert.Equal(1, s_oneElement.OfType<int>().Count()); Assert.Equal(1, s_twoElementRefTypeWithNull.OfType<string>().Count()); } #if NET35PLUS [Fact] public void Add_ThreadSafety() { // Note the point of this thread-safety test is *not* to test the thread-safety of the test itself. // This test has a known issue where the two threads will stomp on each others updates, but that's not the point. // The point is that ImmutableArray`1.Add should *never* throw. But if it reads its own T[] field more than once, // it *can* throw because the field can be replaced with an array of another length. // In fact, much worse can happen where we corrupt data if we are for example copying data out of the array // in (for example) a CopyTo method and we read from the field more than once. // Also noteworthy: this method only tests the thread-safety of the Add method. // While it proves the general point, any method that reads 'this' more than once is vulnerable. var array = ImmutableArray.Create<int>(); Action mutator = () => { for (int i = 0; i < 100; i++) { ImmutableInterlocked.InterlockedExchange(ref array, array.Add(1)); } }; Task.WaitAll(Task.Factory.StartNew(mutator), Task.Factory.StartNew(mutator)); } #endif [Fact] public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableArray.Create<string>()); // verify empty DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableArray.Create(1, 2, 3)); // verify non-empty } [Fact] public void ICollectionSyncRoot_NotSupported() { ICollection c = ImmutableArray.Create(1, 2, 3); Assert.Throws<NotSupportedException>(() => c.SyncRoot); } protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents) { return ImmutableArray.Create(contents); } /// <summary> /// A structure that takes exactly 3 bytes of memory. /// </summary> private struct ThreeByteStruct : IEquatable<ThreeByteStruct> { public ThreeByteStruct(byte first, byte second, byte third) { this.Field1 = first; this.Field2 = second; this.Field3 = third; } public byte Field1; public byte Field2; public byte Field3; public bool Equals(ThreeByteStruct other) { return this.Field1 == other.Field1 && this.Field2 == other.Field2 && this.Field3 == other.Field3; } public override bool Equals(object obj) { if (obj is ThreeByteStruct) { return this.Equals((ThreeByteStruct)obj); } return false; } public override int GetHashCode() { return this.Field1; } } /// <summary> /// A structure that takes exactly 9 bytes of memory. /// </summary> private struct NineByteStruct : IEquatable<NineByteStruct> { public NineByteStruct(int first, int second, int third, int fourth, int fifth, int sixth, int seventh, int eighth, int ninth) { this.Field1 = (byte)first; this.Field2 = (byte)second; this.Field3 = (byte)third; this.Field4 = (byte)fourth; this.Field5 = (byte)fifth; this.Field6 = (byte)sixth; this.Field7 = (byte)seventh; this.Field8 = (byte)eighth; this.Field9 = (byte)ninth; } public byte Field1; public byte Field2; public byte Field3; public byte Field4; public byte Field5; public byte Field6; public byte Field7; public byte Field8; public byte Field9; public bool Equals(NineByteStruct other) { return this.Field1 == other.Field1 && this.Field2 == other.Field2 && this.Field3 == other.Field3 && this.Field4 == other.Field4 && this.Field5 == other.Field5 && this.Field6 == other.Field6 && this.Field7 == other.Field7 && this.Field8 == other.Field8 && this.Field9 == other.Field9; } public override bool Equals(object obj) { if (obj is NineByteStruct) { return this.Equals((NineByteStruct)obj); } return false; } public override int GetHashCode() { return this.Field1; } } /// <summary> /// A structure that requires 9 bytes of memory but occupies 12 because of memory alignment. /// </summary> private struct TwelveByteStruct : IEquatable<TwelveByteStruct> { public TwelveByteStruct(int first, int second, byte third) { this.Field1 = first; this.Field2 = second; this.Field3 = third; } public int Field1; public int Field2; public byte Field3; public bool Equals(TwelveByteStruct other) { return this.Field1 == other.Field1 && this.Field2 == other.Field2 && this.Field3 == other.Field3; } public override bool Equals(object obj) { if (obj is TwelveByteStruct) { return this.Equals((TwelveByteStruct)obj); } return false; } public override int GetHashCode() { return this.Field1; } } private struct StructWithReferenceTypeField { public string foo; public StructWithReferenceTypeField(string foo) { this.foo = foo; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.DotNet.ProjectModel; using Microsoft.Extensions.DependencyModel; namespace Microsoft.DotNet.Cli.Utils { public class DepsJsonCommandResolver : ICommandResolver { private static readonly string[] s_extensionPreferenceOrder = new[] { "", ".exe", ".dll" }; private string _nugetPackageRoot; private Muxer _muxer; public DepsJsonCommandResolver(string nugetPackageRoot) : this(new Muxer(), nugetPackageRoot) { } public DepsJsonCommandResolver(Muxer muxer, string nugetPackageRoot) { _muxer = muxer; _nugetPackageRoot = nugetPackageRoot; } public CommandSpec Resolve(CommandResolverArguments commandResolverArguments) { if (commandResolverArguments.CommandName == null || commandResolverArguments.DepsJsonFile == null) { return null; } return ResolveFromDepsJsonFile( commandResolverArguments.CommandName, commandResolverArguments.CommandArguments.OrEmptyIfNull(), commandResolverArguments.DepsJsonFile); } private CommandSpec ResolveFromDepsJsonFile( string commandName, IEnumerable<string> commandArgs, string depsJsonFile) { var dependencyContext = LoadDependencyContextFromFile(depsJsonFile); var commandPath = GetCommandPathFromDependencyContext(commandName, dependencyContext); if (commandPath == null) { return null; } return CreateCommandSpecUsingMuxerIfPortable( commandPath, commandArgs, depsJsonFile, CommandResolutionStrategy.DepsFile, _nugetPackageRoot, IsPortableApp(commandPath)); } public DependencyContext LoadDependencyContextFromFile(string depsJsonFile) { DependencyContext dependencyContext = null; DependencyContextJsonReader contextReader = new DependencyContextJsonReader(); using (var contextStream = File.OpenRead(depsJsonFile)) { dependencyContext = contextReader.Read(contextStream); } return dependencyContext; } public string GetCommandPathFromDependencyContext(string commandName, DependencyContext dependencyContext) { var commandCandidates = new List<CommandCandidate>(); var assemblyCommandCandidates = GetCommandCandidates( commandName, dependencyContext, CommandCandidateType.RuntimeCommandCandidate); var nativeCommandCandidates = GetCommandCandidates( commandName, dependencyContext, CommandCandidateType.NativeCommandCandidate); commandCandidates.AddRange(assemblyCommandCandidates); commandCandidates.AddRange(nativeCommandCandidates); var command = ChooseCommandCandidate(commandCandidates); return command?.GetAbsoluteCommandPath(_nugetPackageRoot); } private IEnumerable<CommandCandidate> GetCommandCandidates( string commandName, DependencyContext dependencyContext, CommandCandidateType commandCandidateType) { var commandCandidates = new List<CommandCandidate>(); foreach (var runtimeLibrary in dependencyContext.RuntimeLibraries) { IEnumerable<RuntimeAssetGroup> runtimeAssetGroups = null; if (commandCandidateType == CommandCandidateType.NativeCommandCandidate) { runtimeAssetGroups = runtimeLibrary.NativeLibraryGroups; } else if (commandCandidateType == CommandCandidateType.RuntimeCommandCandidate) { runtimeAssetGroups = runtimeLibrary.RuntimeAssemblyGroups; } commandCandidates.AddRange(GetCommandCandidatesFromRuntimeAssetGroups( commandName, runtimeAssetGroups, runtimeLibrary.Name, runtimeLibrary.Version)); } return commandCandidates; } private IEnumerable<CommandCandidate> GetCommandCandidatesFromRuntimeAssetGroups( string commandName, IEnumerable<RuntimeAssetGroup> runtimeAssetGroups, string PackageName, string PackageVersion) { var candidateAssetGroups = runtimeAssetGroups .Where(r => r.Runtime == string.Empty) .Where(a => a.AssetPaths.Any(p => Path.GetFileNameWithoutExtension(p).Equals(commandName, StringComparison.OrdinalIgnoreCase))); var commandCandidates = new List<CommandCandidate>(); foreach (var candidateAssetGroup in candidateAssetGroups) { var candidateAssetPaths = candidateAssetGroup.AssetPaths.Where( p => Path.GetFileNameWithoutExtension(p) .Equals(commandName, StringComparison.OrdinalIgnoreCase)); foreach (var candidateAssetPath in candidateAssetPaths) { commandCandidates.Add(new CommandCandidate { PackageName = PackageName, PackageVersion = PackageVersion, RelativeCommandPath = candidateAssetPath }); } } return commandCandidates; } private CommandCandidate ChooseCommandCandidate(IEnumerable<CommandCandidate> commandCandidates) { foreach (var extension in s_extensionPreferenceOrder) { var candidate = commandCandidates .FirstOrDefault(p => Path.GetExtension(p.RelativeCommandPath) .Equals(extension, StringComparison.OrdinalIgnoreCase)); if (candidate != null) { return candidate; } } return null; } private CommandSpec CreateCommandSpecUsingMuxerIfPortable( string commandPath, IEnumerable<string> commandArgs, string depsJsonFile, CommandResolutionStrategy commandResolutionStrategy, string nugetPackagesRoot, bool isPortable) { var depsFileArguments = GetDepsFileArguments(depsJsonFile); var additionalProbingPathArguments = GetAdditionalProbingPathArguments(); var muxerArgs = new List<string>(); muxerArgs.Add("exec"); muxerArgs.AddRange(depsFileArguments); muxerArgs.AddRange(additionalProbingPathArguments); muxerArgs.Add(commandPath); muxerArgs.AddRange(commandArgs); var escapedArgString = ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(muxerArgs); return new CommandSpec(_muxer.MuxerPath, escapedArgString, commandResolutionStrategy); } private bool IsPortableApp(string commandPath) { var commandDir = Path.GetDirectoryName(commandPath); var runtimeConfigPath = Directory.EnumerateFiles(commandDir) .FirstOrDefault(x => x.EndsWith("runtimeconfig.json")); if (runtimeConfigPath == null) { return false; } var runtimeConfig = new RuntimeConfig(runtimeConfigPath); return runtimeConfig.IsPortable; } private IEnumerable<string> GetDepsFileArguments(string depsJsonFile) { return new[] { "--depsfile", depsJsonFile }; } private IEnumerable<string> GetAdditionalProbingPathArguments() { return new[] { "--additionalProbingPath", _nugetPackageRoot }; } private class CommandCandidate { public string PackageName { get; set; } public string PackageVersion { get; set; } public string RelativeCommandPath { get; set; } public string GetAbsoluteCommandPath(string nugetPackageRoot) { return Path.Combine( nugetPackageRoot.Replace('/', Path.DirectorySeparatorChar), PackageName.Replace('/', Path.DirectorySeparatorChar), PackageVersion.Replace('/', Path.DirectorySeparatorChar), RelativeCommandPath.Replace('/', Path.DirectorySeparatorChar)); } } private enum CommandCandidateType { NativeCommandCandidate, RuntimeCommandCandidate } } }
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // 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.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Security.Cryptography; using System.Text; using NakedObjects; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using AdventureWorksModel.Attr; using NakedFramework; using NakedFramework.Value; namespace AdventureWorksModel { public class Person : BusinessEntity { #region Life Cycle Methods public override void Persisting() { //base.Persisting(); CreateSaltAndHash(InitialPassword); rowguid = Guid.NewGuid(); BusinessEntityRowguid = rowguid; ModifiedDate = DateTime.Now; BusinessEntityModifiedDate = ModifiedDate; } public override void Updating() { //base.Updating(); ModifiedDate = DateTime.Now; BusinessEntityModifiedDate = ModifiedDate; } #endregion #region AdditionalContactInfo [Optionally] [MemberOrder(30)] public virtual string AdditionalContactInfo { get; set; } #endregion #region Title public override string ToString() { var t = Container.NewTitleBuilder(); if (NameStyle) { t.Append(LastName).Append(FirstName); } else { t.Append(FirstName).Append(LastName); } return t.ToString(); } #endregion [NotPersisted] [NakedObjectsIgnore] public IBusinessEntity ForEntity { get; set; } [MemberOrder(2)] [NotPersisted][Hidden(WhenTo.OncePersisted)] public virtual ContactType ContactType { get; set; } public void Persisted() { var relationship = Container.NewTransientInstance<BusinessEntityContact>(); relationship.BusinessEntityID = ForEntity.BusinessEntityID; relationship.PersonID = this.BusinessEntityID; relationship.ContactTypeID = ContactType.ContactTypeID; Container.Persist(ref relationship); } #region Name fields #region NameStyle [MemberOrder(15), DefaultValue(false), DisplayName("Reverse name order")] public virtual bool NameStyle { get; set; } #endregion #region Title [Optionally] [StringLength(8)] [MemberOrder(11)] public virtual string Title { get; set; } #endregion #region FirstName [StringLength(50)] [MemberOrder(12)] public virtual string FirstName { get; set; } #endregion #region MiddleName [StringLength(50)] [Optionally] [MemberOrder(13)] public virtual string MiddleName { get; set; } #endregion #region LastName [StringLength(50)] [MemberOrder(14)] public virtual string LastName { get; set; } #endregion #region Suffix [Optionally] [StringLength(10)] [MemberOrder(15)] public virtual string Suffix { get; set; } #endregion #endregion #region Communication #region EmailPromotion [MemberOrder(21), DefaultValue(1)] public virtual EmailPromotion EmailPromotion { get; set; } #endregion #endregion #region Password [NakedObjectsIgnore] public virtual Password Password { get; set; } #region ChangePassword (Action) [Hidden(WhenTo.UntilPersisted)] [MemberOrder(1)] public void ChangePassword([DataType(DataType.Password)] string oldPassword, [DataType(DataType.Password)] string newPassword, [Named("New Password (Confirm)"), DataType(DataType.Password)] string confirm) { CreateSaltAndHash(newPassword); } internal void CreateSaltAndHash(string newPassword) { Password.PasswordSalt = CreateRandomSalt(); Password.PasswordHash = Hashed(newPassword, Password.PasswordSalt); } public virtual string ValidateChangePassword(string oldPassword, string newPassword, string confirm) { var rb = new ReasonBuilder(); //if (Hashed(oldPassword, Password.PasswordSalt) != Password.PasswordHash) { // rb.Append("Old Password is incorrect"); //} if (newPassword != confirm) { rb.Append("New Password and Confirmation don't match"); } if (newPassword.Length < 6) { rb.Append("New Password must be at least 6 characters"); } if (newPassword == oldPassword) { rb.Append("New Password should be different from Old Password"); } return rb.Reason; } #endregion #region InitialPassword Property //See Persisting method [NotPersisted] [Hidden(WhenTo.OncePersisted)] [MemberOrder(27)] [DataType(DataType.Password)] public string InitialPassword { get; set; } public void ModifyInitialPassword([DataType(DataType.Password)] string value) { InitialPassword = value; ChangePassword(null, value, null); } #endregion private static string Hashed(string password, string salt) { string saltedPassword = password + salt; byte[] data = Encoding.UTF8.GetBytes(saltedPassword); byte[] hash = SHA256.Create().ComputeHash(data); char[] chars = Encoding.UTF8.GetChars(hash); return new string(chars); } private static string CreateRandomSalt() { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var random = new Random(); var output = new StringBuilder(); for (int i = 1; i <= 7; i++) { output.Append(chars.Substring(random.Next(chars.Length - 1), 1)); } output.Append("="); return output.ToString(); } #endregion //To test a null image [NotMapped] public virtual Image Photo { get { return null; } } #region Row Guid and Modified Date #region rowguid [NakedObjectsIgnore] public virtual Guid rowguid { get; set; } #endregion #region ModifiedDate [MemberOrder(99)] [Disabled] public virtual DateTime ModifiedDate { get; set; } #endregion #endregion public override bool HideContacts() { return true; } #region EmailAddresses (collection) private ICollection<EmailAddress> _EmailAddresses = new List<EmailAddress>(); [Eagerly(Do.Rendering)] [TableView(false, nameof(EmailAddress.EmailAddress1))] public virtual ICollection<EmailAddress> EmailAddresses { get { return _EmailAddresses; } set { _EmailAddresses = value; } } #endregion #region PhoneNumbers (collection) [AWNotCounted] [TableView(false, nameof(PersonPhone.PhoneNumberType), nameof(PersonPhone.PhoneNumber))] public virtual ICollection<PersonPhone> PhoneNumbers { get; set; } = new List<PersonPhone>(); public void CreateNewPhoneNumber(PhoneNumberType type, [RegularExpression(@"[0-9][0-9\s-]+")]string phoneNumber) { var pp = Container.NewTransientInstance<PersonPhone>(); pp.BusinessEntityID = this.BusinessEntityID; pp.Person = this; pp.PhoneNumberType = type; pp.PhoneNumberTypeID = type.PhoneNumberTypeID; pp.PhoneNumber = phoneNumber; Container.Persist(ref pp); this.PhoneNumbers.Add(pp); } #endregion [NakedObjectsIgnore] public virtual Employee Employee { get; set; } #region CreditCards public CreditCard CreateNewCreditCard() { var newCard = Container.NewTransientInstance<CreditCard>(); newCard.ForContact = this; return newCard; } public IList<CreditCard> ListCreditCards() { int id = this.BusinessEntityID; return Container.Instances<PersonCreditCard>().Where(pcc => pcc.PersonID == id).Select(pcc => pcc.CreditCard).ToList(); } public IQueryable<CreditCard> RecentCreditCards() { int id = this.BusinessEntityID; return Container.Instances<PersonCreditCard>().Where(pcc => pcc.PersonID == id).Select(pcc => pcc.CreditCard).OrderByDescending(cc => cc.ModifiedDate); } #endregion #region Actions for test purposes only public void UpdateMiddleName(string newName) { MiddleName = newName; } [QueryOnly] //This action is deliberately marked QueryOnly even //though it is not. Don't change it! public void UpdateSuffix(string newSuffix) { Suffix = newSuffix; } //To test a ViewModelEdit public EmailTemplate CreateEmail() { var email = Container.NewViewModel<EmailTemplate>(); email.Status = EmailStatus.New; return email; } public void CreateLetter(Address toAddress) { } public Address Default0CreateLetter() { return this.Addresses.First().Address; } #endregion } public class EmailTemplate : IViewModelEdit { #region Injected Services public IDomainObjectContainer Container { set; protected get; } #endregion #region public string[] DeriveKeys() { return new[] { To, From, Subject, Message, Status.ToString() }; } public void PopulateUsingKeys(string[] keys) { this.To = keys[0]; this.From = keys[1]; this.Subject = keys[2]; this.Message = keys[3]; this.Status = (EmailStatus)Enum.Parse(typeof(EmailStatus), keys[4]); } #endregion public override string ToString() { var t = Container.NewTitleBuilder(); t.Append(Status).Append("email"); return t.ToString(); } [MemberOrder(10), Optionally] public virtual string To { get; set; } [MemberOrder(20), Optionally] public virtual string From { get; set; } [MemberOrder(30), Optionally] public virtual string Subject { get; set; } public virtual IQueryable<string> AutoCompleteSubject([MinLength(2)] string value) { var matchingNames = new List<string> { "Subject1", "Subject2", "Subject3" }; return from p in matchingNames.AsQueryable() select p.Trim(); } [MemberOrder(40), Optionally] public virtual string Message { get; set; } [Disabled] public virtual EmailStatus Status { get; set; } public EmailTemplate Send() { this.Status = EmailStatus.Sent; return this; } } public enum EmailStatus { New, Sent, Failed } public enum EmailPromotion { NoPromotions = 0, AdventureworksOnly = 1, AdventureworksAndPartners = 2 } }
using Microsoft.SharePoint.Administration; using Microsoft.SharePoint.Utilities; using System; using System.Diagnostics; using Microsoft.SharePoint; using System.Reflection; using SharepointCommon.Attributes; using SharepointCommon.Common; namespace SharepointCommon.Impl { [DebuggerDisplay("Url = {Web.Url}")] internal sealed class QueryWeb : IQueryWeb { private readonly string _webUrl; private readonly bool _shouldDispose = true; internal QueryWeb(string webUrl, bool elevate) { _webUrl = webUrl; if (elevate == false) { Site = new SPSite(webUrl); } else { Site = new SPSite(webUrl, SPUserToken.SystemAccount); } Web = Site.OpenWeb(); } internal QueryWeb(Guid site, Guid web, bool elevate, SPUrlZone? zone = null) { if (elevate == false) { Site = new SPSite(site, zone == null ? SPUrlZone.Default : zone.Value); } else { Site = new SPSite(site, zone == null ? SPUrlZone.Default : zone.Value, SPUserToken.SystemAccount); } Web = Site.OpenWeb(web); _webUrl = Web.Url; } internal QueryWeb(Guid site, bool elevate) { if (elevate == false) { Site = new SPSite(site); } else { Site = new SPSite(site, SPUserToken.SystemAccount); } Web = Site.OpenWeb(); _webUrl = Web.Url; } internal QueryWeb(SPWeb web) { _webUrl = web.Url; _shouldDispose = false; Site = web.Site; Web = web; } public SPSite Site { get; set; } public SPWeb Web { get; set; } public IQueryWeb Elevate() { return new QueryWeb(_webUrl, true); } public IQueryWeb Unsafe() { Web.AllowUnsafeUpdates = true; return this; } public IQueryList<T> GetByUrl<T>(string listUrl) where T : Item, new() { var list = Web.GetList(CommonHelper.CombineUrls(Web.ServerRelativeUrl, listUrl)); return new ListBase<T>(list, this); } public IQueryList<T> GetByName<T>(string listName) where T : Item, new() { var list = Web.Lists[listName]; return new ListBase<T>(list, this); } public IQueryList<T> GetById<T>(Guid id) where T : Item, new() { var list = Web.Lists[id]; return new ListBase<T>(list, this); } public IQueryList<T> CurrentList<T>() where T : Item, new() { Assert.CurrentContextAvailable(); return new ListBase<T>(SPContext.Current.List, this); } public IQueryList<T> Create<T>(string listName) where T : Item, new() { SPListTemplateType listType = GetListType<T>(); var id = Web.Lists.Add(listName, string.Empty, listType); var list = GetById<T>(id); try { var itemType = typeof(T); if (itemType.GetCustomAttributes(typeof(ContentTypeAttribute), false).Length > 0) { if (SPListTemplateType.GenericList == listType) { if (itemType != typeof(Item)) { list.RemoveContentType<Item>(); list.AddContentType<T>(); } } else { if (itemType != typeof(Document)) { list.RemoveContentType<Document>(); list.AddContentType<T>(); } } } else { list.EnsureFields(); } return list; } catch { list.DeleteList(false); throw; } } public bool ExistsByUrl(string listUrl) { try { var list = Web.GetList(CommonHelper.CombineUrls(Web.ServerRelativeUrl, listUrl)); return list != null; } catch (System.IO.FileNotFoundException) { return false; } } public bool ExistsByName(string listName) { var list = Web.Lists.TryGetList(listName); return list != null; } public bool ExistsById(Guid id) { try { var list = Web.Lists[id]; return list != null; } catch (SPException) { return false; } } public void Dispose() { if (_shouldDispose == false) return; if (Site != null) Site.Dispose(); if (Web != null) Web.Dispose(); } internal object Create(Type entityType, string listName) { var qw = typeof(QueryWeb); var createMethod = qw.GetMethod( "Create", BindingFlags.Public | BindingFlags.Instance, null, new[] { typeof(string) }, null); var g = createMethod.MakeGenericMethod(entityType); return g.Invoke(this, new object[] { listName }); } internal object GetByName(Type entityType, string listName) { var list = Web.Lists[listName]; var type = typeof(ListBase<>); var typeGeneric = type.MakeGenericType(entityType); return Activator.CreateInstance(typeGeneric, BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { list, this }, null); } internal object GetByUrl(Type entityType, string listUrl) { var list = Web.GetList(CommonHelper.CombineUrls(Web.ServerRelativeUrl, listUrl)); var type = typeof(ListBase<>); var typeGeneric = type.MakeGenericType(entityType); return Activator.CreateInstance(typeGeneric, BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { list, this }, null); } private SPListTemplateType GetListType<T>() { if (typeof(Document).IsAssignableFrom(typeof(T))) { return SPListTemplateType.DocumentLibrary; } if (typeof(Item).IsAssignableFrom(typeof(T))) { return SPListTemplateType.GenericList; } throw new SharepointCommonException("Cant determine actual list type. Do you inherited item from 'Item' or 'Document'?"); } } }
using System; using System.Text; using SimpleJson; using System.Collections; using System.Collections.Generic; namespace Pomelo.Protobuf { public class MsgDecoder { private JsonObject protos { set; get; }//The message format(like .proto file) private int offset { set; get; } private byte[] buffer { set; get; }//The binary message from server. private Util util { set; get; } public MsgDecoder(JsonObject protos) { if (protos == null) protos = new JsonObject(); this.protos = protos; this.util = new Util(); } /// <summary> /// Decode message from server. /// </summary> /// <param name='route'> /// Route. /// </param> /// <param name='buf'> /// JsonObject. /// </param> public JsonObject decode(string route, byte[] buf) { this.buffer = buf; this.offset = 0; object proto = null; if (this.protos.TryGetValue(route, out proto)) { JsonObject msg = new JsonObject(); return this.decodeMsg(msg, (JsonObject)proto, this.buffer.Length); } return null; } /// <summary> /// Decode the message. /// </summary> /// <returns> /// The message. /// </returns> /// <param name='msg'> /// JsonObject. /// </param> /// <param name='proto'> /// JsonObject. /// </param> /// <param name='length'> /// int. /// </param> private JsonObject decodeMsg(JsonObject msg, JsonObject proto, int length) { while (this.offset < length) { Dictionary<string, int> head = this.getHead(); int tag; if (head.TryGetValue("tag", out tag)) { object _tags = null; if (proto.TryGetValue("__tags", out _tags)) { object name; if (((JsonObject)_tags).TryGetValue(tag.ToString(), out name)) { object value; if (proto.TryGetValue(name.ToString(), out value)) { object option; if (((JsonObject)(value)).TryGetValue("option", out option)) { switch (option.ToString()) { case "optional": case "required": object type; if (((JsonObject)(value)).TryGetValue("type", out type)) { msg.Add(name.ToString(), this.decodeProp(type.ToString(), proto)); } break; case "repeated": object _name; if (!msg.TryGetValue(name.ToString(), out _name)) { msg.Add(name.ToString(), new List<object>()); } object value_type; if (msg.TryGetValue(name.ToString(), out _name) && ((JsonObject)(value)).TryGetValue("type", out value_type)) { decodeArray((List<object>)_name, value_type.ToString(), proto); } break; } } } } } } } return msg; } /// <summary> /// Decode array in message. /// </summary> private void decodeArray(List<object> list, string type, JsonObject proto) { if (this.util.isSimpleType(type)) { int length = (int)Decoder.decodeUInt32(this.getBytes()); for (int i = 0; i < length; i++) { list.Add(this.decodeProp(type, null)); } } else { list.Add(this.decodeProp(type, proto)); } } /// <summary> /// Decode each simple type in message. /// </summary> private object decodeProp(string type, JsonObject proto) { switch (type) { case "uInt32": return Decoder.decodeUInt32(this.getBytes()); case "int32": case "sInt32": return Decoder.decodeSInt32(this.getBytes()); case "float": return this.decodeFloat(); case "double": return this.decodeDouble(); case "string": return this.decodeString(); default: return this.decodeObject(type, proto); } } //Decode the user-defined object type in message. private JsonObject decodeObject(string type, JsonObject proto) { if (proto != null) { object __messages; if (proto.TryGetValue("__messages", out __messages)) { object _type; if (((JsonObject)__messages).TryGetValue(type, out _type) || protos.TryGetValue("message " + type, out _type)) { int l = (int)Decoder.decodeUInt32(this.getBytes()); JsonObject msg = new JsonObject(); return this.decodeMsg(msg, (JsonObject)_type, this.offset + l); } } } return new JsonObject(); } //Decode string type. private string decodeString() { int length = (int)Decoder.decodeUInt32(this.getBytes()); string msg_string = Encoding.UTF8.GetString(this.buffer, this.offset, length); this.offset += length; return msg_string; } //Decode double type. private double decodeDouble() { double msg_double = BitConverter.Int64BitsToDouble((long)this.ReadRawLittleEndian64()); this.offset += 8; return msg_double; } //Decode float type private float decodeFloat() { float msg_float = BitConverter.ToSingle(this.buffer, this.offset); this.offset += 4; return msg_float; } //Read long in littleEndian private ulong ReadRawLittleEndian64() { ulong b1 = buffer[this.offset]; ulong b2 = buffer[this.offset + 1]; ulong b3 = buffer[this.offset + 2]; ulong b4 = buffer[this.offset + 3]; ulong b5 = buffer[this.offset + 4]; ulong b6 = buffer[this.offset + 5]; ulong b7 = buffer[this.offset + 6]; ulong b8 = buffer[this.offset + 7]; return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24) | (b5 << 32) | (b6 << 40) | (b7 << 48) | (b8 << 56); } //Get the type and tag. private Dictionary<string, int> getHead() { int tag = (int)Decoder.decodeUInt32(this.getBytes()); Dictionary<string, int> head = new Dictionary<string, int>(); head.Add("type", tag & 0x7); head.Add("tag", tag >> 3); return head; } //Get bytes. private byte[] getBytes() { List<byte> arrayList = new List<byte>(); int pos = this.offset; byte b; do { b = this.buffer[pos]; arrayList.Add(b); pos++; } while (b >= 128); this.offset = pos; int length = arrayList.Count; byte[] bytes = new byte[length]; for (int i = 0; i < length; i++) { bytes[i] = arrayList[i]; } return bytes; } } }
// 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.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace System.Globalization { // needs to be kept in sync with CalendarDataType in System.Globalization.Native internal enum CalendarDataType { Uninitialized = 0, NativeName = 1, MonthDay = 2, ShortDates = 3, LongDates = 4, YearMonths = 5, DayNames = 6, AbbrevDayNames = 7, MonthNames = 8, AbbrevMonthNames = 9, SuperShortDayNames = 10, MonthGenitiveNames = 11, AbbrevMonthGenitiveNames = 12, EraNames = 13, AbbrevEraNames = 14, } internal partial class CalendarData { private bool LoadCalendarDataFromSystem(String localeName, CalendarId calendarId) { bool result = true; result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.NativeName, out this.sNativeName); result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.MonthDay, out this.sMonthDay); this.sMonthDay = NormalizeDatePattern(this.sMonthDay); result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.ShortDates, out this.saShortDates); result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.LongDates, out this.saLongDates); result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.YearMonths, out this.saYearMonths); result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.DayNames, out this.saDayNames); result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.AbbrevDayNames, out this.saAbbrevDayNames); result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.SuperShortDayNames, out this.saSuperShortDayNames); result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthNames, out this.saMonthNames); result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthNames, out this.saAbbrevMonthNames); result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthGenitiveNames, out this.saMonthGenitiveNames); result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthGenitiveNames, out this.saAbbrevMonthGenitiveNames); result &= EnumEraNames(localeName, calendarId, CalendarDataType.EraNames, out this.saEraNames); result &= EnumEraNames(localeName, calendarId, CalendarDataType.AbbrevEraNames, out this.saAbbrevEraNames); return result; } internal static int GetTwoDigitYearMax(CalendarId calendarId) { // There is no user override for this value on Linux or in ICU. // So just return -1 to use the hard-coded defaults. return -1; } // Call native side to figure out which calendars are allowed internal static int GetCalendars(string localeName, bool useUserOverride, CalendarId[] calendars) { Debug.Assert(!GlobalizationMode.Invariant); // NOTE: there are no 'user overrides' on Linux int count = Interop.GlobalizationInterop.GetCalendars(localeName, calendars, calendars.Length); // ensure there is at least 1 calendar returned if (count == 0 && calendars.Length > 0) { calendars[0] = CalendarId.GREGORIAN; count = 1; } return count; } private static bool SystemSupportsTaiwaneseCalendar() { return true; } // PAL Layer ends here private static bool GetCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string calendarString) { Debug.Assert(!GlobalizationMode.Invariant); return Interop.CallStringMethod( (locale, calId, type, stringBuilder) => Interop.GlobalizationInterop.GetCalendarInfo( locale, calId, type, stringBuilder, stringBuilder.Capacity), localeName, calendarId, dataType, out calendarString); } private static bool EnumDatePatterns(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] datePatterns) { datePatterns = null; CallbackContext callbackContext = new CallbackContext(); callbackContext.DisallowDuplicates = true; bool result = EnumCalendarInfo(localeName, calendarId, dataType, callbackContext); if (result) { List<string> datePatternsList = callbackContext.Results; datePatterns = new string[datePatternsList.Count]; for (int i = 0; i < datePatternsList.Count; i++) { datePatterns[i] = NormalizeDatePattern(datePatternsList[i]); } } return result; } /// <summary> /// The ICU date format characters are not exactly the same as the .NET date format characters. /// NormalizeDatePattern will take in an ICU date pattern and return the equivalent .NET date pattern. /// </summary> /// <remarks> /// see Date Field Symbol Table in http://userguide.icu-project.org/formatparse/datetime /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx /// </remarks> private static string NormalizeDatePattern(string input) { StringBuilder destination = StringBuilderCache.Acquire(input.Length); int index = 0; while (index < input.Length) { switch (input[index]) { case '\'': // single quotes escape characters, like 'de' in es-SP // so read verbatim until the next single quote destination.Append(input[index++]); while (index < input.Length) { char current = input[index++]; destination.Append(current); if (current == '\'') { break; } } break; case 'E': case 'e': case 'c': // 'E' in ICU is the day of the week, which maps to 3 or 4 'd's in .NET // 'e' in ICU is the local day of the week, which has no representation in .NET, but // maps closest to 3 or 4 'd's in .NET // 'c' in ICU is the stand-alone day of the week, which has no representation in .NET, but // maps closest to 3 or 4 'd's in .NET NormalizeDayOfWeek(input, destination, ref index); break; case 'L': case 'M': // 'L' in ICU is the stand-alone name of the month, // which maps closest to 'M' in .NET since it doesn't support stand-alone month names in patterns // 'M' in both ICU and .NET is the month, // but ICU supports 5 'M's, which is the super short month name int occurrences = CountOccurrences(input, input[index], ref index); if (occurrences > 4) { // 5 'L's or 'M's in ICU is the super short name, which maps closest to MMM in .NET occurrences = 3; } destination.Append('M', occurrences); break; case 'G': // 'G' in ICU is the era, which maps to 'g' in .NET occurrences = CountOccurrences(input, 'G', ref index); // it doesn't matter how many 'G's, since .NET only supports 'g' or 'gg', and they // have the same meaning destination.Append('g'); break; case 'y': // a single 'y' in ICU is the year with no padding or trimming. // a single 'y' in .NET is the year with 1 or 2 digits // so convert any single 'y' to 'yyyy' occurrences = CountOccurrences(input, 'y', ref index); if (occurrences == 1) { occurrences = 4; } destination.Append('y', occurrences); break; default: const string unsupportedDateFieldSymbols = "YuUrQqwWDFg"; Debug.Assert(unsupportedDateFieldSymbols.IndexOf(input[index]) == -1, string.Format(CultureInfo.InvariantCulture, "Encountered an unexpected date field symbol '{0}' from ICU which has no known corresponding .NET equivalent.", input[index])); destination.Append(input[index++]); break; } } return StringBuilderCache.GetStringAndRelease(destination); } private static void NormalizeDayOfWeek(string input, StringBuilder destination, ref int index) { char dayChar = input[index]; int occurrences = CountOccurrences(input, dayChar, ref index); occurrences = Math.Max(occurrences, 3); if (occurrences > 4) { // 5 and 6 E/e/c characters in ICU is the super short names, which maps closest to ddd in .NET occurrences = 3; } destination.Append('d', occurrences); } private static int CountOccurrences(string input, char value, ref int index) { int startIndex = index; while (index < input.Length && input[index] == value) { index++; } return index - startIndex; } private static bool EnumMonthNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] monthNames) { monthNames = null; CallbackContext callbackContext = new CallbackContext(); bool result = EnumCalendarInfo(localeName, calendarId, dataType, callbackContext); if (result) { // the month-name arrays are expected to have 13 elements. If ICU only returns 12, add an // extra empty string to fill the array. if (callbackContext.Results.Count == 12) { callbackContext.Results.Add(string.Empty); } monthNames = callbackContext.Results.ToArray(); } return result; } private static bool EnumEraNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] eraNames) { bool result = EnumCalendarInfo(localeName, calendarId, dataType, out eraNames); // .NET expects that only the Japanese calendars have more than 1 era. // So for other calendars, only return the latest era. if (calendarId != CalendarId.JAPAN && calendarId != CalendarId.JAPANESELUNISOLAR && eraNames.Length > 0) { string[] latestEraName = new string[] { eraNames[eraNames.Length - 1] }; eraNames = latestEraName; } return result; } internal static bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] calendarData) { calendarData = null; CallbackContext callbackContext = new CallbackContext(); bool result = EnumCalendarInfo(localeName, calendarId, dataType, callbackContext); if (result) { calendarData = callbackContext.Results.ToArray(); } return result; } private static bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, CallbackContext callbackContext) { GCHandle context = GCHandle.Alloc(callbackContext); try { return Interop.GlobalizationInterop.EnumCalendarInfo(EnumCalendarInfoCallback, localeName, calendarId, dataType, (IntPtr)context); } finally { context.Free(); } } private static void EnumCalendarInfoCallback(string calendarString, IntPtr context) { try { CallbackContext callbackContext = (CallbackContext)((GCHandle)context).Target; if (callbackContext.DisallowDuplicates) { foreach (string existingResult in callbackContext.Results) { if (string.Equals(calendarString, existingResult, StringComparison.Ordinal)) { // the value is already in the results, so don't add it again return; } } } callbackContext.Results.Add(calendarString); } catch (Exception e) { Debug.Assert(false, e.ToString()); // we ignore the managed exceptions here because EnumCalendarInfoCallback will get called from the native code. // If we don't ignore the exception here that can cause the runtime to fail fast. } } private class CallbackContext { private List<string> _results = new List<string>(); public CallbackContext() { } public List<string> Results { get { return _results; } } public bool DisallowDuplicates { get; set; } } } }
namespace NavigatorPlayground { 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.kryptonNavigator1 = new ComponentFactory.Krypton.Navigator.KryptonNavigator(); this.kryptonPage1 = new ComponentFactory.Krypton.Navigator.KryptonPage(); this.kryptonPage2 = new ComponentFactory.Krypton.Navigator.KryptonPage(); this.groupBoxProperties = new System.Windows.Forms.GroupBox(); this.propertyGrid1 = new System.Windows.Forms.PropertyGrid(); this.buttonClose = new System.Windows.Forms.Button(); this.groupBoxPages = new System.Windows.Forms.GroupBox(); this.kryptonButtonEnable = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kryptonButtonClear = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kryptonButtonRemove = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kryptonButtonAdd = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.kryptonManager1 = new ComponentFactory.Krypton.Toolkit.KryptonManager(this.components); ((System.ComponentModel.ISupportInitialize)(this.kryptonNavigator1)).BeginInit(); this.kryptonNavigator1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage2)).BeginInit(); this.groupBoxProperties.SuspendLayout(); this.groupBoxPages.SuspendLayout(); this.SuspendLayout(); // // kryptonNavigator1 // this.kryptonNavigator1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.kryptonNavigator1.Location = new System.Drawing.Point(18, 31); this.kryptonNavigator1.Name = "kryptonNavigator1"; this.kryptonNavigator1.Pages.AddRange(new ComponentFactory.Krypton.Navigator.KryptonPage[] { this.kryptonPage1, this.kryptonPage2}); this.kryptonNavigator1.SelectedIndex = 0; this.kryptonNavigator1.Size = new System.Drawing.Size(297, 355); this.kryptonNavigator1.TabIndex = 0; this.kryptonNavigator1.Text = "kryptonNavigator1"; this.kryptonNavigator1.SelectedPageChanged += new System.EventHandler(this.kryptonNavigator1_SelectedPageChanged); // // kryptonPage1 // this.kryptonPage1.AutoHiddenSlideSize = new System.Drawing.Size(200, 200); this.kryptonPage1.Flags = 65534; this.kryptonPage1.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonPage1.ImageLarge"))); this.kryptonPage1.ImageMedium = ((System.Drawing.Image)(resources.GetObject("kryptonPage1.ImageMedium"))); this.kryptonPage1.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonPage1.ImageSmall"))); this.kryptonPage1.LastVisibleSet = true; this.kryptonPage1.MinimumSize = new System.Drawing.Size(50, 50); this.kryptonPage1.Name = "kryptonPage1"; this.kryptonPage1.Size = new System.Drawing.Size(295, 329); this.kryptonPage1.Text = "Page 1"; this.kryptonPage1.TextDescription = "Page 1 Description"; this.kryptonPage1.TextTitle = "Page 1 Title"; this.kryptonPage1.ToolTipTitle = "Page ToolTip"; this.kryptonPage1.UniqueName = "DA289FB3CA334928DA289FB3CA334928"; // // kryptonPage2 // this.kryptonPage2.AutoHiddenSlideSize = new System.Drawing.Size(200, 200); this.kryptonPage2.Flags = 65534; this.kryptonPage2.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonPage2.ImageLarge"))); this.kryptonPage2.ImageMedium = ((System.Drawing.Image)(resources.GetObject("kryptonPage2.ImageMedium"))); this.kryptonPage2.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonPage2.ImageSmall"))); this.kryptonPage2.LastVisibleSet = true; this.kryptonPage2.MinimumSize = new System.Drawing.Size(50, 50); this.kryptonPage2.Name = "kryptonPage2"; this.kryptonPage2.Size = new System.Drawing.Size(295, 329); this.kryptonPage2.Text = "Page 2"; this.kryptonPage2.TextDescription = "Page 2 Description"; this.kryptonPage2.TextTitle = "Page 2 Title"; this.kryptonPage2.ToolTipTitle = "Page ToolTip"; this.kryptonPage2.UniqueName = "FAFF770F50A44D94FAFF770F50A44D94"; // // groupBoxProperties // this.groupBoxProperties.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBoxProperties.Controls.Add(this.propertyGrid1); this.groupBoxProperties.Location = new System.Drawing.Point(328, 12); this.groupBoxProperties.Name = "groupBoxProperties"; this.groupBoxProperties.Padding = new System.Windows.Forms.Padding(5); this.groupBoxProperties.Size = new System.Drawing.Size(312, 464); this.groupBoxProperties.TabIndex = 2; this.groupBoxProperties.TabStop = false; this.groupBoxProperties.Text = "Properties for KryptonNavigator"; // // propertyGrid1 // this.propertyGrid1.Dock = System.Windows.Forms.DockStyle.Fill; this.propertyGrid1.Location = new System.Drawing.Point(5, 19); this.propertyGrid1.Name = "propertyGrid1"; this.propertyGrid1.Size = new System.Drawing.Size(302, 440); this.propertyGrid1.TabIndex = 0; this.propertyGrid1.ToolbarVisible = false; // // buttonClose // this.buttonClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonClose.Location = new System.Drawing.Point(565, 485); this.buttonClose.Name = "buttonClose"; this.buttonClose.Size = new System.Drawing.Size(75, 23); this.buttonClose.TabIndex = 3; this.buttonClose.Text = "Close"; this.buttonClose.UseVisualStyleBackColor = true; this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click); // // groupBoxPages // this.groupBoxPages.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.groupBoxPages.Controls.Add(this.kryptonButtonEnable); this.groupBoxPages.Controls.Add(this.kryptonButtonClear); this.groupBoxPages.Controls.Add(this.kryptonButtonRemove); this.groupBoxPages.Controls.Add(this.kryptonButtonAdd); this.groupBoxPages.Location = new System.Drawing.Point(13, 407); this.groupBoxPages.Name = "groupBoxPages"; this.groupBoxPages.Size = new System.Drawing.Size(309, 69); this.groupBoxPages.TabIndex = 1; this.groupBoxPages.TabStop = false; this.groupBoxPages.Text = "Pages"; // // kryptonButtonEnable // this.kryptonButtonEnable.Location = new System.Drawing.Point(234, 26); this.kryptonButtonEnable.Name = "kryptonButtonEnable"; this.kryptonButtonEnable.Size = new System.Drawing.Size(65, 29); this.kryptonButtonEnable.TabIndex = 3; this.kryptonButtonEnable.Values.Text = "Enable"; this.kryptonButtonEnable.Click += new System.EventHandler(this.kryptonButtonEnable_Click); // // kryptonButtonClear // this.kryptonButtonClear.Location = new System.Drawing.Point(159, 26); this.kryptonButtonClear.Name = "kryptonButtonClear"; this.kryptonButtonClear.Size = new System.Drawing.Size(65, 29); this.kryptonButtonClear.TabIndex = 2; this.kryptonButtonClear.Values.Text = "Clear"; this.kryptonButtonClear.Click += new System.EventHandler(this.kryptonButtonClear_Click); // // kryptonButtonRemove // this.kryptonButtonRemove.Location = new System.Drawing.Point(84, 26); this.kryptonButtonRemove.Name = "kryptonButtonRemove"; this.kryptonButtonRemove.Size = new System.Drawing.Size(65, 29); this.kryptonButtonRemove.TabIndex = 1; this.kryptonButtonRemove.Values.Text = "Remove"; this.kryptonButtonRemove.Click += new System.EventHandler(this.kryptonButtonRemove_Click); // // kryptonButtonAdd // this.kryptonButtonAdd.Location = new System.Drawing.Point(9, 26); this.kryptonButtonAdd.Name = "kryptonButtonAdd"; this.kryptonButtonAdd.Size = new System.Drawing.Size(65, 29); this.kryptonButtonAdd.TabIndex = 0; this.kryptonButtonAdd.Values.Text = "Add"; this.kryptonButtonAdd.Click += new System.EventHandler(this.kryptonButtonAdd_Click); // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; this.imageList1.Images.SetKeyName(0, "airmail_closed.png"); this.imageList1.Images.SetKeyName(1, "brickwall.png"); this.imageList1.Images.SetKeyName(2, "calculator.png"); this.imageList1.Images.SetKeyName(3, "clients.png"); this.imageList1.Images.SetKeyName(4, "fire.png"); this.imageList1.Images.SetKeyName(5, "newspaper.png"); this.imageList1.Images.SetKeyName(6, "robber.png"); this.imageList1.Images.SetKeyName(7, "virus.png"); this.imageList1.Images.SetKeyName(8, "web.png"); this.imageList1.Images.SetKeyName(9, "worm.png"); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(652, 516); this.Controls.Add(this.groupBoxPages); this.Controls.Add(this.buttonClose); this.Controls.Add(this.groupBoxProperties); this.Controls.Add(this.kryptonNavigator1); 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.MaximizeBox = false; this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size(530, 326); this.Name = "Form1"; this.Text = "Navigator Playground"; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.kryptonNavigator1)).EndInit(); this.kryptonNavigator1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage2)).EndInit(); this.groupBoxProperties.ResumeLayout(false); this.groupBoxPages.ResumeLayout(false); this.ResumeLayout(false); } #endregion private ComponentFactory.Krypton.Navigator.KryptonNavigator kryptonNavigator1; private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage1; private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage2; private System.Windows.Forms.GroupBox groupBoxProperties; private System.Windows.Forms.PropertyGrid propertyGrid1; private System.Windows.Forms.Button buttonClose; private System.Windows.Forms.GroupBox groupBoxPages; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButtonClear; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButtonRemove; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButtonAdd; private System.Windows.Forms.ImageList imageList1; private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButtonEnable; private ComponentFactory.Krypton.Toolkit.KryptonManager kryptonManager1; } }
/* Copyright (c) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.IO; using System.Net; using Google.GData.Client; using Google.GData.Extensions; using Google.GData.AccessControl; using Google.GData.Documents; using System.Collections.Generic; namespace Google.Documents { /// <summary> /// the base class for all documents in the document service. A document can represent folders, documents, spreadsheets etc. /// </summary> public class Document : Entry { /// <summary> /// descripes the type of the document entry /// </summary> public enum DocumentType { /// <summary> /// a document /// </summary> Document, /// <summary> /// a spreadsheet /// </summary> Spreadsheet, /// <summary> /// a pdf file /// </summary> PDF, /// <summary> /// a presentation /// </summary> Presentation, /// <summary> /// a folder /// </summary> Folder, /// <summary> /// a form /// </summary> Form, /// <summary> /// a drawing /// </summary> Drawing, /// <summary> /// an unknown document type /// </summary> Unknown } /// <summary> /// describes the download type, in what format you want to download the document /// </summary> public enum DownloadType { /// <summary> /// text file /// </summary> txt, /// <summary> /// open document format /// </summary> odt, /// <summary> /// portable document format PDF /// </summary> pdf, /// <summary> /// html format /// </summary> html, /// <summary> /// rich text format /// </summary> rtf, /// <summary> /// microsoft word format /// </summary> doc, /// <summary> /// portable network graphics format /// </summary> png, /// <summary> /// zip format /// </summary> zip, /// <summary> /// flash format /// </summary> swf, /// <summary> /// Microsoft Powerpoint format /// </summary> ppt, /// <summary> /// Microsoft Excel format /// </summary> xls, /// <summary> /// commma separated value format /// </summary> csv, /// <summary> /// open document spreadsheet format /// </summary> ods, /// <summary> /// tab separated values format /// </summary> tsv, /// <summary> /// Scalable Vector Graphics format /// </summary> svg, /// <summary> /// jpeg format /// </summary> jpeg } /// <summary> /// creates the inner document entry object when needed /// </summary> /// <returns></returns> protected override void EnsureInnerObject() { if (this.AtomEntry == null) { this.AtomEntry = new DocumentEntry(); } } /// <summary> /// readonly accessor for the DocumentEntry that is underneath this object. /// </summary> /// <returns></returns> public DocumentEntry DocumentEntry { get { EnsureInnerObject(); return this.AtomEntry as DocumentEntry; } } /// <summary> /// the type of the document entry /// </summary> /// <returns></returns> public Document.DocumentType Type { get { EnsureInnerObject(); if (this.DocumentEntry.IsDocument) { return Document.DocumentType.Document; } else if (this.DocumentEntry.IsPDF) { return Document.DocumentType.PDF; } else if (this.DocumentEntry.IsSpreadsheet) { return Document.DocumentType.Spreadsheet; } else if (this.DocumentEntry.IsFolder) { return Document.DocumentType.Folder; } else if (this.DocumentEntry.IsPresentation) { return Document.DocumentType.Presentation; } else if (this.DocumentEntry.IsDrawing) { return Document.DocumentType.Drawing; } return Document.DocumentType.Unknown; } set { EnsureInnerObject(); switch (value) { case Document.DocumentType.Document: this.DocumentEntry.IsDocument = true; break; case Document.DocumentType.Folder: this.DocumentEntry.IsFolder = true; break; case Document.DocumentType.PDF: this.DocumentEntry.IsPDF = true; break; case Document.DocumentType.Presentation: this.DocumentEntry.IsPresentation = true; break; case Document.DocumentType.Spreadsheet: this.DocumentEntry.IsSpreadsheet = true; break; case Document.DocumentType.Unknown: break; } } } /// <summary> /// returns the href values of the parent link relationships /// can be used to retrieve the parent folder /// </summary> /// <returns></returns> public List<string> ParentFolders { get { EnsureInnerObject(); List<string> strings = new List<string>(); foreach (AtomLink l in this.DocumentEntry.ParentFolders) { strings.Add(l.HRef.ToString()); } return strings; } } /// <summary> /// returns the document resource id of the object. /// this uses the gd:resourceId element /// </summary> /// <returns></returns> public string ResourceId { get { EnsureInnerObject(); return this.DocumentEntry.ResourceId; } } /// <summary> /// returns true if collaborators are allowed to modify /// the document ACL list /// </summary> /// <returns></returns> public bool WritersCanInvite { get { EnsureInnerObject(); return this.DocumentEntry.WritersCanInvite; } set { EnsureInnerObject(); this.DocumentEntry.WritersCanInvite = value; } } /// <summary> /// Returns the last viewed timestamp /// </summary> /// <returns></returns> public DateTime LastViewed { get { EnsureInnerObject(); return this.DocumentEntry.LastViewed; } } /// <summary> /// returns the LastModifiedBy object indicating /// who last edited the document /// </summary> /// <returns></returns> public LastModifiedBy LastModified { get { EnsureInnerObject(); return this.DocumentEntry.LastModified; } } /// <summary> /// returns the quota used by the object. 0 if not available /// </summary> [CLSCompliant(false)] public ulong QuotaBytesUsed { get { EnsureInnerObject(); if (this.DocumentEntry.QuotaUsed != null) { return this.DocumentEntry.QuotaUsed.UnsignedLongValue; } return 0; } } /// <summary> /// returns the Uri to the access control list /// </summary> /// <returns>the value of the href attribute for the acl feedlink, or null if not found</returns> public Uri AccessControlList { get { EnsureInnerObject(); return this.DocumentEntry.AccessControlList != null ? new Uri(this.DocumentEntry.AccessControlList) : null; } } /// <summary> /// returns the Uri to the revision document /// </summary> /// <returns>The value of the href attribute of the revisions feedlink, or null if not found</returns> public Uri RevisionDocument { get { EnsureInnerObject(); return this.DocumentEntry.RevisionDocument != null ? new Uri(this.DocumentEntry.RevisionDocument) : null; } } } ////////////////////////////////////////////////////////////////////// /// <summary> /// The Google Documents List Data API allows client applications /// to view and update documents (spreadsheets and word processor) /// using a Google Data API feed. Your client application can request /// a list of a user's documents, query the content of a /// user's documents, and upload new documents. /// </summary> /// <example> /// The following code illustrates a possible use of /// the <c>DocumentsRequest</c> object: /// <code> /// RequestSettings settings = new RequestSettings("yourApp"); /// settings.PageSize = 50; /// settings.AutoPaging = true; /// DocumentsRequest c = new DocumentsRequest(settings); /// Feed&lt;Dcouments&gt; feed = c.GetDocuments(); /// /// foreach (Document d in feed.Entries) /// { /// Console.WriteLine(d.Title); /// } /// </code> /// </example> ////////////////////////////////////////////////////////////////////// public class DocumentsRequest : FeedRequest<DocumentsService> { private string baseUri = DocumentsListQuery.documentsBaseUri; private Service spreadsheetsService; /// <summary> /// default constructor for a DocumentsRequest /// </summary> /// <param name="settings"></param> public DocumentsRequest(RequestSettings settings) : base(settings) { this.Service = new DocumentsService(settings.Application); // we hardcode the service name here to avoid having a dependency // on the spreadsheet dll for now. this.spreadsheetsService = new Service("wise", settings.Application); this.spreadsheetsService.ProtocolMajor = 2; PrepareService(); PrepareService(this.spreadsheetsService); } /// <summary> /// the base string to use for queries. Defaults to /// DocumentsListQuery.documentsBaseUri /// </summary> /// <returns></returns> public string BaseUri { get { return this.baseUri; } set { this.baseUri = value; } } /// <summary> /// called to set additional proxies if required. Overloaded on the document service /// </summary> /// <param name="proxy"></param> /// <returns></returns> protected override void OnSetOtherProxies(IWebProxy proxy) { base.OnSetOtherProxies(proxy); GDataRequestFactory x = this.spreadsheetsService.RequestFactory as GDataRequestFactory; if (x != null) { x.Proxy = proxy; } else { throw new ArgumentException("Can not set a proxy on the spreadsheet service"); } } /// <summary> /// returns a Feed of all documents and folders for the authorized user /// </summary> /// <returns>a feed of everyting</returns> public Feed<Document> GetEverything() { DocumentsListQuery q = PrepareQuery<DocumentsListQuery>(this.BaseUri); q.ShowFolders = true; return PrepareFeed<Document>(q); } /// <summary> /// returns a Feed of all documents for the authorized user /// </summary> /// <returns>a feed of Documents</returns> public Feed<Document> GetDocuments() { TextDocumentQuery q = PrepareQuery<TextDocumentQuery>(this.BaseUri); return PrepareFeed<Document>(q); } /// <summary> /// returns a Feed of all presentations for the authorized user /// </summary> /// <returns>a feed of Documents</returns> public Feed<Document> GetPresentations() { PresentationsQuery q = PrepareQuery<PresentationsQuery>(this.BaseUri); return PrepareFeed<Document>(q); } /// <summary> /// returns a Feed of all spreadsheets for the authorized user /// </summary> /// <returns>a feed of Documents</returns> public Feed<Document> GetSpreadsheets() { SpreadsheetQuery q = PrepareQuery<SpreadsheetQuery>(this.BaseUri); return PrepareFeed<Document>(q); } /// <summary> /// returns a Feed of all pdf files for the authorized user /// </summary> /// <returns>a feed of Documents</returns> public Feed<Document> GetPDFs() { PDFsQuery q = PrepareQuery<PDFsQuery>(this.BaseUri); return PrepareFeed<Document>(q); } /// <summary> /// returns a Feed of all files that are owned by the authorized user /// </summary> /// <returns>a feed of Documents</returns> public Feed<Document> GetMyDocuments() { DocumentsListQuery q = PrepareQuery<DocumentsListQuery>(this.BaseUri); q.Categories.Add(DocumentsListQuery.MINE); return PrepareFeed<Document>(q); } /// <summary> /// returns a Feed of all folders for the authorized user /// </summary> /// <returns>a feed of Documents</returns> public Feed<Document> GetFolders() { DocumentsListQuery q = PrepareQuery<DocumentsListQuery>(DocumentsListQuery.allFoldersUri); return PrepareFeed<Document>(q); } /// <summary> /// returns all items the user has viewed recently /// </summary> /// <returns></returns> public Feed<Document> GetViewed() { DocumentsListQuery q = PrepareQuery<DocumentsListQuery>(this.BaseUri); q.Categories.Add(DocumentsListQuery.VIEWED); return PrepareFeed<Document>(q); } /// <summary> /// returns all forms for the authorized user /// </summary> /// <returns></returns> public Feed<Document> GetForms() { DocumentsListQuery q = PrepareQuery<DocumentsListQuery>(this.BaseUri); q.Categories.Add(DocumentsListQuery.FORMS); return PrepareFeed<Document>(q); } /// <summary> /// returns a feed of documents for the specified folder /// </summary> /// <param name="folder"></param> /// <returns></returns> public Feed<Document> GetFolderContent(Document folder) { if (folder.Type != Document.DocumentType.Folder) { throw new ArgumentException("The parameter folder is not a folder"); } string uri = String.Format(DocumentsListQuery.foldersUriTemplate, folder.ResourceId); DocumentsListQuery q = PrepareQuery<DocumentsListQuery>(uri); return PrepareFeed<Document>(q); } /// <summary> /// this will create an empty document or folder, according to /// the content of the newDocument parameter /// </summary> /// <param name="newDocument"></param> /// <returns>the created document from the server</returns> public Document CreateDocument(Document newDocument) { return Insert(new Uri(DocumentsListQuery.documentsBaseUri), newDocument); } /// <summary> /// this will create an empty document or folder, according to /// the content of the newDocument parameter. This will append /// the convert=false parameter to allow arbitrary file uploads /// </summary> /// <param name="newDocument"></param> /// <returns>the created document from the server</returns> public Document CreateFile(Document newDocument) { return Insert(new Uri(DocumentsListQuery.documentsBaseUri + "?convert=false"), newDocument); } /// <summary> /// moves a document or a folder into a folder /// </summary> /// <param name="parent">this has to be a folder</param> /// <param name="child">can be a folder or a document</param> /// <returns></returns> public Document MoveDocumentTo(Document parent, Document child) { if (parent == null || child == null) { throw new ArgumentNullException("parent or child can not be null"); } if (parent.AtomEntry.Content == null || parent.AtomEntry.Content.AbsoluteUri == null) { throw new ArgumentException("parent has no content uri"); } if (parent.Type != Document.DocumentType.Folder) { throw new ArgumentException("wrong parent type"); } Document payload = new Document(); payload.DocumentEntry.Id = new AtomId(child.Id); payload.Type = child.Type; // to do that, we just need to post the CHILD // against the URI of the parent return Insert(new Uri(parent.AtomEntry.Content.AbsoluteUri), payload); } /// <summary> /// downloads a document. /// </summary> /// <param name="document">The document to download. It needs to have the document type set, as well as the id link</param> /// <param name="type">The output format of the document you want to download</param> /// <returns></returns> public Stream Download(Document document, Document.DownloadType type) { return this.Download(document, type, null, 0); } /// <summary> /// downloads a document. /// </summary> /// <param name="document">The document to download. It needs to have the document type set, as well as the id link</param> /// <param name="type">The output format of the document you want to download</param> /// <param name="sheetNumber">When requesting a CSV or TSV file you must specify an additional parameter called /// gid which indicates which grid, or sheet, you wish to get (the index is 0-based, so gid 1 /// actually refers to the second sheet sheet on a given spreadsheet). </param> /// <param name="baseDomain">OBSOLETE - if null, default is used. Otherwise needs to specify the domain to download from, ending with a slash</param> /// <returns></returns> public Stream Download(Document document, Document.DownloadType type, string baseDomain, int sheetNumber) { if (document.Type == Document.DocumentType.Folder) { throw new ArgumentException("Document is a folder, can not be downloaded"); } Service s = this.Service; string queryUri = this.BuildDocumentPartialExportUrl(document.DocumentEntry.Content.Src.ToString()); switch (document.Type) { case Document.DocumentType.Spreadsheet: s = this.spreadsheetsService; switch (type) { case Document.DownloadType.xls: queryUri += "xls"; break; case Document.DownloadType.csv: queryUri += "csv&gid=" + sheetNumber.ToString(); break; case Document.DownloadType.pdf: queryUri += "pdf"; break; case Document.DownloadType.ods: queryUri += "ods"; break; case Document.DownloadType.tsv: queryUri += "tsv&gid=" + sheetNumber.ToString(); ; break; case Document.DownloadType.html: queryUri += "html"; break; default: throw new ArgumentException("type is invalid for a spreadsheet"); } break; case Document.DocumentType.Presentation: switch (type) { case Document.DownloadType.swf: queryUri += "swf"; break; case Document.DownloadType.pdf: queryUri += "pdf"; break; case Document.DownloadType.ppt: queryUri += "ppt"; break; default: throw new ArgumentException("type is invalid for a presentation"); } break; case Document.DocumentType.Unknown: break; default: queryUri += type.ToString(); break; } Uri target = new Uri(queryUri); return s.Query(target); } /// <summary> /// Downloads arbitrary documents, where the link to the document is inside the /// content field. /// </summary> /// <param name="document">a Document Entry</param> /// <param name="exportFormat">a string for the exportformat parameter or null</param> /// <returns></returns> public Stream Download(Document document, string exportFormat) { if (document == null) { throw new ArgumentException("Document should not be null"); } if (document.DocumentEntry == null) { throw new ArgumentException("document.DocumentEntry should not be null"); } if (document.DocumentEntry.Content == null) { throw new ArgumentException("document.DocumentEntry.Content should not be null"); } string url = document.DocumentEntry.Content.Src.ToString(); if (!String.IsNullOrEmpty(exportFormat)) { url = BuildDocumentPartialExportUrl(url) + exportFormat; } Service s = this.Service; // figure out if we need to use the spreadsheet service if (document.Type == Document.DocumentType.Spreadsheet) { s = this.spreadsheetsService; } Uri target = new Uri(url); return s.Query(target); } /// <summary> /// helper function used by the Download methods /// </summary> private string BuildDocumentPartialExportUrl(string baseUrl) { if (!baseUrl.ToLowerInvariant().Contains("/export")) { return baseUrl; } char r = '?'; if (baseUrl.IndexOf('?') != -1) { r = '&'; } return baseUrl + r + "exportFormat="; } } }
/* * Naiad ver. 0.5 * 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.Linq; using System.Text; using System.Threading; using Microsoft.Research.Naiad.DataStructures; using Microsoft.Research.Naiad.Dataflow.Channels; using Microsoft.Research.Naiad.Serialization; using Microsoft.Research.Naiad.Frameworks; using System.IO; using System.Threading.Tasks; using System.Collections.Concurrent; using System.Net.Sockets; using System.Net; using Microsoft.Research.Naiad.Utilities; using Microsoft.Research.Naiad.Scheduling; using Microsoft.Research.Naiad.Runtime.Controlling; using Microsoft.Research.Naiad.Runtime.Networking; using Microsoft.Research.Naiad.Runtime.Progress; using Microsoft.Research.Naiad.Diagnostics; using System.Collections.Specialized; namespace Microsoft.Research.Naiad { internal enum RuntimeStatistic { TxProgressMessages, TxProgressBytes, RxProgressMessages, RxProgressBytes, ProgressLocalRecords, TxHighPriorityMessages, TxHighPriorityBytes, TxNormalPriorityMessages, TxNormalPriorityBytes, RxNetMessages, RxNetBytes, NUM_STATISTICS } /// <summary> /// Configuration information /// </summary> public class Configuration { /// <summary> /// Network protocol used to broadcast progress updates /// </summary> public enum BroadcastProtocol { /// <summary> /// Use TCP only. /// </summary> TcpOnly, /// <summary> /// Use UDP only; non-functional unless UDP is lossless. /// </summary> UdpOnly, /// <summary> /// Use both TCP and UDP. /// </summary> TcpUdp } /// <summary> /// Level of pooling used for network send buffers /// </summary> public enum SendBufferMode { /// <summary> /// Use a single pool for all connections. /// </summary> Global, /// <summary> /// Use one pool for each connection. /// </summary> PerRemoteProcess, /// <summary> /// Use one pool for each worker in this process. /// </summary> PerWorker } /// <summary> /// Defines how the buffer pool is divided /// </summary> public SendBufferMode SendBufferPolicy { get { return this.sendBufferPolicy; } set { this.sendBufferPolicy = value; } } private SendBufferMode sendBufferPolicy = SendBufferMode.PerRemoteProcess; /// <summary> /// Number of pages used for sending network data /// </summary> public int SendPageCount { get { return this.sendPageCount; } set { this.sendPageCount = value; } } private int sendPageCount = 1 << 16; /// <summary> /// Size in bytes of pages used for sending network data /// </summary> public int SendPageSize { get { return this.sendPageSize; } set { this.sendPageSize = value; } } private int sendPageSize = 1 << 14; private int processID = 0; /// <summary> /// The ID of the local process in this computation (starting at 0). /// </summary> public int ProcessID { get { return this.processID; } set { this.processID = value; } } /// <summary> /// The number of processes in this computation. /// </summary> public int Processes { get { return this.endpoints != null ? this.endpoints.Length : 1; } } private int workerCount = 1; /// <summary> /// The number of workers (i.e. CPUs used) in the local process. /// /// N.B. At present, all processes in a computation must use the same worker count. /// </summary> public int WorkerCount { get { return this.workerCount; } set { this.workerCount = value; } } private bool readEndpointsFromPPM = false; /// <summary> /// Setting this to true causes the server to assume it has been spawned by a Peloponnese manager, and /// contact the manager to find out the endpoints of the other processes in the system /// </summary> public bool ReadEndpointsFromPPM { get { return this.readEndpointsFromPPM; } set { this.readEndpointsFromPPM = value; } } private IPEndPoint[] endpoints = null; /// <summary> /// The network addresses of the processes in this computation, indexed by process ID. /// </summary> public IPEndPoint[] Endpoints { get { return this.endpoints == null ? null : this.endpoints.ToArray(); } set { this.endpoints = value.ToArray(); } } private int reachabilityInterval = 1000; /// <summary> /// The periodic interval in milliseconds at which Naiad will attempt to compact its collection state. /// </summary> public int CompactionInterval { get { return this.reachabilityInterval; } set { this.reachabilityInterval = value; } } private int deadlockTimeout = Timeout.Infinite; /// <summary> /// Setting this to a value other than Timeout.Infinite will cause Naiad to print diagnostic information /// after a process sleeps for that number of milliseconds. /// </summary> public int DeadlockTimeout { get { return this.deadlockTimeout; } set { this.deadlockTimeout = value; } } private bool multipleLocalProcesses = true; /// <summary> /// Setting this to true ensures that, if cores are pinned to CPUs, subsequent processes are pinned to different /// sets of CPUs. /// </summary> public bool MultipleLocalProcesses { get { return this.multipleLocalProcesses; } set { this.multipleLocalProcesses = value; } } internal int CentralizerProcessId { get { return this.centralizerProcessId; } set { this.centralizerProcessId = value; } } private int centralizerProcessId = 0; internal int CentralizerThreadId { get { return this.centralizerThreadId; } set { this.centralizerThreadId = value; } } private int centralizerThreadId = 0; private bool distributedProgressTracker = false; /// <summary> /// EXPERIMENTAL: Setting this to true enables the (original) distributed progress tracker. Default is false. /// </summary> public bool DistributedProgressTracker { get { return this.distributedProgressTracker; } set { this.distributedProgressTracker = value; } } internal bool Impersonation { get { return this.impersonation; } set { this.impersonation = value; } } private bool impersonation = false; private bool duplexSockets = false; /// <summary> /// If true, uses the same socket for sending and receiving data. /// </summary> public bool DuplexSockets { get { return this.duplexSockets; } set { this.duplexSockets = value; } } private bool nagling = false; /// <summary> /// If true, uses Nagling on sockets /// </summary> public bool Nagling { get { return this.nagling; } set { this.nagling = value; } } private bool keepalives = false; /// <summary> /// If true, enable TCP KeepAlives on sockets /// </summary> public bool KeepAlives { get { return this.keepalives; } set { this.keepalives = value; } } private bool nothighpriorityqueue = false; /// <summary> /// If true, don't use the high priority queue for progress traffic /// </summary> internal bool DontUseHighPriorityQueue { get { return this.nothighpriorityqueue; } set { this.nothighpriorityqueue = value; } } private bool domainReporting = false; /// <summary> /// Enables a reporting graph manager. In the future this is intended to be used for logging messages that /// are aggregated according to real time, though for now it is mostly vestigial. Calling Log(string) on the /// reporter at a vertex will only deliver the messages to a central location if domain reporting is enabled. /// Messages are all written to a file called rtdomain.txt at the root vertex's computer. /// </summary> internal bool DomainReporting { get { return this.domainReporting; } set { this.domainReporting = value; } } private bool inlineReporting = false; /// <summary> /// Enables inline reporting in the user graph domain. This is used for logging messages that are aggregated /// according to logical times, e.g. to discover the number of messages written by a stage during a particular /// loop iteration, or epoch. Calling Log(string,time) on the reporter at a vertex will only deliver the messages /// to a central location if domain reporting is enabled. Messages are all written to a file called rtinline.txt /// at the root vertex's computer. /// </summary> internal bool InlineReporting { get { return this.inlineReporting; } set { this.inlineReporting = value; } } private bool aggregateReporting = false; /// <summary> /// Enables aggregation in inline reporting in the graph manager domain. Calling LogAggregate(...) on the reporter at a /// vertex will only aggregate and log messages if both InlineReporting and AggregateReporting are true. Aggregates /// are written to the rtinline.txt file at the root vertex's computer. /// </summary> internal bool AggregateReporting { get { return this.aggregateReporting; } set { this.aggregateReporting = value; } } private BroadcastProtocol broadcast = BroadcastProtocol.TcpOnly; /// <summary> /// The network protocol to be used for broadcasting control messages. /// /// N.B. Support for TcpUdp and UdpOnly is experimental. The BroadcastAddress must be set to use these modes. /// </summary> public BroadcastProtocol Broadcast { get { return this.broadcast; } set { this.broadcast = value; } } /// <summary> /// Version information about serialization format /// </summary> internal Pair<int, int> SerializerVersion { get { return this.serializerVersion; } set { this.serializerVersion = value; } } private Pair<int, int> serializerVersion = new Pair<int, int>(2, 2); /// <summary> /// Uses a new code generation technique to generate more efficient code for serialization. /// </summary> public bool UseInlineSerialization { get { return this.serializerVersion.First == 2; } set { if (value) this.SerializerVersion = new Pair<int, int>(2, 1); else this.SerializerVersion = new Pair<int, int>(1, 0); } } /// <summary> /// The address and port to be used for sending or receiving broadcast control messages. /// /// N.B. Support for broadcast primitives is experimental. This must be set to use the TcpUdp and UdpOnly broadcast protocols. /// </summary> public IPEndPoint BroadcastAddress { get { return this.broadcastAddress; } set { this.broadcastAddress = value; } } private IPEndPoint broadcastAddress = null; /// <summary> /// Uses optimization to wake multiple threads with a single kernel event. /// </summary> public bool UseBroadcastWakeup { get { return this.useBroadcastWakeup; } set { this.useBroadcastWakeup = value; } } private bool useBroadcastWakeup = false; /// <summary> /// Uses optimization to wake multiple networking threads with a single kernel event. /// </summary> public bool UseNetworkBroadcastWakeup { get { return this.useNetworkBroadcastWakeup; } set { this.useNetworkBroadcastWakeup = value; } } private bool useNetworkBroadcastWakeup = false; /// <summary> /// Collection of application-specific settings. /// </summary> public NameValueCollection AdditionalSettings { get { return this.additionalSettings; } } private NameValueCollection additionalSettings = new NameValueCollection(); /// <summary> /// Prints information about the standard Naiad command-line options, which are used to build /// a configuration in Configuration.FromArgs(). /// </summary> public static void Usage() { Console.Error.WriteLine("Naiad options:\n" + String.Format("\t--procid,-p\tProcess ID (default 0)\n") + String.Format("\t--threads,-t\tNumber of threads (default 1)\n") + String.Format("\t--numprocs,-n\tNumber of processes (default 1)\n") + "\t--hosts,-h\tList of hostnames in the form host:port\n" + "\t--local\t\tShorthand for -h localhost:2101 localhost:2102 ... localhost:2100+numprocs\n" //+ String.Format("\t--log-level,-l\tDebug|Info|Progress|Error|Fatal|Off (default Progress)\n") //+ String.Format("\t--log-type\tConsole|File|Memory (default Console)\n") //+ String.Format("\t--reachability\tmilliseconds per reachability (default {0})\n", reachabilityInterval) //+ String.Format("\t--deadlocktimeout\tmilliseconds before exit if deadlocked (default {0})\n", deadlockTimeout) ); Console.Error.WriteLine("Runs single-process by default, optionally set -t for number of threads"); Console.Error.WriteLine("To run multiprocess, specify -p, -n, and -h"); Console.Error.WriteLine(" Example for 2 machines, M1 and M2, using TCP port 2101:"); Console.Error.WriteLine(" M1> NaiadProgram.exe -p 0 -n 2 -h M1:2101 M2:2101"); Console.Error.WriteLine(" M2> NaiadProgram.exe -p 1 -n 2 -h M1:2101 M2:2101"); Console.Error.WriteLine("To run multiprocess on one machine, specify -p, -n and --local for each process"); } /// <summary> /// Builds a Naiad configuration from the given command-line arguments, interpreting them according to /// the output of Configuration.Usage(). /// </summary> /// <param name="args">The command-line arguments.</param> /// <param name="strippedArgs">The command-line arguments with Naiad-specific arguments removed.</param> /// <returns>A new <see cref="Configuration"/> based on the given arguments.</returns> public static Configuration BuildFromArguments(string[] args, out string[] strippedArgs) { string[] copiedArgs = args.ToArray(); Configuration ret = FromArgs(ref copiedArgs); strippedArgs = copiedArgs; return ret; } /// <summary> /// Builds a Naiad configuration from the given command-line arguments, interpreting them according to /// the output of Configuration.Usage(). /// </summary> /// <param name="args">The command-line arguments, which will have Naiad-specific arguments removed.</param> /// <returns>A new <see cref="Configuration"/> based on the given arguments.</returns> public static Configuration FromArgs(ref string[] args) { var config = new Configuration(); List<string> strippedArgs = new List<string>(); // Defaults string[] prefixes = new string[] { "localhost:2101" }; bool procIDSet = false; bool numProcsSet = false; bool hostsSet = false; bool usePPM = false; bool multipleProcsSingleMachine = true; int processes = 1; Logging.Init(); #if TRACING_ON Console.Error.WriteLine("Tracing enabled (recompile without TRACING_ON to disable)"); #else //Console.Error.WriteLine("Tracing disabled (recompile with TRACING_ON to enable)"); #endif int i = 0; while (i < args.Length) { switch (args[i]) { case "--usage": case "--help": case "-?": Usage(); ++i; break; case "--procid": case "-p": if (usePPM) { Logging.Error("Error: --procid can't be used with --ppm"); Usage(); System.Environment.Exit(-1); } config.ProcessID = Int32.Parse(args[i + 1]); i += 2; procIDSet = true; break; case "--threads": case "-t": config.WorkerCount = Int32.Parse(args[i + 1]); i += 2; break; case "--inlineserializer": config.UseInlineSerialization = true; ++i; break; case "--numprocs": case "-n": if (usePPM) { Logging.Error("Error: --numprocs can't be used with --ppm"); Usage(); System.Environment.Exit(-1); } processes = Int32.Parse(args[i + 1]); i += 2; numProcsSet = true; break; case "--hosts": case "-h": if (!numProcsSet) { Logging.Error("Error: --numprocs must be specified before --hosts"); Usage(); System.Environment.Exit(-1); } if (hostsSet) { Logging.Error("Error: --hosts cannot be combined with --local or --ppm"); Usage(); System.Environment.Exit(-1); } prefixes = new string[processes]; if (args[i + 1].StartsWith("@")) { string hostsFilename = args[i + 1].Substring(1); try { using (StreamReader reader = File.OpenText(hostsFilename)) { for (int j = 0; j < processes; ++j) { if (reader.EndOfStream) { Logging.Error("Error: insufficient number of hosts in the given hosts file, {0}", hostsFilename); System.Environment.Exit(-1); } prefixes[j] = reader.ReadLine().Trim(); } } } catch (Exception) { Logging.Error("Error: cannot read hosts file, {0}", hostsFilename); System.Environment.Exit(-1); } i += 2; } else { Array.Copy(args, i + 1, prefixes, 0, processes); i += 1 + processes; } hostsSet = true; break; case "--local": if (!numProcsSet) { Logging.Error("Error: --numprocs must be specified before --local"); Usage(); System.Environment.Exit(-1); } if (hostsSet) { Logging.Error("Error: --local cannot be combined with --hosts or --ppm"); Usage(); System.Environment.Exit(-1); } prefixes = Enumerable.Range(2101, processes).Select(x => string.Format("localhost:{0}", x)).ToArray(); i++; hostsSet = true; break; case "--ppm": if (hostsSet || numProcsSet || procIDSet) { Logging.Error("Error: --ppm cannot be combined with --hosts or --local, or --numprocs or --procid"); Usage(); System.Environment.Exit(-1); } config.ReadEndpointsFromPPM = true; hostsSet = true; usePPM = true; i++; break; case "--reachability": config.CompactionInterval = Convert.ToInt32(args[i + 1]); i += 2; break; case "--deadlocktimeout": config.DeadlockTimeout = int.Parse(args[i + 1]); i += 2; break; case "--distributedprogresstracker": config.DistributedProgressTracker = true; i++; break; case "--impersonation": config.Impersonation = true; i++; break; case "--duplex": config.DuplexSockets = true; i++; break; case "--nagling": config.Nagling = true; i++; break; case "--keepalives": config.KeepAlives = true; Logging.Progress("TCP keep-alives enabled"); i++; break; case "--nothighpriorityqueue": config.DontUseHighPriorityQueue = true; i++; break; case "--domainreporting": config.DomainReporting = true; i++; break; case "--inlinereporting": config.InlineReporting = true; i++; break; case "--aggregatereporting": config.AggregateReporting = true; i++; break; case "--broadcastprotocol": switch (args[i + 1].ToLower()) { case "tcp": case "tcponly": config.Broadcast = BroadcastProtocol.TcpOnly; break; case "udp": case "udponly": config.Broadcast = BroadcastProtocol.UdpOnly; break; case "tcpudp": case "udptcp": case "both": config.Broadcast = BroadcastProtocol.TcpUdp; break; default: Logging.Error("Warning: unknown broadcast protocol ({0})", args[i + 1]); Logging.Error("Valid broadcast protocols are: tcp, udp, both"); config.Broadcast = BroadcastProtocol.TcpOnly; break; } i += 2; break; case "--broadcastaddress": { string broadcastHostname; int broadcastPort = 2101; bool success = ParseName(args[i + 1], out broadcastHostname, ref broadcastPort); if (!success) { Logging.Error("Error: cannot set broadcast address to {0}", args[i + 1]); System.Environment.Exit(-1); } config.BroadcastAddress = new IPEndPoint(GetIPAddressForHostname(broadcastHostname), broadcastPort); } i += 2; break; case "--broadcastwakeup": { config.UseBroadcastWakeup = true; Console.Error.WriteLine("Using broadcast wakeup"); i++; break; } case "--netbroadcastwakeup": { config.UseNetworkBroadcastWakeup = true; Console.Error.WriteLine("Using broadcast wakeup for networking threads"); i++; break; } case "--sendpool": { switch (args[i + 1].ToLower()) { case "global": config.SendBufferPolicy = SendBufferMode.Global; break; case "process": config.SendBufferPolicy = SendBufferMode.PerRemoteProcess; break; case "worker": config.SendBufferPolicy = SendBufferMode.PerWorker; break; default: Logging.Error("Warning: send buffer policy ({0})", args[i + 1]); Logging.Error("Valid broadcast protocols are: global, process, worker"); config.SendBufferPolicy = SendBufferMode.PerRemoteProcess; break; } i += 2; break; } case "--sendpagesize": { config.SendPageSize = int.Parse(args[i + 1]); i += 2; break; } case "--sendpagecount": { config.SendPageCount = int.Parse(args[i + 1]); i += 2; break; } case "--addsetting": { config.AdditionalSettings.Add(args[i + 1], args[i + 2]); i += 3; break; } default: strippedArgs.Add(args[i]); i++; break; } } if (procIDSet && !numProcsSet) { Logging.Error("Error: Number of processes not supplied (use the --numprocs option, followed by an integer)"); Usage(); System.Environment.Exit(-1); } if (numProcsSet && processes > 1 && !hostsSet) { Logging.Error("Error: List of hosts not supplied (use the --hosts option, followed by {0} hostnames)", processes); System.Environment.Exit(-1); } if (config.Broadcast != BroadcastProtocol.TcpOnly && config.BroadcastAddress == null) { Logging.Error("Error: Must set --broadcastaddress to use non-TCP broadcast protocol"); System.Environment.Exit(-1); } //TOCHECK: names isn't used: can we delete it? var names = prefixes.Select(x => x.Split(':')).ToArray(); if (!usePPM) { IPEndPoint[] endpoints = new IPEndPoint[processes]; // Check whether we have multiple processes on the same machine (used for affinitizing purposes) string prevHostName = prefixes[0].Split(':')[0]; for (int j = 0; j < endpoints.Length; ++j) { string hostname; int port = 2101; bool success = ParseName(prefixes[j], out hostname, ref port); if (!success) System.Environment.Exit(-1); if (hostname != prevHostName) multipleProcsSingleMachine = false; else prevHostName = hostname; IPAddress ipv4Address = GetIPAddressForHostname(hostname); try { endpoints[j] = new System.Net.IPEndPoint(ipv4Address, port); } catch (ArgumentOutOfRangeException) { Logging.Error("Error: invalid port ({0}) for process {1}", port, j); System.Environment.Exit(-1); } } config.Endpoints = endpoints; } args = strippedArgs.ToArray(); // Used to set scheduler thread affinity config.MultipleLocalProcesses = multipleProcsSingleMachine; return config; } private static bool ParseName(string prefix, out string hostname, ref int port) { string[] splitName = prefix.Split(':'); hostname = splitName[0]; if (splitName.Length == 2 && !int.TryParse(splitName[1], out port)) { Logging.Error("Error: invalid port number ({0})", splitName[1]); return false; } return true; } private static bool IsAutoConf(IPAddress addr) { byte[] bytes = addr.GetAddressBytes(); if (bytes[0] == 169 && bytes[1] == 254) return true; return false; } private static IPAddress GetIPAddressForHostname(string hostname) { IPAddress[] ipAddresses = null; try { ipAddresses = Dns.GetHostAddresses(hostname); } catch (Exception) { Logging.Error("Error: could not resolve hostname {0}", hostname); System.Environment.Exit(-1); } IPAddress ipv4Address = ipAddresses.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork && !IsAutoConf(x)); if (ipv4Address == null) { Logging.Error("Error: could not find an IPv4 address for hostname {0}", hostname); Logging.Error("IPv6 is not currently supported."); System.Environment.Exit(-1); } return ipv4Address; } } /// <summary> /// Represents a group of workers and allows registration of callbacks /// </summary> public interface WorkerGroup { /// <summary> /// Number of workers /// </summary> int Count { get; } /// <summary> /// This event is raised by each worker when it initially starts. /// </summary> event EventHandler<WorkerStartArgs> Starting; /// <summary> /// This event is raised by each worker when it wakes from sleeping. /// </summary> event EventHandler<WorkerWakeArgs> Waking; /// <summary> /// This event is raised by a worker immediately before executing a work item. /// </summary> event EventHandler<VertexStartArgs> WorkItemStarting; /// <summary> /// This event is raised by a worker immediately after executing a work item. /// </summary> event EventHandler<VertexEndArgs> WorkItemEnding; /// <summary> /// This event is raised by a worker immediately after enqueueing a work item. /// </summary> event EventHandler<VertexEnqueuedArgs> WorkItemEnqueued; /// <summary> /// This event is raised by a worker when it becomes idle, because it has no work to execute. /// </summary> event EventHandler<WorkerSleepArgs> Sleeping; /// <summary> /// This event is raised by a worker when it has finished all work, and the computation has terminated. /// </summary> event EventHandler<WorkerTerminateArgs> Terminating; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for VirtualNetworkGatewaysOperations. /// </summary> public static partial class VirtualNetworkGatewaysOperationsExtensions { /// <summary> /// Creates or updates a virtual network gateway in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update virtual network gateway operation. /// </param> public static VirtualNetworkGateway CreateOrUpdate(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, virtualNetworkGatewayName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a virtual network gateway in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update virtual network gateway operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGateway> CreateOrUpdateAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the specified virtual network gateway by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> public static VirtualNetworkGateway Get(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName) { return operations.GetAsync(resourceGroupName, virtualNetworkGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified virtual network gateway by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGateway> GetAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified virtual network gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> public static void Delete(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName) { operations.DeleteAsync(resourceGroupName, virtualNetworkGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified virtual network gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets all virtual network gateways by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<VirtualNetworkGateway> List(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Gets all virtual network gateways by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetworkGateway>> ListAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the connections in a virtual network gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> public static IPage<VirtualNetworkGatewayConnectionListEntity> ListConnections(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName) { return operations.ListConnectionsAsync(resourceGroupName, virtualNetworkGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Gets all the connections in a virtual network gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetworkGatewayConnectionListEntity>> ListConnectionsAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListConnectionsWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Resets the primary of the virtual network gateway in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='gatewayVip'> /// Virtual network gateway vip address supplied to the begin reset of the /// active-active feature enabled gateway. /// </param> public static VirtualNetworkGateway Reset(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string)) { return operations.ResetAsync(resourceGroupName, virtualNetworkGatewayName, gatewayVip).GetAwaiter().GetResult(); } /// <summary> /// Resets the primary of the virtual network gateway in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='gatewayVip'> /// Virtual network gateway vip address supplied to the begin reset of the /// active-active feature enabled gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGateway> ResetAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ResetWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, gatewayVip, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Generates VPN client package for P2S client of the virtual network gateway /// in the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the generate virtual network gateway VPN client /// package operation. /// </param> public static string Generatevpnclientpackage(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters) { return operations.GeneratevpnclientpackageAsync(resourceGroupName, virtualNetworkGatewayName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Generates VPN client package for P2S client of the virtual network gateway /// in the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the generate virtual network gateway VPN client /// package operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> GeneratevpnclientpackageAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GeneratevpnclientpackageWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Generates VPN profile for P2S client of the virtual network gateway in the /// specified resource group. Used for IKEV2 and radius based authentication. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the generate virtual network gateway VPN client /// package operation. /// </param> public static string GenerateVpnProfile(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters) { return operations.GenerateVpnProfileAsync(resourceGroupName, virtualNetworkGatewayName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Generates VPN profile for P2S client of the virtual network gateway in the /// specified resource group. Used for IKEV2 and radius based authentication. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the generate virtual network gateway VPN client /// package operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> GenerateVpnProfileAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GenerateVpnProfileWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets pre-generated VPN profile for P2S client of the virtual network /// gateway in the specified resource group. The profile needs to be generated /// first using generateVpnProfile. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> public static string GetVpnProfilePackageUrl(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName) { return operations.GetVpnProfilePackageUrlAsync(resourceGroupName, virtualNetworkGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Gets pre-generated VPN profile for P2S client of the virtual network /// gateway in the specified resource group. The profile needs to be generated /// first using generateVpnProfile. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> GetVpnProfilePackageUrlAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetVpnProfilePackageUrlWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The GetBgpPeerStatus operation retrieves the status of all BGP peers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer to retrieve the status of. /// </param> public static BgpPeerStatusListResult GetBgpPeerStatus(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer = default(string)) { return operations.GetBgpPeerStatusAsync(resourceGroupName, virtualNetworkGatewayName, peer).GetAwaiter().GetResult(); } /// <summary> /// The GetBgpPeerStatus operation retrieves the status of all BGP peers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer to retrieve the status of. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<BgpPeerStatusListResult> GetBgpPeerStatusAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetBgpPeerStatusWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, peer, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a xml format representation for supported vpn devices. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> public static string SupportedVpnDevices(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName) { return operations.SupportedVpnDevicesAsync(resourceGroupName, virtualNetworkGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Gets a xml format representation for supported vpn devices. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> SupportedVpnDevicesAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.SupportedVpnDevicesWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// This operation retrieves a list of routes the virtual network gateway has /// learned, including routes learned from BGP peers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> public static GatewayRouteListResult GetLearnedRoutes(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName) { return operations.GetLearnedRoutesAsync(resourceGroupName, virtualNetworkGatewayName).GetAwaiter().GetResult(); } /// <summary> /// This operation retrieves a list of routes the virtual network gateway has /// learned, including routes learned from BGP peers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<GatewayRouteListResult> GetLearnedRoutesAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetLearnedRoutesWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// This operation retrieves a list of routes the virtual network gateway is /// advertising to the specified peer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer /// </param> public static GatewayRouteListResult GetAdvertisedRoutes(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer) { return operations.GetAdvertisedRoutesAsync(resourceGroupName, virtualNetworkGatewayName, peer).GetAwaiter().GetResult(); } /// <summary> /// This operation retrieves a list of routes the virtual network gateway is /// advertising to the specified peer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<GatewayRouteListResult> GetAdvertisedRoutesAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetAdvertisedRoutesWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, peer, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a xml format representation for vpn device configuration script. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection for which the /// configuration script is generated. /// </param> /// <param name='parameters'> /// Parameters supplied to the generate vpn device script operation. /// </param> public static string VpnDeviceConfigurationScript(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, VpnDeviceScriptParameters parameters) { return operations.VpnDeviceConfigurationScriptAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Gets a xml format representation for vpn device configuration script. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection for which the /// configuration script is generated. /// </param> /// <param name='parameters'> /// Parameters supplied to the generate vpn device script operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> VpnDeviceConfigurationScriptAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, VpnDeviceScriptParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.VpnDeviceConfigurationScriptWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a virtual network gateway in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update virtual network gateway operation. /// </param> public static VirtualNetworkGateway BeginCreateOrUpdate(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, virtualNetworkGatewayName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a virtual network gateway in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update virtual network gateway operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGateway> BeginCreateOrUpdateAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified virtual network gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> public static void BeginDelete(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName) { operations.BeginDeleteAsync(resourceGroupName, virtualNetworkGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified virtual network gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Resets the primary of the virtual network gateway in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='gatewayVip'> /// Virtual network gateway vip address supplied to the begin reset of the /// active-active feature enabled gateway. /// </param> public static VirtualNetworkGateway BeginReset(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string)) { return operations.BeginResetAsync(resourceGroupName, virtualNetworkGatewayName, gatewayVip).GetAwaiter().GetResult(); } /// <summary> /// Resets the primary of the virtual network gateway in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='gatewayVip'> /// Virtual network gateway vip address supplied to the begin reset of the /// active-active feature enabled gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGateway> BeginResetAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginResetWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, gatewayVip, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Generates VPN client package for P2S client of the virtual network gateway /// in the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the generate virtual network gateway VPN client /// package operation. /// </param> public static string BeginGeneratevpnclientpackage(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters) { return operations.BeginGeneratevpnclientpackageAsync(resourceGroupName, virtualNetworkGatewayName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Generates VPN client package for P2S client of the virtual network gateway /// in the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the generate virtual network gateway VPN client /// package operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> BeginGeneratevpnclientpackageAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginGeneratevpnclientpackageWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Generates VPN profile for P2S client of the virtual network gateway in the /// specified resource group. Used for IKEV2 and radius based authentication. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the generate virtual network gateway VPN client /// package operation. /// </param> public static string BeginGenerateVpnProfile(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters) { return operations.BeginGenerateVpnProfileAsync(resourceGroupName, virtualNetworkGatewayName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Generates VPN profile for P2S client of the virtual network gateway in the /// specified resource group. Used for IKEV2 and radius based authentication. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the generate virtual network gateway VPN client /// package operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> BeginGenerateVpnProfileAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginGenerateVpnProfileWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets pre-generated VPN profile for P2S client of the virtual network /// gateway in the specified resource group. The profile needs to be generated /// first using generateVpnProfile. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> public static string BeginGetVpnProfilePackageUrl(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName) { return operations.BeginGetVpnProfilePackageUrlAsync(resourceGroupName, virtualNetworkGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Gets pre-generated VPN profile for P2S client of the virtual network /// gateway in the specified resource group. The profile needs to be generated /// first using generateVpnProfile. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> BeginGetVpnProfilePackageUrlAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginGetVpnProfilePackageUrlWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The GetBgpPeerStatus operation retrieves the status of all BGP peers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer to retrieve the status of. /// </param> public static BgpPeerStatusListResult BeginGetBgpPeerStatus(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer = default(string)) { return operations.BeginGetBgpPeerStatusAsync(resourceGroupName, virtualNetworkGatewayName, peer).GetAwaiter().GetResult(); } /// <summary> /// The GetBgpPeerStatus operation retrieves the status of all BGP peers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer to retrieve the status of. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<BgpPeerStatusListResult> BeginGetBgpPeerStatusAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginGetBgpPeerStatusWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, peer, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// This operation retrieves a list of routes the virtual network gateway has /// learned, including routes learned from BGP peers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> public static GatewayRouteListResult BeginGetLearnedRoutes(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName) { return operations.BeginGetLearnedRoutesAsync(resourceGroupName, virtualNetworkGatewayName).GetAwaiter().GetResult(); } /// <summary> /// This operation retrieves a list of routes the virtual network gateway has /// learned, including routes learned from BGP peers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<GatewayRouteListResult> BeginGetLearnedRoutesAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginGetLearnedRoutesWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// This operation retrieves a list of routes the virtual network gateway is /// advertising to the specified peer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer /// </param> public static GatewayRouteListResult BeginGetAdvertisedRoutes(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer) { return operations.BeginGetAdvertisedRoutesAsync(resourceGroupName, virtualNetworkGatewayName, peer).GetAwaiter().GetResult(); } /// <summary> /// This operation retrieves a list of routes the virtual network gateway is /// advertising to the specified peer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<GatewayRouteListResult> BeginGetAdvertisedRoutesAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginGetAdvertisedRoutesWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, peer, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all virtual network gateways by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<VirtualNetworkGateway> ListNext(this IVirtualNetworkGatewaysOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all virtual network gateways by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetworkGateway>> ListNextAsync(this IVirtualNetworkGatewaysOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the connections in a virtual network gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<VirtualNetworkGatewayConnectionListEntity> ListConnectionsNext(this IVirtualNetworkGatewaysOperations operations, string nextPageLink) { return operations.ListConnectionsNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all the connections in a virtual network gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetworkGatewayConnectionListEntity>> ListConnectionsNextAsync(this IVirtualNetworkGatewaysOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListConnectionsNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using Saga.Map; using Saga.Map.Client; using Saga.Map.Definitions.Misc; using Saga.Map.Utils.Definitions.Misc; using Saga.Packets; using Saga.Structures; using Saga.Structures.Collections; using Saga.Tasks; using System; using System.Collections.Generic; namespace Saga.PrimaryTypes { public delegate void RangeEventHandler(Character regionObject); /// <summary> /// Character class used for by the client /// </summary> [System.Reflection.Obfuscation(Exclude = true, StripAfterObfuscation = true)] [Serializable] public sealed partial class Character : Actor { //Character Members #region Character Constructor / Deconstructor public Character(uint CharacterId) { this.TickLogged = Environment.TickCount; this.LASTBREATH_TICK = Environment.TickCount; this.LASTHP_TICK = Environment.TickCount; //this.LASTLP_TICK = Environment.TickCount; this.LASTSP_TICK = Environment.TickCount; this.ModelId = CharacterId; this.CharacterJobLevel = new byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; this.FaceDetails = new byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; this.job = 1; this.Cexp = 1; this.Jexp = 1; this.jlvl = 1; this._level = 1; this._status.CurrentHp += Singleton.CharacterConfiguration.CalculateMaximumHP(this); this._status.CurrentSp += Singleton.CharacterConfiguration.CalculateMaximumSP(this); this._status.MaxHP += Singleton.CharacterConfiguration.CalculateMaximumHP(this); this._status.MaxSP += Singleton.CharacterConfiguration.CalculateMaximumSP(this); } /// <summary> /// Initialize a new character /// </summary> /// <param name="client"></param> public Character(Client client, uint CharacterId, uint SessionId) { this.client = client; this.TickLogged = Environment.TickCount; this.LASTBREATH_TICK = Environment.TickCount; this.LASTHP_TICK = Environment.TickCount; //this.LASTLP_TICK = Environment.TickCount; this.LASTSP_TICK = Environment.TickCount; this.id = SessionId; this.ModelId = CharacterId; this.CharacterJobLevel = new byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; this.FaceDetails = new byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; this.job = 1; this.Cexp = 1; this.Jexp = 1; this.jlvl = 1; this._level = 1; this._status.CurrentSp += Singleton.CharacterConfiguration.CalculateMaximumSP(this); this._status.CurrentHp += Singleton.CharacterConfiguration.CalculateMaximumHP(this); this._status.MaxSP += Singleton.CharacterConfiguration.CalculateMaximumSP(this); this._status.MaxHP += Singleton.CharacterConfiguration.CalculateMaximumHP(this); } #endregion Character Constructor / Deconstructor #region Character Internal Members //Addition 562 [NonSerialized()] internal float partysprecoveramount; [NonSerialized()] internal object Tag; [NonSerialized()] internal Client client; [NonSerialized()] internal TradeSession TradeSession; [NonSerialized()] internal int UpdateReason = 0; [NonSerialized()] internal uint _ShowLoveDialog; [NonSerialized()] internal uint _Event; [NonSerialized()] internal uint _lastcastedskill = 0; [NonSerialized()] internal int _lastcastedtick = 0; [NonSerialized()] internal byte chatmute = 0; [NonSerialized()] internal byte blockhprecovery = 0; [NonSerialized()] internal byte blocksprecovery = 0; [NonSerialized()] internal CoolDownCollection cooldowncollection = new CoolDownCollection(); /// <summary> /// GmLevel of the character /// </summary> [NonSerialized()] private byte _gmlevel = 0; /// <summary> /// Name of the character /// </summary> private string name = string.Empty; /// <summary> /// Amount of character-experience (overall gameplay experience) /// </summary> private uint _cexp = 0; /// <summary> /// Amount of job-experience (speciafic for the current job) /// </summary> private uint _jexp = 0; /// <summary> /// The gender of your character /// </summary> public byte gender; /// <summary> /// The race of your character /// </summary> public byte race; /// <summary> /// Defines the last updated position tick /// </summary> [NonSerialized()] internal int LastPositionTick = 0; /// <summary> /// Defines the last sp tick /// </summary> [NonSerialized()] internal int LASTSP_TICK = 0; /// <summary> /// Defines the last hp tick /// </summary> [NonSerialized()] internal int LASTHP_TICK = 4000; /// <summary> /// Defines the last lp tick /// </summary> //[NonSerialized()] //internal int LASTLP_TICK = 0; /// <summary> /// Defines the last breath tick /// </summary> [NonSerialized()] internal int LASTBREATH_TICK = 0; /// <summary> /// ??? /// </summary> [NonSerialized()] internal int TickLogged = 0; #endregion Character Internal Members #region Character Public Members (Variables) #region Character - Base stats /// <summary> /// Get's the characters name /// </summary> public string Name { get { return name; } internal set { name = value; } } /// <summary> /// Get's the character experience. /// </summary> public uint Cexp { get { return _cexp; } internal set { _cexp = value; } } /// <summary> /// Get's the Job experience of the current job /// </summary> public uint Jexp { get { return _jexp; } internal set { _jexp = value; } } /// <summary> /// Get's the gender /// </summary> public byte Gender { get { return gender; } internal set { gender = value; } } /// <summary> /// Current job of the character /// </summary> public byte job = 5; /// <summary> /// Current map of the charracter /// </summary> public byte map; /// <summary> /// Job-level of the character /// </summary> public byte jlvl = 0; /// <summary> /// Byte array containing the face details of the character /// </summary> public byte[] FaceDetails; /// <summary> /// Boolean incidacting if the character is diving or not. /// </summary> [NonSerialized()] internal bool IsDiving = false; /// <summary> /// Boolean indicating if the character is in battle position /// </summary> [NonSerialized()] internal bool ISONBATTLE = false; /// <summary> /// The amount of zeny of the character /// </summary> public uint ZENY = 10000; #endregion Character - Base stats #region Character - Rates [NonSerialized()] public double _CexpModifier = 1; [NonSerialized()] public double _JexpModifier = 1; [NonSerialized()] public double _WexpModifier = 1; [NonSerialized()] public double _DropRate = 0; #endregion Character - Rates #region Character - Location /// <summary> /// Save location /// </summary> public WorldCoordinate savelocation; /// <summary> /// Last known location /// </summary> public WorldCoordinate lastlocation; #endregion Character - Location #region Character - Misc /// <summary> /// Internally used as a container for all of your weapons /// friends. /// </summary> internal WeaponCollection weapons = new WeaponCollection(); /// <summary> /// Internally used as a container for all of your jobs with the associated /// job levels. They form milestones of your jobs. /// </summary> internal byte[] CharacterJobLevel = new byte[15]; /// <summary> /// Internally used as a container for all of your registered /// friends. /// </summary> internal List<string> _friendlist = new List<string>(); /// <summary> /// Internally used as a container for all of your registered /// characteracters on your blacklist. /// </summary> /// <remarks> /// Because the blacklist also contains a definition for reason /// why you put him there we are using a KeyValuePair. So in order /// to perform a name based lookup use a anoumous predicate. /// </remarks> internal List<KeyValuePair<string, byte>> _blacklist = new List<KeyValuePair<string, byte>>(); /// <summary> /// Byte containing the zone information of all learned maps /// </summary> internal byte[] ZoneInformation = new byte[256]; internal List<byte> ParticipatedEvents = new List<byte>(); [NonSerialized()] internal PartySession sessionParty = null; internal Rag2Collection container = new Rag2Collection(); internal Rag2Collection STORAGE = new Rag2Collection(); internal Rag2Item[] Equipment = new Rag2Item[16]; internal List<Rag2Item> REBUY = new List<Rag2Item>(); internal Skill[] SpecialSkills = new Skill[16]; internal List<Skill> learnedskills = new List<Skill>(); internal CharacterStats stats = new CharacterStats(); internal uint ActiveDialog = 0; internal uint TakenDamage = 0; internal byte LastEquipmentDuraLoss = 0; internal Saga.Quests.Objectives.ObjectiveList QuestObjectives = new Saga.Quests.Objectives.ObjectiveList(); #endregion Character - Misc #endregion Character Public Members (Variables) #region Character Public Members (Properties) public WorldCoordinate SavePosition { get { return this.savelocation; } set { this.savelocation = value; } } /// <summary> /// Get's the character level /// </summary> public byte Clvl { get { return this._level; } } /// <summary> /// Get's the job level /// </summary> public byte Jlvl { get { return this.jlvl; } } /// <summary> /// Get's the gm level /// </summary> public byte GmLevel { get { return this._gmlevel; } internal set { _gmlevel = value; } } #endregion Character Public Members (Properties) #region Character Public Methods public bool FindRequiredRootSkill(uint RootSkill) { Predicate<Skill> Query = delegate(Skill skill) { uint SkillId = (uint)((skill.Id / 100) * 100); if (RootSkill == SkillId) return true; return false; }; return this.learnedskills.FindIndex(Query) > -1; } /// <summary> /// Calculates the current position /// </summary> /// <returns></returns> public Point CalculatePosition() { if (stance == 4 || stance == 5) { int t_diff = Environment.TickCount - LastPositionTick; float diff = t_diff * 0.1F; Point Loc = this.Position; double rad = Saga.Structures.Yaw.ToRadiants(Yaw.rotation); Loc.x += (float)(diff * Math.Cos(rad)); Loc.y += (float)(diff * Math.Sin(rad)); return Loc; } else { return this.Position; } } public uint ComputeAugeSkill() { int NewWeaponIndex = (this.weapons.ActiveWeaponIndex == 1) ? this.weapons.SeconairyWeaponIndex : this.weapons.PrimaryWeaponIndex; if (NewWeaponIndex < this.weapons.UnlockedWeaponSlots) return this.weapons[NewWeaponIndex]._augeskill; return 0; } #endregion Character Public Methods //Character Events (Special) #region Character Events [NonSerialized()] public RangeEventHandler PartyMemberAppearsInRange; [NonSerialized()] public RangeEventHandler PartyMemberDisappears; /// <summary> /// /// </summary> /// <returns></returns> /// <remarks> /// The natural hp recovery is invoked every seccond /// /// The natural sp & hp recovery are affected by additional stats/bonusses. Therefor /// we'll process HPRECOVERY only when the latest tick is greater than 1000 minus /// HP_RECOVERYRATE. The same storrie applies to SPRECOVERY, we'll only process that /// if the lastest tick is greater than 4000 minus SPRECOVERYRATE. /// /// Note: delta tick means the ellapsed time difference specified in millisecconds /// between tick start and tick end. So 4000 makes 4 secconds and 1000 makes 1 seccond. /// </remarks> /// <notes> /// TODO: Add official regenaration hp bonus /// /// Regeneration details of 26th dec patch: /// clvl 34 - 1657MHP -> 15HP per seccond /// clvl 38 - 1870MHP -> 16HP per seccond /// </notes> public bool OnRegenerateHP() { if (this.ISONBATTLE == false && this.HP < this.HPMAX && Environment.TickCount - LASTHP_TICK > (1000 - this._status.HpRecoveryRate)) { LASTHP_TICK = Environment.TickCount; ushort REGENHP_BONUS = (ushort)(15 + _status.HpRecoveryQuantity); ushort newHP = (ushort)(this.HP + REGENHP_BONUS); this.HP = (newHP < this.HPMAX) ? newHP : this.HPMAX; this._status.Updates |= 1; return true; } return false; } /// <summary> /// /// </summary> /// <returns></returns> /// <remarks> /// The natural sp recovery is invoked every 4 secconds /// /// The natural sp & hp recovery are affected by additional stats/bonusses. Therefor /// we'll process HPRECOVERY only when the latest tick is greater than 1000 minus /// HP_RECOVERYRATE. The same storrie applies to SPRECOVERY, we'll only process that /// if the lastest tick is greater than 4000 minus SPRECOVERYRATE. /// /// Note: delta tick means the ellapsed time difference specified in millisecconds /// between tick start and tick end. So 4000 makes 4 secconds and 1000 makes 1 seccond. /// </remarks> public bool OnRegenerateSP() { if (this.SP < this.SPMAX && Environment.TickCount - LASTSP_TICK > (4000 - this._status.SpRecoveryRate)) { LASTSP_TICK = Environment.TickCount; ushort REGENSP_BONUS = (ushort)(((double)this.SPMAX * 0.35) + _status.SpRecoveryQuantity); ushort newSP = (ushort)(this.SP + REGENSP_BONUS); this.SP = (newSP < this.SPMAX) ? newSP : this.SPMAX; this._status.Updates |= 1; return true; } return false; } /// <summary> /// /// </summary> /// <returns></returns> /// <remarks> /// The natural breath cheacking is invoked every seccond. /// /// Youre beath capacity equals 10% of your MHP per seccond multiplied /// by the delta_t. Time difference between the first and the last tick. /// /// First when breathing we'll substract 1 LC per seccond which represents /// your breath capacity. Once your LC drops down to 0 we'll invoked for damage /// packets if the player is still diving. /// </remarks> public bool OnBreath() { int delta_t = Environment.TickCount - LASTBREATH_TICK; LASTBREATH_TICK = Environment.TickCount; if (IsDiving == true) { if (delta_t > 1000) { if (_status.CurrentOxygen > 0) { _status.CurrentOxygen--; this._status.Updates |= 1; } else { ushort damage = (ushort)((double)this.HPMAX * 0.0001 * delta_t); damage = (this.HP > damage) ? damage : this.HP; this.HP -= damage; this._status.Updates |= 1; CommonFunctions.SendOxygenTakeDamage(this, damage); } return true; } } else { if (delta_t > 1000 - _status.OxygenRecoveryRate) { bool LCRegen = _status.CurrentOxygen < _status.MaximumOxygen; if (LCRegen == true) _status.CurrentOxygen += 10; this._status.Updates |= 1; return LCRegen; } return false; } return false; } /// <summary> /// Occurs when reducing the LP for reduction /// </summary> /// <returns>True if LP is reduced</returns> //public bool OnLPReduction() //{ // if(LASTLP_TICK<_status.LASTLP_ADD) // LASTLP_TICK=_status.LASTLP_ADD; // int delta_t = Environment.TickCount - LASTLP_TICK; // if (delta_t > 60000) // { // LASTLP_TICK = Environment.TickCount; // if (_status.CurrentLp > 0) // { // _status.CurrentLp--; // this._status.Updates |= 1; // return true; // } // } // return false; //} public override void OnSkillUsedByTarget(MapObject source, SkillBaseEventArgs e) { //If durabillity could be checked if (e.CanCheckEquipmentDurabillity) Common.Durabillity.DoEquipment(this.Target as Character, e.Damage); //Set sword drawn if (e.SpellInfo.hate > 0) this.ISONBATTLE = true; //Use base skill base.OnSkillUsedByTarget(source, e); } /// <summary> /// Occurs when the character dies /// </summary> /// <returns>Returns always true</returns> public bool OnDie() { //Pronounce my dead to other people if (this.sessionParty != null) foreach (Character target in this.sessionParty.GetCharacters()) { if (target.id == this.id) continue; if (target.client.isloaded == true) { SMSG_PARTYMEMBERDIED spkt = new SMSG_PARTYMEMBERDIED(); spkt.SessionId = target.id; spkt.Index = 1; spkt.ActorId = this.id; target.client.Send((byte[])spkt); } } // SUBSCRIBE FOR RESPAWN this.ISONBATTLE = false; Respawns.Subscribe(this); return true; } public override void OnEnemyDie(MapObject enemy) { if (MapObject.IsNpc(enemy)) { Quests.QuestBase.UserEliminateTarget(enemy.ModelId, this); } } #endregion Character Events //Interface Memebers public override void Appears(Character character) { if (character.sessionParty != null && this.sessionParty != null) { if (character.sessionParty._Characters.Contains(this)) { character.PartyMemberAppearsInRange(this); this.PartyMemberAppearsInRange(character); } } } public override void Disappear(Character character) { if (character.sessionParty != null && this.sessionParty != null) { if (character.sessionParty._Characters.Contains(this)) { character.PartyMemberDisappears(this); this.PartyMemberDisappears(character); } } } public override void ShowObject(Character character) { //HELPER VARIABLES Rag2Item item; //STRUCTIRIZE GENERAL INFORMATION SMSG_CHARACTERINFO spkt = new SMSG_CHARACTERINFO(); spkt.race = 0; spkt.Gender = this.gender; spkt.Name = this.Name; spkt.X = this.Position.x; spkt.Y = this.Position.y; spkt.Z = this.Position.z; spkt.ActorID = this.id; spkt.face = this.FaceDetails; spkt.AugeSkillID = this.ComputeAugeSkill(); spkt.yaw = this.Yaw; spkt.Job = this.job; spkt.Stance = this.stance; //STRUCTURIZE EQUIPMENT INFORMATION item = this.Equipment[0]; if (item != null && item.active > 0) spkt.SetHeadTop(item.info.item, item.dyecolor); item = this.Equipment[1]; if (item != null && item.active > 0) spkt.SetHeadMiddle(item.info.item, item.dyecolor); item = this.Equipment[2]; if (item != null && item.active > 0) spkt.SetHeadBottom(item.info.item, item.dyecolor); item = this.Equipment[14]; if (item != null && item.active > 0) spkt.SetShield(item.info.item, item.dyecolor); item = this.Equipment[8]; if (item != null && item.active > 0) spkt.SetBack(item.info.item, item.dyecolor); item = this.Equipment[3]; if (item != null && item.active > 0) spkt.SetShirt(item.info.item, item.dyecolor); item = this.Equipment[4]; if (item != null && item.active > 0) spkt.SetPants(item.info.item, item.dyecolor); item = this.Equipment[5]; if (item != null && item.active > 0) spkt.SetGloves(item.info.item, item.dyecolor); item = this.Equipment[6]; if (item != null && item.active > 0) spkt.SetFeet(item.info.item, item.dyecolor); foreach (AdditionState state in this._additions) spkt.SetWeapon(state.Addition, state.Lifetime); lock (character) { spkt.SessionId = character.id; character.client.Send((byte[])spkt); if (this._Event > 0) { SMSG_SCENARIOEVENTBEGIN spkt2 = new SMSG_SCENARIOEVENTBEGIN(); spkt2.Event = this._Event; spkt2.ActorId = this.id; spkt2.SessionId = character.id; character.client.Send((byte[])spkt2); } } } public override string ToString() { return string.Format("Character name:{1} id:{0}", this.id, this.name); } } [Serializable()] public class CharacterStats { private static Stats _BASE = new Stats(5, 3, 3, 2, 0); public Stats CHARACTER = new Stats(); public Stats EQUIPMENT = new Stats(); public Stats ENCHANTMENT = new Stats(); public ushort REMAINING = 0; public Stats BASE { get { return _BASE; } } public ushort Strength { get { return (ushort)( _BASE.strength + //ADD STATS FROM THE BASE TEMPLATE CHARACTER.strength + //ADD STATS CHOOSEN BY THE CHARACTER EQUIPMENT.strength + //ADD STATS GIVEN BY EQUIPMENT ENCHANTMENT.strength //ADD STATS GIVEN BY ENCHANTMENTS, BUFFS, SKILLS ); } } public ushort Dexterity { get { return (ushort)( _BASE.dexterity + //ADD STATS FROM THE BASE TEMPLATE CHARACTER.dexterity + //ADD STATS CHOOSEN BY THE CHARACTER EQUIPMENT.dexterity + //ADD STATS GIVEN BY EQUIPMENT ENCHANTMENT.dexterity //ADD STATS GIVEN BY ENCHANTMENTS, BUFFS, SKILLS ); } } public ushort Concentration { get { return (ushort)( _BASE.concentration + //ADD STATS FROM THE BASE TEMPLATE CHARACTER.concentration + //ADD STATS CHOOSEN BY THE CHARACTER EQUIPMENT.concentration + //ADD STATS GIVEN BY EQUIPMENT ENCHANTMENT.concentration //ADD STATS GIVEN BY ENCHANTMENTS, BUFFS, SKILLS ); } } public ushort Intelligence { get { return (ushort)( _BASE.intelligence + //ADD STATS FROM THE BASE TEMPLATE CHARACTER.intelligence + //ADD STATS CHOOSEN BY THE CHARACTER EQUIPMENT.intelligence + //ADD STATS GIVEN BY EQUIPMENT ENCHANTMENT.intelligence //ADD STATS GIVEN BY ENCHANTMENTS, BUFFS, SKILLS ); } } public ushort Luck { get { return (ushort)( _BASE.luck + //ADD STATS FROM THE BASE TEMPLATE CHARACTER.luck + //ADD STATS CHOOSEN BY THE CHARACTER EQUIPMENT.luck + //ADD STATS GIVEN BY EQUIPMENT ENCHANTMENT.luck //ADD STATS GIVEN BY ENCHANTMENTS, BUFFS, SKILLS ); } } [Serializable()] public class Stats { public ushort strength = 0; //CONTAINER FOR STRENGTH STAT public ushort dexterity = 0; //CONTAINER FOR DEXTERITY STAT public ushort intelligence = 0; //CONTAINER FOR INTELLIGENCE STAT public ushort concentration = 0; //CONTAINER FOR CONCENTRATION STAT public ushort luck = 0; //CONTAINER FOR LUCK STAT public Stats() { } public Stats(ushort strength, ushort dexterity, ushort intelligence, ushort concentration, ushort luck) { this.strength = strength; this.dexterity = dexterity; this.intelligence = intelligence; this.concentration = concentration; this.luck = luck; } public static implicit operator ushort[](Stats f) { return new ushort[] { f.strength, f.dexterity, f.intelligence, f.concentration, f.luck }; } } } }