context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Threading; using osu.Game.Graphics; using osu.Game.Tournament.Components; using osu.Game.Tournament.Screens; using osu.Game.Tournament.Screens.Drawings; using osu.Game.Tournament.Screens.Editors; using osu.Game.Tournament.Screens.Gameplay; using osu.Game.Tournament.Screens.Ladder; using osu.Game.Tournament.Screens.MapPool; using osu.Game.Tournament.Screens.Schedule; using osu.Game.Tournament.Screens.Setup; using osu.Game.Tournament.Screens.Showcase; using osu.Game.Tournament.Screens.TeamIntro; using osu.Game.Tournament.Screens.TeamWin; using osuTK; using osuTK.Graphics; namespace osu.Game.Tournament { [Cached] public class TournamentSceneManager : CompositeDrawable { private Container screens; private TourneyVideo video; public const float CONTROL_AREA_WIDTH = 160; public const float STREAM_AREA_WIDTH = 1366; public const double REQUIRED_WIDTH = CONTROL_AREA_WIDTH * 2 + STREAM_AREA_WIDTH; [Cached] private TournamentMatchChatDisplay chat = new TournamentMatchChatDisplay(); private Container chatContainer; private FillFlowContainer buttons; public TournamentSceneManager() { RelativeSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load() { InternalChildren = new Drawable[] { new Container { RelativeSizeAxes = Axes.Y, X = CONTROL_AREA_WIDTH, FillMode = FillMode.Fit, FillAspectRatio = 16 / 9f, Anchor = Anchor.TopLeft, Origin = Anchor.TopLeft, Width = STREAM_AREA_WIDTH, //Masking = true, Children = new Drawable[] { video = new TourneyVideo("main", true) { Loop = true, RelativeSizeAxes = Axes.Both, }, screens = new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new SetupScreen(), new ScheduleScreen(), new LadderScreen(), new LadderEditorScreen(), new TeamEditorScreen(), new RoundEditorScreen(), new ShowcaseScreen(), new MapPoolScreen(), new TeamIntroScreen(), new SeedingScreen(), new DrawingsScreen(), new GameplayScreen(), new TeamWinScreen() } }, chatContainer = new Container { RelativeSizeAxes = Axes.Both, Child = chat }, } }, new Container { RelativeSizeAxes = Axes.Y, Width = CONTROL_AREA_WIDTH, Children = new Drawable[] { new Box { Colour = Color4.Black, RelativeSizeAxes = Axes.Both, }, buttons = new FillFlowContainer { RelativeSizeAxes = Axes.Both, Direction = FillDirection.Vertical, Spacing = new Vector2(5), Padding = new MarginPadding(5), Children = new Drawable[] { new ScreenButton(typeof(SetupScreen)) { Text = "Setup", RequestSelection = SetScreen }, new Separator(), new ScreenButton(typeof(TeamEditorScreen)) { Text = "Team Editor", RequestSelection = SetScreen }, new ScreenButton(typeof(RoundEditorScreen)) { Text = "Rounds Editor", RequestSelection = SetScreen }, new ScreenButton(typeof(LadderEditorScreen)) { Text = "Bracket Editor", RequestSelection = SetScreen }, new Separator(), new ScreenButton(typeof(ScheduleScreen)) { Text = "Schedule", RequestSelection = SetScreen }, new ScreenButton(typeof(LadderScreen)) { Text = "Bracket", RequestSelection = SetScreen }, new Separator(), new ScreenButton(typeof(TeamIntroScreen)) { Text = "Team Intro", RequestSelection = SetScreen }, new ScreenButton(typeof(SeedingScreen)) { Text = "Seeding", RequestSelection = SetScreen }, new Separator(), new ScreenButton(typeof(MapPoolScreen)) { Text = "Map Pool", RequestSelection = SetScreen }, new ScreenButton(typeof(GameplayScreen)) { Text = "Gameplay", RequestSelection = SetScreen }, new Separator(), new ScreenButton(typeof(TeamWinScreen)) { Text = "Win", RequestSelection = SetScreen }, new Separator(), new ScreenButton(typeof(DrawingsScreen)) { Text = "Drawings", RequestSelection = SetScreen }, new ScreenButton(typeof(ShowcaseScreen)) { Text = "Showcase", RequestSelection = SetScreen }, } }, }, }, }; foreach (var drawable in screens) drawable.Hide(); SetScreen(typeof(SetupScreen)); } private float depth; private Drawable currentScreen; private ScheduledDelegate scheduledHide; private Drawable temporaryScreen; public void SetScreen(Drawable screen) { currentScreen?.Hide(); currentScreen = null; screens.Add(temporaryScreen = screen); } public void SetScreen(Type screenType) { temporaryScreen?.Expire(); var target = screens.FirstOrDefault(s => s.GetType() == screenType); if (target == null || currentScreen == target) return; if (scheduledHide?.Completed == false) { scheduledHide.RunTask(); scheduledHide.Cancel(); // see https://github.com/ppy/osu-framework/issues/2967 scheduledHide = null; } var lastScreen = currentScreen; currentScreen = target; if (currentScreen is IProvideVideo) { video.FadeOut(200); // delay the hide to avoid a double-fade transition. scheduledHide = Scheduler.AddDelayed(() => lastScreen?.Hide(), TournamentScreen.FADE_DELAY); } else { lastScreen?.Hide(); video.Show(); } screens.ChangeChildDepth(currentScreen, depth--); currentScreen.Show(); switch (currentScreen) { case MapPoolScreen _: chatContainer.FadeIn(TournamentScreen.FADE_DELAY); chatContainer.ResizeWidthTo(1, 500, Easing.OutQuint); break; case GameplayScreen _: chatContainer.FadeIn(TournamentScreen.FADE_DELAY); chatContainer.ResizeWidthTo(0.5f, 500, Easing.OutQuint); break; default: chatContainer.FadeOut(TournamentScreen.FADE_DELAY); break; } foreach (var s in buttons.OfType<ScreenButton>()) s.IsSelected = screenType == s.Type; } private class Separator : CompositeDrawable { public Separator() { RelativeSizeAxes = Axes.X; Height = 20; } } private class ScreenButton : TourneyButton { public readonly Type Type; public ScreenButton(Type type) { Type = type; BackgroundColour = OsuColour.Gray(0.2f); Action = () => RequestSelection?.Invoke(type); RelativeSizeAxes = Axes.X; } private bool isSelected; public Action<Type> RequestSelection; public bool IsSelected { get => isSelected; set { if (value == isSelected) return; isSelected = value; BackgroundColour = isSelected ? Color4.SkyBlue : OsuColour.Gray(0.2f); SpriteText.Colour = isSelected ? Color4.Black : Color4.White; } } } } }
// // Accessible.cs // // Author: // Vsevolod Kukol <[email protected]> // // Copyright (c) 2017 Microsoft Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Xwt.Backends; namespace Xwt.Accessibility { [BackendType (typeof (IAccessibleBackend))] public sealed class Accessible : IFrontend { readonly XwtComponent parentComponent; readonly object parentNativeObject; readonly AccessibleBackendHost backendHost; Widget labelWidget; class AccessibleBackendHost : BackendHost<Accessible, IAccessibleBackend>, IAccessibleEventSink { protected override IBackend OnCreateBackend () { var b = base.OnCreateBackend (); if (b == null) b = new DefaultNoOpAccessibleBackend (); return b; } protected override void OnBackendCreated () { object parentBackend = Parent.parentComponent?.GetBackend (); if (parentBackend is IWidgetBackend) Backend.Initialize ((IWidgetBackend) parentBackend, this); else if (parentBackend is IPopoverBackend) Backend.Initialize ((IPopoverBackend) parentBackend, this); else if (parentBackend is IMenuBackend) Backend.Initialize ((IMenuBackend) parentBackend, this); else if (parentBackend is IMenuItemBackend) Backend.Initialize ((IMenuItemBackend) parentBackend, this); else Backend.Initialize (Parent.parentNativeObject, this); } public bool OnPress () { return Parent.OnPress (); } } internal Accessible (Widget parent): this ((XwtComponent)parent) { } internal Accessible (Popover parent): this ((XwtComponent)parent) { } internal Accessible (Menu parent): this ((XwtComponent)parent) { } internal Accessible (MenuItem parent): this ((XwtComponent)parent) { } Accessible (XwtComponent parent) { if (parent == null) throw new ArgumentNullException (nameof (parent)); parentComponent = parent; backendHost = new AccessibleBackendHost (); backendHost.Parent = this; if (parent.GetBackend () is XwtWidgetBackend) backendHost.SetCustomBackend (new XwtAccessibleBackend()); } internal Accessible (object nativeParent) { if (nativeParent == null) throw new ArgumentNullException (nameof (nativeParent)); parentNativeObject = nativeParent; backendHost = new AccessibleBackendHost (); backendHost.Parent = this; } IAccessibleBackend Backend { get { return backendHost.Backend; } } object IFrontend.Backend { get { return Backend; } } Toolkit IFrontend.ToolkitEngine { get { return backendHost.ToolkitEngine; } } public bool IsAccessible { get { return Backend.IsAccessible; } set { Backend.IsAccessible = value; OnPropertyChanged(); } } public string Identifier { get { return Backend.Identifier; } set { Backend.Identifier = value; OnPropertyChanged(); } } public string Label { get { return Backend.Label; } set { Backend.Label = value; OnPropertyChanged(); } } public Widget LabelWidget { get { return labelWidget; } set { labelWidget = value; Backend.LabelWidget = value; OnPropertyChanged(); } } public string Title { get { return Backend.Title; } set { Backend.Title = value; OnPropertyChanged(); } } public string Description { get { return Backend.Description; } set { Backend.Description = value; OnPropertyChanged(); } } public string Value { get { return Backend.Value; } set { Backend.Value = value; OnPropertyChanged(); } } public Uri Uri { get { return Backend.Uri; } set { Backend.Uri = value; OnPropertyChanged(); } } public Rectangle Bounds { get { return Backend.Bounds; } set { Backend.Bounds = value; OnPropertyChanged(); } } public Role Role { get { return Backend.Role; } set { Backend.Role = value; OnPropertyChanged(); } } public string RoleDescription { get { return Backend.RoleDescription; } set { Backend.RoleDescription = value; OnPropertyChanged (); } } public IEnumerable<object> GetChildren () { return Backend.GetChildren (); } public void AddChild (object nativeChild) { Backend.AddChild (nativeChild); } public void RemoveChild (object nativeChild) { Backend.RemoveChild (nativeChild); } public void RemoveAllChildren () { Backend.RemoveAllChildren (); } bool OnPress () { var args = new WidgetEventArgs (); press?.Invoke (this, args); return args.Handled; } event EventHandler<WidgetEventArgs> press; public event EventHandler<WidgetEventArgs> Press { add { backendHost.OnBeforeEventAdd (AccessibleEvent.Press, press); press += value; } remove { press -= value; backendHost.OnAfterEventRemove (AccessibleEvent.Press, press); } } void OnPropertyChanged ([CallerMemberName] string propertyName = null) { if (propertyName != null) { PropertyChanged?.Invoke (this, new PropertyChangedEventArgs (propertyName)); } } public event PropertyChangedEventHandler PropertyChanged; /// <param name="polite">(WPF, XamMac, GtkMac) will use AutomationLiveSetting.Polite/NSAccessibilityPriorityLevel.Medium /// if true and AutomationLiveSetting.Assertive/NSAccessibilityPriorityLevel.High otherwise (default)</param> public void MakeAnnouncement (string message, bool polite = false) { Backend.MakeAnnouncement (message, polite); } /// <summary> /// Returns true if Narrator, VoiceOver or a third-party accessibility means are in use /// </summary> public bool AccessibilityInUse { get { return Backend.AccessibilityInUse; } } /// <summary> /// Supported on XamMac and GtkMac only /// </summary> public event EventHandler AccessibilityInUseChanged { add { Backend.AccessibilityInUseChanged += value; } remove { Backend.AccessibilityInUseChanged -= value; } } } class DefaultNoOpAccessibleBackend : IAccessibleBackend { public Rectangle Bounds { get; set; } public string Description { get; set; } public string Identifier { get; set; } public string Label { get; set; } public Widget LabelWidget { set { } } public Role Role { get; set; } public string RoleDescription { get; set; } public string Title { get; set; } public string Value { get; set; } public Uri Uri { get; set; } public bool IsAccessible { get; set; } public bool AccessibilityInUse { get; } #pragma warning disable 067 public event EventHandler AccessibilityInUseChanged; #pragma warning restore 067 public void AddChild (object nativeChild) { } public void RemoveChild (object nativeChild) { } public void RemoveAllChildren () { } public IEnumerable<object> GetChildren () { return Enumerable.Empty<object>(); } public void DisableEvent (object eventId) { } public void EnableEvent (object eventId) { } public void Initialize (IWidgetBackend parentWidget, IAccessibleEventSink eventSink) { } public void Initialize (IPopoverBackend parentPopover, IAccessibleEventSink eventSink) { } public void Initialize(IMenuBackend parentMenu, IAccessibleEventSink eventSink) { } public void Initialize (IMenuItemBackend parentMenuItem, IAccessibleEventSink eventSink) { } public void Initialize (object parentWidget, IAccessibleEventSink eventSink) { } public void InitializeBackend (object frontend, ApplicationContext context) { } public void MakeAnnouncement(string message, bool polite = false) { } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Reflection; using System.Threading; using System.Xml; using OpenLiveWriter.CoreServices.Diagnostics; using OpenLiveWriter.CoreServices.Threading; namespace OpenLiveWriter.CoreServices { /// <summary> /// Class for downloading files from the web and storing them in a local cache. Note /// that files downloaded with this class must also exist as resources in the calling /// assembly as a last-ditch backup. /// </summary> public class ResourceFileDownloader { private static bool _allowResourceFileDownloads = ApplicationEnvironment.PreferencesSettingsRoot.GetSubSettings("Resources").GetBoolean("DownloadResources", true); /// <summary> /// Version of the ResourceFileDownloader with cache mapped to standard Local Settings directory /// </summary> public static ResourceFileDownloader Application { get { return _application; } } private static readonly ResourceFileDownloader _application = new ResourceFileDownloader(Path.Combine(ApplicationEnvironment.LocalApplicationDataDirectory, "ResourceCache"), _allowResourceFileDownloads); public object ProcessLocalResourceSafelyAndRefresh(string name, string url, string contentType, ResourceFileProcessor processor, int delayMs) { Assembly assembly = Assembly.GetCallingAssembly(); lock (_downloadedResources.SyncRoot) { if (!_downloadedResources.Contains(url)) { _downloadedResources.Add(url); new DelayUpdateHelper(assembly, name, url, contentType, this, processor, delayMs).StartBackgroundUpdate(); } } return ProcessResourceSafely(assembly, name, string.Empty, contentType, REQUIREDFRESHNESSDAYS, TIMEOUTMS, processor); } private const int REQUIREDFRESHNESSDAYS = 1; private const int TIMEOUTMS = 10000; private readonly static HashSet _downloadedResources = new HashSet(); private class DelayUpdateHelper { /// <summary> /// Trims the working set after a given delay /// </summary> /// <param name="delayMs">The delay prior to trimming the working set</param> /// <returns></returns> public DelayUpdateHelper(Assembly callingAssembly, string name, string url, string contentType, ResourceFileDownloader downloader, ResourceFileProcessor processor, int delayMs) { _callingAssembly = callingAssembly; _name = name; _url = url; _contentType = contentType; _processor = processor; _downloader = downloader; _delayMs = delayMs; } private readonly string _name; private readonly string _url; private readonly string _contentType; private readonly ResourceFileProcessor _processor; private readonly ResourceFileDownloader _downloader; private readonly Assembly _callingAssembly; private readonly int _delayMs; public void StartBackgroundUpdate() { Thread t = ThreadHelper.NewThread(new ThreadStart(DownloadResource), "Background Resource Download", true, false, true); t.Start(); } private void DownloadResource() { Thread.Sleep(_delayMs); _downloader.ProcessResourceSafely(_callingAssembly, _name, _url, _contentType, REQUIREDFRESHNESSDAYS, TIMEOUTMS, _processor); } } /// <summary> /// Initialize the downloader with the appropriate paths and options /// </summary> /// <param name="fileCacheBasePath">Base directory for writing cached copies of resources locally</param> /// <param name="enableDownloading">Enable downloading of resources from the network</param> public ResourceFileDownloader(string fileCacheBasePath, bool enableDownloading) { _fileCacheBasePath = fileCacheBasePath; _enableDownloading = enableDownloading && !ApplicationDiagnostics.SuppressBackgroundRequests; } /// <summary> /// Get a resource -- the name should be the "." separated path to the resource /// within the calling assembly. The resource should also be located at the same /// path relative to the resourceUrlBasePath on the target web server. /// </summary> /// <param name="name">resource name</param> /// <param name="resourceUrl">url where the resource can be found</param> /// <param name="requiredFreshnessDays">number of days for which we can use cached copies</param> /// <param name="timeoutMs">timeout in ms for request to web server</param> /// <returns>Stream to resource contents</returns> public Stream GetResource(string name, string resourceUrl, string contentType, int requiredFreshnessDays, int timeoutMs) { return GetResource(Assembly.GetCallingAssembly(), name, resourceUrl, contentType, requiredFreshnessDays, timeoutMs); } /// <summary> /// Get and process a resource (see comment on GetResource for more info on resources) /// This method attempts to load the resource normally (i.e. from the network). If /// an exception of any kind happens during processing we revert back to processing /// the version built into the assembly. /// </summary> /// <param name="name">resource name</param> /// <param name="requiredFreshnessDays">number of days for which we can use cached copies</param> /// <param name="timeoutMs">timeout in ms for request to web server</param> /// <param name="processor">callback used for processing the resource</param> /// <returns>result of processing</returns> public object ProcessResourceSafely(string name, string resourceUrl, string contentType, int requiredFreshnessDays, int timeoutMs, ResourceFileProcessor processor) { // record calling assembly return ProcessResourceSafely(Assembly.GetCallingAssembly(), name, resourceUrl, contentType, requiredFreshnessDays, timeoutMs, processor); } private object ProcessResourceSafely(Assembly callingAssembly, string name, string resourceUrl, string contentType, int requiredFreshnessDays, int timeoutMs, ResourceFileProcessor processor) { if (contentType == MimeHelper.TEXT_XML) processor = new ResourceFileProcessor(new XPPResourceFileProcessor(processor).ProcessXmlResource); // attempt to load and process the resource (potentially loading new data from the network) try { using (Stream stream = GetResource(callingAssembly, name, resourceUrl, contentType, requiredFreshnessDays, timeoutMs)) { return processor(stream); } // verify content type of responding url } catch (Exception ex) { // report failure Trace.WriteLine(String.Format(CultureInfo.InvariantCulture, "Unexpected exception occurred while processing resource {0}: {1}", name, ex.ToString())); // NOTE: we should save the last successfully download/used file and // "restore" from this rather than the embedded copy in the case of // an error or failure reading from the downloaded file. // safely delete the locally cached file (it contains bad data) SafeDeleteLocalCacheFile(callingAssembly, name); // try again on local data using (Stream stream = GetResourceLocal(callingAssembly, name)) return processor(stream); } } private class XPPResourceFileProcessor { public XPPResourceFileProcessor(ResourceFileProcessor processor) { _processor = processor; } private ResourceFileProcessor _processor; public object ProcessXmlResource(Stream stream) { XmlPreprocessor preprocessor = new XmlPreprocessor(); preprocessor.Add("version", new Version(ApplicationEnvironment.ProductVersion)); preprocessor.Add("language", CultureInfo.CurrentUICulture.TwoLetterISOLanguageName); preprocessor.Add("culture", CultureInfo.CurrentUICulture.Name); XmlDocument document = new XmlDocument(); document.Load(stream); preprocessor.Munge(document); MemoryStream processedStream = new MemoryStream(); document.Save(processedStream); processedStream.Seek(0, SeekOrigin.Begin); return _processor(processedStream); } } private Stream GetResource(Assembly assembly, string name, string resourceUrl, string contentType, int requiredFreshnessDays, int timeoutMs) { // get the path to the resource string assemblyResourcePath = FormatResourcePath(assembly, name); // in debug builds we need to verify that the resource has been included in the assembly DebugVerifyResourcePath(assembly, assemblyResourcePath); try { // first see if there is a fresh enough local file version string fileResourcePath = GetLocalCachePath(assemblyResourcePath); if (File.Exists(fileResourcePath) && (File.GetLastWriteTime(fileResourcePath).AddDays(requiredFreshnessDays) > DateTime.Now)) { return new FileStream(fileResourcePath, FileMode.Open, FileAccess.Read, FileShare.Read); } // local file doesn't exist or is out of date, try downloading from the web if (_enableDownloading && (resourceUrl != String.Empty)) { using (Stream urlStream = SafeDownloadUrl(resourceUrl, contentType, timeoutMs)) { if (urlStream != null) { // got a stream, save it to our cache Directory.CreateDirectory(Path.GetDirectoryName(fileResourcePath)); using (FileStream fileStream = new FileStream(fileResourcePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) { StreamHelper.Transfer(urlStream, fileStream); } // return reference to local file stream return new FileStream(fileResourcePath, FileMode.Open, FileAccess.Read, FileShare.Read); } else { if (File.Exists(fileResourcePath)) return new FileStream(fileResourcePath, FileMode.Open, FileAccess.Read, FileShare.Read); } } } } catch (Exception ex) { Trace.Fail(String.Format(CultureInfo.InvariantCulture, "Unexpected exception attempting to load resource {0}: {1}", assemblyResourcePath, ex.ToString())); } // if we get this far it means downloading was disabled, we couldn't find the file // on the web, or an unexpected error occurred (e.g. file sharing violation), in // these cases fallback to returning the stream from within the assembly return assembly.GetManifestResourceStream(assemblyResourcePath); } private Stream SafeDownloadUrl(string url, string contentType, int timeoutMs) { HttpWebResponse response = HttpRequestHelper.SafeSendRequest(url, delegate (HttpWebRequest request) { request.Timeout = timeoutMs; request.ReadWriteTimeout = timeoutMs * 5; }); if (response == null) return null; string baseContentType = response.ContentType.Split(new char[] { ';' }, 2)[0].Trim(); if (!UrlHelper.SafeToAbsoluteUri(response.ResponseUri).StartsWith("http://www.msn.com/", StringComparison.OrdinalIgnoreCase)) // This seems weird, but our g-links redirect to www.msn.com (rather than 404) if they aren't deployed. good times Debug.Assert(baseContentType == contentType, "Mismatching content type on downloaded resource. Expected " + contentType + " and got " + baseContentType); else Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "The resource url at {0} appears not to be deployed.", url)); if (baseContentType == contentType) { return response.GetResponseStream(); } else { response.Close(); return null; } } /// <summary> /// Get the specified resource from the local cache /// </summary> /// <param name="name">name of resource</param> /// <returns>stream to resource</returns> public Stream GetResourceLocal(string name) { return GetResourceLocal(Assembly.GetCallingAssembly(), name); } private Stream GetResourceLocal(Assembly assembly, string name) { // calculate the full resource path name string assemblyResourcePath = FormatResourcePath(assembly, name); // return the resource stream return assembly.GetManifestResourceStream(assemblyResourcePath); } private void SafeDeleteLocalCacheFile(Assembly assembly, string resourceName) { try { string resourcePath = FormatResourcePath(assembly, resourceName); string localCacheFilePath = GetLocalCachePath(resourcePath); File.Delete(localCacheFilePath); } catch { } } private string GetLocalCachePath(string assemblyResourcePath) { if (_fileCacheBasePath != String.Empty) return Path.Combine(_fileCacheBasePath, ConvertResourcePath(assemblyResourcePath, '\\')); else return String.Empty; } private string FormatResourcePath(Assembly assembly, string name) { return String.Format(CultureInfo.InvariantCulture, "{0}.{1}", assembly.GetName().Name, name); } private string ConvertResourcePath(string resourcePath, char pathSeparator) { int extensionIndex = resourcePath.LastIndexOf('.'); string path = resourcePath.Substring(0, extensionIndex); string extension = resourcePath.Substring(extensionIndex); return path.Replace('.', pathSeparator) + extension; } private void DebugVerifyResourcePath(Assembly assembly, string assemblyResourcePath) { #if DEBUG using (Stream stream = assembly.GetManifestResourceStream(assemblyResourcePath)) { if (stream == null) Debug.Fail("Resource requested from ResourceFileDownloader not included in calling asssembly! (" + assemblyResourcePath + ")"); } #endif } private string _fileCacheBasePath; private bool _enableDownloading; } /// <summary> /// Callback for processing the contents of a resource file /// </summary> public delegate object ResourceFileProcessor(Stream resourceFile); }
using System.Diagnostics; namespace YAF.Lucene.Net.Codecs { /* * 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 IndexOutput = YAF.Lucene.Net.Store.IndexOutput; using MathUtil = YAF.Lucene.Net.Util.MathUtil; using RAMOutputStream = YAF.Lucene.Net.Store.RAMOutputStream; /// <summary> /// This abstract class writes skip lists with multiple levels. /// /// <code> /// /// Example for skipInterval = 3: /// c (skip level 2) /// c c c (skip level 1) /// x x x x x x x x x x (skip level 0) /// d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d (posting list) /// 3 6 9 12 15 18 21 24 27 30 (df) /// /// d - document /// x - skip data /// c - skip data with child pointer /// /// Skip level i contains every skipInterval-th entry from skip level i-1. /// Therefore the number of entries on level i is: floor(df / ((skipInterval ^ (i + 1))). /// /// Each skip entry on a level i>0 contains a pointer to the corresponding skip entry in list i-1. /// this guarantees a logarithmic amount of skips to find the target document. /// /// While this class takes care of writing the different skip levels, /// subclasses must define the actual format of the skip data. /// </code> /// <para/> /// @lucene.experimental /// </summary> public abstract class MultiLevelSkipListWriter { /// <summary> /// Number of levels in this skip list. </summary> protected internal int m_numberOfSkipLevels; /// <summary> /// The skip interval in the list with level = 0. </summary> private int skipInterval; /// <summary> /// SkipInterval used for level &gt; 0. </summary> private int skipMultiplier; /// <summary> /// For every skip level a different buffer is used. </summary> private RAMOutputStream[] skipBuffer; /// <summary> /// Creates a <see cref="MultiLevelSkipListWriter"/>. </summary> protected MultiLevelSkipListWriter(int skipInterval, int skipMultiplier, int maxSkipLevels, int df) { this.skipInterval = skipInterval; this.skipMultiplier = skipMultiplier; // calculate the maximum number of skip levels for this document frequency if (df <= skipInterval) { m_numberOfSkipLevels = 1; } else { m_numberOfSkipLevels = 1 + MathUtil.Log(df / skipInterval, skipMultiplier); } // make sure it does not exceed maxSkipLevels if (m_numberOfSkipLevels > maxSkipLevels) { m_numberOfSkipLevels = maxSkipLevels; } } /// <summary> /// Creates a <see cref="MultiLevelSkipListWriter"/>, where /// <see cref="skipInterval"/> and <see cref="skipMultiplier"/> are /// the same. /// </summary> protected MultiLevelSkipListWriter(int skipInterval, int maxSkipLevels, int df) : this(skipInterval, skipInterval, maxSkipLevels, df) { } /// <summary> /// Allocates internal skip buffers. </summary> protected virtual void Init() { skipBuffer = new RAMOutputStream[m_numberOfSkipLevels]; for (int i = 0; i < m_numberOfSkipLevels; i++) { skipBuffer[i] = new RAMOutputStream(); } } /// <summary> /// Creates new buffers or empties the existing ones. </summary> public virtual void ResetSkip() { if (skipBuffer == null) { Init(); } else { for (int i = 0; i < skipBuffer.Length; i++) { skipBuffer[i].Reset(); } } } /// <summary> /// Subclasses must implement the actual skip data encoding in this method. /// </summary> /// <param name="level"> The level skip data shall be writing for. </param> /// <param name="skipBuffer"> The skip buffer to write to. </param> protected abstract void WriteSkipData(int level, IndexOutput skipBuffer); /// <summary> /// Writes the current skip data to the buffers. The current document frequency determines /// the max level is skip data is to be written to. /// </summary> /// <param name="df"> The current document frequency. </param> /// <exception cref="System.IO.IOException"> If an I/O error occurs. </exception> public virtual void BufferSkip(int df) { Debug.Assert(df % skipInterval == 0); int numLevels = 1; df /= skipInterval; // determine max level while ((df % skipMultiplier) == 0 && numLevels < m_numberOfSkipLevels) { numLevels++; df /= skipMultiplier; } long childPointer = 0; for (int level = 0; level < numLevels; level++) { WriteSkipData(level, skipBuffer[level]); long newChildPointer = skipBuffer[level].GetFilePointer(); if (level != 0) { // store child pointers for all levels except the lowest skipBuffer[level].WriteVInt64(childPointer); } //remember the childPointer for the next level childPointer = newChildPointer; } } /// <summary> /// Writes the buffered skip lists to the given output. /// </summary> /// <param name="output"> The <see cref="IndexOutput"/> the skip lists shall be written to. </param> /// <returns> The pointer the skip list starts. </returns> public virtual long WriteSkip(IndexOutput output) { long skipPointer = output.GetFilePointer(); //System.out.println("skipper.writeSkip fp=" + skipPointer); if (skipBuffer == null || skipBuffer.Length == 0) { return skipPointer; } for (int level = m_numberOfSkipLevels - 1; level > 0; level--) { long length = skipBuffer[level].GetFilePointer(); if (length > 0) { output.WriteVInt64(length); skipBuffer[level].WriteTo(output); } } skipBuffer[0].WriteTo(output); return skipPointer; } } }
/* * 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.Generic; using Spring.Objects.Factory.Config; namespace Spring.Objects.Factory.Support { /// <summary> /// Programmatic means of constructing a <see cref="IObjectDefinition"/> using the builder pattern. Intended primarily /// for use when implementing custom namespace parsers. /// </summary> /// <remarks>Set methods are used instead of properties, so that chaining of methods can be used to create /// 'one-liner'definitions that set multiple properties at one.</remarks> /// <author>Rod Johnson</author> /// <author>Rob Harrop</author> /// <author>Juergen Hoeller</author> /// <author>Mark Pollack (.NET)</author> public class ObjectDefinitionBuilder { private AbstractObjectDefinition objectDefinition; private IObjectDefinitionFactory objectDefinitionFactory; private int constructorArgIndex; /// <summary> /// Initializes a new instance of the <see cref="ObjectDefinitionBuilder"/> class, private /// to force use of factory methods. /// </summary> private ObjectDefinitionBuilder() { } /// <summary> /// Creates a new <see cref="ObjectDefinitionBuilder"/> used to construct a <see cref="Spring.Objects.Factory.Support.GenericObjectDefinition"/>. /// </summary> public static ObjectDefinitionBuilder GenericObjectDefinition() { ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder(); builder.objectDefinition = new GenericObjectDefinition(); return builder; } /// <summary> /// Creates a new <see cref="ObjectDefinitionBuilder"/> used to construct a <see cref="Spring.Objects.Factory.Support.GenericObjectDefinition"/>. /// </summary> /// <param name="objectType">the <see cref="Type"/> of the object that the definition is being created for</param> public static ObjectDefinitionBuilder GenericObjectDefinition(Type objectType) { ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder(); builder.objectDefinition = new GenericObjectDefinition(); builder.objectDefinition.ObjectType = objectType; return builder; } /// <summary> /// Creates a new <see cref="ObjectDefinitionBuilder"/> used to construct a <see cref="Spring.Objects.Factory.Support.GenericObjectDefinition"/>. /// </summary> /// <param name="objectTypeName">the name of the <see cref="Type"/> of the object that the definition is being created for</param> public static ObjectDefinitionBuilder GenericObjectDefinition(string objectTypeName) { ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder(); builder.objectDefinition = new GenericObjectDefinition(); builder.objectDefinition.ObjectTypeName = objectTypeName; return builder; } /// <summary> /// Create a new <code>ObjectDefinitionBuilder</code> used to construct a root object definition. /// </summary> /// <param name="objectDefinitionFactory">The object definition factory.</param> /// <param name="objectTypeName">The type name of the object.</param> /// <returns>A new <code>ObjectDefinitionBuilder</code> instance.</returns> public static ObjectDefinitionBuilder RootObjectDefinition(IObjectDefinitionFactory objectDefinitionFactory, string objectTypeName) { return RootObjectDefinition(objectDefinitionFactory, objectTypeName, null); } /// <summary> /// Create a new <code>ObjectDefinitionBuilder</code> used to construct a root object definition. /// </summary> /// <param name="objectDefinitionFactory">The object definition factory.</param> /// <param name="objectTypeName">Name of the object type.</param> /// <param name="factoryMethodName">Name of the factory method.</param> /// <returns>A new <code>ObjectDefinitionBuilder</code> instance.</returns> public static ObjectDefinitionBuilder RootObjectDefinition(IObjectDefinitionFactory objectDefinitionFactory, string objectTypeName, string factoryMethodName) { ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder(); builder.objectDefinitionFactory = objectDefinitionFactory; // Pass in null for parent name and also AppDomain to force object definition to be register by name and not type. builder.objectDefinition = objectDefinitionFactory.CreateObjectDefinition(objectTypeName, null, null); builder.objectDefinition.FactoryMethodName = factoryMethodName; return builder; } /// <summary> /// Create a new <code>ObjectDefinitionBuilder</code> used to construct a root object definition. /// </summary> /// <param name="objectDefinitionFactory">The object definition factory.</param> /// <param name="objectType">Type of the object.</param> /// <returns>A new <code>ObjectDefinitionBuilder</code> instance.</returns> public static ObjectDefinitionBuilder RootObjectDefinition(IObjectDefinitionFactory objectDefinitionFactory, Type objectType) { return RootObjectDefinition(objectDefinitionFactory, objectType, null); } /// <summary> /// Create a new <code>ObjectDefinitionBuilder</code> used to construct a root object definition. /// </summary> /// <param name="objectDefinitionFactory">The object definition factory.</param> /// <param name="objectType">Type of the object.</param> /// <param name="factoryMethodName">Name of the factory method.</param> /// <returns>A new <code>ObjectDefinitionBuilder</code> instance.</returns> public static ObjectDefinitionBuilder RootObjectDefinition(IObjectDefinitionFactory objectDefinitionFactory, Type objectType, string factoryMethodName) { ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder(); builder.objectDefinitionFactory = objectDefinitionFactory; builder.objectDefinition = objectDefinitionFactory.CreateObjectDefinition(objectType.FullName, null, AppDomain.CurrentDomain); builder.objectDefinition.ObjectType = objectType; builder.objectDefinition.FactoryMethodName = factoryMethodName; return builder; } /// <summary> /// Create a new <code>ObjectDefinitionBuilder</code> used to construct a child object definition.. /// </summary> /// <param name="objectDefinitionFactory">The object definition factory.</param> /// <param name="parentObjectName">Name of the parent object.</param> /// <returns></returns> public static ObjectDefinitionBuilder ChildObjectDefinition(IObjectDefinitionFactory objectDefinitionFactory, string parentObjectName) { ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder(); builder.objectDefinitionFactory = objectDefinitionFactory; builder.objectDefinition = objectDefinitionFactory.CreateObjectDefinition(null, parentObjectName, AppDomain.CurrentDomain); return builder; } /// <summary> /// Gets the current object definition in its raw (unvalidated) form. /// </summary> /// <value>The raw object definition.</value> public AbstractObjectDefinition RawObjectDefinition { get { return objectDefinition; } } /// <summary> /// Validate and gets the object definition. /// </summary> /// <value>The object definition.</value> public AbstractObjectDefinition ObjectDefinition { get { objectDefinition.Validate(); return objectDefinition; } } //TODO add expression support. /// <summary> /// Adds the property value under the given name. /// </summary> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns> public ObjectDefinitionBuilder AddPropertyValue(string name, object value) { objectDefinition.PropertyValues.Add(new PropertyValue(name, value)); return this; } /// <summary> /// Adds a reference to the specified object name under the property specified. /// </summary> /// <param name="name">The name.</param> /// <param name="objectName">Name of the object.</param> /// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns> public ObjectDefinitionBuilder AddPropertyReference(string name, string objectName) { objectDefinition.PropertyValues.Add(new PropertyValue(name, new RuntimeObjectReference(objectName))); return this; } /// <summary> /// Adds an index constructor arg value. The current index is tracked internally and all addtions are /// at the present point /// </summary> /// <param name="value">The constructor arg value.</param> /// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns> public ObjectDefinitionBuilder AddConstructorArg(object value) { objectDefinition.ConstructorArgumentValues.AddIndexedArgumentValue(constructorArgIndex++,value); return this; } /// <summary> /// Adds a reference to the named object as a constructor argument. /// </summary> /// <param name="objectName">Name of the object.</param> /// <returns></returns> public ObjectDefinitionBuilder AddConstructorArgReference(string objectName) { return AddConstructorArg(new RuntimeObjectReference(objectName)); } /// <summary> /// Sets the name of the factory method to use for this definition. /// </summary> /// <param name="factoryMethod">The factory method.</param> /// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns> public ObjectDefinitionBuilder SetFactoryMethod(string factoryMethod) { objectDefinition.FactoryMethodName = factoryMethod; return this; } /// <summary> /// Sets the name of the factory object to use for this definition. /// </summary> /// <param name="factoryObject">The factory object.</param> /// <param name="factoryMethod">The factory method.</param> /// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns> public ObjectDefinitionBuilder SetFactoryObject(string factoryObject, string factoryMethod) { objectDefinition.FactoryObjectName = factoryObject; objectDefinition.FactoryMethodName = factoryMethod; return this; } /// <summary> /// Sets whether or not this definition describes a singleton object. /// </summary> /// <param name="singleton">if set to <c>true</c> [singleton].</param> /// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns> public ObjectDefinitionBuilder SetSingleton(bool singleton) { objectDefinition.IsSingleton = singleton; return this; } /// <summary> /// Sets whether objects or not this definition is abstract. /// </summary> /// <param name="flag">if set to <c>true</c> [flag].</param> /// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns> public ObjectDefinitionBuilder SetAbstract(bool flag) { objectDefinition.IsAbstract = flag; return this; } /// <summary> /// Sets whether objects for this definition should be lazily initialized or not. /// </summary> /// <param name="lazy">if set to <c>true</c> [lazy].</param> /// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns> public ObjectDefinitionBuilder SetLazyInit(bool lazy) { objectDefinition.IsLazyInit = lazy; return this; } /// <summary> /// Sets the autowire mode for this definition. /// </summary> /// <param name="autowireMode">The autowire mode.</param> /// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns> public ObjectDefinitionBuilder SetAutowireMode(AutoWiringMode autowireMode) { objectDefinition.AutowireMode = autowireMode; return this; } /// <summary> /// Sets the autowire candidate value for this definition. /// </summary> /// <param name="autowireCandidate">The autowire candidate value</param> /// <returns></returns> public ObjectDefinitionBuilder SetAutowireCandidate(bool autowireCandidate) { objectDefinition.IsAutowireCandidate = autowireCandidate; return this; } /// <summary> /// Sets the primary value for this definition. /// </summary> /// <param name="primary">If object is primary</param> /// <returns></returns> public ObjectDefinitionBuilder SetPrimary(bool primary) { objectDefinition.IsPrimary = primary; return this; } /// <summary> /// Sets the dependency check mode for this definition. /// </summary> /// <param name="dependencyCheck">The dependency check.</param> /// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns> public ObjectDefinitionBuilder SetDependencyCheck(DependencyCheckingMode dependencyCheck) { objectDefinition.DependencyCheck = dependencyCheck; return this; } /// <summary> /// Sets the name of the destroy method for this definition. /// </summary> /// <param name="methodName">Name of the method.</param> /// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns> public ObjectDefinitionBuilder SetDestroyMethodName(string methodName) { objectDefinition.DestroyMethodName = methodName; return this; } /// <summary> /// Sets the name of the init method for this definition. /// </summary> /// <param name="methodName">Name of the method.</param> /// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns> public ObjectDefinitionBuilder SetInitMethodName(string methodName) { objectDefinition.InitMethodName = methodName; return this; } /// <summary> /// Sets the resource description for this definition. /// </summary> /// <param name="resourceDescription">The resource description.</param> /// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns> public ObjectDefinitionBuilder SetResourceDescription(string resourceDescription) { objectDefinition.ResourceDescription = resourceDescription; return this; } /// <summary> /// Adds the specified object name to the list of objects that this definition depends on. /// </summary> /// <param name="objectName">Name of the object.</param> /// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns> public ObjectDefinitionBuilder AddDependsOn(string objectName) { if (objectDefinition.DependsOn == null) { objectDefinition.DependsOn = new[] {objectName}; } else { var list = new List<string>(objectDefinition.DependsOn.Count + 1); list.AddRange(objectDefinition.DependsOn); list.Add(objectName); objectDefinition.DependsOn = list; } 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.Collections.Generic; using System.Linq; using System.Net.Security; using System.Net.Test.Common; using System.Runtime.InteropServices; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Xunit; namespace System.Net.Http.Functional.Tests { using Configuration = System.Net.Test.Common.Configuration; [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework throws PNSE for ServerCertificateCustomValidationCallback")] public partial class HttpClientHandler_ServerCertificates_Test : HttpClientTestBase { private static bool ClientSupportsDHECipherSuites => (!PlatformDetection.IsWindows || PlatformDetection.IsWindows10Version1607OrGreater); private bool BackendSupportsCustomCertificateHandlingAndClientSupportsDHECipherSuites => (BackendSupportsCustomCertificateHandling && ClientSupportsDHECipherSuites); [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.Uap)] public void Ctor_ExpectedDefaultPropertyValues_UapPlatform() { using (HttpClientHandler handler = CreateHttpClientHandler()) { Assert.Null(handler.ServerCertificateCustomValidationCallback); Assert.True(handler.CheckCertificateRevocationList); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] public void Ctor_ExpectedDefaultValues_NotUapPlatform() { using (HttpClientHandler handler = CreateHttpClientHandler()) { Assert.Null(handler.ServerCertificateCustomValidationCallback); Assert.False(handler.CheckCertificateRevocationList); } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task NoCallback_ValidCertificate_SuccessAndExpectedPropertyBehavior() { HttpClientHandler handler = CreateHttpClientHandler(); using (var client = new HttpClient(handler)) { using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.SecureRemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } Assert.Throws<InvalidOperationException>(() => handler.ServerCertificateCustomValidationCallback = null); Assert.Throws<InvalidOperationException>(() => handler.CheckCertificateRevocationList = false); } } [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP won't send requests through a custom proxy")] [OuterLoop] // TODO: Issue #11345 [Fact] public async Task UseCallback_HaveNoCredsAndUseAuthenticatedCustomProxyAndPostToSecureServer_ProxyAuthenticationRequiredStatusCode() { if (!BackendSupportsCustomCertificateHandling) { return; } if (UseManagedHandler) { return; // TODO #23136: SSL proxy tunneling not yet implemented in ManagedHandler } int port; Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync( out port, requireAuth: true, expectCreds: false); Uri proxyUrl = new Uri($"http://localhost:{port}"); HttpClientHandler handler = CreateHttpClientHandler(); handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, null); handler.ServerCertificateCustomValidationCallback = delegate { return true; }; using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> responseTask = client.PostAsync( Configuration.Http.SecureRemoteEchoServer, new StringContent("This is a test")); await TestHelper.WhenAllCompletedOrAnyFailed(proxyTask, responseTask); using (responseTask.Result) { Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, responseTask.Result.StatusCode); } } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task UseCallback_NotSecureConnection_CallbackNotCalled() { if (!BackendSupportsCustomCertificateHandling) { Console.WriteLine($"Skipping {nameof(UseCallback_NotSecureConnection_CallbackNotCalled)}()"); return; } HttpClientHandler handler = CreateHttpClientHandler(); using (var client = new HttpClient(handler)) { bool callbackCalled = false; handler.ServerCertificateCustomValidationCallback = delegate { callbackCalled = true; return true; }; using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } Assert.False(callbackCalled); } } public static IEnumerable<object[]> UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls() { foreach (bool checkRevocation in new[] { true, false }) { yield return new object[] { Configuration.Http.SecureRemoteEchoServer, checkRevocation }; yield return new object[] { Configuration.Http.RedirectUriForDestinationUri( secure:true, statusCode:302, destinationUri:Configuration.Http.SecureRemoteEchoServer, hops:1), checkRevocation }; } } [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls))] public async Task UseCallback_ValidCertificate_ExpectedValuesDuringCallback(Uri url, bool checkRevocation) { if (!BackendSupportsCustomCertificateHandling) { Console.WriteLine($"Skipping {nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback)}({url}, {checkRevocation})"); return; } HttpClientHandler handler = CreateHttpClientHandler(); using (var client = new HttpClient(handler)) { bool callbackCalled = false; handler.CheckCertificateRevocationList = checkRevocation; handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => { callbackCalled = true; Assert.NotNull(request); X509ChainStatusFlags flags = chain.ChainStatus.Aggregate(X509ChainStatusFlags.NoError, (cur, status) => cur | status.Status); bool ignoreErrors = // https://github.com/dotnet/corefx/issues/21922#issuecomment-315555237 RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && checkRevocation && errors == SslPolicyErrors.RemoteCertificateChainErrors && flags == X509ChainStatusFlags.RevocationStatusUnknown; Assert.True(ignoreErrors || errors == SslPolicyErrors.None, $"Expected {SslPolicyErrors.None}, got {errors} with chain status {flags}"); Assert.True(chain.ChainElements.Count > 0); Assert.NotEmpty(cert.Subject); // UWP always uses CheckCertificateRevocationList=true regardless of setting the property and // the getter always returns true. So, for this next Assert, it is better to get the property // value back from the handler instead of using the parameter value of the test. Assert.Equal( handler.CheckCertificateRevocationList ? X509RevocationMode.Online : X509RevocationMode.NoCheck, chain.ChainPolicy.RevocationMode); return true; }; using (HttpResponseMessage response = await client.GetAsync(url)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } Assert.True(callbackCalled); } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task UseCallback_CallbackReturnsFailure_ThrowsException() { if (!BackendSupportsCustomCertificateHandling) { Console.WriteLine($"Skipping {nameof(UseCallback_CallbackReturnsFailure_ThrowsException)}()"); return; } HttpClientHandler handler = CreateHttpClientHandler(); using (var client = new HttpClient(handler)) { handler.ServerCertificateCustomValidationCallback = delegate { return false; }; await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer)); } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task UseCallback_CallbackThrowsException_ExceptionPropagatesAsBaseException() { if (!BackendSupportsCustomCertificateHandling) { Console.WriteLine($"Skipping {nameof(UseCallback_CallbackThrowsException_ExceptionPropagatesAsBaseException)}()"); return; } HttpClientHandler handler = CreateHttpClientHandler(); using (var client = new HttpClient(handler)) { var e = new DivideByZeroException(); handler.ServerCertificateCustomValidationCallback = delegate { throw e; }; HttpRequestException ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer)); Assert.Same(e, ex.GetBaseException()); } } public static readonly object[][] CertificateValidationServers = { new object[] { Configuration.Http.ExpiredCertRemoteServer }, new object[] { Configuration.Http.SelfSignedCertRemoteServer }, new object[] { Configuration.Http.WrongHostNameCertRemoteServer }, }; [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(ClientSupportsDHECipherSuites))] [MemberData(nameof(CertificateValidationServers))] public async Task NoCallback_BadCertificate_ThrowsException(string url) { using (HttpClient client = CreateHttpClient()) { await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)); } } [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP doesn't allow revocation checking to be turned off")] [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(ClientSupportsDHECipherSuites))] public async Task NoCallback_RevokedCertificate_NoRevocationChecking_Succeeds() { // On macOS (libcurl+darwinssl) we cannot turn revocation off. // But we also can't realistically say that the default value for // CheckCertificateRevocationList throws in the general case. try { using (HttpClient client = CreateHttpClient()) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RevokedCertRemoteServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } catch (HttpRequestException) { if (UseManagedHandler || !ShouldSuppressRevocationException) throw; } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task NoCallback_RevokedCertificate_RevocationChecking_Fails() { if (!BackendSupportsCustomCertificateHandling) { Console.WriteLine($"Skipping {nameof(NoCallback_RevokedCertificate_RevocationChecking_Fails)}()"); return; } HttpClientHandler handler = CreateHttpClientHandler(); handler.CheckCertificateRevocationList = true; using (var client = new HttpClient(handler)) { await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.RevokedCertRemoteServer)); } } public static readonly object[][] CertificateValidationServersAndExpectedPolicies = { new object[] { Configuration.Http.ExpiredCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors }, new object[] { Configuration.Http.SelfSignedCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors }, new object[] { Configuration.Http.WrongHostNameCertRemoteServer , SslPolicyErrors.RemoteCertificateNameMismatch}, }; private async Task UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(string url, bool useManagedHandler, SslPolicyErrors expectedErrors) { if (!BackendSupportsCustomCertificateHandling) { Console.WriteLine($"Skipping {nameof(UseCallback_BadCertificate_ExpectedPolicyErrors)}({url}, {expectedErrors})"); return; } HttpClientHandler handler = CreateHttpClientHandler(useManagedHandler); using (var client = new HttpClient(handler)) { bool callbackCalled = false; handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => { callbackCalled = true; Assert.NotNull(request); Assert.NotNull(cert); Assert.NotNull(chain); if (!useManagedHandler) { // TODO #23137: This test is failing with the managed handler on the exact value of the managed errors, // e.g. reporting "RemoteCertificateNameMismatch, RemoteCertificateChainErrors" when we only expect // "RemoteCertificateChainErrors" Assert.Equal(expectedErrors, errors); } return true; }; using (HttpResponseMessage response = await client.GetAsync(url)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } Assert.True(callbackCalled); } } [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(CertificateValidationServersAndExpectedPolicies))] public async Task UseCallback_BadCertificate_ExpectedPolicyErrors(string url, SslPolicyErrors expectedErrors) { const int SEC_E_BUFFER_TOO_SMALL = unchecked((int)0x80090321); if (!BackendSupportsCustomCertificateHandlingAndClientSupportsDHECipherSuites) { return; } try { if (PlatformDetection.IsUap) { // UAP HTTP stack caches connections per-process. This causes interference when these tests run in // the same process as the other tests. Each test needs to be isolated to its own process. // See dicussion: https://github.com/dotnet/corefx/issues/21945 RemoteInvoke((remoteUrl, remoteExpectedErrors, useManagedHandlerString) => { UseCallback_BadCertificate_ExpectedPolicyErrors_Helper( remoteUrl, bool.Parse(useManagedHandlerString), (SslPolicyErrors)Enum.Parse(typeof(SslPolicyErrors), remoteExpectedErrors)).Wait(); return SuccessExitCode; }, url, expectedErrors.ToString(), UseManagedHandler.ToString()).Dispose(); } else { await UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(url, UseManagedHandler, expectedErrors); } } catch (HttpRequestException e) when (e.InnerException?.GetType().Name == "WinHttpException" && e.InnerException.HResult == SEC_E_BUFFER_TOO_SMALL && !PlatformDetection.IsWindows10Version1607OrGreater) { // Testing on old Windows versions can hit https://github.com/dotnet/corefx/issues/7812 // Ignore SEC_E_BUFFER_TOO_SMALL error on such cases. } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task SSLBackendNotSupported_Callback_ThrowsPlatformNotSupportedException() { if (BackendSupportsCustomCertificateHandling) { return; } HttpClientHandler handler = CreateHttpClientHandler(); handler.ServerCertificateCustomValidationCallback = delegate { return true; }; using (var client = new HttpClient(handler)) { await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer)); } } [OuterLoop] // TODO: Issue #11345 [Fact] // For macOS the "custom handling" means that revocation can't be *disabled*. So this test does not apply. [PlatformSpecific(~TestPlatforms.OSX)] public async Task SSLBackendNotSupported_Revocation_ThrowsPlatformNotSupportedException() { if (BackendSupportsCustomCertificateHandling) { return; } HttpClientHandler handler = CreateHttpClientHandler(); handler.CheckCertificateRevocationList = true; using (var client = new HttpClient(handler)) { await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer)); } } [OuterLoop] // TODO: Issue #11345 [PlatformSpecific(TestPlatforms.Windows)] // CopyToAsync(Stream, TransportContext) isn't used on unix [Fact] public async Task PostAsync_Post_ChannelBinding_ConfiguredCorrectly() { var content = new ChannelBindingAwareContent("Test contest"); using (HttpClient client = CreateHttpClient()) using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.SecureRemoteEchoServer, content)) { // Validate status. Assert.Equal(HttpStatusCode.OK, response.StatusCode); // Validate the ChannelBinding object exists. ChannelBinding channelBinding = content.ChannelBinding; if (PlatformDetection.IsUap) { // UAP currently doesn't expose channel binding information. Assert.Null(channelBinding); } else { Assert.NotNull(channelBinding); // Validate the ChannelBinding's validity. if (BackendSupportsCustomCertificateHandling) { Assert.False(channelBinding.IsInvalid, "Expected valid binding"); Assert.NotEqual(IntPtr.Zero, channelBinding.DangerousGetHandle()); // Validate the ChannelBinding's description. string channelBindingDescription = channelBinding.ToString(); Assert.NotNull(channelBindingDescription); Assert.NotEmpty(channelBindingDescription); Assert.True((channelBindingDescription.Length + 1) % 3 == 0, $"Unexpected length {channelBindingDescription.Length}"); for (int i = 0; i < channelBindingDescription.Length; i++) { char c = channelBindingDescription[i]; if (i % 3 == 2) { Assert.Equal(' ', c); } else { Assert.True((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'), $"Expected hex, got {c}"); } } } else { // Backend doesn't support getting the details to create the CBT. Assert.True(channelBinding.IsInvalid, "Expected invalid binding"); Assert.Equal(IntPtr.Zero, channelBinding.DangerousGetHandle()); Assert.Null(channelBinding.ToString()); } } } } } }
namespace RatioMaster_source { partial class AboutForm { /// <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.lblProgramName = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.linkGitHub = new System.Windows.Forms.LinkLabel(); this.lblGitHubAdress = new System.Windows.Forms.Label(); this.linkWebSite = new System.Windows.Forms.LinkLabel(); this.lblWebSite = new System.Windows.Forms.Label(); this.linkEMail = new System.Windows.Forms.LinkLabel(); this.linkAuthorWebSite = new System.Windows.Forms.LinkLabel(); this.lblInfoEMail = new System.Windows.Forms.Label(); this.lblInfoAuthorWebSite = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // lblProgramName // this.lblProgramName.AutoSize = true; this.lblProgramName.Font = new System.Drawing.Font("Microsoft Sans Serif", 28F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.lblProgramName.Location = new System.Drawing.Point(71, 27); this.lblProgramName.Name = "lblProgramName"; this.lblProgramName.Size = new System.Drawing.Size(327, 44); this.lblProgramName.TabIndex = 0; this.lblProgramName.Text = "RatioMaster.NET"; // // groupBox1 // this.groupBox1.Controls.Add(this.linkGitHub); this.groupBox1.Controls.Add(this.lblGitHubAdress); this.groupBox1.Controls.Add(this.linkWebSite); this.groupBox1.Controls.Add(this.lblWebSite); this.groupBox1.Controls.Add(this.linkEMail); this.groupBox1.Controls.Add(this.linkAuthorWebSite); this.groupBox1.Controls.Add(this.lblInfoEMail); this.groupBox1.Controls.Add(this.lblInfoAuthorWebSite); this.groupBox1.Location = new System.Drawing.Point(12, 98); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(443, 65); this.groupBox1.TabIndex = 2; this.groupBox1.TabStop = false; this.groupBox1.Text = "Communication"; // // linkGitHub // this.linkGitHub.AutoSize = true; this.linkGitHub.Cursor = System.Windows.Forms.Cursors.Help; this.linkGitHub.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.linkGitHub.Location = new System.Drawing.Point(272, 44); this.linkGitHub.Name = "linkGitHub"; this.linkGitHub.Size = new System.Drawing.Size(104, 13); this.linkGitHub.TabIndex = 5; this.linkGitHub.TabStop = true; this.linkGitHub.Text = "RatioMaster.NET"; this.linkGitHub.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkGitHubPage_LinkClicked); // // lblGitHubAdress // this.lblGitHubAdress.AutoSize = true; this.lblGitHubAdress.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.lblGitHubAdress.Location = new System.Drawing.Point(221, 44); this.lblGitHubAdress.Name = "lblGitHubAdress"; this.lblGitHubAdress.Size = new System.Drawing.Size(50, 13); this.lblGitHubAdress.TabIndex = 4; this.lblGitHubAdress.Text = "GitHub:"; // // linkWebSite // this.linkWebSite.AutoSize = true; this.linkWebSite.Cursor = System.Windows.Forms.Cursors.Help; this.linkWebSite.Location = new System.Drawing.Point(50, 22); this.linkWebSite.Name = "linkWebSite"; this.linkWebSite.Size = new System.Drawing.Size(107, 13); this.linkWebSite.TabIndex = 1; this.linkWebSite.TabStop = true; this.linkWebSite.Text = "http://ratiomaster.net"; this.linkWebSite.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkWebSite_LinkClicked); // // lblWebSite // this.lblWebSite.AutoSize = true; this.lblWebSite.Location = new System.Drawing.Point(6, 22); this.lblWebSite.Name = "lblWebSite"; this.lblWebSite.Size = new System.Drawing.Size(33, 13); this.lblWebSite.TabIndex = 0; this.lblWebSite.Text = "Web:"; // // linkEMail // this.linkEMail.AutoSize = true; this.linkEMail.Cursor = System.Windows.Forms.Cursors.Help; this.linkEMail.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.linkEMail.Location = new System.Drawing.Point(50, 44); this.linkEMail.Name = "linkEMail"; this.linkEMail.Size = new System.Drawing.Size(110, 13); this.linkEMail.TabIndex = 7; this.linkEMail.TabStop = true; this.linkEMail.Text = "[email protected]"; this.linkEMail.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkEMail_LinkClicked); // // linkAuthorWebSite // this.linkAuthorWebSite.AutoSize = true; this.linkAuthorWebSite.Cursor = System.Windows.Forms.Cursors.Help; this.linkAuthorWebSite.Location = new System.Drawing.Point(272, 22); this.linkAuthorWebSite.Name = "linkAuthorWebSite"; this.linkAuthorWebSite.Size = new System.Drawing.Size(79, 13); this.linkAuthorWebSite.TabIndex = 3; this.linkAuthorWebSite.TabStop = true; this.linkAuthorWebSite.Text = "http://nikolay.it"; this.linkAuthorWebSite.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkAuthorWebSite_LinkClicked); // // lblInfoEMail // this.lblInfoEMail.AutoSize = true; this.lblInfoEMail.Location = new System.Drawing.Point(6, 44); this.lblInfoEMail.Name = "lblInfoEMail"; this.lblInfoEMail.Size = new System.Drawing.Size(38, 13); this.lblInfoEMail.TabIndex = 6; this.lblInfoEMail.Text = "E-mail:"; // // lblInfoAuthorWebSite // this.lblInfoAuthorWebSite.AutoSize = true; this.lblInfoAuthorWebSite.Location = new System.Drawing.Point(221, 22); this.lblInfoAuthorWebSite.Name = "lblInfoAuthorWebSite"; this.lblInfoAuthorWebSite.Size = new System.Drawing.Size(41, 13); this.lblInfoAuthorWebSite.TabIndex = 2; this.lblInfoAuthorWebSite.Text = "Author:"; // // button1 // this.button1.Cursor = System.Windows.Forms.Cursors.Hand; this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.button1.Location = new System.Drawing.Point(12, 169); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(443, 27); this.button1.TabIndex = 5; this.button1.Text = "OK"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // AboutForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(467, 209); this.Controls.Add(this.button1); this.Controls.Add(this.groupBox1); this.Controls.Add(this.lblProgramName); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Name = "AboutForm"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "About RatioMaster.NET"; this.Load += new System.EventHandler(this.AboutForm_Load); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label lblProgramName; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.LinkLabel linkGitHub; private System.Windows.Forms.Label lblGitHubAdress; private System.Windows.Forms.LinkLabel linkWebSite; private System.Windows.Forms.Label lblWebSite; private System.Windows.Forms.LinkLabel linkEMail; private System.Windows.Forms.LinkLabel linkAuthorWebSite; private System.Windows.Forms.Label lblInfoEMail; private System.Windows.Forms.Label lblInfoAuthorWebSite; private System.Windows.Forms.Button button1; } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using NodaTime; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Orders; using QuantConnect.Packets; using QuantConnect.Securities; using QuantConnect.Util; namespace QuantConnect.Brokerages.Oanda { /// <summary> /// Oanda REST API base class /// </summary> public abstract class OandaRestApiBase : Brokerage, IDataQueueHandler { private static readonly TimeSpan SubscribeDelay = TimeSpan.FromMilliseconds(250); private readonly ManualResetEvent _refreshEvent = new ManualResetEvent(false); private readonly CancellationTokenSource _streamingCancellationTokenSource = new CancellationTokenSource(); private bool _isConnected; /// <summary> /// This lock is used to sync 'PlaceOrder' and callback 'OnTransactionDataReceived' /// </summary> protected readonly object Locker = new object(); /// <summary> /// This container is used to keep pending to be filled market orders, so when the callback comes in we send the filled event /// </summary> protected readonly ConcurrentDictionary<int, OrderStatus> PendingFilledMarketOrders = new ConcurrentDictionary<int, OrderStatus>(); /// <summary> /// The connection handler for pricing /// </summary> protected readonly IConnectionHandler PricingConnectionHandler; /// <summary> /// The connection handler for transactions /// </summary> protected readonly IConnectionHandler TransactionsConnectionHandler; /// <summary> /// The list of currently subscribed symbols /// </summary> protected IEnumerable<Symbol> SubscribedSymbols => _subscriptionManager.GetSubscribedSymbols(); /// <summary> /// The symbol mapper /// </summary> protected OandaSymbolMapper SymbolMapper; /// <summary> /// The order provider /// </summary> protected IOrderProvider OrderProvider; /// <summary> /// The security provider /// </summary> protected ISecurityProvider SecurityProvider; /// <summary> /// The data aggregator /// </summary> protected IDataAggregator Aggregator; /// <summary> /// Data Queue Handler subscription manager /// </summary> private readonly EventBasedDataQueueHandlerSubscriptionManager _subscriptionManager; /// <summary> /// The Oanda enviroment /// </summary> protected Environment Environment; /// <summary> /// The Oanda access token /// </summary> protected string AccessToken; /// <summary> /// The Oanda account ID /// </summary> protected string AccountId; /// <summary> /// The Oanda agent string /// </summary> protected string Agent; /// <summary> /// The HTTP header key for Oanda agent /// </summary> protected const string OandaAgentKey = "OANDA-Agent"; /// <summary> /// The default HTTP header value for Oanda agent /// </summary> public const string OandaAgentDefaultValue = "QuantConnect/0.0.0 (LEAN)"; /// <summary> /// Initializes a new instance of the <see cref="OandaRestApiBase"/> class. /// </summary> /// <param name="symbolMapper">The symbol mapper.</param> /// <param name="orderProvider">The order provider.</param> /// <param name="securityProvider">The holdings provider.</param> /// <param name="aggregator">Consolidate ticks</param> /// <param name="environment">The Oanda environment (Trade or Practice)</param> /// <param name="accessToken">The Oanda access token (can be the user's personal access token or the access token obtained with OAuth by QC on behalf of the user)</param> /// <param name="accountId">The account identifier.</param> /// <param name="agent">The Oanda agent string</param> protected OandaRestApiBase(OandaSymbolMapper symbolMapper, IOrderProvider orderProvider, ISecurityProvider securityProvider, IDataAggregator aggregator, Environment environment, string accessToken, string accountId, string agent) : base("Oanda Brokerage") { SymbolMapper = symbolMapper; OrderProvider = orderProvider; SecurityProvider = securityProvider; Environment = environment; AccessToken = accessToken; AccountId = accountId; Agent = agent; Aggregator = aggregator; _subscriptionManager = new EventBasedDataQueueHandlerSubscriptionManager(); _subscriptionManager.SubscribeImpl += (s, t) => Refresh(); _subscriptionManager.UnsubscribeImpl += (s, t) => Refresh(); PricingConnectionHandler = new DefaultConnectionHandler { MaximumIdleTimeSpan = TimeSpan.FromSeconds(20) }; PricingConnectionHandler.ConnectionLost += OnPricingConnectionLost; PricingConnectionHandler.ConnectionRestored += OnPricingConnectionRestored; PricingConnectionHandler.ReconnectRequested += OnPricingReconnectRequested; PricingConnectionHandler.Initialize(null); TransactionsConnectionHandler = new DefaultConnectionHandler { MaximumIdleTimeSpan = TimeSpan.FromSeconds(20) }; TransactionsConnectionHandler.ConnectionLost += OnTransactionsConnectionLost; TransactionsConnectionHandler.ConnectionRestored += OnTransactionsConnectionRestored; TransactionsConnectionHandler.ReconnectRequested += OnTransactionsReconnectRequested; TransactionsConnectionHandler.Initialize(null); Task.Factory.StartNew( () => { do { _refreshEvent.WaitOne(); Thread.Sleep(SubscribeDelay); if (!_isConnected) { continue; } _refreshEvent.Reset(); var symbolsToSubscribe = SubscribedSymbols; // restart streaming session SubscribeSymbols(symbolsToSubscribe); } while (!_streamingCancellationTokenSource.IsCancellationRequested); }, TaskCreationOptions.LongRunning ); } private void OnPricingConnectionLost(object sender, EventArgs e) { Log.Trace("OnPricingConnectionLost(): pricing connection lost."); OnMessage(BrokerageMessageEvent.Disconnected("Pricing connection with Oanda server lost. " + "This could be because of internet connectivity issues. ")); } private void OnPricingConnectionRestored(object sender, EventArgs e) { Log.Trace("OnPricingConnectionRestored(): pricing connection restored"); OnMessage(BrokerageMessageEvent.Reconnected("Pricing connection with Oanda server restored.")); } private void OnPricingReconnectRequested(object sender, EventArgs e) { Log.Trace("OnPricingReconnectRequested(): resubscribing symbols."); // check if we have a connection GetInstrumentList(); // restore rates session SubscribeSymbols(SubscribedSymbols); Log.Trace("OnPricingReconnectRequested(): symbols resubscribed."); } private void OnTransactionsConnectionLost(object sender, EventArgs e) { Log.Trace("OnTransactionsConnectionLost(): transactions connection lost."); OnMessage(BrokerageMessageEvent.Disconnected("Transactions connection with Oanda server lost. " + "This could be because of internet connectivity issues. ")); } private void OnTransactionsConnectionRestored(object sender, EventArgs e) { Log.Trace("OnTransactionsConnectionRestored(): transactions connection restored"); OnMessage(BrokerageMessageEvent.Reconnected("Transactions connection with Oanda server restored.")); } private void OnTransactionsReconnectRequested(object sender, EventArgs e) { Log.Trace("OnTransactionsReconnectRequested(): restarting transaction stream."); // check if we have a connection GetInstrumentList(); // restore events session StopTransactionStream(); StartTransactionStream(); Log.Trace("OnTransactionsReconnectRequested(): transaction stream restarted."); } /// <summary> /// Dispose of the brokerage instance /// </summary> public override void Dispose() { Aggregator.DisposeSafely(); _refreshEvent.DisposeSafely(); _streamingCancellationTokenSource.Cancel(); PricingConnectionHandler.ConnectionLost -= OnPricingConnectionLost; PricingConnectionHandler.ConnectionRestored -= OnPricingConnectionRestored; PricingConnectionHandler.ReconnectRequested -= OnPricingReconnectRequested; PricingConnectionHandler.Dispose(); TransactionsConnectionHandler.ConnectionLost -= OnTransactionsConnectionLost; TransactionsConnectionHandler.ConnectionRestored -= OnTransactionsConnectionRestored; TransactionsConnectionHandler.ReconnectRequested -= OnTransactionsReconnectRequested; TransactionsConnectionHandler.Dispose(); } /// <summary> /// Returns true if we're currently connected to the broker /// </summary> public override bool IsConnected => _isConnected && !TransactionsConnectionHandler.IsConnectionLost && !PricingConnectionHandler.IsConnectionLost; /// <summary> /// Connects the client to the broker's remote servers /// </summary> public override void Connect() { AccountBaseCurrency = GetAccountBaseCurrency(); // Register to the event session to receive events. StartTransactionStream(); _isConnected = true; TransactionsConnectionHandler.EnableMonitoring(true); } /// <summary> /// Disconnects the client from the broker's remote servers /// </summary> public override void Disconnect() { TransactionsConnectionHandler.EnableMonitoring(false); PricingConnectionHandler.EnableMonitoring(false); StopTransactionStream(); StopPricingStream(); _isConnected = false; } /// <summary> /// Gets the account base currency /// </summary> public abstract string GetAccountBaseCurrency(); /// <summary> /// Gets the list of available tradable instruments/products from Oanda /// </summary> public abstract List<string> GetInstrumentList(); /// <summary> /// Retrieves the current rate for each of a list of instruments /// </summary> /// <param name="instruments">the list of instruments to check</param> /// <returns>Dictionary containing the current quotes for each instrument</returns> public abstract Dictionary<string, Tick> GetRates(List<string> instruments); /// <summary> /// Starts streaming transactions for the active account /// </summary> public abstract void StartTransactionStream(); /// <summary> /// Stops streaming transactions for the active account /// </summary> public abstract void StopTransactionStream(); /// <summary> /// Starts streaming prices for a list of instruments /// </summary> public abstract void StartPricingStream(List<string> instruments); /// <summary> /// Stops streaming prices for all instruments /// </summary> public abstract void StopPricingStream(); /// <summary> /// Downloads a list of TradeBars at the requested resolution /// </summary> /// <param name="symbol">The symbol</param> /// <param name="startTimeUtc">The starting time (UTC)</param> /// <param name="endTimeUtc">The ending time (UTC)</param> /// <param name="resolution">The requested resolution</param> /// <param name="requestedTimeZone">The requested timezone for the data</param> /// <returns>The list of bars</returns> public abstract IEnumerable<TradeBar> DownloadTradeBars(Symbol symbol, DateTime startTimeUtc, DateTime endTimeUtc, Resolution resolution, DateTimeZone requestedTimeZone); /// <summary> /// Downloads a list of QuoteBars at the requested resolution /// </summary> /// <param name="symbol">The symbol</param> /// <param name="startTimeUtc">The starting time (UTC)</param> /// <param name="endTimeUtc">The ending time (UTC)</param> /// <param name="resolution">The requested resolution</param> /// <param name="requestedTimeZone">The requested timezone for the data</param> /// <returns>The list of bars</returns> public abstract IEnumerable<QuoteBar> DownloadQuoteBars(Symbol symbol, DateTime startTimeUtc, DateTime endTimeUtc, Resolution resolution, DateTimeZone requestedTimeZone); /// <summary> /// Subscribe to the specified configuration /// </summary> /// <param name="dataConfig">defines the parameters to subscribe to a data feed</param> /// <param name="newDataAvailableHandler">handler to be fired on new data available</param> /// <returns>The new enumerator for this subscription request</returns> public IEnumerator<BaseData> Subscribe(SubscriptionDataConfig dataConfig, EventHandler newDataAvailableHandler) { if (!CanSubscribe(dataConfig.Symbol)) { return null; } var enumerator = Aggregator.Add(dataConfig, newDataAvailableHandler); _subscriptionManager.Subscribe(dataConfig); return enumerator; } /// <summary> /// Sets the job we're subscribing for /// </summary> /// <param name="job">Job we're subscribing for</param> public void SetJob(LiveNodePacket job) { } /// <summary> /// Removes the specified configuration /// </summary> /// <param name="dataConfig">Subscription config to be removed</param> public void Unsubscribe(SubscriptionDataConfig dataConfig) { _subscriptionManager.Unsubscribe(dataConfig); Aggregator.Remove(dataConfig); } /// <summary> /// Returns true if this brokerage supports the specified symbol /// </summary> private bool CanSubscribe(Symbol symbol) { // ignore unsupported security types if (symbol.ID.SecurityType != SecurityType.Forex && symbol.ID.SecurityType != SecurityType.Cfd) return false; // ignore universe symbols return !symbol.Value.Contains("-UNIVERSE-") && symbol.ID.Market == Market.Oanda; } private bool Refresh() { _refreshEvent.Set(); return true; } /// <summary> /// Subscribes to the requested symbols (using a single streaming session) /// </summary> /// <param name="symbolsToSubscribe">The list of symbols to subscribe</param> protected void SubscribeSymbols(IEnumerable<Symbol> symbolsToSubscribe) { var instruments = symbolsToSubscribe .Select(symbol => SymbolMapper.GetBrokerageSymbol(symbol)) .ToList(); PricingConnectionHandler.EnableMonitoring(false); StopPricingStream(); if (instruments.Count > 0) { StartPricingStream(instruments); PricingConnectionHandler.EnableMonitoring(true); } } /// <summary> /// Emit ticks /// </summary> /// <param name="tick">The new tick to emit</param> protected void EmitTick(Tick tick) { Aggregator.Update(tick); } } }
using System; using Tweetinvi.Exceptions; using Tweetinvi.Parameters; namespace Tweetinvi.Core.Client.Validators { public interface ITwitterListsClientParametersValidator { void Validate(ICreateListParameters parameters); void Validate(IGetListParameters parameters); void Validate(IGetListsSubscribedByUserParameters parameters); void Validate(IUpdateListParameters parameters); void Validate(IDestroyListParameters parameters); void Validate(IGetListsOwnedByAccountParameters parameters); void Validate(IGetListsOwnedByUserParameters parameters); void Validate(IGetTweetsFromListParameters parameters); // MEMBERS void Validate(IAddMemberToListParameters parameters); void Validate(IAddMembersToListParameters parameters); void Validate(IGetUserListMembershipsParameters parameters); void Validate(IGetMembersOfListParameters parameters); void Validate(ICheckIfUserIsMemberOfListParameters parameters); void Validate(IRemoveMemberFromListParameters parameters); void Validate(IRemoveMembersFromListParameters parameters); void Validate(IGetAccountListMembershipsParameters parameters); // SUBSCRIBERS void Validate(ISubscribeToListParameters parameters); void Validate(IUnsubscribeFromListParameters parameters); void Validate(IGetListSubscribersParameters parameters); void Validate(IGetAccountListSubscriptionsParameters parameters); void Validate(IGetUserListSubscriptionsParameters parameters); void Validate(ICheckIfUserIsSubscriberOfListParameters parameters); } public class TwitterListsClientParametersValidator : ITwitterListsClientParametersValidator { private readonly ITwitterClient _client; private readonly ITwitterListsClientRequiredParametersValidator _twitterListsClientRequiredParametersValidator; public TwitterListsClientParametersValidator( ITwitterClient client, ITwitterListsClientRequiredParametersValidator twitterListsClientRequiredParametersValidator) { _client = client; _twitterListsClientRequiredParametersValidator = twitterListsClientRequiredParametersValidator; } private TwitterLimits Limits => _client.Config.Limits; public void Validate(ICreateListParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); var maxNameSize = Limits.LISTS_CREATE_NAME_MAX_SIZE; if (parameters.Name.Length > maxNameSize) { throw new TwitterArgumentLimitException($"{nameof(parameters.Name)}", maxNameSize, nameof(Limits.LISTS_CREATE_NAME_MAX_SIZE), "characters"); } } public void Validate(IGetListParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); } public void Validate(IGetListsSubscribedByUserParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); } public void Validate(IUpdateListParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); } public void Validate(IDestroyListParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); } public void Validate(IGetListsOwnedByAccountParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); var maxPageSize = Limits.LISTS_GET_USER_OWNED_LISTS_MAX_SIZE; if (parameters.PageSize > maxPageSize) { throw new TwitterArgumentLimitException($"{nameof(parameters.PageSize)}", maxPageSize, nameof(Limits.LISTS_GET_USER_OWNED_LISTS_MAX_SIZE), "page size"); } } public void Validate(IGetListsOwnedByUserParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); var maxPageSize = Limits.LISTS_GET_USER_OWNED_LISTS_MAX_SIZE; if (parameters.PageSize > maxPageSize) { throw new TwitterArgumentLimitException($"{nameof(parameters.PageSize)}", maxPageSize, nameof(Limits.LISTS_GET_USER_OWNED_LISTS_MAX_SIZE), "page size"); } } public void Validate(IGetTweetsFromListParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); var maxPageSize = Limits.LISTS_GET_TWEETS_MAX_PAGE_SIZE; if (parameters.PageSize > maxPageSize) { throw new TwitterArgumentLimitException($"{nameof(parameters.PageSize)}", maxPageSize, nameof(Limits.LISTS_GET_TWEETS_MAX_PAGE_SIZE), "page size"); } } public void Validate(IAddMemberToListParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); } public void Validate(IAddMembersToListParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); if (parameters.Users.Count == 0) { throw new ArgumentOutOfRangeException($"{nameof(parameters.Users)}", "You must have at least 1 user"); } var maxUsers = Limits.LISTS_ADD_MEMBERS_MAX_USERS; if (parameters.Users.Count > maxUsers) { throw new TwitterArgumentLimitException($"{nameof(parameters.Users)}", maxUsers, nameof(Limits.LISTS_ADD_MEMBERS_MAX_USERS), "users"); } } public void Validate(IGetUserListMembershipsParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); var maxPageSize = Limits.LISTS_GET_USER_MEMBERSHIPS_MAX_PAGE_SIZE; if (parameters.PageSize > maxPageSize) { throw new TwitterArgumentLimitException($"{nameof(parameters.PageSize)}", maxPageSize, nameof(Limits.LISTS_GET_USER_MEMBERSHIPS_MAX_PAGE_SIZE), "page size"); } } public void Validate(IGetMembersOfListParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); var maxPageSize = Limits.LISTS_GET_MEMBERS_MAX_PAGE_SIZE; if (parameters.PageSize > maxPageSize) { throw new TwitterArgumentLimitException($"{nameof(parameters.PageSize)}", maxPageSize, nameof(Limits.LISTS_GET_MEMBERS_MAX_PAGE_SIZE), "page size"); } } public void Validate(ICheckIfUserIsMemberOfListParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); } public void Validate(IRemoveMemberFromListParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); } public void Validate(IRemoveMembersFromListParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); if (parameters.Users.Count == 0) { throw new ArgumentOutOfRangeException($"{nameof(parameters.Users)}", "You must have at least 1 user"); } var maxUsers = Limits.LISTS_REMOVE_MEMBERS_MAX_USERS; if (parameters.Users.Count > maxUsers) { throw new TwitterArgumentLimitException($"{nameof(parameters.Users)}", maxUsers, nameof(Limits.LISTS_REMOVE_MEMBERS_MAX_USERS), "users"); } } public void Validate(IGetAccountListMembershipsParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); } public void Validate(ISubscribeToListParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); } public void Validate(IUnsubscribeFromListParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); } public void Validate(IGetListSubscribersParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); var maxPageSize = Limits.LISTS_GET_SUBSCRIBERS_MAX_PAGE_SIZE; if (parameters.PageSize > maxPageSize) { throw new TwitterArgumentLimitException($"{nameof(parameters.PageSize)}", maxPageSize, nameof(Limits.LISTS_GET_SUBSCRIBERS_MAX_PAGE_SIZE), "page size"); } } public void Validate(IGetAccountListSubscriptionsParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); var maxPageSize = Limits.LISTS_GET_USER_SUBSCRIPTIONS_MAX_PAGE_SIZE; if (parameters.PageSize > maxPageSize) { throw new TwitterArgumentLimitException($"{nameof(parameters.PageSize)}", maxPageSize, nameof(Limits.LISTS_GET_USER_SUBSCRIPTIONS_MAX_PAGE_SIZE), "page size"); } } public void Validate(IGetUserListSubscriptionsParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); var maxPageSize = Limits.LISTS_GET_USER_SUBSCRIPTIONS_MAX_PAGE_SIZE; if (parameters.PageSize > maxPageSize) { throw new TwitterArgumentLimitException($"{nameof(parameters.PageSize)}", maxPageSize, nameof(Limits.LISTS_GET_USER_SUBSCRIPTIONS_MAX_PAGE_SIZE), "page size"); } } public void Validate(ICheckIfUserIsSubscriberOfListParameters parameters) { _twitterListsClientRequiredParametersValidator.Validate(parameters); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Reflection.Metadata.Decoding; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.Metadata { public struct MethodDefinition { private readonly MetadataReader _reader; // Workaround: JIT doesn't generate good code for nested structures, so use RowId. private readonly uint _treatmentAndRowId; internal MethodDefinition(MetadataReader reader, uint treatmentAndRowId) { Debug.Assert(reader != null); Debug.Assert(treatmentAndRowId != 0); _reader = reader; _treatmentAndRowId = treatmentAndRowId; } private int RowId { get { return (int)(_treatmentAndRowId & TokenTypeIds.RIDMask); } } private MethodDefTreatment Treatment { get { return (MethodDefTreatment)(_treatmentAndRowId >> TokenTypeIds.RowIdBitCount); } } private MethodDefinitionHandle Handle { get { return MethodDefinitionHandle.FromRowId(RowId); } } public StringHandle Name { get { if (Treatment == 0) { return _reader.MethodDefTable.GetName(Handle); } return GetProjectedName(); } } public BlobHandle Signature { get { if (Treatment == 0) { return _reader.MethodDefTable.GetSignature(Handle); } return GetProjectedSignature(); } } public MethodSignature<TType> DecodeSignature<TType>(ISignatureTypeProvider<TType> provider, SignatureDecoderOptions options = SignatureDecoderOptions.None) { var decoder = new SignatureDecoder<TType>(provider, _reader, options); var blobReader = _reader.GetBlobReader(Signature); return decoder.DecodeMethodSignature(ref blobReader); } public int RelativeVirtualAddress { get { if (Treatment == 0) { return _reader.MethodDefTable.GetRva(Handle); } return GetProjectedRelativeVirtualAddress(); } } public MethodAttributes Attributes { get { if (Treatment == 0) { return _reader.MethodDefTable.GetFlags(Handle); } return GetProjectedFlags(); } } public MethodImplAttributes ImplAttributes { get { if (Treatment == 0) { return _reader.MethodDefTable.GetImplFlags(Handle); } return GetProjectedImplFlags(); } } public TypeDefinitionHandle GetDeclaringType() { return _reader.GetDeclaringType(Handle); } public ParameterHandleCollection GetParameters() { return new ParameterHandleCollection(_reader, Handle); } public GenericParameterHandleCollection GetGenericParameters() { return _reader.GenericParamTable.FindGenericParametersForMethod(Handle); } public MethodImport GetImport() { int implMapRid = _reader.ImplMapTable.FindImplForMethod(Handle); if (implMapRid == 0) { return default(MethodImport); } return _reader.ImplMapTable.GetImport(implMapRid); } public CustomAttributeHandleCollection GetCustomAttributes() { return new CustomAttributeHandleCollection(_reader, Handle); } public DeclarativeSecurityAttributeHandleCollection GetDeclarativeSecurityAttributes() { return new DeclarativeSecurityAttributeHandleCollection(_reader, Handle); } #region Projections private StringHandle GetProjectedName() { if ((Treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.DisposeMethod) { return StringHandle.FromVirtualIndex(StringHandle.VirtualIndex.Dispose); } return _reader.MethodDefTable.GetName(Handle); } private MethodAttributes GetProjectedFlags() { MethodAttributes flags = _reader.MethodDefTable.GetFlags(Handle); MethodDefTreatment treatment = Treatment; if ((treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.HiddenInterfaceImplementation) { flags = (flags & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Private; } if ((treatment & MethodDefTreatment.MarkAbstractFlag) != 0) { flags |= MethodAttributes.Abstract; } if ((treatment & MethodDefTreatment.MarkPublicFlag) != 0) { flags = (flags & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Public; } return flags | MethodAttributes.HideBySig; } private MethodImplAttributes GetProjectedImplFlags() { MethodImplAttributes flags = _reader.MethodDefTable.GetImplFlags(Handle); switch (Treatment & MethodDefTreatment.KindMask) { case MethodDefTreatment.DelegateMethod: flags |= MethodImplAttributes.Runtime; break; case MethodDefTreatment.DisposeMethod: case MethodDefTreatment.AttributeMethod: case MethodDefTreatment.InterfaceMethod: case MethodDefTreatment.HiddenInterfaceImplementation: case MethodDefTreatment.Other: flags |= MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall; break; } return flags; } private BlobHandle GetProjectedSignature() { return _reader.MethodDefTable.GetSignature(Handle); } private int GetProjectedRelativeVirtualAddress() { return 0; } #endregion } }
// Copyright (c) 2013-2014 Robert Rouhani <[email protected]> and other contributors (see CONTRIBUTORS file). // Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE using System; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using SharpNav; using SharpNav.Geometry; using SharpNav.Pathfinding; using SharpNav.Crowds; using System.Collections.Generic; //Prevents name collision under the Standalone configuration #if STANDALONE using Vector3 = OpenTK.Vector3; using SVector3 = SharpNav.Geometry.Vector3; #elif OPENTK using SVector3 = OpenTK.Vector3; #endif //Doesn't compile if in an unsupported configuration #if STANDALONE || OPENTK namespace SharpNav.Examples { public partial class ExampleWindow { private int levelVbo, levelNormVbo, heightfieldVoxelVbo, heightfieldVoxelIbo, squareVbo, squareIbo; private int levelNumVerts; private bool levelHasNorm; private ObjModel level; private AgentCylinder agentCylinder = new AgentCylinder(); public class AgentCylinder { int segments = 12; // Higher numbers improve quality float radius = 0.6f; // The radius (width) of the cylinder float height { get {return radius * 2;}} // The height of the cylinder List<Vector3> vertices = new List<Vector3>(); List<int> indices = new List<int>(); public float Radius { get { return radius; } set { radius = value; Init(); } } public void Init() { vertices.Clear(); for (double y = 0; y < 2; y++) { for (double x = 0; x < segments; x++) { double theta = (x / (segments - 1)) * 2 * Math.PI; vertices.Add(new Vector3() { X = (float)(radius * Math.Cos(theta)), Y = (float)(height * y), Z = (float)(radius * Math.Sin(theta)), }); } } indices.Clear(); for (int x = 0; x < segments - 1; x++) { indices.Add(x); indices.Add(x + segments); indices.Add(x + segments + 1); indices.Add(x + segments + 1); indices.Add(x + 1); indices.Add(x); } for (int x = 1; x < segments - 1; x++) { indices.Add(segments); indices.Add(x + segments + 1); indices.Add(x + segments); } } public void Draw(Vector3 pos) { GL.Begin(BeginMode.Triangles); foreach (int index in indices) GL.Vertex3(vertices[index] + pos); GL.End(); } } private static readonly byte[] squareInds = { 0, 1, 2, 0, 2, 3 }; private static readonly float[] squareVerts = { 0.5f, 0, 0.5f, 0, 1, 0, 0.5f, 0, -0.5f, 0, 1, 0, -0.5f, 0, -0.5f, 0, 1, 0, -0.5f, 0, 0.5f, 0, 1, 0 }; private static readonly byte[] voxelInds = { 0, 2, 1, 0, 3, 2, //-Z 4, 6, 5, 4, 7, 6, //+X 8, 10, 9, 8, 11, 10, //+Z 12, 14, 13, 12, 15, 14, //-X 16, 18, 17, 16, 19, 18, //+Y 20, 22, 21, 20, 23, 22 //-Y }; private static readonly float[] voxelVerts = { //-Z face -0.5f, 0.5f, -0.5f, 0, 0, -1, -0.5f, -0.5f, -0.5f, 0, 0, -1, 0.5f, -0.5f, -0.5f, 0, 0, -1, 0.5f, 0.5f, -0.5f, 0, 0, -1, //+X face 0.5f, 0.5f, -0.5f, 1, 0, 0, 0.5f, -0.5f, -0.5f, 1, 0, 0, 0.5f, -0.5f, 0.5f, 1, 0, 0, 0.5f, 0.5f, 0.5f, 1, 0, 0, //+Z face 0.5f, 0.5f, 0.5f, 0, 0, 1, 0.5f, -0.5f, 0.5f, 0, 0, 1, -0.5f, -0.5f, 0.5f, 0, 0, 1, -0.5f, 0.5f, 0.5f, 0, 0, 1, //-X face -0.5f, 0.5f, 0.5f, -1, 0, 0, -0.5f, -0.5f, 0.5f, -1, 0, 0, -0.5f, -0.5f, -0.5f, -1, 0, 0, -0.5f, 0.5f, -0.5f, -1, 0, 0, //+Y face -0.5f, 0.5f, 0.5f, 0, 1, 0, -0.5f, 0.5f, -0.5f, 0, 1, 0, 0.5f, 0.5f, -0.5f, 0, 1, 0, 0.5f, 0.5f, 0.5f, 0, 1, 0, //-Y face -0.5f, -0.5f, -0.5f, 0, -1, 0, -0.5f, -0.5f, 0.5f, 0, -1, 0, 0.5f, -0.5f, 0.5f, 0, -1, 0, 0.5f, -0.5f, -0.5f, 0, -1, 0 }; private void InitializeOpenGL() { GL.Enable(EnableCap.DepthTest); GL.DepthMask(true); GL.DepthFunc(DepthFunction.Lequal); GL.Enable(EnableCap.CullFace); GL.FrontFace(FrontFaceDirection.Ccw); GL.Enable(EnableCap.Blend); GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha); GL.ClearColor(Color4.CornflowerBlue); GL.Enable(EnableCap.Lighting); GL.Enable(EnableCap.Light0); GL.Light(LightName.Light0, LightParameter.Ambient, new Vector4(0.6f, 0.6f, 0.6f, 1f)); GL.Disable(EnableCap.Light0); GL.Disable(EnableCap.Lighting); } private void LoadLevel() { level = new ObjModel("nav_test.obj"); var levelTris = level.GetTriangles(); var levelNorms = level.GetNormals(); levelNumVerts = levelTris.Length * 3 * 3; levelHasNorm = levelNorms != null && levelNorms.Length > 0; var bounds = TriangleEnumerable.FromTriangle(levelTris, 0, levelTris.Length).GetBoundingBox(); cam.Position = new Vector3(bounds.Max.X, bounds.Max.Y, bounds.Max.Z) * 1.5f; cam.RotateHeadingTo(-25); cam.RotatePitchTo(315); //TODO fix camera, it breaks with lookat... //cam.LookAt(new Vector3(bounds.Center.X, bounds.Center.Y, bounds.Center.Z)); levelVbo = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ArrayBuffer, levelVbo); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(levelNumVerts * 4), levelTris, BufferUsageHint.StaticDraw); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); if (levelHasNorm) { levelNormVbo = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ArrayBuffer, levelNormVbo); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(levelNorms.Length * 3 * 4), levelNorms, BufferUsageHint.StaticDraw); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); } } private void LoadDebugMeshes() { heightfieldVoxelVbo = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ArrayBuffer, heightfieldVoxelVbo); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(voxelVerts.Length * 4), voxelVerts, BufferUsageHint.StaticDraw); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); heightfieldVoxelIbo = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ElementArrayBuffer, heightfieldVoxelIbo); GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)voxelInds.Length, voxelInds, BufferUsageHint.StaticDraw); GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); squareVbo = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ArrayBuffer, squareVbo); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(squareVerts.Length * 4), squareVerts, BufferUsageHint.StaticDraw); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); squareIbo = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ElementArrayBuffer, squareIbo); GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)squareInds.Length, squareInds, BufferUsageHint.StaticDraw); GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); } private void UnloadLevel() { GL.DeleteBuffer(levelVbo); GL.DeleteBuffer(levelNormVbo); } private void UnloadDebugMeshes() { GL.DeleteBuffer(heightfieldVoxelVbo); GL.DeleteBuffer(heightfieldVoxelIbo); GL.DeleteBuffer(squareVbo); GL.DeleteBuffer(squareIbo); } private void DrawUI() { GL.PushMatrix(); GL.LoadIdentity(); GL.MatrixMode(MatrixMode.Projection); GL.PushMatrix(); GL.LoadMatrix(ref gwenProjection); GL.FrontFace(FrontFaceDirection.Cw); gwenCanvas.RenderCanvas(); GL.FrontFace(FrontFaceDirection.Ccw); GL.PopMatrix(); GL.MatrixMode(MatrixMode.Modelview); GL.PopMatrix(); } private void DrawLevel() { GL.EnableClientState(ArrayCap.VertexArray); if (levelHasNorm) GL.EnableClientState(ArrayCap.NormalArray); GL.BindBuffer(BufferTarget.ArrayBuffer, levelVbo); GL.VertexPointer(3, VertexPointerType.Float, 0, 0); if (levelHasNorm) { GL.BindBuffer(BufferTarget.ArrayBuffer, levelNormVbo); GL.NormalPointer(NormalPointerType.Float, 0, 0); } GL.DrawArrays(PrimitiveType.Triangles, 0, levelNumVerts); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); if (levelHasNorm) GL.DisableClientState(ArrayCap.NormalArray); GL.DisableClientState(ArrayCap.VertexArray); } private void DrawHeightfield() { if (heightfield == null) return; GL.EnableClientState(ArrayCap.VertexArray); GL.EnableClientState(ArrayCap.NormalArray); GL.Enable(EnableCap.Lighting); GL.Enable(EnableCap.Light0); GL.Light(LightName.Light0, LightParameter.Position, new Vector4(0f, 1, 0f, 0)); GL.BindBuffer(BufferTarget.ArrayBuffer, heightfieldVoxelVbo); GL.VertexPointer(3, VertexPointerType.Float, 6 * 4, 0); GL.NormalPointer(NormalPointerType.Float, 6 * 4, 3 * 4); GL.Color4(0.5f, 0.5f, 0.5f, 1f); GL.BindBuffer(BufferTarget.ElementArrayBuffer, heightfieldVoxelIbo); var cellSize = heightfield.CellSize; var halfCellSize = cellSize * 0.5f; Matrix4 spanLoc, spanScale; for (int i = 0; i < heightfield.Length; i++) { for (int j = 0; j < heightfield.Width; j++) { var cellLoc = new Vector3(j * cellSize.X + halfCellSize.X + heightfield.Bounds.Min.X, heightfield.Bounds.Min.Y, i * cellSize.Z + halfCellSize.Z + heightfield.Bounds.Min.Z); var cell = heightfield[j, i]; foreach (var span in cell.Spans) { GL.PushMatrix(); Matrix4.CreateTranslation(cellLoc.X, ((span.Minimum + span.Maximum) * 0.5f) * cellSize.Y + cellLoc.Y, cellLoc.Z, out spanLoc); GL.MultMatrix(ref spanLoc); Matrix4.CreateScale(cellSize.X, cellSize.Y * span.Height, cellSize.Z, out spanScale); GL.MultMatrix(ref spanScale); GL.DrawElements(PrimitiveType.Triangles, voxelInds.Length, DrawElementsType.UnsignedByte, 0); GL.PopMatrix(); } } } GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); GL.Disable(EnableCap.Light0); GL.Disable(EnableCap.Lighting); GL.DisableClientState(ArrayCap.VertexArray); GL.DisableClientState(ArrayCap.NormalArray); } private void DrawCompactHeightfield() { if (compactHeightfield == null) return; GL.EnableClientState(ArrayCap.VertexArray); GL.EnableClientState(ArrayCap.NormalArray); GL.BindBuffer(BufferTarget.ArrayBuffer, squareVbo); GL.VertexPointer(3, VertexPointerType.Float, 6 * 4, 0); GL.NormalPointer(NormalPointerType.Float, 6 * 4, 3 * 4); GL.BindBuffer(BufferTarget.ElementArrayBuffer, squareIbo); var cellSize = heightfield.CellSize; var halfCellSize = cellSize * 0.5f; Matrix4 squareScale, squareTrans; Vector3 squarePos; Matrix4.CreateScale(cellSize.X, 1, cellSize.Z, out squareScale); for (int i = 0; i < compactHeightfield.Length; i++) { for (int j = 0; j < compactHeightfield.Width; j++) { squarePos = new Vector3(j * cellSize.X + halfCellSize.X + heightfield.Bounds.Min.X, heightfield.Bounds.Min.Y, i * cellSize.Z + halfCellSize.Z + heightfield.Bounds.Min.Z); var cell = compactHeightfield[j, i]; foreach (var span in cell) { GL.PushMatrix(); int numCons = 0; for (var dir = Direction.West; dir <= Direction.South; dir++) { if (span.IsConnected(dir)) numCons++; } GL.Color4(numCons / 4f, numCons / 4f, numCons / 4f, 1f); var squarePosFinal = new OpenTK.Vector3(squarePos.X, squarePos.Y, squarePos.Z); squarePosFinal.Y += span.Minimum * cellSize.Y; Matrix4.CreateTranslation(ref squarePosFinal, out squareTrans); GL.MultMatrix(ref squareTrans); GL.MultMatrix(ref squareScale); GL.DrawElements(PrimitiveType.Triangles, squareInds.Length, DrawElementsType.UnsignedByte, 0); GL.PopMatrix(); } } } GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); GL.DisableClientState(ArrayCap.VertexArray); GL.DisableClientState(ArrayCap.NormalArray); } private void DrawDistanceField() { if (compactHeightfield == null) return; GL.EnableClientState(ArrayCap.VertexArray); GL.EnableClientState(ArrayCap.NormalArray); GL.BindBuffer(BufferTarget.ArrayBuffer, squareVbo); GL.VertexPointer(3, VertexPointerType.Float, 6 * 4, 0); GL.NormalPointer(NormalPointerType.Float, 6 * 4, 3 * 4); GL.BindBuffer(BufferTarget.ElementArrayBuffer, squareIbo); int maxdist = compactHeightfield.MaxDistance; var cellSize = heightfield.CellSize; var halfCellSize = cellSize * 0.5f; Matrix4 squareScale, squareTrans; Vector3 squarePos; Matrix4.CreateScale(cellSize.X, 1, cellSize.Z, out squareScale); for (int i = 0; i < compactHeightfield.Length; i++) { for (int j = 0; j < compactHeightfield.Width; j++) { squarePos = new Vector3(j * cellSize.X + halfCellSize.X + heightfield.Bounds.Min.X, heightfield.Bounds.Min.Y, i * cellSize.Z + halfCellSize.Z + heightfield.Bounds.Min.Z); var cell = compactHeightfield.Cells[i * compactHeightfield.Width + j]; for (int k = cell.StartIndex, kEnd = cell.StartIndex + cell.Count; k < kEnd; k++) { GL.PushMatrix(); int dist = compactHeightfield.Distances[k]; float val = (float)dist / (float)maxdist; GL.Color4(val, val, val, 1f); var span = compactHeightfield.Spans[k]; var squarePosFinal = new OpenTK.Vector3(squarePos.X, squarePos.Y, squarePos.Z); squarePosFinal.Y += span.Minimum * cellSize.Y; Matrix4.CreateTranslation(ref squarePosFinal, out squareTrans); GL.MultMatrix(ref squareTrans); GL.MultMatrix(ref squareScale); GL.DrawElements(PrimitiveType.Triangles, squareInds.Length, DrawElementsType.UnsignedByte, 0); GL.PopMatrix(); } } } GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); GL.DisableClientState(ArrayCap.VertexArray); GL.DisableClientState(ArrayCap.NormalArray); } private void DrawRegions() { if (compactHeightfield == null) return; GL.EnableClientState(ArrayCap.VertexArray); GL.EnableClientState(ArrayCap.NormalArray); GL.BindBuffer(BufferTarget.ArrayBuffer, squareVbo); GL.VertexPointer(3, VertexPointerType.Float, 6 * 4, 0); GL.NormalPointer(NormalPointerType.Float, 6 * 4, 3 * 4); GL.BindBuffer(BufferTarget.ElementArrayBuffer, squareIbo); int maxdist = compactHeightfield.MaxDistance; var cellSize = heightfield.CellSize; var halfCellSize = cellSize * 0.5f; Matrix4 squareScale, squareTrans; Vector3 squarePos; Matrix4.CreateScale(cellSize.X, 1, cellSize.Z, out squareScale); for (int i = 0; i < compactHeightfield.Length; i++) { for (int j = 0; j < compactHeightfield.Width; j++) { var cell = compactHeightfield.Cells[i * compactHeightfield.Width + j]; squarePos = new Vector3(j * cellSize.X + halfCellSize.X + heightfield.Bounds.Min.X, heightfield.Bounds.Min.Y, i * cellSize.Z + halfCellSize.Z + heightfield.Bounds.Min.Z); for (int k = cell.StartIndex, kEnd = cell.StartIndex + cell.Count; k < kEnd; k++) { GL.PushMatrix(); var span = compactHeightfield.Spans[k]; int region = span.Region.Id; //if (Region.IsBorder(region)) //region = Region.RemoveFlags(region); Color4 col = regionColors[region]; GL.Color4(col); var squarePosFinal = new OpenTK.Vector3(squarePos.X, squarePos.Y, squarePos.Z); squarePosFinal.Y += span.Minimum * cellSize.Y; Matrix4.CreateTranslation(ref squarePosFinal, out squareTrans); GL.MultMatrix(ref squareTrans); GL.MultMatrix(ref squareScale); GL.DrawElements(PrimitiveType.Triangles, squareInds.Length, DrawElementsType.UnsignedByte, 0); GL.PopMatrix(); } } } GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); GL.DisableClientState(ArrayCap.VertexArray); GL.DisableClientState(ArrayCap.NormalArray); } private void DrawContours() { if (contourSet == null) return; GL.EnableClientState(ArrayCap.VertexArray); int maxdist = compactHeightfield.MaxDistance; var cellSize = heightfield.CellSize; var halfCellSize = cellSize * 0.5f; GL.PushMatrix(); Matrix4 squareScale, squareTrans; Matrix4.CreateTranslation(heightfield.Bounds.Min.X + cellSize.X * compactHeightfield.BorderSize, heightfield.Bounds.Min.Y, heightfield.Bounds.Min.Z + cellSize.Z * compactHeightfield.BorderSize, out squareTrans); GL.MultMatrix(ref squareTrans); Matrix4.CreateScale(cellSize.X, cellSize.Y, cellSize.Z, out squareScale); GL.MultMatrix(ref squareScale); GL.LineWidth(5f); GL.Begin(PrimitiveType.Lines); foreach (var c in contourSet) { RegionId region = c.RegionId; //skip border regions if (RegionId.HasFlags(region, RegionFlags.Border)) continue; Color4 col = regionColors[(int)region]; GL.Color4(col); for (int i = 0; i < c.Vertices.Length; i++) { int ni = (i + 1) % c.Vertices.Length; GL.Vertex3(c.Vertices[i].X, c.Vertices[i].Y, c.Vertices[i].Z); GL.Vertex3(c.Vertices[ni].X, c.Vertices[ni].Y, c.Vertices[ni].Z); } } GL.End(); GL.PopMatrix(); GL.DisableClientState(ArrayCap.VertexArray); } private void DrawPolyMesh() { if (polyMesh == null) return; GL.PushMatrix(); Matrix4 squareScale, squareTrans; Matrix4.CreateTranslation(polyMesh.Bounds.Min.X, polyMesh.Bounds.Min.Y, polyMesh.Bounds.Min.Z, out squareTrans); GL.MultMatrix(ref squareTrans); Matrix4.CreateScale(polyMesh.CellSize, polyMesh.CellHeight, polyMesh.CellSize, out squareScale); GL.MultMatrix(ref squareScale); Color4 color = Color4.DarkViolet; color.A = 0.5f; GL.Color4(color); GL.Begin(PrimitiveType.Triangles); for (int i = 0; i < polyMesh.PolyCount; i++) { if (!polyMesh.Polys[i].Area.IsWalkable) continue; for (int j = 2; j < polyMesh.NumVertsPerPoly; j++) { if (polyMesh.Polys[i].Vertices[j] == PolyMesh.NullId) break; int vertIndex0 = polyMesh.Polys[i].Vertices[0]; int vertIndex1 = polyMesh.Polys[i].Vertices[j - 1]; int vertIndex2 = polyMesh.Polys[i].Vertices[j]; var v = polyMesh.Verts[vertIndex0]; GL.Vertex3(v.X, v.Y, v.Z); v = polyMesh.Verts[vertIndex1]; GL.Vertex3(v.X, v.Y, v.Z); v = polyMesh.Verts[vertIndex2]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); GL.DepthMask(false); //neighbor edges GL.Color4(Color4.Purple); GL.LineWidth(1.5f); GL.Begin(PrimitiveType.Lines); for (int i = 0; i < polyMesh.PolyCount; i++) { for (int j = 0; j < polyMesh.NumVertsPerPoly; j++) { if (polyMesh.Polys[i].Vertices[j] == PolyMesh.NullId) break; if (PolyMesh.IsBoundaryEdge(polyMesh.Polys[i].NeighborEdges[j])) continue; int nj = (j + 1 >= polyMesh.NumVertsPerPoly || polyMesh.Polys[i].Vertices[j + 1] == PolyMesh.NullId) ? 0 : j + 1; int vertIndex0 = polyMesh.Polys[i].Vertices[j]; int vertIndex1 = polyMesh.Polys[i].Vertices[nj]; var v = polyMesh.Verts[vertIndex0]; GL.Vertex3(v.X, v.Y, v.Z); v = polyMesh.Verts[vertIndex1]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); //boundary edges GL.LineWidth(3.5f); GL.Begin(PrimitiveType.Lines); for (int i = 0; i < polyMesh.PolyCount; i++) { for (int j = 0; j < polyMesh.NumVertsPerPoly; j++) { if (polyMesh.Polys[i].Vertices[j] == PolyMesh.NullId) break; if (PolyMesh.IsInteriorEdge(polyMesh.Polys[i].NeighborEdges[j])) continue; int nj = (j + 1 >= polyMesh.NumVertsPerPoly || polyMesh.Polys[i].Vertices[j + 1] == PolyMesh.NullId) ? 0 : j + 1; int vertIndex0 = polyMesh.Polys[i].Vertices[j]; int vertIndex1 = polyMesh.Polys[i].Vertices[nj]; var v = polyMesh.Verts[vertIndex0]; GL.Vertex3(v.X, v.Y, v.Z); v = polyMesh.Verts[vertIndex1]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); GL.PointSize(4.8f); GL.Begin(PrimitiveType.Points); for (int i = 0; i < polyMesh.VertCount; i++) { var v = polyMesh.Verts[i]; GL.Vertex3(v.X, v.Y, v.Z); } GL.End(); GL.DepthMask(true); GL.PopMatrix(); } private void DrawPolyMeshDetail() { if (polyMeshDetail == null) return; GL.PushMatrix(); Color4 color = Color4.DarkViolet; color.A = 0.5f; GL.Color4(color); GL.Begin(PrimitiveType.Triangles); for (int i = 0; i < polyMeshDetail.MeshCount; i++) { PolyMeshDetail.MeshData m = polyMeshDetail.Meshes[i]; int vertIndex = m.VertexIndex; int triIndex = m.TriangleIndex; for (int j = 0; j < m.TriangleCount; j++) { var t = polyMeshDetail.Tris[triIndex + j]; var v = polyMeshDetail.Verts[vertIndex + t.VertexHash0]; GL.Vertex3(v.X, v.Y, v.Z); v = polyMeshDetail.Verts[vertIndex + t.VertexHash1]; GL.Vertex3(v.X, v.Y, v.Z); v = polyMeshDetail.Verts[vertIndex + t.VertexHash2]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); GL.Color4(Color4.Purple); GL.LineWidth(1.5f); GL.Begin(PrimitiveType.Lines); for (int i = 0; i < polyMeshDetail.MeshCount; i++) { var m = polyMeshDetail.Meshes[i]; int vertIndex = m.VertexIndex; int triIndex = m.TriangleIndex; for (int j = 0; j < m.TriangleCount; j++) { var t = polyMeshDetail.Tris[triIndex + j]; for (int k = 0, kp = 2; k < 3; kp = k++) { if (((t.Flags >> (kp * 2)) & 0x3) == 0) { if (t[kp] < t[k]) { var v = polyMeshDetail.Verts[vertIndex + t[kp]]; GL.Vertex3(v.X, v.Y, v.Z); v = polyMeshDetail.Verts[vertIndex + t[k]]; GL.Vertex3(v.X, v.Y, v.Z); } } } } } GL.End(); GL.LineWidth(3.5f); GL.Begin(PrimitiveType.Lines); for (int i = 0; i < polyMeshDetail.MeshCount; i++) { var m = polyMeshDetail.Meshes[i]; int vertIndex = m.VertexIndex; int triIndex = m.TriangleIndex; for (int j = 0; j < m.TriangleCount; j++) { var t = polyMeshDetail.Tris[triIndex + j]; for (int k = 0, kp = 2; k < 3; kp = k++) { if (((t.Flags >> (kp * 2)) & 0x3) != 0) { var v = polyMeshDetail.Verts[vertIndex + t[kp]]; GL.Vertex3(v.X, v.Y, v.Z); v = polyMeshDetail.Verts[vertIndex + t[k]]; GL.Vertex3(v.X, v.Y, v.Z); } } } } GL.End(); GL.PointSize(4.8f); GL.Begin(PrimitiveType.Points); for (int i = 0; i < polyMeshDetail.MeshCount; i++) { var m = polyMeshDetail.Meshes[i]; for (int j = 0; j < m.VertexCount; j++) { var v = polyMeshDetail.Verts[m.VertexIndex + j]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); GL.PopMatrix(); } private void DrawNavMesh() { if (tiledNavMesh == null) return; var tile = tiledNavMesh.GetTileAt(0, 0, 0); GL.PushMatrix(); Color4 color = Color4.DarkViolet; color.A = 0.5f; GL.Color4(color); GL.Begin(PrimitiveType.Triangles); for (int i = 0; i < tile.Polys.Length; i++) { //if (!tile.Polys[i].Area.IsWalkable) //continue; for (int j = 2; j < PathfindingCommon.VERTS_PER_POLYGON; j++) { if (tile.Polys[i].Verts[j] == 0) break; int vertIndex0 = tile.Polys[i].Verts[0]; int vertIndex1 = tile.Polys[i].Verts[j - 1]; int vertIndex2 = tile.Polys[i].Verts[j]; var v = tile.Verts[vertIndex0]; GL.Vertex3(v.X, v.Y, v.Z); v = tile.Verts[vertIndex1]; GL.Vertex3(v.X, v.Y, v.Z); v = tile.Verts[vertIndex2]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); GL.DepthMask(false); //neighbor edges GL.Color4(Color4.Purple); GL.LineWidth(1.5f); GL.Begin(PrimitiveType.Lines); for (int i = 0; i < tile.Polys.Length; i++) { for (int j = 0; j < PathfindingCommon.VERTS_PER_POLYGON; j++) { if (tile.Polys[i].Verts[j] == 0) break; if (PolyMesh.IsBoundaryEdge(tile.Polys[i].Neis[j])) continue; int nj = (j + 1 >= PathfindingCommon.VERTS_PER_POLYGON || tile.Polys[i].Verts[j + 1] == 0) ? 0 : j + 1; int vertIndex0 = tile.Polys[i].Verts[j]; int vertIndex1 = tile.Polys[i].Verts[nj]; var v = tile.Verts[vertIndex0]; GL.Vertex3(v.X, v.Y, v.Z); v = tile.Verts[vertIndex1]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); //boundary edges GL.LineWidth(3.5f); GL.Begin(PrimitiveType.Lines); for (int i = 0; i < tile.Polys.Length; i++) { for (int j = 0; j < PathfindingCommon.VERTS_PER_POLYGON; j++) { if (tile.Polys[i].Verts[j] == 0) break; if (PolyMesh.IsInteriorEdge(tile.Polys[i].Neis[j])) continue; int nj = (j + 1 >= PathfindingCommon.VERTS_PER_POLYGON || tile.Polys[i].Verts[j + 1] == 0) ? 0 : j + 1; int vertIndex0 = tile.Polys[i].Verts[j]; int vertIndex1 = tile.Polys[i].Verts[nj]; var v = tile.Verts[vertIndex0]; GL.Vertex3(v.X, v.Y, v.Z); v = tile.Verts[vertIndex1]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); GL.PointSize(4.8f); GL.Begin(PrimitiveType.Points); for (int i = 0; i < tile.Verts.Length; i++) { var v = tile.Verts[i]; GL.Vertex3(v.X, v.Y, v.Z); } GL.End(); GL.DepthMask(true); GL.PopMatrix(); } private void DrawPathfinding() { GL.PushMatrix(); Color4 color = Color4.Cyan; GL.Begin(PrimitiveType.Triangles); for (int i = 0; i < path.Count; i++) { if (i == 0) color = Color4.Cyan; else if (i == path.Count - 1) color = Color4.PaleVioletRed; else color = Color4.LightYellow; GL.Color4(color); int polyRef = path[i]; MeshTile tile; Poly poly; tiledNavMesh.TryGetTileAndPolyByRefUnsafe(polyRef, out tile, out poly); for (int j = 2; j < poly.VertCount; j++) { int vertIndex0 = poly.Verts[0]; int vertIndex1 = poly.Verts[j - 1]; int vertIndex2 = poly.Verts[j]; var v = tile.Verts[vertIndex0]; GL.Vertex3(v.X, v.Y, v.Z); v = tile.Verts[vertIndex1]; GL.Vertex3(v.X, v.Y, v.Z); v = tile.Verts[vertIndex2]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); GL.DepthMask(false); //neighbor edges GL.LineWidth(1.5f); GL.Begin(PrimitiveType.Lines); for (int i = 0; i < path.Count; i++) { if (i == 0) color = Color4.Blue; else if (i == path.Count - 1) color = Color4.Red; else color = Color4.Yellow; GL.Color4(color); int polyRef = path[i]; MeshTile tile; Poly poly; tiledNavMesh.TryGetTileAndPolyByRefUnsafe(polyRef, out tile, out poly); for (int j = 0; j < poly.VertCount; j++) { int vertIndex0 = poly.Verts[j]; int vertIndex1 = poly.Verts[(j + 1) % poly.VertCount]; var v = tile.Verts[vertIndex0]; GL.Vertex3(v.X, v.Y, v.Z); v = tile.Verts[vertIndex1]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); //steering path GL.Color4(Color4.Black); GL.Begin(PrimitiveType.Lines); for (int i = 0; i < smoothPath.Count - 1; i++) { SVector3 v0 = smoothPath[i]; GL.Vertex3(v0.X, v0.Y, v0.Z); SVector3 v1 = smoothPath[i + 1]; GL.Vertex3(v1.X, v1.Y, v1.Z); } GL.End(); GL.DepthMask(true); GL.PopMatrix(); } private void DrawCrowd() { if (crowd == null) return; GL.PushMatrix(); //The black line represents the actual path that the agent takes /*GL.Color4(Color4.Black); GL.Begin(PrimitiveType.Lines); for (int i = 0; i < numActiveAgents; i++) { for (int j = 0; j < numIterations - 1; j++) { SVector3 v0 = trails[i].Trail[j]; GL.Vertex3(v0.X, v0.Y, v0.Z); SVector3 v1 = trails[i].Trail[j + 1]; GL.Vertex3(v1.X, v1.Y, v1.Z); } } GL.End(); //The yellow line represents the ideal path from the start to the target GL.Color4(Color4.Yellow); GL.LineWidth(1.5f); GL.Begin(PrimitiveType.Lines); for (int i = 0; i < numActiveAgents; i++) { SVector3 v0 = trails[i].Trail[0]; GL.Vertex3(v0.X, v0.Y, v0.Z); SVector3 v1 = trails[i].Trail[AGENT_MAX_TRAIL - 1]; GL.Vertex3(v1.X, v1.Y, v1.Z); } GL.End(); //The cyan point represents the agent's starting location GL.PointSize(100.0f); GL.Color4(Color4.Cyan); GL.Begin(PrimitiveType.Points); for (int i = 0; i < numActiveAgents; i++) { SVector3 v0 = trails[i].Trail[0]; GL.Vertex3(v0.X, v0.Y, v0.Z); } GL.End(); //The red point represent's the agent's target location GL.Color4(Color4.PaleVioletRed); GL.Begin(PrimitiveType.Points); for (int i = 0; i < numActiveAgents; i++) { SVector3 v0 = trails[i].Trail[AGENT_MAX_TRAIL - 1]; GL.Vertex3(v0.X, v0.Y, v0.Z); } GL.End();*/ //GL.DepthMask(true); GL.Color4(Color4.PaleVioletRed); GL.PointSize(10); GL.Begin(PrimitiveType.Points); //for (int i = 0; i < numActiveAgents; i++) //{ // SVector3 p = crowd.GetAgent(i).Position; // GL.Vertex3(p.X, p.Y + settings.AgentRadius, p.Z); //} GL.Color4(Color4.Blue); for (int i = 0; i < numActiveAgents; i++) { SVector3 p = crowd.GetAgent(i).TargetPosition; GL.Vertex3(p.X, p.Y + settings.AgentRadius, p.Z); } GL.End(); GL.Color4(Color4.LightGray); for (int i = 0; i < numActiveAgents; i++) { SVector3 p = crowd.GetAgent(i).Position; agentCylinder.Draw(new Vector3(p.X, p.Y, p.Z)); } GL.PopMatrix(); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Collections.Specialized { [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BitVector32 { public BitVector32(System.Collections.Specialized.BitVector32 value) { throw new System.NotImplementedException(); } public BitVector32(int data) { throw new System.NotImplementedException(); } public int Data { get { return default(int); } } public int this[System.Collections.Specialized.BitVector32.Section section] { get { return default(int); } set { } } public bool this[int bit] { get { return default(bool); } set { } } public static int CreateMask() { return default(int); } public static int CreateMask(int previous) { return default(int); } public static System.Collections.Specialized.BitVector32.Section CreateSection(short maxValue) { return default(System.Collections.Specialized.BitVector32.Section); } public static System.Collections.Specialized.BitVector32.Section CreateSection(short maxValue, System.Collections.Specialized.BitVector32.Section previous) { return default(System.Collections.Specialized.BitVector32.Section); } public override bool Equals(object o) { return default(bool); } public override int GetHashCode() { return default(int); } public override string ToString() { return default(string); } public static string ToString(System.Collections.Specialized.BitVector32 value) { return default(string); } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Section { public short Mask { get { return default(short); } } public short Offset { get { return default(short); } } public bool Equals(System.Collections.Specialized.BitVector32.Section obj) { return default(bool); } public override bool Equals(object o) { return default(bool); } public override int GetHashCode() { return default(int); } public static bool operator ==(System.Collections.Specialized.BitVector32.Section a, System.Collections.Specialized.BitVector32.Section b) { return default(bool); } public static bool operator !=(System.Collections.Specialized.BitVector32.Section a, System.Collections.Specialized.BitVector32.Section b) { return default(bool); } public override string ToString() { return default(string); } public static string ToString(System.Collections.Specialized.BitVector32.Section value) { return default(string); } } } public partial class HybridDictionary : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { public HybridDictionary() { } public HybridDictionary(bool caseInsensitive) { } public HybridDictionary(int initialSize) { } public HybridDictionary(int initialSize, bool caseInsensitive) { } public int Count { get { return default(int); } } public bool IsFixedSize { get { return default(bool); } } public bool IsReadOnly { get { return default(bool); } } public bool IsSynchronized { get { return default(bool); } } public object this[object key] { get { return default(object); } set { } } public System.Collections.ICollection Keys { get { return default(System.Collections.ICollection); } } public object SyncRoot { get { return default(object); } } public System.Collections.ICollection Values { get { return default(System.Collections.ICollection); } } public void Add(object key, object value) { } public void Clear() { } public bool Contains(object key) { return default(bool); } public void CopyTo(System.Array array, int index) { } public System.Collections.IDictionaryEnumerator GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); } public void Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } public partial interface IOrderedDictionary : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { object this[int index] { get; set; } new System.Collections.IDictionaryEnumerator GetEnumerator(); void Insert(int index, object key, object value); void RemoveAt(int index); } public partial class ListDictionary : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { public ListDictionary() { } public ListDictionary(System.Collections.IComparer comparer) { } public int Count { get { return default(int); } } public bool IsFixedSize { get { return default(bool); } } public bool IsReadOnly { get { return default(bool); } } public bool IsSynchronized { get { return default(bool); } } public object this[object key] { get { return default(object); } set { } } public System.Collections.ICollection Keys { get { return default(System.Collections.ICollection); } } public object SyncRoot { get { return default(object); } } public System.Collections.ICollection Values { get { return default(System.Collections.ICollection); } } public void Add(object key, object value) { } public void Clear() { } public bool Contains(object key) { return default(bool); } public void CopyTo(System.Array array, int index) { } public System.Collections.IDictionaryEnumerator GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); } public void Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } public abstract partial class NameObjectCollectionBase : System.Collections.ICollection, System.Collections.IEnumerable { protected NameObjectCollectionBase() { } protected NameObjectCollectionBase(System.Collections.IEqualityComparer equalityComparer) { } protected NameObjectCollectionBase(int capacity) { } protected NameObjectCollectionBase(int capacity, System.Collections.IEqualityComparer equalityComparer) { } public virtual int Count { get { return default(int); } } protected bool IsReadOnly { get { return default(bool); } set { } } public virtual System.Collections.Specialized.NameObjectCollectionBase.KeysCollection Keys { get { return default(System.Collections.Specialized.NameObjectCollectionBase.KeysCollection); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } protected void BaseAdd(string name, object value) { } protected void BaseClear() { } protected object BaseGet(int index) { return default(object); } protected object BaseGet(string name) { return default(object); } protected string[] BaseGetAllKeys() { return default(string[]); } protected object[] BaseGetAllValues() { return default(object[]); } protected object[] BaseGetAllValues(System.Type type) { return default(object[]); } protected string BaseGetKey(int index) { return default(string); } protected bool BaseHasKeys() { return default(bool); } protected void BaseRemove(string name) { } protected void BaseRemoveAt(int index) { } protected void BaseSet(int index, object value) { } protected void BaseSet(string name, object value) { } public virtual System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } public partial class KeysCollection : System.Collections.ICollection, System.Collections.IEnumerable { internal KeysCollection() { } public int Count { get { return default(int); } } public string this[int index] { get { return default(string); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } public virtual string Get(int index) { return default(string); } public System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } } } public partial class NameValueCollection : System.Collections.Specialized.NameObjectCollectionBase { public NameValueCollection() { } public NameValueCollection(System.Collections.IEqualityComparer equalityComparer) { } public NameValueCollection(System.Collections.Specialized.NameValueCollection col) { } public NameValueCollection(int capacity) { } public NameValueCollection(int capacity, System.Collections.IEqualityComparer equalityComparer) { } public NameValueCollection(int capacity, System.Collections.Specialized.NameValueCollection col) { } public virtual string[] AllKeys { get { return default(string[]); } } public string this[int index] { get { return default(string); } } public string this[string name] { get { return default(string); } set { } } public void Add(System.Collections.Specialized.NameValueCollection c) { } public virtual void Add(string name, string value) { } public virtual void Clear() { } public void CopyTo(System.Array dest, int index) { } public virtual string Get(int index) { return default(string); } public virtual string Get(string name) { return default(string); } public virtual string GetKey(int index) { return default(string); } public virtual string[] GetValues(int index) { return default(string[]); } public virtual string[] GetValues(string name) { return default(string[]); } public bool HasKeys() { return default(bool); } protected void InvalidateCachedArrays() { } public virtual void Remove(string name) { } public virtual void Set(string name, string value) { } } public partial class OrderedDictionary : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable, System.Collections.Specialized.IOrderedDictionary { public OrderedDictionary() { } public OrderedDictionary(System.Collections.IEqualityComparer comparer) { } public OrderedDictionary(int capacity) { } public OrderedDictionary(int capacity, System.Collections.IEqualityComparer comparer) { } public int Count { get { return default(int); } } public bool IsReadOnly { get { return default(bool); } } public object this[int index] { get { return default(object); } set { } } public object this[object key] { get { return default(object); } set { } } public System.Collections.ICollection Keys { get { return default(System.Collections.ICollection); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } bool System.Collections.IDictionary.IsFixedSize { get { return default(bool); } } public System.Collections.ICollection Values { get { return default(System.Collections.ICollection); } } public void Add(object key, object value) { } public System.Collections.Specialized.OrderedDictionary AsReadOnly() { return default(System.Collections.Specialized.OrderedDictionary); } public void Clear() { } public bool Contains(object key) { return default(bool); } public void CopyTo(System.Array array, int index) { } public virtual System.Collections.IDictionaryEnumerator GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); } public void Insert(int index, object key, object value) { } public void Remove(object key) { } public void RemoveAt(int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } public partial class StringCollection : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { public StringCollection() { } public int Count { get { return default(int); } } public bool IsReadOnly { get { return default(bool); } } public bool IsSynchronized { get { return default(bool); } } public string this[int index] { get { return default(string); } set { } } public object SyncRoot { get { return default(object); } } bool System.Collections.IList.IsFixedSize { get { return default(bool); } } bool System.Collections.IList.IsReadOnly { get { return default(bool); } } object System.Collections.IList.this[int index] { get { return default(object); } set { } } public int Add(string value) { return default(int); } public void AddRange(string[] value) { } public void Clear() { } public bool Contains(string value) { return default(bool); } public void CopyTo(string[] array, int index) { } public System.Collections.Specialized.StringEnumerator GetEnumerator() { return default(System.Collections.Specialized.StringEnumerator); } public int IndexOf(string value) { return default(int); } public void Insert(int index, string value) { } public void Remove(string value) { } public void RemoveAt(int index) { } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } int System.Collections.IList.Add(object value) { return default(int); } bool System.Collections.IList.Contains(object value) { return default(bool); } int System.Collections.IList.IndexOf(object value) { return default(int); } void System.Collections.IList.Insert(int index, object value) { } void System.Collections.IList.Remove(object value) { } } public partial class StringDictionary : System.Collections.IEnumerable { public StringDictionary() { } public virtual int Count { get { return default(int); } } public virtual bool IsSynchronized { get { return default(bool); } } public virtual string this[string key] { get { return default(string); } set { } } public virtual System.Collections.ICollection Keys { get { return default(System.Collections.ICollection); } } public virtual object SyncRoot { get { return default(object); } } public virtual System.Collections.ICollection Values { get { return default(System.Collections.ICollection); } } public virtual void Add(string key, string value) { } public virtual void Clear() { } public virtual bool ContainsKey(string key) { return default(bool); } public virtual bool ContainsValue(string value) { return default(bool); } public virtual void CopyTo(System.Array array, int index) { } public virtual System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); } public virtual void Remove(string key) { } } public partial class StringEnumerator { internal StringEnumerator() { } public string Current { get { return default(string); } } public bool MoveNext() { return default(bool); } public void Reset() { } } }
using System; using System.Linq; namespace ClosedXML.Excel { using System.Collections.Generic; internal class XLFilterColumn : IXLFilterColumn { private readonly XLAutoFilter _autoFilter; private readonly Int32 _column; public XLFilterColumn(XLAutoFilter autoFilter, Int32 column) { _autoFilter = autoFilter; _column = column; } #region IXLFilterColumn Members public void Clear() { if (_autoFilter.Filters.ContainsKey(_column)) _autoFilter.Filters.Remove(_column); } public IXLFilteredColumn AddFilter<T>(T value) where T : IComparable<T> { if (typeof(T) == typeof(String)) { ApplyCustomFilter(value, XLFilterOperator.Equal, v => v.ToString().Equals(value.ToString(), StringComparison.InvariantCultureIgnoreCase), XLFilterType.Regular); } else { ApplyCustomFilter(value, XLFilterOperator.Equal, v => v.CastTo<T>().CompareTo(value) == 0, XLFilterType.Regular); } return new XLFilteredColumn(_autoFilter, _column); } public IXLDateTimeGroupFilteredColumn AddDateGroupFilter(DateTime date, XLDateTimeGrouping dateTimeGrouping) { Func<Object, Boolean> condition = date2 => XLDateTimeGroupFilteredColumn.IsMatch(date, (DateTime)date2, dateTimeGrouping); _autoFilter.Enabled = true; if (_autoFilter.Filters.TryGetValue(_column, out List<XLFilter> filterList)) filterList.Add( new XLFilter { Value = date, Operator = XLFilterOperator.Equal, Connector = XLConnector.Or, Condition = condition, DateTimeGrouping = dateTimeGrouping } ); else { _autoFilter.Filters.Add( _column, new List<XLFilter> { new XLFilter { Value = date, Operator = XLFilterOperator.Equal, Connector = XLConnector.Or, Condition = condition, DateTimeGrouping = dateTimeGrouping } } ); } _autoFilter.Column(_column).FilterType = XLFilterType.DateTimeGrouping; var ws = _autoFilter.Range.Worksheet as XLWorksheet; ws.SuspendEvents(); var rows = _autoFilter.Range.Rows(2, _autoFilter.Range.RowCount()); foreach (IXLRangeRow row in rows) { if (row.Cell(_column).DataType == XLDataType.DateTime && condition(row.Cell(_column).GetDateTime())) row.WorksheetRow().Unhide(); else row.WorksheetRow().Hide(); } ws.ResumeEvents(); return new XLDateTimeGroupFilteredColumn(_autoFilter, _column); } public void Top(Int32 value, XLTopBottomType type = XLTopBottomType.Items) { _autoFilter.Column(_column).TopBottomPart = XLTopBottomPart.Top; SetTopBottom(value, type); } public void Bottom(Int32 value, XLTopBottomType type = XLTopBottomType.Items) { _autoFilter.Column(_column).TopBottomPart = XLTopBottomPart.Bottom; SetTopBottom(value, type, false); } public void AboveAverage() { ShowAverage(true); } public void BelowAverage() { ShowAverage(false); } public IXLFilterConnector EqualTo<T>(T value) where T : IComparable<T> { if (typeof(T) == typeof(String)) { return ApplyCustomFilter(value, XLFilterOperator.Equal, v => v.ToString().Equals(value.ToString(), StringComparison.InvariantCultureIgnoreCase)); } return ApplyCustomFilter(value, XLFilterOperator.Equal, v => v.CastTo<T>().CompareTo(value) == 0); } public IXLFilterConnector NotEqualTo<T>(T value) where T : IComparable<T> { if (typeof(T) == typeof(String)) { return ApplyCustomFilter(value, XLFilterOperator.NotEqual, v => !v.ToString().Equals(value.ToString(), StringComparison.InvariantCultureIgnoreCase)); } return ApplyCustomFilter(value, XLFilterOperator.NotEqual, v => v.CastTo<T>().CompareTo(value) != 0); } public IXLFilterConnector GreaterThan<T>(T value) where T : IComparable<T> { return ApplyCustomFilter(value, XLFilterOperator.GreaterThan, v => v.CastTo<T>().CompareTo(value) > 0); } public IXLFilterConnector LessThan<T>(T value) where T : IComparable<T> { return ApplyCustomFilter(value, XLFilterOperator.LessThan, v => v.CastTo<T>().CompareTo(value) < 0); } public IXLFilterConnector EqualOrGreaterThan<T>(T value) where T : IComparable<T> { return ApplyCustomFilter(value, XLFilterOperator.EqualOrGreaterThan, v => v.CastTo<T>().CompareTo(value) >= 0); } public IXLFilterConnector EqualOrLessThan<T>(T value) where T : IComparable<T> { return ApplyCustomFilter(value, XLFilterOperator.EqualOrLessThan, v => v.CastTo<T>().CompareTo(value) <= 0); } public void Between<T>(T minValue, T maxValue) where T : IComparable<T> { EqualOrGreaterThan(minValue).And.EqualOrLessThan(maxValue); } public void NotBetween<T>(T minValue, T maxValue) where T : IComparable<T> { LessThan(minValue).Or.GreaterThan(maxValue); } public IXLFilterConnector BeginsWith(String value) { return ApplyCustomFilter(value + "*", XLFilterOperator.Equal, s => ((string)s).StartsWith(value, StringComparison.InvariantCultureIgnoreCase)); } public IXLFilterConnector NotBeginsWith(String value) { return ApplyCustomFilter(value + "*", XLFilterOperator.NotEqual, s => !((string)s).StartsWith(value, StringComparison.InvariantCultureIgnoreCase)); } public IXLFilterConnector EndsWith(String value) { return ApplyCustomFilter("*" + value, XLFilterOperator.Equal, s => ((string)s).EndsWith(value, StringComparison.InvariantCultureIgnoreCase)); } public IXLFilterConnector NotEndsWith(String value) { return ApplyCustomFilter("*" + value, XLFilterOperator.NotEqual, s => !((string)s).EndsWith(value, StringComparison.InvariantCultureIgnoreCase)); } public IXLFilterConnector Contains(String value) { return ApplyCustomFilter("*" + value + "*", XLFilterOperator.Equal, s => ((string)s).ToLower().Contains(value.ToLower())); } public IXLFilterConnector NotContains(String value) { return ApplyCustomFilter("*" + value + "*", XLFilterOperator.Equal, s => !((string)s).ToLower().Contains(value.ToLower())); } public XLFilterType FilterType { get; set; } public Int32 TopBottomValue { get; set; } public XLTopBottomType TopBottomType { get; set; } public XLTopBottomPart TopBottomPart { get; set; } public XLFilterDynamicType DynamicType { get; set; } public Double DynamicValue { get; set; } #endregion IXLFilterColumn Members private void SetTopBottom(Int32 value, XLTopBottomType type, Boolean takeTop = true) { _autoFilter.Enabled = true; _autoFilter.Column(_column).SetFilterType(XLFilterType.TopBottom) .SetTopBottomValue(value) .SetTopBottomType(type); var values = GetValues(value, type, takeTop); Clear(); _autoFilter.Filters.Add(_column, new List<XLFilter>()); Boolean addToList = true; var ws = _autoFilter.Range.Worksheet as XLWorksheet; ws.SuspendEvents(); var rows = _autoFilter.Range.Rows(2, _autoFilter.Range.RowCount()); foreach (IXLRangeRow row in rows) { Boolean foundOne = false; foreach (double val in values) { Func<Object, Boolean> condition = v => (v as IComparable).CompareTo(val) == 0; if (addToList) { _autoFilter.Filters[_column].Add(new XLFilter { Value = val, Operator = XLFilterOperator.Equal, Connector = XLConnector.Or, Condition = condition }); } var cell = row.Cell(_column); if (cell.DataType != XLDataType.Number || !condition(cell.GetDouble())) continue; row.WorksheetRow().Unhide(); foundOne = true; } if (!foundOne) row.WorksheetRow().Hide(); addToList = false; } ws.ResumeEvents(); } private IEnumerable<double> GetValues(int value, XLTopBottomType type, bool takeTop) { var column = _autoFilter.Range.Column(_column); var subColumn = column.Column(2, column.CellCount()); var cellsUsed = subColumn.CellsUsed(c => c.DataType == XLDataType.Number); if (takeTop) { if (type == XLTopBottomType.Items) { return cellsUsed.Select(c => c.GetDouble()).OrderByDescending(d => d).Take(value).Distinct(); } var numerics1 = cellsUsed.Select(c => c.GetDouble()); Int32 valsToTake1 = numerics1.Count() * value / 100; return numerics1.OrderByDescending(d => d).Take(valsToTake1).Distinct(); } if (type == XLTopBottomType.Items) { return cellsUsed.Select(c => c.GetDouble()).OrderBy(d => d).Take(value).Distinct(); } var numerics = cellsUsed.Select(c => c.GetDouble()); Int32 valsToTake = numerics.Count() * value / 100; return numerics.OrderBy(d => d).Take(valsToTake).Distinct(); } private void ShowAverage(Boolean aboveAverage) { _autoFilter.Enabled = true; _autoFilter.Column(_column).SetFilterType(XLFilterType.Dynamic) .SetDynamicType(aboveAverage ? XLFilterDynamicType.AboveAverage : XLFilterDynamicType.BelowAverage); var values = GetAverageValues(aboveAverage); Clear(); _autoFilter.Filters.Add(_column, new List<XLFilter>()); Boolean addToList = true; var ws = _autoFilter.Range.Worksheet as XLWorksheet; ws.SuspendEvents(); var rows = _autoFilter.Range.Rows(2, _autoFilter.Range.RowCount()); foreach (IXLRangeRow row in rows) { Boolean foundOne = false; foreach (double val in values) { Func<Object, Boolean> condition = v => (v as IComparable).CompareTo(val) == 0; if (addToList) { _autoFilter.Filters[_column].Add(new XLFilter { Value = val, Operator = XLFilterOperator.Equal, Connector = XLConnector.Or, Condition = condition }); } var cell = row.Cell(_column); if (cell.DataType != XLDataType.Number || !condition(cell.GetDouble())) continue; row.WorksheetRow().Unhide(); foundOne = true; } if (!foundOne) row.WorksheetRow().Hide(); addToList = false; } ws.ResumeEvents(); } private IEnumerable<double> GetAverageValues(bool aboveAverage) { var column = _autoFilter.Range.Column(_column); var subColumn = column.Column(2, column.CellCount()); Double average = subColumn.CellsUsed(c => c.DataType == XLDataType.Number).Select(c => c.GetDouble()) .Average(); if (aboveAverage) { return subColumn.CellsUsed(c => c.DataType == XLDataType.Number).Select(c => c.GetDouble()) .Where(c => c > average).Distinct(); } return subColumn.CellsUsed(c => c.DataType == XLDataType.Number).Select(c => c.GetDouble()) .Where(c => c < average).Distinct(); } private IXLFilterConnector ApplyCustomFilter<T>(T value, XLFilterOperator op, Func<Object, Boolean> condition, XLFilterType filterType = XLFilterType.Custom) where T : IComparable<T> { _autoFilter.Enabled = true; if (filterType == XLFilterType.Custom) { Clear(); _autoFilter.Filters.Add(_column, new List<XLFilter> { new XLFilter { Value = value, Operator = op, Connector = XLConnector.Or, Condition = condition } }); } else { if (_autoFilter.Filters.TryGetValue(_column, out List<XLFilter> filterList)) filterList.Add(new XLFilter { Value = value, Operator = op, Connector = XLConnector.Or, Condition = condition }); else { _autoFilter.Filters.Add(_column, new List<XLFilter> { new XLFilter { Value = value, Operator = op, Connector = XLConnector.Or, Condition = condition } }); } } _autoFilter.Column(_column).FilterType = filterType; Boolean isText = typeof(T) == typeof(String); Boolean isDateTime = typeof(T) == typeof(DateTime); var ws = _autoFilter.Range.Worksheet as XLWorksheet; ws.SuspendEvents(); var rows = _autoFilter.Range.Rows(2, _autoFilter.Range.RowCount()); foreach (IXLRangeRow row in rows) { Boolean match; if (isText) match = condition(row.Cell(_column).GetFormattedString()); else if (isDateTime) match = row.Cell(_column).DataType == XLDataType.DateTime && condition(row.Cell(_column).GetDateTime()); else match = row.Cell(_column).DataType == XLDataType.Number && condition(row.Cell(_column).GetDouble()); if (match) row.WorksheetRow().Unhide(); else row.WorksheetRow().Hide(); } ws.ResumeEvents(); return new XLFilterConnector(_autoFilter, _column); } public IXLFilterColumn SetFilterType(XLFilterType value) { FilterType = value; return this; } public IXLFilterColumn SetTopBottomValue(Int32 value) { TopBottomValue = value; return this; } public IXLFilterColumn SetTopBottomType(XLTopBottomType value) { TopBottomType = value; return this; } public IXLFilterColumn SetTopBottomPart(XLTopBottomPart value) { TopBottomPart = value; return this; } public IXLFilterColumn SetDynamicType(XLFilterDynamicType value) { DynamicType = value; return this; } public IXLFilterColumn SetDynamicValue(Double value) { DynamicValue = value; return this; } } }
/// Refly License /// /// Copyright (c) 2004 Jonathan de Halleux, http://www.dotnetwiki.org /// /// This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. /// /// Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: /// /// 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. /// /// 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. /// ///3. This notice may not be removed or altered from any source distribution. using System; using System.Collections; using System.Collections.Specialized; using System.Threading; using System.Reflection; using System.CodeDom; using System.Xml.Serialization; using System.IO; namespace Refly.Xsd { using Refly.CodeDom; using Refly.CodeDom.Collections; using Refly.CodeDom.Expressions; using Refly.CodeDom.Statements; /// <summary> /// Transforms the XSD wrapper classes outputed by the Xsd.exe utility /// to nicer classes using Reflection. /// </summary> /// <remarks> /// </remarks> public class XsdWrapperGenerator { private NamespaceDeclaration ns; private NameConformer conformer; private TypeTypeDeclarationDictionary types = new TypeTypeDeclarationDictionary(); private XsdWrapperConfig config = new XsdWrapperConfig(); /// <summary> /// Creates a new wrapper generator. /// </summary> /// <param name="name"></param> public XsdWrapperGenerator(string name) { if (name==null) throw new ArgumentNullException("name"); this.conformer = new NameConformer(); this.ns = new NamespaceDeclaration(name,this.conformer); this.ns.Imports.Add("System.Xml"); this.ns.Imports.Add("System.Xml.Serialization"); this.ns.Imports.Add("System.IO"); } public NameConformer Conformer { get { return this.conformer; } } public NamespaceDeclaration Ns { get { return this.ns; } } public TypeTypeDeclarationDictionary Types { get { return this.types; } } public XsdWrapperConfig Config { get { return this.config; } set { this.config = value; } } /// <summary> /// Adds a class to the wrapped class list /// </summary> /// <param name="t"></param> public void Add(Type t) { if (t==null) throw new ArgumentNullException("t"); if (t.IsEnum) CreateEnum(t); else if (t.IsClass) CreateClass(t); } public void Generate() { foreach(Type t in this.types.Keys) { if (t.IsEnum) GenerateEnumType(t); else if (t.IsClass) GenerateClassType(t); } } private void CreateClass(Type t) { ClassDeclaration c = this.ns.AddClass(this.conformer.ToCapitalized(t.Name)); // check if XmlType present if(TypeHelper.HasCustomAttribute(t,typeof(XmlTypeAttribute))) { XmlTypeAttribute typeAttr = (XmlTypeAttribute)TypeHelper.GetFirstCustomAttribute(t,typeof(XmlTypeAttribute)); AttributeDeclaration type =c.CustomAttributes.Add(typeof(XmlTypeAttribute)); type.Arguments.Add("IncludeInSchema",Expr.Prim(typeAttr.IncludeInSchema)); if (this.Config.KeepNamespaces) { type.Arguments.Add("Namespace",Expr.Prim(typeAttr.Namespace)); } type.Arguments.Add("TypeName",Expr.Prim(typeAttr.TypeName)); } // check if XmlRoot present if(TypeHelper.HasCustomAttribute(t,typeof(XmlRootAttribute)) ) { XmlRootAttribute rootAttr = (XmlRootAttribute)TypeHelper.GetFirstCustomAttribute(t,typeof(XmlRootAttribute)); AttributeDeclaration root = c.CustomAttributes.Add(typeof(XmlRootAttribute)); root.Arguments.Add("ElementName",Expr.Prim(rootAttr.ElementName)); root.Arguments.Add("IsNullable",Expr.Prim(rootAttr.IsNullable)); if (this.Config.KeepNamespaces) { root.Arguments.Add("Namespace",Expr.Prim(rootAttr.Namespace)); } root.Arguments.Add("DataType",Expr.Prim(rootAttr.DataType)); } else { AttributeDeclaration root =c.CustomAttributes.Add(typeof(XmlRootAttribute)); root.Arguments.Add("ElementName",Expr.Prim(t.Name)); } this.types.Add(t,c); } private void CreateEnum(Type t) { bool flags = TypeHelper.HasCustomAttribute(t,typeof(FlagsAttribute)); EnumDeclaration e = this.ns.AddEnum(this.conformer.ToCapitalized(t.Name),flags); this.types.Add(t,e); } private void GenerateClassType(Type t) { ClassDeclaration c = this.ns.Classes[this.conformer.ToCapitalized(t.Name)]; if (c==null) throw new Exception(this.conformer.ToCapitalized(t.Name) + " not found."); c.CustomAttributes.Add(typeof(SerializableAttribute)); // generate fields and properties foreach(FieldInfo f in t.GetFields()) { if (f.FieldType.IsArray) { AddArrayField(c,f); } else { AddField(c,f); } } // add constructors GenerateDefaultConstructor(c); } private void GenerateEnumType(Type t) { EnumDeclaration e = this.ns.Enums[this.conformer.ToCapitalized(t.Name)]; e.CustomAttributes.Add(typeof(SerializableAttribute)); if (e==null) throw new Exception(); // generate fields and properties foreach(FieldInfo f in t.GetFields()) { if (f.Name == "Value__") continue; FieldDeclaration field = e.AddField(f.Name); // add XmlEnum attribute AttributeDeclaration xmlEnum = field.CustomAttributes.Add(typeof(XmlEnumAttribute)); AttributeArgument arg = xmlEnum.Arguments.Add( "Name", Expr.Prim(f.Name) ); } } private void AddArrayField(ClassDeclaration c, FieldInfo f) { // create a collection ClassDeclaration col = c.AddClass(conformer.ToSingular(f.Name)+"Collection"); col.Parent = new TypeTypeDeclaration(typeof(System.Collections.CollectionBase)); // add serializable attribute col.CustomAttributes.Add(typeof(SerializableAttribute)); // default constructor col.AddConstructor(); // default indexer IndexerDeclaration index = col.AddIndexer( typeof(Object) ); ParameterDeclaration pindex = index.Signature.Parameters.Add(typeof(int),"index",false); // getter index.Get.Return( Expr.This.Prop("List").Item( Expr.Arg(pindex) ) ); index.Set.AddAssign( Expr.This.Prop("List").Item( Expr.Arg(pindex) ), Expr.Value ); // add object method MethodDeclaration addObject = col.AddMethod("Add"); ParameterDeclaration paraObject = addObject.Signature.Parameters.Add(new TypeTypeDeclaration(typeof(Object)),"o",true); addObject.Body.Add( Expr.This.Prop("List").Method("Add").Invoke(paraObject) ); // if typed array add methods for type if (f.FieldType.GetElementType()!=typeof(Object)) { AddCollectionMethods( col, MapType(f.FieldType.GetElementType()), this.conformer.ToCapitalized(f.FieldType.GetElementType().Name), "o" ); } foreach(XmlElementAttribute ea in f.GetCustomAttributes(typeof(XmlElementAttribute),true)) { string name = this.conformer.ToCapitalized(ea.ElementName); string pname= this.conformer.ToCamel(name); ITypeDeclaration mappedType = null; if (ea.Type!=null) mappedType = MapType(ea.Type); if (mappedType==null || mappedType == f.FieldType.GetElementType()) continue; AddCollectionMethods(col,mappedType,name,pname); } // add field FieldDeclaration fd = c.AddField(col, f.Name); fd.InitExpression = Expr.New( col ); PropertyDeclaration p = c.AddProperty(fd,f.Name,true,true,false); // setting attributes // attach xml text if (TypeHelper.HasCustomAttribute(f,typeof(XmlTextAttribute))) { AttributeDeclaration attr = p.CustomAttributes.Add(typeof(XmlTextAttribute)); attr.Arguments.Add("Type",Expr.TypeOf(typeof(string))); // adding to string to collection MethodDeclaration tostring = col.AddMethod("ToString"); tostring.Signature.ReturnType = new TypeTypeDeclaration(typeof(String)); tostring.Attributes = MemberAttributes.Public | MemberAttributes.Override; VariableDeclarationStatement sw = Stm.Var(typeof(StringWriter),"sw"); sw.InitExpression = Expr.New(typeof(StringWriter)); tostring.Body.Add(sw); ForEachStatement fe = Stm.ForEach( typeof(string),"s",Expr.This.Prop("List"),false); fe.Body.Add( Expr.Var(sw).Method("Write").Invoke(fe.Local) ); tostring.Body.Add(fe); tostring.Body.Return(Expr.Var(sw).Method("ToString").Invoke()); } else if (TypeHelper.HasCustomAttribute(f,typeof(XmlArrayItemAttribute))) { // add xml array attribute AttributeDeclaration attr = p.CustomAttributes.Add(typeof(XmlArrayAttribute)); attr.Arguments.Add("ElementName",Expr.Prim(f.Name)); // add array item attribute XmlArrayItemAttribute arrayItem = (XmlArrayItemAttribute)TypeHelper.GetFirstCustomAttribute(f,typeof(XmlArrayItemAttribute)); attr = p.CustomAttributes.Add(typeof(XmlArrayItemAttribute)); attr.Arguments.Add("ElementName",Expr.Prim(arrayItem.ElementName)); //MMI:attr.Arguments.Add("Type",Expr.Prim(MapType(f.FieldType.GetElementType()).Name)); attr.Arguments.Add("Type",Expr.TypeOf(MapType(f.FieldType.GetElementType()))); if (arrayItem.Type!=null) { attr.Arguments.Add("DataType",Expr.Prim(arrayItem.DataType)); } attr.Arguments.Add("IsNullable",Expr.Prim(arrayItem.IsNullable)); if (this.Config.KeepNamespaces) { attr.Arguments.Add("Namespace",Expr.Prim(arrayItem.Namespace)); } } else { AttachXmlElementAttributes(p,f); } } private void AddCollectionMethods(ClassDeclaration col, ITypeDeclaration mappedType, string name, string pname) { // add method MethodDeclaration add = col.AddMethod("Add"+name); ParameterDeclaration para = add.Signature.Parameters.Add(mappedType,pname,true); add.Body.Add( Expr.This.Prop("List").Method("Add").Invoke(para) ); // add method MethodDeclaration contains = col.AddMethod("Contains"+name); contains.Signature.ReturnType = new TypeTypeDeclaration(typeof(bool)); para = contains.Signature.Parameters.Add(mappedType,pname,true); contains.Body.Return( Expr.This.Prop("List").Method("Contains").Invoke(para) ); // add method MethodDeclaration remove = col.AddMethod("Remove"+name); para = remove.Signature.Parameters.Add(mappedType,pname,true); remove.Body.Add( Expr.This.Prop("List").Method("Remove").Invoke(para) ); } private void AddField(ClassDeclaration c, FieldInfo f) { if(c==null) throw new ArgumentNullException("c"); if (f==null) throw new ArgumentNullException("f"); FieldDeclaration fd = c.AddField(MapType(f.FieldType),f.Name); PropertyDeclaration p = c.AddProperty(fd,f.Name,true,true,false); // adding attributes if (TypeHelper.HasCustomAttribute(f,typeof(XmlAttributeAttribute))) { XmlAttributeAttribute att = (XmlAttributeAttribute)TypeHelper.GetFirstCustomAttribute(f,typeof(XmlAttributeAttribute)); AttributeDeclaration attr = p.CustomAttributes.Add(typeof(XmlAttributeAttribute)); string attrName = att.AttributeName; if (att.AttributeName.Length==0) attrName = f.Name; AttributeArgument arg = attr.Arguments.Add( "AttributeName", Expr.Prim(attrName) ); } else { if (TypeHelper.HasCustomAttribute(f,typeof(XmlElementAttribute))) { AttachXmlElementAttributes(p,f); } else { AttributeDeclaration attr = p.CustomAttributes.Add(typeof(XmlElementAttribute)); attr.Arguments.Add("ElementName",Expr.Prim(f.Name)); } } } private void AttachXmlElementAttributes(PropertyDeclaration p, FieldInfo f) { string customName = null; // if array is type add element if (f.FieldType.IsArray && f.FieldType.GetElementType()!=typeof(Object)) { AttributeDeclaration attr = p.CustomAttributes.Add(typeof(XmlElementAttribute)); attr.Arguments.Add("ElementName",Expr.Prim(f.Name)); //MMI:attr.Arguments.Add("Type",Expr.Prim(MapType(f.FieldType.GetElementType()).Name)); attr.Arguments.Add("Type",Expr.TypeOf(MapType(f.FieldType.GetElementType()))); customName = f.Name; } // attach xml elements foreach(XmlElementAttribute el in f.GetCustomAttributes(typeof(XmlElementAttribute),true)) { if (customName == el.ElementName) continue; AttributeDeclaration attr = p.CustomAttributes.Add(typeof(XmlElementAttribute)); attr.Arguments.Add("ElementName",Expr.Prim(el.ElementName)); if (el.Type!=null) { //MMI:attr.Arguments.Add("Type",Expr.Prim(MapType(el.Type).Name)); attr.Arguments.Add("Type",Expr.TypeOf(MapType(el.Type))); } } } private void GenerateDefaultConstructor(ClassDeclaration c) { ConstructorDeclaration cd = new ConstructorDeclaration(c); } private ITypeDeclaration MapType(string t) { if (t==null) throw new ArgumentNullException("t"); Type type = Type.GetType(t,true); return MapType(type); } private ITypeDeclaration MapType(Type t) { if (t==null) throw new ArgumentNullException("t"); if (this.types.Contains(t)) return this.types[t]; else return new TypeTypeDeclaration(t); } } }
// Copyright 2020 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 // // 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 CommandLine; using Google.Ads.GoogleAds.Lib; using Google.Ads.GoogleAds.V10.Errors; using Google.Ads.GoogleAds.V10.Services; using System; using System.Collections.Generic; using static Google.Ads.GoogleAds.V10.Enums.ConversionAdjustmentTypeEnum.Types; namespace Google.Ads.GoogleAds.Examples.V10 { /// <summary> /// This code example imports conversion adjustments for conversions that already exist. /// To set up a conversion action, run AddConversionAction.cs. /// </summary> public class UploadConversionAdjustment : ExampleBase { /// <summary> /// Command line options for running the <see cref="UploadConversionAdjustment"/> example. /// </summary> public class Options : OptionsBase { /// <summary> /// The Google Ads customer ID for which the conversion action is added. /// </summary> [Option("customerId", Required = true, HelpText = "The Google Ads customer ID for which the conversion action is added.")] public long CustomerId { get; set; } /// <summary> /// ID of the conversion action for which adjustments are uploaded. /// </summary> [Option("conversionActionId", Required = true, HelpText = "ID of the conversion action for which adjustments are uploaded.")] public long ConversionActionId { get; set; } /// <summary> /// The type of adjustment. /// </summary> [Option("adjustmentType", Required = true, HelpText = "The type of adjustment.")] public ConversionAdjustmentType AdjustmentType { get; set; } /// <summary> /// The original conversion time. /// </summary> [Option("conversionDateTime", Required = true, HelpText = "The original conversion time.")] public string ConversionDateTime { get; set; } /// <summary> /// The Google Click ID for which adjustments are uploaded. /// </summary> [Option("gclid", Required = true, HelpText = "The Google Click ID for which adjustments are uploaded.")] public string Gclid { get; set; } /// <summary> /// The adjustment date and time. /// </summary> [Option("adjustmentDateTime", Required = true, HelpText = "The adjustment date and time.")] public string AdjustmentDateTime { get; set; } /// <summary> /// The restatement value. /// </summary> [Option("restatementValue", Required = true, HelpText = "The restatement value.")] public double? RestatementValue { get; set; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { Options options = new Options(); CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult( delegate (Options o) { options = o; return 0; }, delegate (IEnumerable<Error> errors) { // The Google Ads customer ID for which the conversion action is added. options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE"); // ID of the conversion action for which adjustments are uploaded. options.ConversionActionId = long.Parse("INSERT_CONVERSION_ACTION_ID_HERE"); // The type of adjustment. options.AdjustmentType = (ConversionAdjustmentType) Enum.Parse( typeof(ConversionAdjustmentType), "INSERT_ADJUSTMENT_TYPE_HERE"); // The original conversion time. options.ConversionDateTime = "INSERT_CONVERSION_DATE_TIME_HERE"; // The Google Click ID for which adjustments are uploaded. options.Gclid = "INSERT_GCLID_HERE"; // The adjustment time in "yyyy-mm-dd hh:mm:ss+|-hh:mm" format. options.AdjustmentDateTime = "INSERT_ADJUSTMENT_DATE_TIME_HERE"; // The restatement value. options.RestatementValue = double.Parse("INSERT_RESTATEMENT_VALUE_HERE"); return 0; }); UploadConversionAdjustment codeExample = new UploadConversionAdjustment(); Console.WriteLine(codeExample.Description); codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.ConversionActionId, options.Gclid, options.ConversionDateTime, options.AdjustmentDateTime, options.AdjustmentType, options.RestatementValue); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description => "This code example imports conversion adjustments for conversions that already " + "exist. To set up a conversion action, run AddConversionAction.cs."; /// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the conversion action is /// added.</param> /// <param name="conversionActionId">ID of the conversion action for which adjustments are /// uploaded.</param> /// <param name="adjustmentType">The type of adjustment.</param> /// <param name="conversionDateTime">The original conversion time.</param> /// <param name="gclid">The Google Click ID for which adjustments are uploaded.</param> /// <param name="adjustmentDateTime">The adjustment date and time.</param> /// <param name="restatementValue">The restatement value.</param> // [START upload_conversion_adjustment] public void Run(GoogleAdsClient client, long customerId, long conversionActionId, string gclid, string conversionDateTime, string adjustmentDateTime, ConversionAdjustmentType adjustmentType, double? restatementValue) { // Get the ConversionAdjustmentUploadService. ConversionAdjustmentUploadServiceClient conversionAdjustmentUploadService = client.GetService(Services.V10.ConversionAdjustmentUploadService); // Associate conversion adjustments with the existing conversion action. // The GCLID should have been uploaded before with a conversion. ConversionAdjustment conversionAdjustment = new ConversionAdjustment() { ConversionAction = ResourceNames.ConversionAction(customerId, conversionActionId), AdjustmentType = adjustmentType, GclidDateTimePair = new GclidDateTimePair() { Gclid = gclid, ConversionDateTime = conversionDateTime, }, AdjustmentDateTime = adjustmentDateTime, }; // Set adjusted value for adjustment type RESTATEMENT. if (adjustmentType == ConversionAdjustmentType.Restatement) { conversionAdjustment.RestatementValue = new RestatementValue() { AdjustedValue = restatementValue.Value }; } try { // Issue a request to upload the conversion adjustment. UploadConversionAdjustmentsResponse response = conversionAdjustmentUploadService.UploadConversionAdjustments( new UploadConversionAdjustmentsRequest() { CustomerId = customerId.ToString(), ConversionAdjustments = { conversionAdjustment }, PartialFailure = true, ValidateOnly = false }); ConversionAdjustmentResult result = response.Results[0]; // Print the result. Console.WriteLine($"Uploaded conversion adjustment value of" + $" '{result.ConversionAction}' for Google Click ID " + $"'{result.GclidDateTimePair.Gclid}'"); } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } } // [END upload_conversion_adjustment] } }
// // In order to convert some functionality to Visual C#, the Java Language Conversion Assistant // creates "support classes" that duplicate the original functionality. // // Support classes replicate the functionality of the original code, but in some cases they are // substantially different architecturally. Although every effort is made to preserve the // original architecture of the application in the converted project, the user should be aware that // the primary goal of these support classes is to replicate functionality, and that at times // the architecture of the resulting solution may differ somewhat. // using System; using System.Collections.Generic; /// <summary> /// Contains conversion support elements such as classes, interfaces and static methods. /// </summary> public class SupportClass { /// <summary> /// Converts an array of sbytes to an array of bytes /// </summary> /// <param name="sbyteArray">The array of sbytes to be converted</param> /// <returns>The new array of bytes</returns> public static byte[] ToByteArray(sbyte[] sbyteArray) { byte[] byteArray = null; if (sbyteArray != null) { byteArray = new byte[sbyteArray.Length]; for(int index=0; index < sbyteArray.Length; index++) byteArray[index] = (byte) sbyteArray[index]; } return byteArray; } /// <summary> /// Converts a string to an array of bytes /// </summary> /// <param name="sourceString">The string to be converted</param> /// <returns>The new array of bytes</returns> public static byte[] ToByteArray(System.String sourceString) { return System.Text.UTF8Encoding.UTF8.GetBytes(sourceString); } /// <summary> /// Converts a array of object-type instances to a byte-type array. /// </summary> /// <param name="tempObjectArray">Array to convert.</param> /// <returns>An array of byte type elements.</returns> public static byte[] ToByteArray(System.Object[] tempObjectArray) { byte[] byteArray = null; if (tempObjectArray != null) { byteArray = new byte[tempObjectArray.Length]; for (int index = 0; index < tempObjectArray.Length; index++) byteArray[index] = (byte)tempObjectArray[index]; } return byteArray; } /*******************************/ /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static int URShift(int number, int bits) { if ( number >= 0) return number >> bits; else return (number >> bits) + (2 << ~bits); } /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static int URShift(int number, long bits) { return URShift(number, (int)bits); } /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static long URShift(long number, int bits) { if ( number >= 0) return number >> bits; else return (number >> bits) + (2L << ~bits); } /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static long URShift(long number, long bits) { return URShift(number, (int)bits); } /*******************************/ /// <summary> /// This method returns the literal value received /// </summary> /// <param name="literal">The literal to return</param> /// <returns>The received value</returns> public static long Identity(long literal) { return literal; } /// <summary> /// This method returns the literal value received /// </summary> /// <param name="literal">The literal to return</param> /// <returns>The received value</returns> public static ulong Identity(ulong literal) { return literal; } /// <summary> /// This method returns the literal value received /// </summary> /// <param name="literal">The literal to return</param> /// <returns>The received value</returns> public static float Identity(float literal) { return literal; } /// <summary> /// This method returns the literal value received /// </summary> /// <param name="literal">The literal to return</param> /// <returns>The received value</returns> public static double Identity(double literal) { return literal; } /*******************************/ /// <summary> /// Copies an array of chars obtained from a String into a specified array of chars /// </summary> /// <param name="sourceString">The String to get the chars from</param> /// <param name="sourceStart">Position of the String to start getting the chars</param> /// <param name="sourceEnd">Position of the String to end getting the chars</param> /// <param name="destinationArray">Array to return the chars</param> /// <param name="destinationStart">Position of the destination array of chars to start storing the chars</param> /// <returns>An array of chars</returns> public static void GetCharsFromString(System.String sourceString, int sourceStart, int sourceEnd, char[] destinationArray, int destinationStart) { int sourceCounter; int destinationCounter; sourceCounter = sourceStart; destinationCounter = destinationStart; while (sourceCounter < sourceEnd) { destinationArray[destinationCounter] = (char) sourceString[sourceCounter]; sourceCounter++; destinationCounter++; } } /*******************************/ /// <summary> /// Sets the capacity for the specified ArrayList /// </summary> /// <param name="vector">The ArrayList which capacity will be set</param> /// <param name="newCapacity">The new capacity value</param> public static void SetCapacity(List<object> vector, int newCapacity) { if (newCapacity > vector.Count) vector.AddRange(new Array[newCapacity-vector.Count]); else if (newCapacity < vector.Count) vector.RemoveRange(newCapacity, vector.Count - newCapacity); vector.Capacity = newCapacity; } /*******************************/ /// <summary> /// Receives a byte array and returns it transformed in an sbyte array /// </summary> /// <param name="byteArray">Byte array to process</param> /// <returns>The transformed array</returns> public static sbyte[] ToSByteArray(byte[] byteArray) { sbyte[] sbyteArray = null; if (byteArray != null) { sbyteArray = new sbyte[byteArray.Length]; for(int index=0; index < byteArray.Length; index++) sbyteArray[index] = (sbyte) byteArray[index]; } return sbyteArray; } }
// <copyright file="TurnBasedMultiplayerManager.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if UNITY_ANDROID namespace GooglePlayGames.Native.Cwrapper { using System; using System.Runtime.InteropServices; using System.Text; internal static class TurnBasedMultiplayerManager { internal delegate void TurnBasedMatchCallback( /* from(TurnBasedMultiplayerManager_TurnBasedMatchResponse_t) */ IntPtr arg0, /* from(void *) */ IntPtr arg1); internal delegate void MultiplayerStatusCallback( /* from(MultiplayerStatus_t) */ CommonErrorStatus.MultiplayerStatus arg0, /* from(void *) */ IntPtr arg1); internal delegate void TurnBasedMatchesCallback( /* from(TurnBasedMultiplayerManager_TurnBasedMatchesResponse_t) */ IntPtr arg0, /* from(void *) */ IntPtr arg1); internal delegate void MatchInboxUICallback( /* from(TurnBasedMultiplayerManager_MatchInboxUIResponse_t) */ IntPtr arg0, /* from(void *) */ IntPtr arg1); internal delegate void PlayerSelectUICallback( /* from(TurnBasedMultiplayerManager_PlayerSelectUIResponse_t) */ IntPtr arg0, /* from(void *) */ IntPtr arg1); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_ShowPlayerSelectUI( HandleRef self, /* from(uint32_t) */uint minimum_players, /* from(uint32_t) */uint maximum_players, [MarshalAs(UnmanagedType.I1)] /* from(bool) */ bool allow_automatch, /* from(TurnBasedMultiplayerManager_PlayerSelectUICallback_t) */PlayerSelectUICallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_CancelMatch( HandleRef self, /* from(TurnBasedMatch_t) */IntPtr match, /* from(TurnBasedMultiplayerManager_MultiplayerStatusCallback_t) */MultiplayerStatusCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_DismissMatch( HandleRef self, /* from(TurnBasedMatch_t) */IntPtr match); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_ShowMatchInboxUI( HandleRef self, /* from(TurnBasedMultiplayerManager_MatchInboxUICallback_t) */MatchInboxUICallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_SynchronizeData( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_Rematch( HandleRef self, /* from(TurnBasedMatch_t) */IntPtr match, /* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_DismissInvitation( HandleRef self, /* from(MultiplayerInvitation_t) */IntPtr invitation); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_FetchMatch( HandleRef self, /* from(char const *) */string match_id, /* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_DeclineInvitation( HandleRef self, /* from(MultiplayerInvitation_t) */IntPtr invitation); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_FinishMatchDuringMyTurn( HandleRef self, /* from(TurnBasedMatch_t) */IntPtr match, /* from(uint8_t const *) */byte[] match_data, /* from(size_t) */UIntPtr match_data_size, /* from(ParticipantResults_t) */IntPtr results, /* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_FetchMatches( HandleRef self, /* from(TurnBasedMultiplayerManager_TurnBasedMatchesCallback_t) */TurnBasedMatchesCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_CreateTurnBasedMatch( HandleRef self, /* from(TurnBasedMatchConfig_t) */IntPtr config, /* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_AcceptInvitation( HandleRef self, /* from(MultiplayerInvitation_t) */IntPtr invitation, /* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_TakeMyTurn( HandleRef self, /* from(TurnBasedMatch_t) */IntPtr match, /* from(uint8_t const *) */byte[] match_data, /* from(size_t) */UIntPtr match_data_size, /* from(ParticipantResults_t) */IntPtr results, /* from(MultiplayerParticipant_t) */IntPtr next_participant, /* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_ConfirmPendingCompletion( HandleRef self, /* from(TurnBasedMatch_t) */IntPtr match, /* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_LeaveMatchDuringMyTurn( HandleRef self, /* from(TurnBasedMatch_t) */IntPtr match, /* from(MultiplayerParticipant_t) */IntPtr next_participant, /* from(TurnBasedMultiplayerManager_MultiplayerStatusCallback_t) */MultiplayerStatusCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_LeaveMatchDuringTheirTurn( HandleRef self, /* from(TurnBasedMatch_t) */IntPtr match, /* from(TurnBasedMultiplayerManager_MultiplayerStatusCallback_t) */MultiplayerStatusCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_TurnBasedMatchResponse_Dispose( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(MultiplayerStatus_t) */ CommonErrorStatus.MultiplayerStatus TurnBasedMultiplayerManager_TurnBasedMatchResponse_GetStatus( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(TurnBasedMatch_t) */ IntPtr TurnBasedMultiplayerManager_TurnBasedMatchResponse_GetMatch( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_TurnBasedMatchesResponse_Dispose( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(MultiplayerStatus_t) */ CommonErrorStatus.MultiplayerStatus TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetStatus( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(size_t) */ UIntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetInvitations_Length( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(MultiplayerInvitation_t) */ IntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetInvitations_GetElement( HandleRef self, /* from(size_t) */UIntPtr index); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(size_t) */ UIntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetMyTurnMatches_Length( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(TurnBasedMatch_t) */ IntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetMyTurnMatches_GetElement( HandleRef self, /* from(size_t) */UIntPtr index); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(size_t) */ UIntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetTheirTurnMatches_Length( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(TurnBasedMatch_t) */ IntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetTheirTurnMatches_GetElement( HandleRef self, /* from(size_t) */UIntPtr index); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(size_t) */ UIntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetCompletedMatches_Length( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(TurnBasedMatch_t) */ IntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetCompletedMatches_GetElement( HandleRef self, /* from(size_t) */UIntPtr index); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_MatchInboxUIResponse_Dispose( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(UIStatus_t) */ CommonErrorStatus.UIStatus TurnBasedMultiplayerManager_MatchInboxUIResponse_GetStatus( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(TurnBasedMatch_t) */ IntPtr TurnBasedMultiplayerManager_MatchInboxUIResponse_GetMatch( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_PlayerSelectUIResponse_Dispose( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(UIStatus_t) */ CommonErrorStatus.UIStatus TurnBasedMultiplayerManager_PlayerSelectUIResponse_GetStatus( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(size_t) */ UIntPtr TurnBasedMultiplayerManager_PlayerSelectUIResponse_GetPlayerIds_Length( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(size_t) */ UIntPtr TurnBasedMultiplayerManager_PlayerSelectUIResponse_GetPlayerIds_GetElement( HandleRef self, /* from(size_t) */UIntPtr index, [In, Out] /* from(char *) */byte[] out_arg, /* from(size_t) */UIntPtr out_size); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(uint32_t) */ uint TurnBasedMultiplayerManager_PlayerSelectUIResponse_GetMinimumAutomatchingPlayers( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(uint32_t) */ uint TurnBasedMultiplayerManager_PlayerSelectUIResponse_GetMaximumAutomatchingPlayers( HandleRef self); } } #endif //UNITY_ANDROID
// Copyright (c) 2015 fjz13. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Design; using System.IO; using System.Windows.Forms.Design; using GameKit.Packing; using GameKit.UI; using Medusa.CoreProto; using Version = System.Version; namespace GameKit.Publish { public class PublishTarget { public static PublishTarget Current = new PublishTarget(); public PublishTarget() { Platform = PublishPlatform.Win; Device = PublishDevices.all; Language = PublishLanguages.all; Version = PublishVersions.all; IsOptimzed = true; IsRecursively = true; IsGenerateUpdateServer = false; IsGuidName = false; LimitSize = Size.Empty; ClientVersion = new Version(1,0); IsPVR = true; UpdateServerStatus = UpdateServer.UpdateServerStatus.OK; UpdateServerMinClientVersion = new Version(1,0); IsGod = false; IsCacheEnabled = false; } [Category("??"), Description("??????,????")] public bool IsGod { get; set; } [Category("??"), Description("??????,?????????,?????????PVR")] public bool IsCacheEnabled { get; set; } [Category("PVR"), Description("?????PVR?????")] public bool IsPVR { get; set; } [Category("PVR"), Description("PVR??")] public string PVRFormat { get { if (Platform == PublishPlatform.Android) { return "PVRTC1_4"; } if (Platform == PublishPlatform.IOS) { return "PVRTC1_4"; } return "PVRTC1_4"; } } [Category("PVR"), Description("PVR??")] public PVRQuality PVRQuality { get; set; } [Category("??"), Description("?????")] [TypeConverter(typeof(FlagsEnumConverter))] public PublishPlatform Platform { get; set; } [Category("??"), Description("????")] [TypeConverter(typeof(FlagsEnumConverter))] public PublishDevices Device { get; set; } [Category("??"), Description("??")] [TypeConverter(typeof(FlagsEnumConverter))] public PublishLanguages Language { get; set; } [Category("??"), Description("??")] [TypeConverter(typeof(FlagsEnumConverter))] public PublishVersions Version { get; set; } [Category("??"), Description("?????0,0???????????")] public Size LimitSize { get; set; } private bool mIsPOT = false; [Category("??"), Description("???????????2??")] public bool IsPOT { get { if (IsPVR) { return true; } return mIsPOT; } set { mIsPOT = value; } } private bool mIsSquare = false; [Category("??"), Description("????????????")] public bool IsSquare { get { if (IsPVR) { return true; } return mIsSquare; } set { mIsSquare = value; } } private bool mIsOptimzed = false; [Category("??"), Description("??????????????")] public bool IsOptimzed { get { //if (IsPVR) //{ // return true; //} return mIsOptimzed; } set { mIsOptimzed = value; } } [Category("??"), Description("???????????")] public bool IsGenerateUpdateServer { get; set; } [Category("??"), Description("????Android?????")] public bool IsGenerateAndroid { get { return (Platform & PublishPlatform.Android) != 0; } } private bool mIsPack = true; [Category("??"), Description("??????")] public bool IsPack { get { if (IsPVR) { return true; } return mIsPack; } set { mIsPack = value; } } [Category("??"), Description("????")] public bool IsEncrypt { get; set; } [Category("??"), Description("????")] public bool IsCompress { get; set; } [Category("??"), Description("???????????")] public Size DefaultImageSize { get { return new Size(128, 128); } } [Category("??"), Description("??????")] public Size MaxImageSize { get { if (LimitSize == Size.Empty) { if ((Device & PublishDevices.sd) == PublishDevices.sd || Device == PublishDevices.none) { return new Size(512, 512); } if (Device == PublishDevices.hd) { return new Size(1024, 1024); } if ((Platform & PublishPlatform.Android) != 0) { return new Size(2048, 2048); } return new Size(2048, 2048); } return LimitSize; } } [Category("??"), Description("???????")] public bool IsGuidName { get; set; } [Category("??"), Description("??")] public string DataPath { get { if (PathManager.DataPath == null) { return string.Empty; } return PathManager.DataPath.FullName; } } [Category("??"), Description("????")] public string InputPath { get { if (PathManager.InputPath == null) { return string.Empty; } return PathManager.InputPath.FullName; } } [Category("??"), Description("???????")] public bool IsRecursively { get; set; } [Category("??"), Description("????")] public string OutputPath { get { if (PathManager.OutputPath == null) { return string.Empty; } return PathManager.OutputPath.FullName; } } [Browsable(false)] public string FileSystemFileName { get; set; } [Browsable(false)] public string FileListFileName { get; set; } [Category("???"), Description("?????")] [TypeConverter(typeof(VersionConverter))] public Version ClientVersion { get; set; } [Category("?????"), Description("???????")] public UpdateServer.UpdateServerStatus UpdateServerStatus { get; set; } [Category("?????"), Description("???????????????")] [TypeConverter(typeof(VersionConverter))] public Version UpdateServerMinClientVersion { get; set; } [Category("?????"), Description("?????????")] public string UpdateServerPath { get { if (PathManager.UpdateServerPath == null) { return string.Empty; } return PathManager.UpdateServerPath.FullName; } } [Category("?????"), Description("??????????")] public string UpdateServerConfigFileName { get; set; } [Category("?????"), Description("?????????")] public string UpdateServerDescription { get; set; } [Category("?????"), Description("?????????")] public string GameServerPath { get { if (PathManager.GameServerPath == null) { return string.Empty; } return PathManager.GameServerPath.FullName; } } [Category("??"), Description("????????")] public string ProjectPath { get { if (PathManager.ProjectPath == null) { return string.Empty; } return PathManager.ProjectPath.FullName; } } [Category("??"), Description("????")] public string DevPath { get { if (PathManager.DevPath == null) { return string.Empty; } return PathManager.DevPath.FullName; } } [Category("??"), Description("???????")] //[Editor(typeof(FolderNameEditor), typeof(UITypeEditor))] public string RootPath { get { if (PathManager.RootPath == null) { return string.Empty; } return PathManager.RootPath.FullName; } //set //{ // PathManager.RootPath = new DirectoryInfo(value); //} } [Browsable(false)] public string FileSystemFilePath { get { return OutputPath + System.IO.Path.AltDirectorySeparatorChar + FileSystemFileName; } } [Browsable(false)] public string FileListFilePath { get { return OutputPath + System.IO.Path.AltDirectorySeparatorChar + FileListFileName; } } [Browsable(false)] public string ServerConfigFilePath { get { return UpdateServerPath + System.IO.Path.AltDirectorySeparatorChar + UpdateServerConfigFileName; } } [Browsable(false)] public PublishInfo PublishInfo { get { return new PublishInfo(Version, Device, Language); } } [Browsable(false)] public DirectoryInfo InputDirectoryInfo { get { return new DirectoryInfo(InputPath); } } [Browsable(false)] public DirectoryInfo OutputDirectoryInfo { get { return new DirectoryInfo(OutputPath); } } } }
// 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 Fixtures.AcceptanceTestsAzureCompositeModelClient { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// InheritanceOperations operations. /// </summary> internal partial class InheritanceOperations : IServiceOperations<AzureCompositeModel>, IInheritanceOperations { /// <summary> /// Initializes a new instance of the InheritanceOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal InheritanceOperations(AzureCompositeModel client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AzureCompositeModel /// </summary> public AzureCompositeModel Client { get; private set; } /// <summary> /// Get complex types that extend others /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Siamese>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/inheritance/valid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Siamese>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Siamese>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put complex types that extend others /// </summary> /// <param name='complexBody'> /// Please put a siamese with id=2, name="Siameee", color=green, /// breed=persion, which hates 2 dogs, the 1st one named "Potato" with id=1 /// and food="tomato", and the 2nd one named "Tomato" with id=-1 and /// food="french fries". /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PutValidWithHttpMessagesAsync(Siamese complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/inheritance/valid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(complexBody != null) { _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// // X509CertificateBuilder.cs: Handles building of X.509 certificates. // // Author: // Sebastien Pouliot <[email protected]> // // (C) 2003 Motus Technologies Inc. (http://www.motus.com) // (C) 2004 Novell (http://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. // using System; using System.Security.Cryptography; namespace Mono.Security.X509 { // From RFC3280 /* * Certificate ::= SEQUENCE { * tbsCertificate TBSCertificate, * signatureAlgorithm AlgorithmIdentifier, * signature BIT STRING * } * TBSCertificate ::= SEQUENCE { * version [0] Version DEFAULT v1, * serialNumber CertificateSerialNumber, * signature AlgorithmIdentifier, * issuer Name, * validity Validity, * subject Name, * subjectPublicKeyInfo SubjectPublicKeyInfo, * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL, * -- If present, version MUST be v2 or v3 * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL, * -- If present, version MUST be v2 or v3 * extensions [3] Extensions OPTIONAL * -- If present, version MUST be v3 -- * } * Version ::= INTEGER { v1(0), v2(1), v3(2) } * CertificateSerialNumber ::= INTEGER * Validity ::= SEQUENCE { * notBefore Time, * notAfter Time * } * Time ::= CHOICE { * utcTime UTCTime, * generalTime GeneralizedTime * } */ internal class X509CertificateBuilder : X509Builder { private byte version; private byte[] sn; private string issuer; private DateTime notBefore; private DateTime notAfter; private string subject; private AsymmetricAlgorithm aa; private byte[] issuerUniqueID; private byte[] subjectUniqueID; private X509ExtensionCollection extensions; public X509CertificateBuilder () : this (3) {} public X509CertificateBuilder (byte version) { if (version > 3) throw new ArgumentException ("Invalid certificate version"); this.version = version; extensions = new X509ExtensionCollection (); } public byte Version { get { return version; } set { version = value; } } public byte[] SerialNumber { get { return sn; } set { sn = value; } } public string IssuerName { get { return issuer; } set { issuer = value; } } public DateTime NotBefore { get { return notBefore; } set { notBefore = value; } } public DateTime NotAfter { get { return notAfter; } set { notAfter = value; } } public string SubjectName { get { return subject; } set { subject = value; } } public AsymmetricAlgorithm SubjectPublicKey { get { return aa; } set { aa = value; } } public byte[] IssuerUniqueId { get { return issuerUniqueID; } set { issuerUniqueID = value; } } public byte[] SubjectUniqueId { get { return subjectUniqueID; } set { subjectUniqueID = value; } } public X509ExtensionCollection Extensions { get { return extensions; } } /* SubjectPublicKeyInfo ::= SEQUENCE { * algorithm AlgorithmIdentifier, * subjectPublicKey BIT STRING } */ private ASN1 SubjectPublicKeyInfo () { ASN1 keyInfo = new ASN1 (0x30); if (aa is RSA) { keyInfo.Add (PKCS7.AlgorithmIdentifier ("1.2.840.113549.1.1.1")); RSAParameters p = (aa as RSA).ExportParameters (false); /* RSAPublicKey ::= SEQUENCE { * modulus INTEGER, -- n * publicExponent INTEGER } -- e */ ASN1 key = new ASN1 (0x30); key.Add (ASN1Convert.FromUnsignedBigInteger (p.Modulus)); key.Add (ASN1Convert.FromUnsignedBigInteger (p.Exponent)); keyInfo.Add (new ASN1 (UniqueIdentifier (key.GetBytes ()))); } else if (aa is DSA) { DSAParameters p = (aa as DSA).ExportParameters (false); /* Dss-Parms ::= SEQUENCE { * p INTEGER, * q INTEGER, * g INTEGER } */ ASN1 param = new ASN1 (0x30); param.Add (ASN1Convert.FromUnsignedBigInteger (p.P)); param.Add (ASN1Convert.FromUnsignedBigInteger (p.Q)); param.Add (ASN1Convert.FromUnsignedBigInteger (p.G)); keyInfo.Add (PKCS7.AlgorithmIdentifier ("1.2.840.10040.4.1", param)); ASN1 key = keyInfo.Add (new ASN1 (0x03)); // DSAPublicKey ::= INTEGER -- public key, y key.Add (ASN1Convert.FromUnsignedBigInteger (p.Y)); } else throw new NotSupportedException ("Unknown Asymmetric Algorithm " + aa.ToString ()); return keyInfo; } private byte[] UniqueIdentifier (byte[] id) { // UniqueIdentifier ::= BIT STRING ASN1 uid = new ASN1 (0x03); // first byte in a BITSTRING is the number of unused bits in the first byte byte[] v = new byte [id.Length + 1]; Buffer.BlockCopy (id, 0, v, 1, id.Length); uid.Value = v; return uid.GetBytes (); } protected override ASN1 ToBeSigned (string oid) { // TBSCertificate ASN1 tbsCert = new ASN1 (0x30); if (version > 1) { // TBSCertificate / [0] Version DEFAULT v1, byte[] ver = { (byte)(version - 1) }; ASN1 v = tbsCert.Add (new ASN1 (0xA0)); v.Add (new ASN1 (0x02, ver)); } // TBSCertificate / CertificateSerialNumber, tbsCert.Add (new ASN1 (0x02, sn)); // TBSCertificate / AlgorithmIdentifier, tbsCert.Add (PKCS7.AlgorithmIdentifier (oid)); // TBSCertificate / Name tbsCert.Add (X501.FromString (issuer)); // TBSCertificate / Validity ASN1 validity = tbsCert.Add (new ASN1 (0x30)); // TBSCertificate / Validity / Time validity.Add (ASN1Convert.FromDateTime (notBefore)); // TBSCertificate / Validity / Time validity.Add (ASN1Convert.FromDateTime (notAfter)); // TBSCertificate / Name tbsCert.Add (X501.FromString (subject)); // TBSCertificate / SubjectPublicKeyInfo tbsCert.Add (SubjectPublicKeyInfo ()); if (version > 1) { // TBSCertificate / [1] IMPLICIT UniqueIdentifier OPTIONAL if (issuerUniqueID != null) tbsCert.Add (new ASN1 (0xA1, UniqueIdentifier (issuerUniqueID))); // TBSCertificate / [2] IMPLICIT UniqueIdentifier OPTIONAL if (subjectUniqueID != null) tbsCert.Add (new ASN1 (0xA1, UniqueIdentifier (subjectUniqueID))); // TBSCertificate / [3] Extensions OPTIONAL if ((version > 2) && (extensions.Count > 0)) tbsCert.Add (new ASN1 (0xA3, extensions.GetBytes ())); } return tbsCert; } } }
using System; using FarseerGames.FarseerPhysics.Collisions; using FarseerGames.FarseerPhysics.Dynamics.Joints; using FarseerGames.FarseerPhysics.Dynamics.Springs; using FarseerGames.FarseerPhysics.Factories; #if(XNA) using Microsoft.Xna.Framework; #else using FarseerGames.FarseerPhysics.Mathematics; #endif namespace FarseerGames.FarseerPhysics.Dynamics { /// <summary> /// Path Generator. Used to create dynamic paths along control points. /// </summary> public class Path { private const float _controlPointSize = 6; // size of control point used in PointInControlPoint private const float _precision = 0.0005f; // a coeffient used to decide how precise to place bodies private GenericList<Body> _bodies; // holds all bodies for this path private Vertices _controlPoints; // holds all control points for this path private GenericList<Geom> _geoms; // holds all geoms for this path private GenericList<Spring> _springs; // holds all springs for this path private float _height; // width and height of bodies to create private GenericList<Joint> _joints; // holds all the joints for this path private bool _loop; // is this path a loop private float _mass; // mass of bodies to create private bool _recalculate = true; // will be set to true if path needs to be recalculated private float _width; // width and height of bodies to create private float _linkWidth; // distance between links. Decoupled from body width. /// <summary> /// Initializes a new instance of the <see cref="Path"/> class. /// </summary> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="mass">The mass.</param> /// <param name="endless">if set to <c>true</c> [endless].</param> public Path(float width, float height, float mass, bool endless) : this(width, height, width, mass, endless) { } /// <summary> /// Initializes a new instance of the <see cref="Path"/> class. /// </summary> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="linkWidth">The distance between links.</param> /// <param name="mass">The mass.</param> /// <param name="endless">if set to <c>true</c> [endless].</param> public Path(float width, float height, float linkWidth, float mass, bool endless) { _width = width; _linkWidth = linkWidth; _height = height; _loop = endless; _mass = mass; _geoms = new GenericList<Geom>(); _bodies = new GenericList<Body>(); _joints = new GenericList<Joint>(); _springs = new GenericList<Spring>(); _controlPoints = new Vertices(); } /// <summary> /// Gets the bodies. /// </summary> /// <Value>The bodies.</Value> public GenericList<Body> Bodies { get { return _bodies; } } /// <summary> /// Gets the joints. /// </summary> /// <Value>The joints.</Value> public GenericList<Joint> Joints { get { return _joints; } } /// <summary> /// Gets the geoms. /// </summary> /// <Value>The geoms.</Value> public GenericList<Geom> Geoms { get { return _geoms; } } /// <summary> /// Gets the springs. /// </summary> /// <Value>The springs.</Value> public GenericList<Spring> Springs { get { return _springs; } } /// <summary> /// Gets the control points. /// </summary> /// <Value>The control points.</Value> public Vertices ControlPoints { get { return _controlPoints; } } /// <summary> /// Links the bodies. /// </summary> /// <param name="type">The type of Joint to link with.</param> /// <param name="min">The min.</param> /// <param name="max">The max.</param> /// <param name="springConstant">The spring constant.</param> /// <param name="dampingConstant">The damping constant.</param> public void LinkBodies(LinkType type, float min, float max, float springConstant, float dampingConstant) { LinkBodies(type, min, max, springConstant, dampingConstant, 1f); } /// <summary> /// Links the bodies. /// </summary> /// <param name="type">The type of Joint to link with.</param> /// <param name="min">The min.</param> /// <param name="max">The max.</param> /// <param name="springConstant">The spring constant.</param> /// <param name="dampingConstant">The damping constant.</param> /// <param name="springRestLengthFactor">The spring rest length factor</param> public void LinkBodies(LinkType type, float min, float max, float springConstant, float dampingConstant, float springRestLengthFactor) { RevoluteJoint revoluteJoint; PinJoint pinJoint, d; SliderJoint sliderJoint; LinearSpring linearSpring, a; Vector2 midPoint; float midDeltaX; float midDeltaY; for (int i = 0; i < _bodies.Count; i++) { if (i < _bodies.Count - 1) { if (_bodies[i].position.X < _bodies[i + 1].position.X) { midDeltaX = Math.Abs(_bodies[i].position.X - _bodies[i + 1].position.X) * 0.5f; // find x axis midpoint } else { midDeltaX = (_bodies[i + 1].position.X - _bodies[i].position.X) * 0.5f; // find x axis midpoint } if (_bodies[i].position.Y < _bodies[i + 1].position.Y) { midDeltaY = Math.Abs(_bodies[i].position.Y - _bodies[i + 1].position.Y) * 0.5f; // find x axis midpoint } else { midDeltaY = (_bodies[i + 1].position.Y - _bodies[i].position.Y) * 0.5f; // find x axis midpoint } midPoint = new Vector2(_bodies[i].position.X + midDeltaX, _bodies[i].position.Y + midDeltaY); // set midPoint switch (type) { case LinkType.RevoluteJoint: revoluteJoint = JointFactory.Instance.CreateRevoluteJoint(_bodies[i], _bodies[i + 1], midPoint); revoluteJoint.BiasFactor = 0.2f; revoluteJoint.Softness = 0.01f; _joints.Add(revoluteJoint); break; case LinkType.LinearSpring: if (_bodies[i].Position.X < _bodies[i + 1].Position.X) { linearSpring = SpringFactory.Instance.CreateLinearSpring(_bodies[i], new Vector2(_width / 2.0f, 0), _bodies[i + 1], new Vector2(-_width / 2.0f, 0), springConstant, dampingConstant); } else { linearSpring = SpringFactory.Instance.CreateLinearSpring(_bodies[i], new Vector2(-_width / 2.0f, 0), _bodies[i + 1], new Vector2(_width / 2.0f, 0), springConstant, dampingConstant); } if (i >= 1) { a = (LinearSpring)_springs[i - 1]; linearSpring.RestLength = Vector2.Distance(a.AttachPoint2, linearSpring.AttachPoint1) * springRestLengthFactor; } _springs.Add(linearSpring); break; case LinkType.PinJoint: if (_bodies[i].Position.X < _bodies[i + 1].Position.X) { pinJoint = JointFactory.Instance.CreatePinJoint(_bodies[i], new Vector2(_width / 2.0f, 0), _bodies[i + 1], new Vector2(-_width / 2.0f, 0)); } else { pinJoint = JointFactory.Instance.CreatePinJoint(_bodies[i], new Vector2(-_width / 2.0f, 0), _bodies[i + 1], new Vector2(_width / 2.0f, 0)); } pinJoint.BiasFactor = 0.2f; pinJoint.Softness = 0.01f; if (i >= 1) { d = (PinJoint)_joints[i - 1]; pinJoint.TargetDistance = Vector2.Distance(d.Anchor2, pinJoint.Anchor1); } _joints.Add(pinJoint); break; case LinkType.SliderJoint: if (_bodies[i].Position.X < _bodies[i + 1].Position.X) { sliderJoint = JointFactory.Instance.CreateSliderJoint(_bodies[i], new Vector2(_width / 2.0f, 0), _bodies[i + 1], new Vector2(-_width / 2.0f, 0), min, max); } else { sliderJoint = JointFactory.Instance.CreateSliderJoint(_bodies[i], new Vector2(-_width / 2.0f, 0), _bodies[i + 1], new Vector2(_width / 2.0f, 0), min, max); } sliderJoint.BiasFactor = 0.2f; sliderJoint.Softness = 0.01f; _joints.Add(sliderJoint); break; default: //should never get here break; } } } if (_loop) { if (_bodies[0].position.X < _bodies[_bodies.Count - 1].position.X) { midDeltaX = Math.Abs(_bodies[0].position.X - _bodies[_bodies.Count - 1].position.X) * 0.5f; // find x axis midpoint } else { midDeltaX = (_bodies[_bodies.Count - 1].position.X - _bodies[0].position.X) * 0.5f; // find x axis midpoint } if (_bodies[0].position.Y < _bodies[_bodies.Count - 1].position.Y) { midDeltaY = Math.Abs(_bodies[0].position.Y - _bodies[_bodies.Count - 1].position.Y) * 0.5f; // find x axis midpoint } else { midDeltaY = (_bodies[_bodies.Count - 1].position.Y - _bodies[0].position.Y) * 0.5f; // find x axis midpoint } midPoint = new Vector2(_bodies[0].position.X + midDeltaX, _bodies[0].position.Y + midDeltaY); // set midPoint switch (type) { case LinkType.RevoluteJoint: revoluteJoint = JointFactory.Instance.CreateRevoluteJoint(_bodies[0], _bodies[_bodies.Count - 1], midPoint); revoluteJoint.BiasFactor = 0.2f; revoluteJoint.Softness = 0.01f; _joints.Add(revoluteJoint); break; case LinkType.LinearSpring: linearSpring = SpringFactory.Instance.CreateLinearSpring(_bodies[0], new Vector2(-_width / 2.0f, 0), _bodies[_bodies.Count - 1], new Vector2(_width / 2.0f, 0), springConstant, dampingConstant); linearSpring.RestLength = _width; _springs.Add(linearSpring); break; case LinkType.PinJoint: pinJoint = JointFactory.Instance.CreatePinJoint(_bodies[0], new Vector2(-_width / 2.0f, 0), _bodies[_bodies.Count - 1], new Vector2(_width / 2.0f, 0)); pinJoint.BiasFactor = 0.2f; pinJoint.Softness = 0.01f; pinJoint.TargetDistance = _width; _joints.Add(pinJoint); break; case LinkType.SliderJoint: sliderJoint = JointFactory.Instance.CreateSliderJoint(_bodies[0], new Vector2(-_width / 2.0f, 0), _bodies[_bodies.Count - 1], new Vector2(_width / 2.0f, 0), min, max); sliderJoint.BiasFactor = 0.2f; sliderJoint.Softness = 0.01f; _joints.Add(sliderJoint); break; default: //should never get here break; } } } /// <summary> /// Adds to physics simulator. /// </summary> /// <param name="physicsSimulator">The physics simulator.</param> public void AddToPhysicsSimulator(PhysicsSimulator physicsSimulator) { foreach (Body body in _bodies) physicsSimulator.Add(body); foreach (Geom geom in _geoms) physicsSimulator.Add(geom); foreach (Joint joint in _joints) physicsSimulator.Add(joint); foreach (Spring spring in _springs) physicsSimulator.Add(spring); } /// <summary> /// Creates rectangular geoms that match the size of the bodies. /// Then adds the geometries to the given physics simulator. /// </summary> /// <param name="physicsSimulator">The physics simulator.</param> /// <param name="collisionGroup">The collision group.</param> public void CreateGeoms(PhysicsSimulator physicsSimulator, int collisionGroup) { CreateGeoms(collisionGroup); foreach (Geom geom in _geoms) { physicsSimulator.Add(geom); } } /// <summary> /// Creates rectangular geoms that match the size of the bodies. /// </summary> /// <param name="collisionGroup">The collision group.</param> public void CreateGeoms(int collisionGroup) { foreach (Body body in _bodies) { Geom geom = GeomFactory.Instance.CreateRectangleGeom(body, _width, _height); geom.CollisionGroup = collisionGroup; _geoms.Add(geom); } } /// <summary> /// Creates rectangular geoms that match the size of the bodies. /// Then adds the geometries to the given physics simulator. /// </summary> /// <param name="collisionCategory">The collision category of the geometries.</param> /// <param name="collidesWith">The collisioncategory the geometries should collide with..</param> /// <param name="physicsSimulator">The physics simulator.</param> public void CreateGeoms(CollisionCategory collisionCategory, CollisionCategory collidesWith, PhysicsSimulator physicsSimulator) { CreateGeoms(collisionCategory, collidesWith); foreach (Geom geom in _geoms) { physicsSimulator.Add(geom); } } /// <summary> /// Creates rectangular geoms that match the size of the bodies. /// </summary> /// <param name="collisionCategory">The collision category.</param> /// <param name="collidesWith">What collision group geometries collides with.</param> public void CreateGeoms(CollisionCategory collisionCategory, CollisionCategory collidesWith) { foreach (Body body in _bodies) { Geom geom = GeomFactory.Instance.CreateRectangleGeom(body, _width, _height); geom.CollisionCategories = collisionCategory; geom.CollidesWith = collidesWith; _geoms.Add(geom); } } // This is used in my editing application. /// <summary> /// Gets index of control point if point is inside it. /// </summary> /// <param name="point">Point to test against.</param> /// <returns>Index of control point or -1 if no intersection.</returns> public int PointInControlPoint(Vector2 point) { AABB controlPointAABB; foreach (Vector2 controlPoint in _controlPoints) { controlPointAABB = new AABB( new Vector2(controlPoint.X - (_controlPointSize / 2), controlPoint.Y - (_controlPointSize / 2)), new Vector2(controlPoint.X + (_controlPointSize / 2), controlPoint.Y + (_controlPointSize / 2))); if (controlPointAABB.Contains(ref point)) return _controlPoints.IndexOf(controlPoint); } return -1; } /// <summary> /// Moves a control point. /// </summary> /// <param name="position">The position.</param> /// <param name="index">The index.</param> public void MoveControlPoint(Vector2 position, int index) { _controlPoints[index] = position; _recalculate = true; } /// <summary> /// Adds a control point to the paths end. /// </summary> /// <param name="controlPoint">Vector2 to add.</param> public void Add(Vector2 controlPoint) { _controlPoints.Add(controlPoint); // then add it _recalculate = true; // be sure to recalculate the curve } /// <summary> /// Adds the specified body. /// </summary> /// <param name="body">The body.</param> public void Add(Body body) { _bodies.Add(body); } /// <summary> /// Adds the specified geom. /// </summary> /// <param name="geom">The geom.</param> public void Add(Geom geom) { _geoms.Add(geom); } /// <summary> /// Adds the specified joint. /// </summary> /// <param name="joint">The joint.</param> public void Add(Joint joint) { _joints.Add(joint); } /// <summary> /// Adds the specified spring. /// </summary> /// <param name="spring">The spring.</param> public void Add(Spring spring) { _springs.Add(spring); } /// <summary> /// Removes a control point from the path. /// </summary> /// <param name="controlPoint">Vector2 to remove.</param> public void Remove(Vector2 controlPoint) { _controlPoints.Remove(controlPoint); _recalculate = true; // be sure to recalculate the curve } /// <summary> /// Removes a control point from the path by index. /// </summary> /// <param name="index">Index of Vector2 to remove.</param> public void Remove(int index) { _controlPoints.RemoveAt(index); _recalculate = true; // be sure to recalculate the curve } /// <summary> /// Performs a complete update of the path. /// NOTE: should not be performed on a path /// in simulation. /// </summary> public void Update() { float distance = 0.0f; Body tempBody; Vector2 tempVectorA = new Vector2(); Vector2 tempVectorC = new Vector2(); if (_recalculate) // only do the update if something has changed { float k; // first we get our curve ready Curve xCurve = new Curve(); Curve yCurve = new Curve(); float curveIncrement = 1.0f / _controlPoints.Count; for (int i = 0; i < _controlPoints.Count; i++) // for all the control points { k = curveIncrement * (i + 1); xCurve.Keys.Add(new CurveKey(k, _controlPoints[i].X)); // set the keys for x and y yCurve.Keys.Add(new CurveKey(k, _controlPoints[i].Y)); // with a time from 0-1 } k = 0.0f; xCurve.ComputeTangents(CurveTangent.Smooth); // compute x tangents yCurve.ComputeTangents(CurveTangent.Smooth); // compute y tangents // next we find the first point at 1/2 the width because we are finding where the body's center will be placed while (distance < (_linkWidth / 2.0f)) // while the distance along the curve is <= to width / 2 { k += _precision; // we increment along the line at this precision coeffient tempVectorA = new Vector2(xCurve.Evaluate(k), yCurve.Evaluate(k)); distance = Vector2.Distance(_controlPoints[0], tempVectorA); // get the distance } while (distance < _linkWidth) // while the distance along the curve is <= to width / 2 { k += _precision; // we increment along the line at this precision coeffient tempVectorC = new Vector2(xCurve.Evaluate(k), yCurve.Evaluate(k)); distance = Vector2.Distance(_controlPoints[0], tempVectorC); // get the distance } tempBody = BodyFactory.Instance.CreateRectangleBody(_width, _height, _mass); // create the first body tempBody.Position = tempVectorA; tempBody.Rotation = FindNormalAngle(FindVertexNormal(_controlPoints[0], tempVectorA, tempVectorC)); // set the angle _bodies.Add(tempBody); // add the first body Vector2 tempVectorB = tempVectorA; // now that our first body is done we can start on all our other body's // since the curve was created with a time of 0-1 we can just stop creating bodies when k is 1 while (k < 1.0f) { distance = 0.0f; // next we find the first point at the width because we are finding where the body's center will be placed while ((distance < _linkWidth) && (k < 1.0f)) // while the distance along the curve is <= to width { k += _precision; // we increment along the line at this precision coeffient tempVectorA = new Vector2(xCurve.Evaluate(k), yCurve.Evaluate(k)); distance = Vector2.Distance(tempVectorA, tempVectorB); // get the distance } distance = 0.0f; while ((distance < _linkWidth) && (k < 1.0f)) // while the distance along the curve is <= to width { k += _precision; // we increment along the line at this precision coeffient tempVectorC = new Vector2(xCurve.Evaluate(k), yCurve.Evaluate(k)); distance = Vector2.Distance(tempVectorA, tempVectorC); // get the distance } tempBody = BodyFactory.Instance.CreateRectangleBody(_width, _height, _mass); // create the first body tempBody.Position = tempVectorA; tempBody.Rotation = FindNormalAngle(FindVertexNormal(tempVectorB, tempVectorA, tempVectorC)); // set the angle _bodies.Add(tempBody); // add all the rest of the bodies tempVectorB = tempVectorA; } MoveControlPoint(tempVectorC, _controlPoints.Count - 1); _recalculate = false; } } // NOTE: Below are some internal functions to find things like normals and angles. /// <summary> /// Finds the mid-point of two Vector2. /// </summary> /// <param name="firstVector">First Vector2.</param> /// <param name="secondVector">Other Vector2.</param> /// <returns>Mid-point Vector2.</returns> public static Vector2 FindMidpoint(Vector2 firstVector, Vector2 secondVector) { float midDeltaX, midDeltaY; if (firstVector.X < secondVector.X) midDeltaX = Math.Abs((firstVector.X - secondVector.X) * 0.5f); // find x axis midpoint else midDeltaX = (secondVector.X - firstVector.X) * 0.5f; // find x axis midpoint if (firstVector.Y < secondVector.Y) midDeltaY = Math.Abs((firstVector.Y - secondVector.Y) * 0.5f); // find y axis midpoint else midDeltaY = (secondVector.Y - firstVector.Y) * 0.5f; // find y axis midpoint return (new Vector2(firstVector.X + midDeltaX, firstVector.Y + midDeltaY)); // return mid point } /// <summary> /// Finds the angle of an edge. /// </summary> /// <param name="firstVector">First Vector2.</param> /// <param name="secondVector">Other Vector2.</param> /// <returns>Normal of the edge.</returns> private Vector2 FindEdgeNormal(Vector2 firstVector, Vector2 secondVector) { //Xbox360 need this variable to be initialized to Vector2.Zero Vector2 n = Vector2.Zero; Vector2 t = new Vector2(firstVector.X - secondVector.X, firstVector.Y - secondVector.Y); n.X = -t.Y; // get 2D normal n.Y = t.X; // works only on counter clockwise polygons return n; // we don't bother normalizing because we do this when we find the vertex normal } private Vector2 FindVertexNormal(Vector2 firstVector, Vector2 secondVector, Vector2 c) { Vector2 normal = FindEdgeNormal(firstVector, secondVector) + FindEdgeNormal(secondVector, c); normal.Normalize(); return normal; } private float FindNormalAngle(Vector2 n) { if ((n.Y > 0.0f) && (n.X > 0.0f)) return (float)Math.Atan(n.X / -n.Y); if ((n.Y < 0.0f) && (n.X > 0.0f)) return (float)Math.Atan(n.X / -n.Y); // good if ((n.Y > 0.0f) && (n.X < 0.0f)) return (float)Math.Atan(-n.X / n.Y); if ((n.Y < 0.0f) && (n.X < 0.0f)) return (float)Math.Atan(-n.X / n.Y); // good return 0.0f; } } }
using System; using System.Collections; using System.Collections.Generic; namespace /*<com>*/Finegamedesign.Utils { /** * Another option is an extension method. * In-case someone else already made a different extension method, * or the language has different syntax, I used static functions. * For examples of divergent syntax: * ActionScript: items.length * C#: items.Count * Python: len(items) * Some of these use different method names or property names in different languages. */ public sealed class DataUtil { // http://stackoverflow.com/questions/222598/how-do-i-clone-a-generic-list-in-c public static List<T> CloneList<T>(List<T> original) { return new List<T>(original); } public static int Length<T>(List<T> data) { return data.Count; } public static int Length<T, U>(Dictionary<T, U> items) { return items.Count; } public static int Length(ArrayList elements) { return elements.Count; } public static int Length(string text) { return text.Length; } public static void Clear(ArrayList items) { items.Clear(); } public static void Clear<T>(List<T> items) { items.Clear(); } /** * Is integer or single floating point. */ public static bool IsNumber(string text) { float n; return float.TryParse(text, out n); } /** * Is data type flat or a class or collection? */ public static bool IsFlat(object value) { return (bool)((value is string) || (value is float) || (value is int) || (null == value)); } public static ArrayList SplitToArrayList(string text, string delimiter) { return new ArrayList(Split(text, delimiter)); } /** * I wish C# API were as simple as JavaScript and Python: * http://stackoverflow.com/questions/1126915/how-do-i-split-a-string-by-a-multi-character-delimiter-in-c */ public static List<string> Split(string text, string delimiter) { if ("" == delimiter) { return SplitString(text); } else { string[] delimiters = new string[] {delimiter}; string[] parts = text.Split(delimiters, StringSplitOptions.None); List<string> list = new List<string>(parts); return list; } } /** * This was the most concise way I found to split a string without depending on a library. * In ActionScript splitting a string is concise: s.split(""); * C# has characters, which would be more efficient, though less portable. */ public static List<string> SplitString(string text) { List<string> letters = new List<string>(); char[] characters = text.ToCharArray(); for (int i = 0; i < characters.Length; i++) { letters.Add(characters[i].ToString()); } return letters; } // Without depending on LINQ or that each item is already a string. public static string Join(ArrayList items, string delimiter) { string[] parts = new string[items.Count]; for (int index = 0; index < items.Count; index++) { parts[index] = items[index].ToString(); } string joined = string.Join(delimiter, parts); return joined; } public static string Join(List<string> texts, string delimiter) { string[] parts = (string[]) texts.ToArray(); string joined = string.Join(delimiter, parts); return joined; } public static string Trim(string text) { return text.Trim(); } public static string Replace(string text, string from, string to) { return Join(Split(text, from), to); } public static string Join<T>(List<T> items, string delimiter) { string[] parts = new string[items.Count]; for (int i = 0; i < items.Count; i++) { parts[i] = items[i].ToString(); } string joined = string.Join(delimiter, parts); return joined; } public static T Pop<T>(List<T> items) { T item = (T)items[items.Count - 1]; items.RemoveAt(items.Count - 1); return item; } public static dynamic Pop(ArrayList items) { dynamic item = items[items.Count - 1]; items.RemoveAt(items.Count - 1); return item; } public static void RemoveAt<T>(List<T> items, int index) { items.RemoveAt(index); } public static void RemoveAt(ArrayList items, int index) { items.RemoveAt(index); } public static List<T> Slice<T>(List<T> items, int start, int end) { List<T> sliced = new List<T>(); for (int index = start; index < end; index++) { sliced.Add(items[index]); } return sliced; } public static ArrayList Slice(ArrayList items, int start, int end) { ArrayList sliced = new ArrayList(); for (int index = start; index < end; index++) { sliced.Add(items[index]); } return sliced; } public static T Shift<T>(List<T> items) { T item = (T)items[0]; items.RemoveAt(0); return item; } public static dynamic Shift(ArrayList items) { dynamic item = items[0]; items.RemoveAt(0); return item; } public static List<T> ToListItems<T>(T[] rest) { List<T> aList = new List<T>(); for (int i = 0; i < rest.Length; i++) { aList.Add(rest[i]); } return aList; } public static List<T> ToList<T>(params T[] rest) { List<T> aList = new List<T>(); for (int i = 0; i < rest.Length; i++) { aList.Add(rest[i]); } return aList; } public static List<T> ToListItems<T>(ArrayList elements) { List<T> aList = new List<T>(); for (int i = 0; i < elements.Count; i++) { aList.Add((T)elements[i]); } return aList; } public static ArrayList ToArrayList<T>(List<T> aList) { ArrayList items = new ArrayList(); for (int i = 0; i < aList.Count; i++) { aList.Add(aList[i]); } return items; } } }
using System; using System.Reactive.Linq; using Avalonia.Controls.Platform; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Input.Raw; using Avalonia.Input.TextInput; using Avalonia.Layout; using Avalonia.Logging; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.Styling; using Avalonia.Utilities; using Avalonia.VisualTree; using JetBrains.Annotations; namespace Avalonia.Controls { /// <summary> /// Base class for top-level widgets. /// </summary> /// <remarks> /// This class acts as a base for top level widget. /// It handles scheduling layout, styling and rendering as well as /// tracking the widget's <see cref="ClientSize"/>. /// </remarks> public abstract class TopLevel : ContentControl, IInputRoot, ILayoutRoot, IRenderRoot, ICloseable, IStyleHost, ILogicalRoot, ITextInputMethodRoot, IWeakSubscriber<ResourcesChangedEventArgs> { /// <summary> /// Defines the <see cref="ClientSize"/> property. /// </summary> public static readonly DirectProperty<TopLevel, Size> ClientSizeProperty = AvaloniaProperty.RegisterDirect<TopLevel, Size>(nameof(ClientSize), o => o.ClientSize); /// <summary> /// Defines the <see cref="FrameSize"/> property. /// </summary> public static readonly DirectProperty<TopLevel, Size?> FrameSizeProperty = AvaloniaProperty.RegisterDirect<TopLevel, Size?>(nameof(FrameSize), o => o.FrameSize); /// <summary> /// Defines the <see cref="IInputRoot.PointerOverElement"/> property. /// </summary> public static readonly StyledProperty<IInputElement> PointerOverElementProperty = AvaloniaProperty.Register<TopLevel, IInputElement>(nameof(IInputRoot.PointerOverElement)); /// <summary> /// Defines the <see cref="TransparencyLevelHint"/> property. /// </summary> public static readonly StyledProperty<WindowTransparencyLevel> TransparencyLevelHintProperty = AvaloniaProperty.Register<TopLevel, WindowTransparencyLevel>(nameof(TransparencyLevelHint), WindowTransparencyLevel.None); /// <summary> /// Defines the <see cref="ActualTransparencyLevel"/> property. /// </summary> public static readonly DirectProperty<TopLevel, WindowTransparencyLevel> ActualTransparencyLevelProperty = AvaloniaProperty.RegisterDirect<TopLevel, WindowTransparencyLevel>(nameof(ActualTransparencyLevel), o => o.ActualTransparencyLevel, unsetValue: WindowTransparencyLevel.None); /// <summary> /// Defines the <see cref="TransparencyBackgroundFallbackProperty"/> property. /// </summary> public static readonly StyledProperty<IBrush> TransparencyBackgroundFallbackProperty = AvaloniaProperty.Register<TopLevel, IBrush>(nameof(TransparencyBackgroundFallback), Brushes.White); private readonly IInputManager _inputManager; private readonly IAccessKeyHandler _accessKeyHandler; private readonly IKeyboardNavigationHandler _keyboardNavigationHandler; private readonly IPlatformRenderInterface _renderInterface; private readonly IGlobalStyles _globalStyles; private Size _clientSize; private Size? _frameSize; private WindowTransparencyLevel _actualTransparencyLevel; private ILayoutManager _layoutManager; private Border _transparencyFallbackBorder; /// <summary> /// Initializes static members of the <see cref="TopLevel"/> class. /// </summary> static TopLevel() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TopLevel>(KeyboardNavigationMode.Cycle); AffectsMeasure<TopLevel>(ClientSizeProperty); TransparencyLevelHintProperty.Changed.AddClassHandler<TopLevel>( (tl, e) => { if (tl.PlatformImpl != null) { tl.PlatformImpl.SetTransparencyLevelHint((WindowTransparencyLevel)e.NewValue); tl.HandleTransparencyLevelChanged(tl.PlatformImpl.TransparencyLevel); } }); } /// <summary> /// Initializes a new instance of the <see cref="TopLevel"/> class. /// </summary> /// <param name="impl">The platform-specific window implementation.</param> public TopLevel(ITopLevelImpl impl) : this(impl, AvaloniaLocator.Current) { } /// <summary> /// Initializes a new instance of the <see cref="TopLevel"/> class. /// </summary> /// <param name="impl">The platform-specific window implementation.</param> /// <param name="dependencyResolver"> /// The dependency resolver to use. If null the default dependency resolver will be used. /// </param> public TopLevel(ITopLevelImpl impl, IAvaloniaDependencyResolver dependencyResolver) { if (impl == null) { throw new InvalidOperationException( "Could not create window implementation: maybe no windowing subsystem was initialized?"); } PlatformImpl = impl; _actualTransparencyLevel = PlatformImpl.TransparencyLevel; dependencyResolver = dependencyResolver ?? AvaloniaLocator.Current; var styler = TryGetService<IStyler>(dependencyResolver); _accessKeyHandler = TryGetService<IAccessKeyHandler>(dependencyResolver); _inputManager = TryGetService<IInputManager>(dependencyResolver); _keyboardNavigationHandler = TryGetService<IKeyboardNavigationHandler>(dependencyResolver); _renderInterface = TryGetService<IPlatformRenderInterface>(dependencyResolver); _globalStyles = TryGetService<IGlobalStyles>(dependencyResolver); Renderer = impl.CreateRenderer(this); if (Renderer != null) { Renderer.SceneInvalidated += SceneInvalidated; } impl.SetInputRoot(this); impl.Closed = HandleClosed; impl.Input = HandleInput; impl.Paint = HandlePaint; impl.Resized = HandleResized; impl.ScalingChanged = HandleScalingChanged; impl.TransparencyLevelChanged = HandleTransparencyLevelChanged; _keyboardNavigationHandler?.SetOwner(this); _accessKeyHandler?.SetOwner(this); if (_globalStyles is object) { _globalStyles.GlobalStylesAdded += ((IStyleHost)this).StylesAdded; _globalStyles.GlobalStylesRemoved += ((IStyleHost)this).StylesRemoved; } styler?.ApplyStyles(this); ClientSize = impl.ClientSize; FrameSize = impl.FrameSize; this.GetObservable(PointerOverElementProperty) .Select( x => (x as InputElement)?.GetObservable(CursorProperty) ?? Observable.Empty<Cursor>()) .Switch().Subscribe(cursor => PlatformImpl?.SetCursor(cursor?.PlatformImpl)); if (((IStyleHost)this).StylingParent is IResourceHost applicationResources) { WeakSubscriptionManager.Subscribe( applicationResources, nameof(IResourceHost.ResourcesChanged), this); } impl.LostFocus += PlatformImpl_LostFocus; } /// <summary> /// Fired when the window is opened. /// </summary> public event EventHandler Opened; /// <summary> /// Fired when the window is closed. /// </summary> public event EventHandler Closed; /// <summary> /// Gets or sets the client size of the window. /// </summary> public Size ClientSize { get { return _clientSize; } protected set { SetAndRaise(ClientSizeProperty, ref _clientSize, value); } } /// <summary> /// Gets or sets the total size of the window. /// </summary> public Size? FrameSize { get { return _frameSize; } protected set { SetAndRaise(FrameSizeProperty, ref _frameSize, value); } } /// <summary> /// Gets or sets the <see cref="WindowTransparencyLevel"/> that the TopLevel should use when possible. /// </summary> public WindowTransparencyLevel TransparencyLevelHint { get { return GetValue(TransparencyLevelHintProperty); } set { SetValue(TransparencyLevelHintProperty, value); } } /// <summary> /// Gets the achieved <see cref="WindowTransparencyLevel"/> that the platform was able to provide. /// </summary> public WindowTransparencyLevel ActualTransparencyLevel { get => _actualTransparencyLevel; private set => SetAndRaise(ActualTransparencyLevelProperty, ref _actualTransparencyLevel, value); } /// <summary> /// Gets or sets the <see cref="IBrush"/> that transparency will blend with when transparency is not supported. /// By default this is a solid white brush. /// </summary> public IBrush TransparencyBackgroundFallback { get => GetValue(TransparencyBackgroundFallbackProperty); set => SetValue(TransparencyBackgroundFallbackProperty, value); } public ILayoutManager LayoutManager { get { if (_layoutManager == null) _layoutManager = CreateLayoutManager(); return _layoutManager; } } /// <summary> /// Gets the platform-specific window implementation. /// </summary> [CanBeNull] public ITopLevelImpl PlatformImpl { get; private set; } /// <summary> /// Gets the renderer for the window. /// </summary> public IRenderer Renderer { get; private set; } /// <summary> /// Gets the access key handler for the window. /// </summary> IAccessKeyHandler IInputRoot.AccessKeyHandler => _accessKeyHandler; /// <summary> /// Gets or sets the keyboard navigation handler for the window. /// </summary> IKeyboardNavigationHandler IInputRoot.KeyboardNavigationHandler => _keyboardNavigationHandler; /// <summary> /// Gets or sets the input element that the pointer is currently over. /// </summary> IInputElement IInputRoot.PointerOverElement { get { return GetValue(PointerOverElementProperty); } set { SetValue(PointerOverElementProperty, value); } } /// <inheritdoc/> IMouseDevice IInputRoot.MouseDevice => PlatformImpl?.MouseDevice; void IWeakSubscriber<ResourcesChangedEventArgs>.OnEvent(object sender, ResourcesChangedEventArgs e) { ((ILogical)this).NotifyResourcesChanged(e); } /// <summary> /// Gets or sets a value indicating whether access keys are shown in the window. /// </summary> bool IInputRoot.ShowAccessKeys { get { return GetValue(AccessText.ShowAccessKeyProperty); } set { SetValue(AccessText.ShowAccessKeyProperty, value); } } /// <inheritdoc/> double ILayoutRoot.LayoutScaling => PlatformImpl?.RenderScaling ?? 1; /// <inheritdoc/> double IRenderRoot.RenderScaling => PlatformImpl?.RenderScaling ?? 1; IStyleHost IStyleHost.StylingParent => _globalStyles; IRenderTarget IRenderRoot.CreateRenderTarget() => CreateRenderTarget(); /// <inheritdoc/> protected virtual IRenderTarget CreateRenderTarget() { if(PlatformImpl == null) throw new InvalidOperationException("Can't create render target, PlatformImpl is null (might be already disposed)"); return _renderInterface.CreateRenderTarget(PlatformImpl.Surfaces); } /// <inheritdoc/> void IRenderRoot.Invalidate(Rect rect) { PlatformImpl?.Invalidate(rect); } /// <inheritdoc/> Point IRenderRoot.PointToClient(PixelPoint p) { return PlatformImpl?.PointToClient(p) ?? default; } /// <inheritdoc/> PixelPoint IRenderRoot.PointToScreen(Point p) { return PlatformImpl?.PointToScreen(p) ?? default; } /// <summary> /// Creates the layout manager for this <see cref="TopLevel" />. /// </summary> protected virtual ILayoutManager CreateLayoutManager() => new LayoutManager(this); /// <summary> /// Handles a paint notification from <see cref="ITopLevelImpl.Resized"/>. /// </summary> /// <param name="rect">The dirty area.</param> protected virtual void HandlePaint(Rect rect) { Renderer?.Paint(rect); } /// <summary> /// Handles a closed notification from <see cref="ITopLevelImpl.Closed"/>. /// </summary> protected virtual void HandleClosed() { if (_globalStyles is object) { _globalStyles.GlobalStylesAdded -= ((IStyleHost)this).StylesAdded; _globalStyles.GlobalStylesRemoved -= ((IStyleHost)this).StylesRemoved; } Renderer?.Dispose(); Renderer = null; var logicalArgs = new LogicalTreeAttachmentEventArgs(this, this, null); ((ILogical)this).NotifyDetachedFromLogicalTree(logicalArgs); var visualArgs = new VisualTreeAttachmentEventArgs(this, this); OnDetachedFromVisualTreeCore(visualArgs); (this as IInputRoot).MouseDevice?.TopLevelClosed(this); PlatformImpl = null; OnClosed(EventArgs.Empty); LayoutManager?.Dispose(); } [Obsolete("Use HandleResized(Size, PlatformResizeReason)")] protected virtual void HandleResized(Size clientSize) => HandleResized(clientSize, PlatformResizeReason.Unspecified); /// <summary> /// Handles a resize notification from <see cref="ITopLevelImpl.Resized"/>. /// </summary> /// <param name="clientSize">The new client size.</param> /// <param name="reason">The reason for the resize.</param> protected virtual void HandleResized(Size clientSize, PlatformResizeReason reason) { ClientSize = clientSize; FrameSize = PlatformImpl.FrameSize; Width = clientSize.Width; Height = clientSize.Height; LayoutManager.ExecuteLayoutPass(); Renderer?.Resized(clientSize); } /// <summary> /// Handles a window scaling change notification from /// <see cref="ITopLevelImpl.ScalingChanged"/>. /// </summary> /// <param name="scaling">The window scaling.</param> protected virtual void HandleScalingChanged(double scaling) { LayoutHelper.InvalidateSelfAndChildrenMeasure(this); } private bool TransparencyLevelsMatch (WindowTransparencyLevel requested, WindowTransparencyLevel received) { if(requested == received) { return true; } else if(requested >= WindowTransparencyLevel.Blur && received >= WindowTransparencyLevel.Blur) { return true; } return false; } protected virtual void HandleTransparencyLevelChanged(WindowTransparencyLevel transparencyLevel) { if(_transparencyFallbackBorder != null) { if(transparencyLevel == WindowTransparencyLevel.None || TransparencyLevelHint == WindowTransparencyLevel.None || !TransparencyLevelsMatch(TransparencyLevelHint, transparencyLevel)) { _transparencyFallbackBorder.Background = TransparencyBackgroundFallback; } else { _transparencyFallbackBorder.Background = null; } } ActualTransparencyLevel = transparencyLevel; } /// <inheritdoc/> protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) { base.OnAttachedToVisualTree(e); throw new InvalidOperationException( $"Control '{GetType().Name}' is a top level control and cannot be added as a child."); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _transparencyFallbackBorder = e.NameScope.Find<Border>("PART_TransparencyFallback"); HandleTransparencyLevelChanged(PlatformImpl.TransparencyLevel); } /// <summary> /// Raises the <see cref="Opened"/> event. /// </summary> /// <param name="e">The event args.</param> protected virtual void OnOpened(EventArgs e) => Opened?.Invoke(this, e); /// <summary> /// Raises the <see cref="Closed"/> event. /// </summary> /// <param name="e">The event args.</param> protected virtual void OnClosed(EventArgs e) => Closed?.Invoke(this, e); /// <summary> /// Tries to get a service from an <see cref="IAvaloniaDependencyResolver"/>, logging a /// warning if not found. /// </summary> /// <typeparam name="T">The service type.</typeparam> /// <param name="resolver">The resolver.</param> /// <returns>The service.</returns> private T TryGetService<T>(IAvaloniaDependencyResolver resolver) where T : class { var result = resolver.GetService<T>(); if (result == null) { Logger.TryGet(LogEventLevel.Warning, LogArea.Control)?.Log( this, "Could not create {Service} : maybe Application.RegisterServices() wasn't called?", typeof(T)); } return result; } /// <summary> /// Handles input from <see cref="ITopLevelImpl.Input"/>. /// </summary> /// <param name="e">The event args.</param> private void HandleInput(RawInputEventArgs e) { _inputManager.ProcessInput(e); } private void SceneInvalidated(object sender, SceneInvalidatedEventArgs e) { (this as IInputRoot).MouseDevice.SceneInvalidated(this, e.DirtyRect); } void PlatformImpl_LostFocus() { var focused = (IVisual)FocusManager.Instance.Current; if (focused == null) return; while (focused.VisualParent != null) focused = focused.VisualParent; if (focused == this) KeyboardDevice.Instance.SetFocusedElement(null, NavigationMethod.Unspecified, KeyModifiers.None); } ITextInputMethodImpl ITextInputMethodRoot.InputMethod => (PlatformImpl as ITopLevelImplWithTextInputMethod)?.TextInputMethod; } }
namespace WebAPI.Testing.Tests { using System; using Nancy.Tests; using Xunit; using Xunit.Extensions; public class AssertEqualityComparerFixture { [Fact] public void Should_return_false_if_actual_is_null_when_comparing_equality() { // Given var comparer = new AssertEqualityComparer<object>(); // When var results = comparer.Equals(new object(), null); // Then results.ShouldBeFalse(); } [Fact] public void Should_return_false_if_expected_is_null_when_comparing_equality() { // Given var comparer = new AssertEqualityComparer<object>(); // When var results = comparer.Equals(null, new object()); // Then results.ShouldBeFalse(); } [Fact] public void Should_invoke_equals_with_expected_value_when_actual_is_equatable() { // Given var comparer = new AssertEqualityComparer<EquatableModel>(); var actual = new EquatableModel(); var expected = new EquatableModel(); // When comparer.Equals(expected, actual); // Then actual.ExpectedValueThatWasPassedIn.ShouldBeSameAs(expected); } [Theory] [InlineData(false)] [InlineData(true)] public void Should_return_result_from_comparing_equatables(bool expectedReturnValue) { // Given var comparer = new AssertEqualityComparer<EquatableModel>(); var actual = new EquatableModel(expectedReturnValue); var expected = new EquatableModel(); // When var result = comparer.Equals(expected, actual); // Then result.ShouldEqual(expectedReturnValue); } [Fact] public void Should_invoke_compareto_with_expected_value_when_actual_is_generic_comparable() { // Given var comparer = new AssertEqualityComparer<GenericCompareableModel>(); var actual = new GenericCompareableModel(); var expected = new GenericCompareableModel(); // When comparer.Equals(expected, actual); // Then actual.ExpectedValueThatWasPassedIn.ShouldBeSameAs(expected); } [Theory] [InlineData(-1, false)] [InlineData(0, true)] [InlineData(1, false)] public void Should_return_result_from_comparing_generic_comparables(int compareResult, bool expectedResult) { // Given var comparer = new AssertEqualityComparer<GenericCompareableModel>(); var actual = new GenericCompareableModel(compareResult); var expected = new GenericCompareableModel(); // When var result = comparer.Equals(expected, actual); // Then result.ShouldEqual(expectedResult); } [Fact] public void Should_invoke_compareto_with_expected_value_when_actual_is_comparable() { // Given var comparer = new AssertEqualityComparer<CompareableModel>(); var actual = new CompareableModel(); var expected = new CompareableModel(); // When comparer.Equals(expected, actual); // Then actual.ExpectedValueThatWasPassedIn.ShouldBeSameAs(expected); } [Theory] [InlineData(-1, false)] [InlineData(0, true)] [InlineData(1, false)] public void Should_return_result_from_comparing_comparables(int compareResult, bool expectedResult) { // Given var comparer = new AssertEqualityComparer<CompareableModel>(); var actual = new CompareableModel(compareResult); var expected = new CompareableModel(); // When var result = comparer.Equals(expected, actual); // Then result.ShouldEqual(expectedResult); } public class EquatableModel : IEquatable<EquatableModel> { private readonly bool returnValue; public EquatableModel() : this(true) { } public EquatableModel(bool returnValue) { this.returnValue = returnValue; } public EquatableModel ExpectedValueThatWasPassedIn { get; private set; } public bool Equals(EquatableModel expected) { this.ExpectedValueThatWasPassedIn = expected; return this.returnValue; } } public class GenericCompareableModel : IComparable<GenericCompareableModel> { private readonly int returnValue; public GenericCompareableModel() : this(0) { } public GenericCompareableModel(int returnValue) { this.returnValue = returnValue; } public GenericCompareableModel ExpectedValueThatWasPassedIn { get; private set; } public int CompareTo(GenericCompareableModel comparable) { this.ExpectedValueThatWasPassedIn = comparable; return this.returnValue; } } public class CompareableModel : IComparable { private readonly int returnValue; public CompareableModel() : this(0) { } public CompareableModel(int returnValue) { this.returnValue = returnValue; } public object ExpectedValueThatWasPassedIn { get; private set; } public int CompareTo(object comparable) { this.ExpectedValueThatWasPassedIn = comparable; return this.returnValue; } } } }
#region File Description //----------------------------------------------------------------------------- // Ionixx Games 3/9/2009 // Copyright (C) Bryan Phelps. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; using SkinnedModelInstancing; using System.IO; #endregion namespace InstancedSkinningSample { /// <summary> /// Sample game showing how to display skinned character animation. /// </summary> public class SkinnedInstancingSample : Microsoft.Xna.Framework.Game { #region Fields static readonly Vector3 startPosition = new Vector3(0f, 20f, 0f); private GraphicsDeviceManager graphics; private GamePadState currentGamePadState = new GamePadState(); private Model arenaModel; private InstancedSkinnedModel skinnedModel; private float cameraRotationX = 0; private float cameraRotationY = 0; private Vector3 cameraPosition = startPosition; private DwarfArmy dwarfArmy; //Framerate measuring private int frameCounter; private TimeSpan elapsedTime; private int frameRate; //Text rendering private SpriteFont font; private SpriteBatch spriteBatch; #endregion #region Initialization public SkinnedInstancingSample() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.PreferredBackBufferWidth = 1280; graphics.PreferredBackBufferHeight = 720; graphics.MinimumVertexShaderProfile = ShaderProfile.VS_2_0; graphics.MinimumPixelShaderProfile = ShaderProfile.PS_2_0; //We're turning these values off, so we can better measure the performance of the sample IsFixedTimeStep = false; graphics.SynchronizeWithVerticalRetrace = false; } /// <summary> /// Load your graphics content. /// </summary> protected override void LoadContent() { // Load the model. //currentModel = Content.Load<Model>("Models\\PlayerMarine"); skinnedModel = Content.Load<InstancedSkinnedModel>("Models\\dwarf-lod1"); this.arenaModel = Content.Load<Model>("Arena\\arena-final"); this.dwarfArmy = new DwarfArmy(skinnedModel); this.spriteBatch = new SpriteBatch(this.GraphicsDevice); this.font = this.Content.Load<SpriteFont>("Fonts\\Font"); } #endregion #region Update and Draw /// <summary> /// Allows the game to run logic. /// </summary> protected override void Update(GameTime gameTime) { HandleInput(); UpdateCamera(gameTime); this.dwarfArmy.Update(gameTime, cameraPosition); elapsedTime += gameTime.ElapsedGameTime; if (elapsedTime > TimeSpan.FromSeconds(1)) { elapsedTime -= TimeSpan.FromSeconds(1); frameRate = frameCounter; frameCounter = 0; } base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> protected override void Draw(GameTime gameTime) { GraphicsDevice device = graphics.GraphicsDevice; device.Clear(Color.CornflowerBlue); // Reset render states that spritebatch may have reset device.RenderState.DepthBufferEnable = true; device.RenderState.AlphaBlendEnable = false; device.RenderState.AlphaTestEnable = false; float aspectRatio = (float)device.Viewport.Width / (float)device.Viewport.Height; Matrix view = Matrix.CreateLookAt(cameraPosition, cameraPosition + new Vector3((float)Math.Cos(cameraRotationX), (float)Math.Sin(cameraRotationY), (float)Math.Sin(cameraRotationX)), Vector3.Up); Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, 1, 10000); // Sort of a hack to get the textures on the arena to display properly. // For some reason, spritebatch changes these to clamp. GraphicsDevice.SamplerStates[0].AddressU = TextureAddressMode.Wrap; GraphicsDevice.SamplerStates[0].AddressV = TextureAddressMode.Wrap; // Draw the arena foreach (ModelMesh mesh in this.arenaModel.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.EnableDefaultLighting(); effect.World = Matrix.Identity; effect.View = view; effect.Projection = projection; } mesh.Draw(); } // Draw the dwarf army this.dwarfArmy.Draw(view, projection); // Draw the text overlay DrawText(); frameCounter++; } /// <summary> /// Draws text information for the sample /// </summary> private void DrawText() { string text = string.Format("Frames per second: {0}\n" + "Total Instances: {1}\n" + "Visible Instances: {2}\n" + "X = Add instances\n" + "Y = Remove instances\n", frameRate, this.dwarfArmy.InstanceCount, this.dwarfArmy.VisibleInstances); spriteBatch.Begin(); spriteBatch.DrawString(font, text, new Vector2(65, 65), Color.Black); spriteBatch.DrawString(font, text, new Vector2(64, 64), Color.White); spriteBatch.End(); } #endregion #region Handle Input /// <summary> /// Handles input for quitting the game. /// </summary> private void HandleInput() { currentGamePadState = GamePad.GetState(PlayerIndex.One); // Check for exit. if (currentGamePadState.Buttons.Back == ButtonState.Pressed) { Exit(); } } /// <summary> /// Handles camera input. /// </summary> private void UpdateCamera(GameTime gameTime) { float time = (float)gameTime.ElapsedGameTime.TotalMilliseconds; float rotationFactor = 0.005f; float moveFactor = 0.05f; // Implement a basic first person camera cameraRotationX += currentGamePadState.ThumbSticks.Right.X * time * rotationFactor; cameraRotationY += currentGamePadState.ThumbSticks.Right.Y * time * rotationFactor; // Clamp the head rotation if (cameraRotationY > 1.4f) cameraRotationY = 1.4f; if (cameraRotationY < -1.4f) cameraRotationY = -1.4f; // Figure out our right & forward angle sso we can move properly float angle = cameraRotationX; float rightAngle = cameraRotationX + MathHelper.PiOver2; Vector3 forward = new Vector3((float)Math.Cos(angle), 0f, (float)Math.Sin(angle)); Vector3 right = new Vector3((float)Math.Cos(rightAngle), 0f, (float)Math.Sin(rightAngle)); forward.Normalize(); right.Normalize(); cameraPosition += currentGamePadState.ThumbSticks.Left.X * right * time * moveFactor; cameraPosition += currentGamePadState.ThumbSticks.Left.Y * forward * time * moveFactor; // Reset position if they pressed the right stick if (currentGamePadState.Buttons.RightStick == ButtonState.Pressed) { cameraRotationX = 0; cameraRotationY = 0; cameraPosition = startPosition; } int instanceChangeRate = Math.Max(this.dwarfArmy.InstanceCount / 100, 1); // Increase the number of instances? if ( currentGamePadState.Buttons.Y == ButtonState.Pressed) { this.dwarfArmy.InstanceCount -= instanceChangeRate; } // Decrease the number of instances? if ( currentGamePadState.Buttons.X == ButtonState.Pressed) { this.dwarfArmy.InstanceCount += instanceChangeRate; } } #endregion } #region Entry Point /// <summary> /// The main entry point for the application. /// </summary> static class Program { static void Main() { using (SkinnedInstancingSample game = new SkinnedInstancingSample()) { game.Run(); } } } #endregion }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.ComponentModel; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.Core; using Azure.ResourceManager.Management; using Azure.ResourceManager.Resources.Models; namespace Azure.ResourceManager.Resources { /// <summary> /// A class representing the operations that can be performed over a specific subscription. /// </summary> public class Tenant : ArmResource { private readonly ProviderRestOperations _providerRestOperations; private readonly ClientDiagnostics _clientDiagnostics; private readonly TenantData _data; /// <summary> /// Initializes a new instance of the <see cref="Tenant"/> class for mocking. /// </summary> protected Tenant() { } /// <summary> /// Initializes a new instance of the <see cref="Tenant"/> class. /// </summary> /// <param name="operations"> The operations object to copy the client parameters from. </param> /// <param name="tenantData"> The data model representing the generic azure resource. </param> internal Tenant(ArmResource operations, TenantData tenantData) : base(operations, ResourceIdentifier.RootResourceIdentifier) { _data = tenantData; HasData = true; _clientDiagnostics = new ClientDiagnostics(ClientOptions); _providerRestOperations = new ProviderRestOperations(_clientDiagnostics, Pipeline, ClientOptions, Guid.Empty.ToString(), BaseUri); } /// <summary> /// Initializes a new instance of the <see cref="Subscription"/> class. /// </summary> /// <param name="options"> The client parameters to use in these operations. </param> /// <param name="credential"> A credential used to authenticate to an Azure Service. </param> /// <param name="baseUri"> The base URI of the service. </param> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> internal Tenant(ArmClientOptions options, TokenCredential credential, Uri baseUri, HttpPipeline pipeline) : base(new ClientContext(options, credential, baseUri, pipeline), ResourceIdentifier.RootResourceIdentifier) { _clientDiagnostics = new ClientDiagnostics(ClientOptions); _providerRestOperations = new ProviderRestOperations(_clientDiagnostics, Pipeline, ClientOptions, Guid.Empty.ToString(), BaseUri); } /// <summary> /// The resource type for subscription /// </summary> public static readonly ResourceType ResourceType = "Microsoft.Resources/tenants"; /// <summary> /// Gets whether or not the current instance has data. /// </summary> public bool HasData { get; } /// <summary> /// Gets the tenant data model. /// </summary> /// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception> public virtual TenantData Data { get { if (!HasData) throw new InvalidOperationException("The current instance does not have data you must call Get first"); return _data; } } /// <summary> /// Gets the valid resource type for this operation class /// </summary> protected override ResourceType ValidResourceType => ResourceType; /// <summary> /// Provides a way to reuse the protected client context. /// </summary> /// <typeparam name="T"> The actual type returned by the delegate. </typeparam> /// <param name="func"> The method to pass the internal properties to. </param> /// <returns> Whatever the delegate returns. </returns> [EditorBrowsable(EditorBrowsableState.Never)] [ForwardsClientCalls] public virtual T UseClientContext<T>(Func<Uri, TokenCredential, ArmClientOptions, HttpPipeline, T> func) { return func(BaseUri, Credential, ClientOptions, Pipeline); } /// <summary> Gets all resource providers for a subscription. </summary> /// <param name="top"> The number of results to return. If null is passed returns all deployments. </param> /// <param name="expand"> The properties to include in the results. For example, use &amp;$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Pageable<ProviderInfo> GetTenantProviders(int? top = null, string expand = null, CancellationToken cancellationToken = default) { Page<ProviderInfo> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("Tenant.GetTenantProviders"); scope.Start(); try { Response<ProviderInfoListResult> response = _providerRestOperations.ListAtTenantScope(top, expand, cancellationToken); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } Page<ProviderInfo> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("Tenant.GetTenantProviders"); scope.Start(); try { Response<ProviderInfoListResult> response = _providerRestOperations.ListAtTenantScopeNextPage(nextLink, cancellationToken); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Gets all resource providers for a subscription. </summary> /// <param name="top"> The number of results to return. If null is passed returns all deployments. </param> /// <param name="expand"> The properties to include in the results. For example, use &amp;$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual AsyncPageable<ProviderInfo> GetTenantProvidersAsync(int? top = null, string expand = null, CancellationToken cancellationToken = default) { async Task<Page<ProviderInfo>> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("Tenant.GetTenantProviders"); scope.Start(); try { Response<ProviderInfoListResult> response = await _providerRestOperations.ListAtTenantScopeAsync(top, expand, cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } async Task<Page<ProviderInfo>> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("Tenant.GetTenantProviders"); scope.Start(); try { Response<ProviderInfoListResult> response = await _providerRestOperations.ListAtTenantScopeNextPageAsync(nextLink, cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Gets the specified resource provider at the tenant level. </summary> /// <param name="resourceProviderNamespace"> The namespace of the resource provider. </param> /// <param name="expand"> The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceProviderNamespace"/> is null. </exception> public virtual Response<ProviderInfo> GetTenantProvider(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("Tenant.GetTenantProvider"); scope.Start(); try { return _providerRestOperations.GetAtTenantScope(resourceProviderNamespace, expand, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets the specified resource provider at the tenant level. </summary> /// <param name="resourceProviderNamespace"> The namespace of the resource provider. </param> /// <param name="expand"> The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceProviderNamespace"/> is null. </exception> public virtual async Task<Response<ProviderInfo>> GetTenantProviderAsync(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("Tenant.GetTenantProvider"); scope.Start(); try { return await _providerRestOperations.GetAtTenantScopeAsync(resourceProviderNamespace, expand, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Gets the management group container for this tenant. /// </summary> /// <returns> A container of the management groups. </returns> public virtual ManagementGroupContainer GetManagementGroups() { return new ManagementGroupContainer(this); } /// <summary> /// Gets the managmeent group operations object associated with the id. /// </summary> /// <param name="id"> The id of the management group operations. </param> /// <returns> A client to perform operations on the management group. </returns> internal ManagementGroup GetManagementGroup(ResourceIdentifier id) { return new ManagementGroup(this, id); } /// <summary> /// Gets the subscription container for this tenant. /// </summary> /// <returns> A container of the subscriptions. </returns> public virtual SubscriptionContainer GetSubscriptions() { return new SubscriptionContainer(this); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; namespace System.IO { /// <summary>Provides an implementation of a file stream for Unix files.</summary> internal sealed partial class UnixFileStream : FileStreamBase { /// <summary>The file descriptor wrapped in a file handle.</summary> private readonly SafeFileHandle _fileHandle; /// <summary>The path to the opened file.</summary> private readonly string _path; /// <summary>File mode.</summary> private readonly FileMode _mode; /// <summary>Whether the file is opened for reading, writing, or both.</summary> private readonly FileAccess _access; /// <summary>Advanced options requested when opening the file.</summary> private readonly FileOptions _options; /// <summary>If the file was opened with FileMode.Append, the length of the file when opened; otherwise, -1.</summary> private readonly long _appendStart = -1; /// <summary>Whether asynchronous read/write/flush operations should be performed using async I/O.</summary> private readonly bool _useAsyncIO; /// <summary>The length of the _buffer.</summary> private readonly int _bufferLength; /// <summary>Lazily-initialized buffer data from Write waiting to be written to the underlying handle, or data read from the underlying handle and waiting to be Read.</summary> private byte[] _buffer; /// <summary>The number of valid bytes in _buffer.</summary> private int _readLength; /// <summary>The next available byte to be read from the _buffer.</summary> private int _readPos; /// <summary>The next location in which a write should occur to the buffer.</summary> private int _writePos; /// <summary>Lazily-initialized value for whether the file supports seeking.</summary> private bool? _canSeek; /// <summary>Whether the file stream's handle has been exposed.</summary> private bool _exposedHandle; /// <summary> /// Currently cached position in the stream. This should always mirror the underlying file descriptor's actual position, /// and should only ever be out of sync if another stream with access to this same file descriptor manipulates it, at which /// point we attempt to error out. /// </summary> private long _filePosition; /// <summary>Initializes a stream for reading or writing a Unix file.</summary> /// <param name="path">The path to the file.</param> /// <param name="mode">How the file should be opened.</param> /// <param name="access">Whether the file will be read, written, or both.</param> /// <param name="share">What other access to the file should be allowed. This is currently ignored.</param> /// <param name="bufferSize">The size of the buffer to use when buffering.</param> /// <param name="options">Additional options for working with the file.</param> internal UnixFileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent) : base(parent) { // FileStream performs most of the general argument validation. We can assume here that the arguments // are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.) // Store the arguments _path = path; _access = access; _mode = mode; _options = options; _bufferLength = bufferSize; _useAsyncIO = (options & FileOptions.Asynchronous) != 0; // Translate the arguments into arguments for an open call Interop.libc.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, access, options); // FileShare currently ignored Interop.libc.Permissions openPermissions = Interop.libc.Permissions.S_IRWXU; // creator has read/write/execute permissions; no permissions for anyone else // Open the file and store the safe handle. Subsequent code in this method expects the safe handle to be initialized. _fileHandle = SafeFileHandle.Open(path, openFlags, (int)openPermissions); _fileHandle.IsAsync = _useAsyncIO; // Lock the file if requested via FileShare. This is only advisory locking. FileShare.None implies an exclusive // lock on the file and all other modes use a shared lock. While this is not as granular as Windows, not mandatory, // and not atomic with file opening, it's better than nothing. try { Interop.libc.LockOperations lockOperation = (share == FileShare.None) ? Interop.libc.LockOperations.LOCK_EX : Interop.libc.LockOperations.LOCK_SH; SysCall<Interop.libc.LockOperations, int>((fd, op, _) => Interop.libc.flock(fd, op), lockOperation | Interop.libc.LockOperations.LOCK_NB); } catch { _fileHandle.Dispose(); throw; } // Perform additional configurations on the stream based on the provided FileOptions PostOpenConfigureStreamFromOptions(); // Jump to the end of the file if opened as Append. if (_mode == FileMode.Append) { _appendStart = SeekCore(0, SeekOrigin.End); } } /// <summary>Performs additional configuration of the opened stream based on provided options.</summary> partial void PostOpenConfigureStreamFromOptions(); /// <summary>Initializes a stream from an already open file handle (file descriptor).</summary> /// <param name="handle">The handle to the file.</param> /// <param name="access">Whether the file will be read, written, or both.</param> /// <param name="bufferSize">The size of the buffer to use when buffering.</param> /// <param name="useAsyncIO">Whether access to the stream is performed asynchronously.</param> internal UnixFileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool useAsyncIO, FileStream parent) : base(parent) { // Make sure the handle is open if (handle.IsInvalid) throw new ArgumentException(SR.Arg_InvalidHandle, "handle"); if (handle.IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (access < FileAccess.Read || access > FileAccess.ReadWrite) throw new ArgumentOutOfRangeException("access", SR.ArgumentOutOfRange_Enum); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", SR.ArgumentOutOfRange_NeedNonNegNum); if (handle.IsAsync.HasValue && useAsyncIO != handle.IsAsync.Value) throw new ArgumentException(SR.Arg_HandleNotAsync, "handle"); _fileHandle = handle; _access = access; _exposedHandle = true; _bufferLength = bufferSize; _useAsyncIO = useAsyncIO; if (CanSeek) { SeekCore(0, SeekOrigin.Current); } } /// <summary>Gets the array used for buffering reading and writing. If the array hasn't been allocated, this will lazily allocate it.</summary> /// <returns>The buffer.</returns> private byte[] GetBuffer() { Debug.Assert(_buffer == null || _buffer.Length == _bufferLength); return _buffer ?? (_buffer = new byte[_bufferLength]); } /// <summary>Translates the FileMode, FileAccess, and FileOptions values into flags to be passed when opening the file.</summary> /// <param name="mode">The FileMode provided to the stream's constructor.</param> /// <param name="access">The FileAccess provided to the stream's constructor</param> /// <param name="options">The FileOptions provided to the stream's constructor</param> /// <returns>The flags value to be passed to the open system call.</returns> private static Interop.libc.OpenFlags PreOpenConfigurationFromOptions(FileMode mode, FileAccess access, FileOptions options) { // Translate FileMode. Most of the values map cleanly to one or more options for open. Interop.libc.OpenFlags flags = default(Interop.libc.OpenFlags); switch (mode) { default: case FileMode.Open: // Open maps to the default behavior for open(...). No flags needed. break; case FileMode.Append: // Append is the same as OpenOrCreate, except that we'll also separately jump to the end later case FileMode.OpenOrCreate: flags |= Interop.libc.OpenFlags.O_CREAT; break; case FileMode.Create: flags |= (Interop.libc.OpenFlags.O_CREAT | Interop.libc.OpenFlags.O_TRUNC); break; case FileMode.CreateNew: flags |= (Interop.libc.OpenFlags.O_CREAT | Interop.libc.OpenFlags.O_EXCL); break; case FileMode.Truncate: flags |= Interop.libc.OpenFlags.O_TRUNC; break; } // Translate FileAccess. All possible values map cleanly to corresponding values for open. switch (access) { case FileAccess.Read: flags |= Interop.libc.OpenFlags.O_RDONLY; break; case FileAccess.ReadWrite: flags |= Interop.libc.OpenFlags.O_RDWR; break; case FileAccess.Write: flags |= Interop.libc.OpenFlags.O_WRONLY; break; } // Translate some FileOptions; some just aren't supported, and others will be handled after calling open. switch (options) { case FileOptions.Asynchronous: // Handled in ctor, setting _useAsync and SafeFileHandle.IsAsync to true case FileOptions.DeleteOnClose: // DeleteOnClose doesn't have a Unix equivalent, but we approximate it in Dispose case FileOptions.Encrypted: // Encrypted does not have an equivalent on Unix and is ignored. case FileOptions.RandomAccess: // Implemented after open if posix_fadvise is available case FileOptions.SequentialScan: // Implemented after open if posix_fadvise is available break; case FileOptions.WriteThrough: flags |= Interop.libc.OpenFlags.O_SYNC; break; } return flags; } /// <summary>Gets a value indicating whether the current stream supports reading.</summary> public override bool CanRead { [Pure] get { return !_fileHandle.IsClosed && (_access & FileAccess.Read) != 0; } } /// <summary>Gets a value indicating whether the current stream supports writing.</summary> public override bool CanWrite { [Pure] get { return !_fileHandle.IsClosed && (_access & FileAccess.Write) != 0; } } /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> public override bool CanSeek { get { if (_fileHandle.IsClosed) { return false; } if (!_canSeek.HasValue) { // Lazily-initialize whether we're able to seek, tested by seeking to our current location. _canSeek = SysCall<int, int>((fd, _, __) => Interop.libc.lseek(fd, 0, Interop.libc.SeekWhence.SEEK_CUR), throwOnError: false) >= 0; } return _canSeek.Value; } } /// <summary>Gets a value indicating whether the stream was opened for I/O to be performed synchronously or asynchronously.</summary> public override bool IsAsync { get { return _useAsyncIO; } } /// <summary>Gets the length of the stream in bytes.</summary> public override long Length { get { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (!_parent.CanSeek) { throw __Error.GetSeekNotSupported(); } // Get the length of the file as reported by the OS long length = SysCall<int, int>((fd, _, __) => { Interop.libcoreclr.fileinfo fileinfo; int result = Interop.libcoreclr.GetFileInformationFromFd(fd, out fileinfo); return result >= 0 ? fileinfo.size : result; }); // But we may have buffered some data to be written that puts our length // beyond what the OS is aware of. Update accordingly. if (_writePos > 0 && _filePosition + _writePos > length) { length = _writePos + _filePosition; } return length; } } /// <summary>Gets the path that was passed to the constructor.</summary> public override String Name { get { return _path ?? SR.IO_UnknownFileName; } } /// <summary>Gets the SafeFileHandle for the file descriptor encapsulated in this stream.</summary> public override SafeFileHandle SafeFileHandle { get { _parent.Flush(); _exposedHandle = true; return _fileHandle; } } /// <summary>Gets or sets the position within the current stream</summary> public override long Position { get { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (!_parent.CanSeek) { throw __Error.GetSeekNotSupported(); } VerifyBufferInvariants(); VerifyOSHandlePosition(); // We may have read data into our buffer from the handle, such that the handle position // is artificially further along than the consumer's view of the stream's position. // Thus, when reading, our position is really starting from the handle position negatively // offset by the number of bytes in the buffer and positively offset by the number of // bytes into that buffer we've read. When writing, both the read length and position // must be zero, and our position is just the handle position offset positive by how many // bytes we've written into the buffer. return (_filePosition - _readLength) + _readPos + _writePos; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_NeedNonNegNum); } _parent.Seek(value, SeekOrigin.Begin); } } /// <summary>Verifies that state relating to the read/write buffer is consistent.</summary> [Conditional("DEBUG")] private void VerifyBufferInvariants() { // Read buffer values must be in range: 0 <= _bufferReadPos <= _bufferReadLength <= _bufferLength Debug.Assert(0 <= _readPos && _readPos <= _readLength && _readLength <= _bufferLength); // Write buffer values must be in range: 0 <= _bufferWritePos <= _bufferLength Debug.Assert(0 <= _writePos && _writePos <= _bufferLength); // Read buffering and write buffering can't both be active Debug.Assert((_readPos == 0 && _readLength == 0) || _writePos == 0); } /// <summary> /// Verify that the actual position of the OS's handle equals what we expect it to. /// This will fail if someone else moved the UnixFileStream's handle or if /// our position updating code is incorrect. /// </summary> private void VerifyOSHandlePosition() { bool verifyPosition = _exposedHandle; // in release, only verify if we've given out the handle such that someone else could be manipulating it #if DEBUG verifyPosition = true; // in debug, always make sure our position matches what the OS says it should be #endif if (verifyPosition && _parent.CanSeek) { long oldPos = _filePosition; // SeekCore will override the current _position, so save it now long curPos = SeekCore(0, SeekOrigin.Current); if (oldPos != curPos) { // For reads, this is non-fatal but we still could have returned corrupted // data in some cases, so discard the internal buffer. For writes, // this is a problem; discard the buffer and error out. _readPos = _readLength = 0; if (_writePos > 0) { _writePos = 0; throw new IOException(SR.IO_FileStreamHandlePosition); } } } } /// <summary>Releases the unmanaged resources used by the stream.</summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { // Flush and close the file try { if (_fileHandle != null && !_fileHandle.IsClosed) { FlushWriteBuffer(); // Unix doesn't directly support DeleteOnClose but we can mimick it. if ((_options & FileOptions.DeleteOnClose) != 0) { // Since we still have the file open, this will end up deleting // it (assuming we're the only link to it) once it's closed. Interop.libc.unlink(_path); // ignore any error } } } finally { if (_fileHandle != null && !_fileHandle.IsClosed) { _fileHandle.Dispose(); } base.Dispose(disposing); } } /// <summary>Finalize the stream.</summary> ~UnixFileStream() { Dispose(false); } /// <summary>Clears buffers for this stream and causes any buffered data to be written to the file.</summary> public override void Flush() { _parent.Flush(flushToDisk: false); } /// <summary> /// Clears buffers for this stream, and if <param name="flushToDisk"/> is true, /// causes any buffered data to be written to the file. /// </summary> public override void Flush(Boolean flushToDisk) { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } FlushInternalBuffer(); if (flushToDisk && _parent.CanWrite) { FlushOSBuffer(); } } /// <summary>Flushes the OS buffer. This does not flush the internal read/write buffer.</summary> private void FlushOSBuffer() { SysCall<int, int>((fd, _, __) => Interop.libc.fsync(fd)); } /// <summary> /// Flushes the internal read/write buffer for this stream. If write data has been buffered, /// that data is written out to the underlying file. Or if data has been buffered for /// reading from the stream, the data is dumped and our position in the underlying file /// is rewound as necessary. This does not flush the OS buffer. /// </summary> private void FlushInternalBuffer() { VerifyBufferInvariants(); if (_writePos > 0) { FlushWriteBuffer(); } else if (_readPos < _readLength && _parent.CanSeek) { FlushReadBuffer(); } } /// <summary>Writes any data in the write buffer to the underlying stream and resets the buffer.</summary> private void FlushWriteBuffer() { VerifyBufferInvariants(); if (_writePos > 0) { WriteCore(GetBuffer(), 0, _writePos); _writePos = 0; } } /// <summary>Dumps any read data in the buffer and rewinds our position in the stream, accordingly, as necessary.</summary> private void FlushReadBuffer() { VerifyBufferInvariants(); int rewind = _readPos - _readLength; if (rewind != 0) { SeekCore(rewind, SeekOrigin.Current); } _readPos = _readLength = 0; } /// <summary>Asynchronously clears all buffers for this stream, causing any buffered data to be written to the underlying device.</summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous flush operation.</returns> public override Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } // As with Win32FileStream, flush the buffers synchronously to avoid race conditions. try { FlushInternalBuffer(); } catch (Exception e) { return Task.FromException(e); } // We then separately flush to disk asynchronously. This is only // necessary if we support writing; otherwise, we're done. if (_parent.CanWrite) { return Task.Factory.StartNew( state => ((UnixFileStream)state).FlushOSBuffer(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } else { return Task.CompletedTask; } } /// <summary>Sets the length of this stream to the given value.</summary> /// <param name="value">The new length of the stream.</param> public override void SetLength(long value) { if (value < 0) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (!_parent.CanSeek) { throw __Error.GetSeekNotSupported(); } if (!_parent.CanWrite) { throw __Error.GetWriteNotSupported(); } FlushInternalBuffer(); if (_appendStart != -1 && value < _appendStart) { throw new IOException(SR.IO_SetLengthAppendTruncate); } long origPos = _filePosition; VerifyOSHandlePosition(); if (_filePosition != value) { SeekCore(value, SeekOrigin.Begin); } SysCall<long, int>((fd, length, _) => Interop.libc.ftruncate(fd, length), value); // Return file pointer to where it was before setting length if (origPos != value) { if (origPos < value) { SeekCore(origPos, SeekOrigin.Begin); } else { SeekCore(0, SeekOrigin.End); } } } /// <summary>Reads a block of bytes from the stream and writes the data in a given buffer.</summary> /// <param name="array"> /// When this method returns, contains the specified byte array with the values between offset and /// (offset + count - 1) replaced by the bytes read from the current source. /// </param> /// <param name="offset">The byte offset in array at which the read bytes will be placed.</param> /// <param name="count">The maximum number of bytes to read. </param> /// <returns> /// The total number of bytes read into the buffer. This might be less than the number of bytes requested /// if that number of bytes are not currently available, or zero if the end of the stream is reached. /// </returns> public override int Read([In, Out] byte[] array, int offset, int count) { ValidateReadWriteArgs(array, offset, count); PrepareForReading(); // Are there any bytes available in the read buffer? If yes, // we can just return from the buffer. If the buffer is empty // or has no more available data in it, we can either refill it // (and then read from the buffer into the user's buffer) or // we can just go directly into the user's buffer, if they asked // for more data than we'd otherwise buffer. int numBytesAvailable = _readLength - _readPos; if (numBytesAvailable == 0) { // If we're not able to seek, then we're not able to rewind the stream (i.e. flushing // a read buffer), in which case we don't want to use a read buffer. Similarly, if // the user has asked for more data than we can buffer, we also want to skip the buffer. if (!_parent.CanSeek || (count >= _bufferLength)) { // Read directly into the user's buffer int bytesRead = ReadCore(array, offset, count); _readPos = _readLength = 0; // reset after the read just in case read experiences an exception return bytesRead; } else { // Read into our buffer. _readLength = numBytesAvailable = ReadCore(GetBuffer(), 0, _bufferLength); _readPos = 0; if (numBytesAvailable == 0) { return 0; } } } // Now that we know there's data in the buffer, read from it into // the user's buffer. int bytesToRead = Math.Min(numBytesAvailable, count); Buffer.BlockCopy(GetBuffer(), _readPos, array, offset, bytesToRead); _readPos += bytesToRead; return bytesToRead; } /// <summary>Unbuffered, reads a block of bytes from the stream and writes the data in a given buffer.</summary> /// <param name="array"> /// When this method returns, contains the specified byte array with the values between offset and /// (offset + count - 1) replaced by the bytes read from the current source. /// </param> /// <param name="offset">The byte offset in array at which the read bytes will be placed.</param> /// <param name="count">The maximum number of bytes to read. </param> /// <returns> /// The total number of bytes read into the buffer. This might be less than the number of bytes requested /// if that number of bytes are not currently available, or zero if the end of the stream is reached. /// </returns> private unsafe int ReadCore(byte[] array, int offset, int count) { FlushWriteBuffer(); // we're about to read; dump the write buffer VerifyOSHandlePosition(); int bytesRead; fixed (byte* bufPtr = array) { bytesRead = (int)SysCall((fd, ptr, len) => { long result = (long)Interop.libc.read(fd, (byte*)ptr, (IntPtr)len); Debug.Assert(result <= len); return result; }, (IntPtr)(bufPtr + offset), count); } _filePosition += bytesRead; return bytesRead; } /// <summary> /// Asynchronously reads a sequence of bytes from the current stream and advances /// the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">The buffer to write the data into.</param> /// <param name="offset">The byte offset in buffer at which to begin writing data from the stream.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous read operation.</returns> public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<int>(cancellationToken); if (_fileHandle.IsClosed) throw __Error.GetFileNotOpen(); if (_useAsyncIO) { // TODO: Use async I/O instead of sync I/O } return base.ReadAsync(buffer, offset, count, cancellationToken); } /// <summary> /// Reads a byte from the stream and advances the position within the stream /// by one byte, or returns -1 if at the end of the stream. /// </summary> /// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns> public override int ReadByte() { PrepareForReading(); byte[] buffer = GetBuffer(); if (_readPos == _readLength) { _readLength = ReadCore(buffer, 0, _bufferLength); _readPos = 0; if (_readLength == 0) { return -1; } } return buffer[_readPos++]; } /// <summary>Validates that we're ready to read from the stream.</summary> private void PrepareForReading() { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (_readLength == 0 && !_parent.CanRead) { throw __Error.GetReadNotSupported(); } VerifyBufferInvariants(); } /// <summary>Writes a block of bytes to the file stream.</summary> /// <param name="array">The buffer containing data to write to the stream.</param> /// <param name="offset">The zero-based byte offset in array from which to begin copying bytes to the stream.</param> /// <param name="count">The maximum number of bytes to write.</param> public override void Write(byte[] array, int offset, int count) { ValidateReadWriteArgs(array, offset, count); PrepareForWriting(); // If no data is being written, nothing more to do. if (count == 0) { return; } // If there's already data in our write buffer, then we need to go through // our buffer to ensure data isn't corrupted. if (_writePos > 0) { // If there's space remaining in the buffer, then copy as much as // we can from the user's buffer into ours. int spaceRemaining = _bufferLength - _writePos; if (spaceRemaining > 0) { int bytesToCopy = Math.Min(spaceRemaining, count); Buffer.BlockCopy(array, offset, GetBuffer(), _writePos, bytesToCopy); _writePos += bytesToCopy; // If we've successfully copied all of the user's data, we're done. if (count == bytesToCopy) { return; } // Otherwise, keep track of how much more data needs to be handled. offset += bytesToCopy; count -= bytesToCopy; } // At this point, the buffer is full, so flush it out. FlushWriteBuffer(); } // Our buffer is now empty. If using the buffer would slow things down (because // the user's looking to write more data than we can store in the buffer), // skip the buffer. Otherwise, put the remaining data into the buffer. Debug.Assert(_writePos == 0); if (count >= _bufferLength) { WriteCore(array, offset, count); } else { Buffer.BlockCopy(array, offset, GetBuffer(), _writePos, count); _writePos = count; } } /// <summary>Unbuffered, writes a block of bytes to the file stream.</summary> /// <param name="array">The buffer containing data to write to the stream.</param> /// <param name="offset">The zero-based byte offset in array from which to begin copying bytes to the stream.</param> /// <param name="count">The maximum number of bytes to write.</param> private unsafe void WriteCore(byte[] array, int offset, int count) { VerifyOSHandlePosition(); fixed (byte* bufPtr = array) { while (count > 0) { int bytesWritten = (int)SysCall((fd, ptr, len) => { long result = (long)Interop.libc.write(fd, (byte*)ptr, (IntPtr)len); Debug.Assert(result <= len); return result; }, (IntPtr)(bufPtr + offset), count); _filePosition += bytesWritten; count -= bytesWritten; offset += bytesWritten; } } } /// <summary> /// Asynchronously writes a sequence of bytes to the current stream, advances /// the current position within this stream by the number of bytes written, and /// monitors cancellation requests. /// </summary> /// <param name="buffer">The buffer to write data from.</param> /// <param name="offset">The zero-based byte offset in buffer from which to begin copying bytes to the stream.</param> /// <param name="count">The maximum number of bytes to write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous write operation.</returns> public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); if (_fileHandle.IsClosed) throw __Error.GetFileNotOpen(); if (_useAsyncIO) { // TODO: Use async I/O instead of sync I/O } return base.WriteAsync(buffer, offset, count, cancellationToken); } /// <summary> /// Writes a byte to the current position in the stream and advances the position /// within the stream by one byte. /// </summary> /// <param name="value">The byte to write to the stream.</param> public override void WriteByte(byte value) // avoids an array allocation in the base implementation { PrepareForWriting(); // Flush the write buffer if it's full if (_writePos == _bufferLength) { FlushWriteBuffer(); } // We now have space in the buffer. Store the byte. GetBuffer()[_writePos++] = value; } /// <summary> /// Validates that we're ready to write to the stream, /// including flushing a read buffer if necessary. /// </summary> private void PrepareForWriting() { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } // Make sure we're good to write. We only need to do this if there's nothing already // in our write buffer, since if there is something in the buffer, we've already done // this checking and flushing. if (_writePos == 0) { if (!_parent.CanWrite) throw __Error.GetWriteNotSupported(); FlushReadBuffer(); } } /// <summary>Validates arguments to Read and Write and throws resulting exceptions.</summary> /// <param name="array">The buffer to read from or write to.</param> /// <param name="offset">The zero-based offset into the array.</param> /// <param name="count">The maximum number of bytes to read or write.</param> private void ValidateReadWriteArgs(byte[] array, int offset, int count) { if (array == null) { throw new ArgumentNullException("array", SR.ArgumentNull_Buffer); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); } if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> public override long Seek(long offset, SeekOrigin origin) { if (origin < SeekOrigin.Begin || origin > SeekOrigin.End) { throw new ArgumentException(SR.Argument_InvalidSeekOrigin, "origin"); } if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (!_parent.CanSeek) { throw __Error.GetSeekNotSupported(); } VerifyOSHandlePosition(); // Flush our write/read buffer. FlushWrite will output any write buffer we have and reset _bufferWritePos. // We don't call FlushRead, as that will do an unnecessary seek to rewind the read buffer, and since we're // about to seek and update our position, we can simply update the offset as necessary and reset our read // position and length to 0. (In the future, for some simple cases we could potentially add an optimization // here to just move data around in the buffer for short jumps, to avoid re-reading the data from disk.) FlushWriteBuffer(); if (origin == SeekOrigin.Current) { offset -= (_readLength - _readPos); } _readPos = _readLength = 0; // Keep track of where we were, in case we're in append mode and need to verify long oldPos = 0; if (_appendStart >= 0) { oldPos = SeekCore(0, SeekOrigin.Current); } // Jump to the new location long pos = SeekCore(offset, origin); // Prevent users from overwriting data in a file that was opened in append mode. if (_appendStart != -1 && pos < _appendStart) { SeekCore(oldPos, SeekOrigin.Begin); throw new IOException(SR.IO_SeekAppendOverwrite); } // Return the new position return pos; } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> private long SeekCore(long offset, SeekOrigin origin) { Debug.Assert(!_fileHandle.IsClosed && CanSeek); Debug.Assert(origin >= SeekOrigin.Begin && origin <= SeekOrigin.End); long pos = SysCall((fd, off, or) => Interop.libc.lseek(fd, off, or), offset, (Interop.libc.SeekWhence)(int)origin); // SeekOrigin values are the same as Interop.libc.SeekWhence values _filePosition = pos; return pos; } /// <summary> /// Helper for making system calls that involve the stream's file descriptor. /// System calls are expected to return greather than or equal to zero on success, /// and less than zero on failure. In the case of failure, errno is expected to /// be set to the relevant error code. /// </summary> /// <typeparam name="TArg1">Specifies the type of an argument to the system call.</typeparam> /// <typeparam name="TArg2">Specifies the type of another argument to the system call.</typeparam> /// <param name="sysCall">A delegate that invokes the system call.</param> /// <param name="arg1">The first argument to be passed to the system call, after the file descriptor.</param> /// <param name="arg2">The second argument to be passed to the system call.</param> /// <param name="throwOnError">true to throw an exception if a non-interuption error occurs; otherwise, false.</param> /// <returns>The return value of the system call.</returns> /// <remarks> /// Arguments are expected to be passed via <paramref name="arg1"/> and <paramref name="arg2"/> /// so as to avoid delegate and closure allocations at the call sites. /// </remarks> private long SysCall<TArg1, TArg2>( Func<int, TArg1, TArg2, long> sysCall, TArg1 arg1 = default(TArg1), TArg2 arg2 = default(TArg2), bool throwOnError = true) { SafeFileHandle handle = _fileHandle; Debug.Assert(sysCall != null); Debug.Assert(handle != null); bool gotRefOnHandle = false; try { // Get the file descriptor from the handle. We increment the ref count to help // ensure it's not closed out from under us. handle.DangerousAddRef(ref gotRefOnHandle); Debug.Assert(gotRefOnHandle); int fd = (int)handle.DangerousGetHandle(); Debug.Assert(fd >= 0); // System calls may fail due to EINTR (signal interruption). We need to retry in those cases. while (true) { long result = sysCall(fd, arg1, arg2); if (result < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EINTR) { continue; } else if (throwOnError) { throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } return result; } } finally { if (gotRefOnHandle) { handle.DangerousRelease(); } else { throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); } } } } }
/*************************************************************** //This code just called you a tool //What I meant to say is that this code was generated by a tool //so don't mess with it unless you're debugging //subject to change without notice, might regenerate while you're reading, etc ***************************************************************/ using Web; using Voodoo.Messages; using Web.Infrastructure.ExecutionPipeline; using Web.Infrastructure.ExecutionPipeline.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Voodoo; using Core.Operations.Users; using Core.Operations.Users.Extras; using Core.Operations.TestClasses; using Core.Operations.TestClasses.Extras; using Core.Operations.Teams; using Core.Operations.Teams.Extras; using Core.Operations.Projects; using Core.Operations.Projects.Extras; using Core.Operations.Members; using Core.Operations.Members.Extras; using Core.Operations.Lists; using Core.Operations.Errors; using Core.Operations.Errors.Extras; using Core.Operations.CurrentUsers; using Core.Identity; using Core.Operations.ApplicationSettings; using Core.Operations.ApplicationSettings.Extras; namespace Web.Controllers.Api { [Route("api/[controller]")] public class UserController : ApiControllerBase { [HttpDelete] public async Task<Response> Delete ( IdRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <IdRequest, Response> { Command = new UserDeleteCommand(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { "Administrator" } } }; var pipeline = new ExcecutionPipeline<IdRequest, Response> (state); await pipeline.ExecuteAsync(); return state.Response; } [HttpGet] public async Task<Response<UserDetail>> Get ( IdRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <IdRequest, Response<UserDetail>> { Command = new UserDetailQuery(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { "Administrator" } } }; var pipeline = new ExcecutionPipeline<IdRequest, Response<UserDetail>> (state); await pipeline.ExecuteAsync(); return state.Response; } [HttpPut] public async Task<NewItemResponse> Put ([FromBody] UserDetail request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <UserDetail, NewItemResponse> { Command = new UserSaveCommand(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { "Administrator" } } }; var pipeline = new ExcecutionPipeline<UserDetail, NewItemResponse> (state); await pipeline.ExecuteAsync(); return state.Response; } } [Route("api/[controller]")] public class UserListController : ApiControllerBase { [HttpGet] public async Task<UserListResponse> Get ( UserListRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <UserListRequest, UserListResponse> { Command = new UserListQuery(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { "Administrator" } } }; var pipeline = new ExcecutionPipeline<UserListRequest, UserListResponse> (state); await pipeline.ExecuteAsync(); return state.Response; } } [Route("api/[controller]")] public class TestClassController : ApiControllerBase { [HttpDelete] public async Task<Response> Delete ( IdRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <IdRequest, Response> { Command = new TestClassDeleteCommand(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<IdRequest, Response> (state); await pipeline.ExecuteAsync(); return state.Response; } [HttpGet] public async Task<Response<TestClassDetail>> Get ( IdRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <IdRequest, Response<TestClassDetail>> { Command = new TestClassDetailQuery(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<IdRequest, Response<TestClassDetail>> (state); await pipeline.ExecuteAsync(); return state.Response; } [HttpPost] public async Task<NewItemResponse> Post ([FromBody] TestClassDetail request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <TestClassDetail, NewItemResponse> { Command = new TestClassSaveCommand(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<TestClassDetail, NewItemResponse> (state); await pipeline.ExecuteAsync(); return state.Response; } } [Route("api/[controller]")] public class TestClassListController : ApiControllerBase { [HttpGet] public async Task<TestClassListResponse> Get ( TestClassListRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <TestClassListRequest, TestClassListResponse> { Command = new TestClassListQuery(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<TestClassListRequest, TestClassListResponse> (state); await pipeline.ExecuteAsync(); return state.Response; } } [Route("api/[controller]")] public class TeamController : ApiControllerBase { [HttpDelete] public async Task<Response> Delete ( IdRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <IdRequest, Response> { Command = new TeamDeleteCommand(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<IdRequest, Response> (state); await pipeline.ExecuteAsync(); return state.Response; } [HttpGet] public async Task<Response<TeamDetail>> Get ( IdRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <IdRequest, Response<TeamDetail>> { Command = new TeamDetailQuery(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<IdRequest, Response<TeamDetail>> (state); await pipeline.ExecuteAsync(); return state.Response; } [HttpPut] public async Task<NewItemResponse> Put ([FromBody] TeamDetail request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <TeamDetail, NewItemResponse> { Command = new TeamSaveCommand(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<TeamDetail, NewItemResponse> (state); await pipeline.ExecuteAsync(); return state.Response; } } [Route("api/[controller]")] public class TeamListController : ApiControllerBase { [HttpGet] public async Task<TeamListResponse> Get ( TeamListRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <TeamListRequest, TeamListResponse> { Command = new TeamListQuery(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<TeamListRequest, TeamListResponse> (state); await pipeline.ExecuteAsync(); return state.Response; } } [Route("api/[controller]")] public class ProjectController : ApiControllerBase { [HttpDelete] public async Task<Response> Delete ( IdRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <IdRequest, Response> { Command = new ProjectDeleteCommand(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<IdRequest, Response> (state); await pipeline.ExecuteAsync(); return state.Response; } [HttpGet] public async Task<Response<ProjectDetail>> Get ( IdRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <IdRequest, Response<ProjectDetail>> { Command = new ProjectDetailQuery(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<IdRequest, Response<ProjectDetail>> (state); await pipeline.ExecuteAsync(); return state.Response; } [HttpPut] public async Task<NewItemResponse> Put ([FromBody] ProjectDetail request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <ProjectDetail, NewItemResponse> { Command = new ProjectSaveCommand(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<ProjectDetail, NewItemResponse> (state); await pipeline.ExecuteAsync(); return state.Response; } } [Route("api/[controller]")] public class ProjectListController : ApiControllerBase { [HttpGet] public async Task<ProjectListResponse> Get ( ProjectListRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <ProjectListRequest, ProjectListResponse> { Command = new ProjectListQuery(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<ProjectListRequest, ProjectListResponse> (state); await pipeline.ExecuteAsync(); return state.Response; } } [Route("api/[controller]")] public class MemberController : ApiControllerBase { [HttpDelete] public async Task<Response> Delete ( IdRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <IdRequest, Response> { Command = new MemberDeleteCommand(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<IdRequest, Response> (state); await pipeline.ExecuteAsync(); return state.Response; } [HttpGet] public async Task<Response<MemberDetail>> Get ( IdRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <IdRequest, Response<MemberDetail>> { Command = new MemberDetailQuery(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<IdRequest, Response<MemberDetail>> (state); await pipeline.ExecuteAsync(); return state.Response; } [HttpPut] public async Task<NewItemResponse> Put ([FromBody] MemberDetail request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <MemberDetail, NewItemResponse> { Command = new MemberSaveCommand(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<MemberDetail, NewItemResponse> (state); await pipeline.ExecuteAsync(); return state.Response; } } [Route("api/[controller]")] public class MemberListController : ApiControllerBase { [HttpGet] public async Task<MemberListResponse> Get ( MemberListRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <MemberListRequest, MemberListResponse> { Command = new MemberListQuery(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<MemberListRequest, MemberListResponse> (state); await pipeline.ExecuteAsync(); return state.Response; } } [Route("api/[controller]")] public class ListsController : ApiControllerBase { [HttpGet] public async Task<ListsResponse> Get ( ListsRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <ListsRequest, ListsResponse> { Command = new LookupsQuery(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<ListsRequest, ListsResponse> (state); await pipeline.ExecuteAsync(); return state.Response; } } [Route("api/[controller]")] public class ErrorLogController : ApiControllerBase { [HttpGet] public async Task<Response<ErrorDetail>> Get ( IdRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <IdRequest, Response<ErrorDetail>> { Command = new ErrorDetailQuery(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<IdRequest, Response<ErrorDetail>> (state); await pipeline.ExecuteAsync(); return state.Response; } } [Route("api/[controller]")] public class ErrorLogListController : ApiControllerBase { [HttpGet] public async Task<ErrorListResponse> Get ( ErrorListRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <ErrorListRequest, ErrorListResponse> { Command = new ErrorListQuery(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<ErrorListRequest, ErrorListResponse> (state); await pipeline.ExecuteAsync(); return state.Response; } } [Route("api/[controller]")] public class MobileErrorController : ApiControllerBase { [HttpPost] public async Task<Response> Post ([FromBody] MobileErrorRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <MobileErrorRequest, Response> { Command = new MobileErrorAddCommand(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = true, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<MobileErrorRequest, Response> (state); await pipeline.ExecuteAsync(); return state.Response; } } [Route("api/[controller]")] public class CurrentUserController : ApiControllerBase { [HttpGet] public async Task<Response<AppPrincipal>> Get ( EmptyRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <EmptyRequest, Response<AppPrincipal>> { Command = new GetCurrentUserCommand(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = true, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<EmptyRequest, Response<AppPrincipal>> (state); await pipeline.ExecuteAsync(); return state.Response; } } [Route("api/[controller]")] public class ApplicationSettingController : ApiControllerBase { [HttpDelete] public async Task<Response> Delete ( IdRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <IdRequest, Response> { Command = new ApplicationSettingDeleteCommand(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<IdRequest, Response> (state); await pipeline.ExecuteAsync(); return state.Response; } [HttpGet] public async Task<Response<ApplicationSettingDetail>> Get ( IdRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <IdRequest, Response<ApplicationSettingDetail>> { Command = new ApplicationSettingDetailQuery(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<IdRequest, Response<ApplicationSettingDetail>> (state); await pipeline.ExecuteAsync(); return state.Response; } [HttpPut] public async Task<NewItemResponse> Put ([FromBody] ApplicationSettingDetail request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <ApplicationSettingDetail, NewItemResponse> { Command = new ApplicationSettingSaveCommand(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<ApplicationSettingDetail, NewItemResponse> (state); await pipeline.ExecuteAsync(); return state.Response; } } [Route("api/[controller]")] public class ApplicationSettingListController : ApiControllerBase { [HttpGet] public async Task<ApplicationSettingListResponse> Get ( ApplicationSettingListRequest request) { var state = new Infrastructure.ExecutionPipeline.Models.ExecutionState <ApplicationSettingListRequest, ApplicationSettingListResponse> { Command = new ApplicationSettingListQuery(request), Context = HttpContext, ModelState = ModelState, Request = request, SecurityContext = new SecurityContext { AllowAnonymouse = false, Roles=new string[] { } } }; var pipeline = new ExcecutionPipeline<ApplicationSettingListRequest, ApplicationSettingListResponse> (state); await pipeline.ExecuteAsync(); return state.Response; } } }
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion #region Imports using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using Common.Logging; using Common.Logging.Simple; using NUnit.Framework; using Spring.Collections; using Spring.Core; using Spring.Core.TypeConversion; using Spring.Objects.Factory; using Spring.Util; #endregion namespace Spring.Objects { /// <summary> /// Unit tests for the ObjectWrapper class. /// </summary> /// <author>Rod Johnson</author> /// <author>Mark Pollack (.NET)</author> /// <author>Rick Evans (.NET)</author> [TestFixture] public sealed class ObjectWrapperTests { /// <summary> /// The setup logic executed before the execution of this test fixture. /// </summary> [OneTimeSetUp] public void FixtureSetUp() { // enable logging (to nowhere), just to exercisee the logging code... LogManager.Adapter = new NoOpLoggerFactoryAdapter(); } #region Classes Used During Tests public class Person { private IList favoriteNames = new ArrayList(); private IDictionary properties = new Hashtable(); private string sillyString; public Person() { favoriteNames.Add("p1"); favoriteNames.Add("p2"); } public Person(IList favNums) { favoriteNames = favNums; } public string SillyString { get { return sillyString; } } public IList FavoriteNames { get { return favoriteNames; } } public IDictionary Properties { get { return properties; } } public string this[int index] { get { return (string)favoriteNames[index]; } set { favoriteNames[index] = value; } } public string this[string keyName] { get { return (string) properties[keyName]; } set { properties.Add(keyName,value); } } public string this[int index, string keyname] { get { return sillyString; } set { sillyString = index + "-" + keyname + ",val=" + value;} } } public class GenericPerson { private List<string> favoriteNames = new List<string>(); private IDictionary<string, string> properties = new Dictionary<string, string>(); public GenericPerson() { favoriteNames.Add("p1"); favoriteNames.Add("p2"); } public GenericPerson(List<string> favNums) { favoriteNames = favNums; } /* public string this[int index] { get { return (string)favoriteNames[index]; } set { favoriteNames[index] = value; } } */ public string this[string keyName] { get { return properties[keyName]; } set { properties.Add(keyName, value); } } } public class AltPerson { private IList favoriteNames = new ArrayList(); public AltPerson() { favoriteNames.Add("ap1"); favoriteNames.Add("ap2"); } public AltPerson(IList favNums) { favoriteNames = favNums; } [IndexerName("FavoriteName")] public string this[int index] { get { return (string)favoriteNames[index]; } set { favoriteNames[index] = value; } } } public class NoNullsList : ArrayList { public override int Add(object value) { if (value == null) { throw new NullReferenceException("Adding nulls is not supported in this implementation."); } return base.Add(value); } } private class Honey { public Honey(IList akas) { _akas = new Aliases(akas); } protected Aliases _akas; public Aliases AlsoKnownAs { get { return _akas; } } public string this[int index] { get { return AlsoKnownAs[index]; } } } private class NonReadableHoney : Honey { public NonReadableHoney(IList akas) : base(akas) { } new public Aliases AlsoKnownAs { set { _akas = value; } } } private class Milk { public Milk(Honey[] honeys) { } public Honey[] Honeys { set { } } } private sealed class Aliases { private IList _names; public Aliases() : this(new ArrayList()) { } public Aliases(IList names) { _names = names; } public string this[int index] { get { return (string) _names[index]; } set { _names[index] = value; } } } private sealed class RealNestedTestObject { public TestObject Datum { get { return _datum; } set { _datum = value; } } private TestObject _datum; } private sealed class WanPropsClass { public bool IsWan { get { return true; } } } private sealed class StringAppenderConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof (string)) { return true; } return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom( ITypeDescriptorContext context, CultureInfo culture, object val) { if (val is string) { return "OctopusOil : " + val; } return base.ConvertFrom(context, culture, val); } } private sealed class TestStringArrayConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof (string[])) { return true; } return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object val) { if (val is string[]) { return "-" + StringUtils.CollectionToCommaDelimitedString(val as string[]) + "-"; } return base.ConvertFrom(context, culture, val); } } private sealed class TestObjectArrayConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof (string)) { return true; } return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object val) { if (val is string) { return new TestObject((string) val, 99); } return base.ConvertFrom(context, culture, val); } } private sealed class ObjectWithTypeProperty { private Type _type; public Type Type { get { return _type; } set { _type = value; } } } /// <summary> /// A class for use in testing the object wrapper with read only properties. /// </summary> private sealed class NoRead { public int Age { set { } } } private sealed class GetterObject { public string Name { get { if (_name == null) { throw new ApplicationException("name property must be set"); } return _name; } set { _name = value; } } private string _name; } private sealed class ThrowsException { public void DoSomething(Exception t) { throw t; } } internal sealed class PrimitiveArrayObject { public int[] Array { get { return array; } set { this.array = value; } } private int[] array; } private sealed class PropsTest { public NameValueCollection Properties { set { } } public String Name { set { } } public String[] StringArray { set { this.stringArray = value; } } public int[] IntArray { set { this.intArray = value; } } public String[] stringArray; public int[] intArray; } #endregion #region Methods /// <summary> /// Factory method for getting an ObjectWrapper instance. /// </summary> /// <returns>A new object wrapper (with no WrappedObject).</returns> private ObjectWrapper GetWrapper() { return new ObjectWrapper(); } /// <summary> /// Factory method for getting an ObjectWrapper instance. /// </summary> /// <param name="objectToBeWrapped"> /// The object that is to be wrapped by the returned object wrapper. /// </param> /// <returns> /// A new object wrapper that wraps the supplied <paramref name="objectToBeWrapped"/>. /// </returns> private ObjectWrapper GetWrapper(object objectToBeWrapped) { return new ObjectWrapper(objectToBeWrapped); } #endregion [Test] public void SetPropertyUsingValueThatNeedsConversionWithNoCustomConverterRegistered() { ObjectWrapper wrapper = GetWrapper(new TestObject("Rick", 30)); // needs conversion to NestedTestObject... Assert.Throws<TypeMismatchException>(() => wrapper.SetPropertyValue("doctor", "Pollack, Pinch, & Pounce")); } [Test] [Ignore("not used")] public void GetValueOfCustomIndexerProperty() { ObjectWrapper wrapper = GetWrapper(); Honey darwin = new Honey(new string[] {"dickens", "of gaunt"}); wrapper.WrappedInstance = darwin; string alias = (string) wrapper.GetPropertyValue("AlsoKnownAs[1]"); Assert.AreEqual("of gaunt", alias); alias = (string) wrapper.GetPropertyValue("[1]"); Assert.AreEqual("of gaunt", alias, "indexer on object not working."); wrapper.SetPropertyValue("Item[1]", "of foobar"); alias = (string)wrapper.GetPropertyValue("[1]"); Assert.AreEqual("of foobar", alias, "indexer on object not working."); } [Test] [Ignore("not used")] public void GetSetIndexerProperties() { IList favNames = new ArrayList(); favNames.Add("Master Shake"); favNames.Add("Meatwad"); favNames.Add("Frylock"); Person p = new Person(favNames); ObjectWrapper wrapper = GetWrapper(); wrapper.WrappedInstance = p; //This is 'new' Spring.Expressions notation, i.e. not "Item[i]" but plain [i]. string name = (string)wrapper.GetPropertyValue("[0]"); Assert.AreEqual("Master Shake", name); wrapper.SetPropertyValue("[0]", "Carl"); name = (string)wrapper.GetPropertyValue("[0]"); Assert.AreEqual("Carl", name); //Try with Custom Indexer Name. favNames = new ArrayList(); favNames.Add("Master Shake"); favNames.Add("Meatwad"); favNames.Add("Frylock"); AltPerson ap = new AltPerson(favNames); wrapper = GetWrapper(); wrapper.WrappedInstance = ap; name = (string)wrapper.GetPropertyValue("FavoriteName[0]"); Assert.AreEqual("Master Shake", name); } [Test] public void GetValueOfCustomIndexerPropertyWithMalformedIndexer() { ObjectWrapper wrapper = GetWrapper(); Honey darwin = new Honey(new string[] {"dickens", "of gaunt"}); wrapper.WrappedInstance = darwin; Assert.Throws<InvalidPropertyException>(() => wrapper.GetPropertyValue("AlsoKnownAs[1")); } [Test] public void GetPropertyTypeWithNullPropertyPath() { Assert.Throws<FatalObjectException>(() => GetWrapper().GetPropertyType(null)); } [Test] public void GetPropertyTypeWithEmptyPropertyPath() { Assert.Throws<FatalObjectException>(() => GetWrapper().GetPropertyType(string.Empty)); } [Test] public void GetPropertyTypeWithWhitespacedPropertyPath() { Assert.Throws<FatalObjectException>(() => GetWrapper().GetPropertyType(" ")); } [Test] public void GetPropertyType() { ObjectWrapper wrapper = GetWrapper(new TestObject()); Type propertyType = wrapper.GetPropertyType("name"); Assert.AreEqual(typeof (string), propertyType); } [Test] public void GetPropertyTypeFromField_SPRNET502() { ObjectWrapper wrapper = GetWrapper(new TestObject()); Type propertyType = wrapper.GetPropertyType("FileModeEnum"); Assert.AreEqual(typeof (FileMode), propertyType); } [Test] public void GetPropertyTypeWithNestedLookup() { TestObject target = new TestObject(); target.Spouse = new TestObject("Fiona", 28); ObjectWrapper wrapper = GetWrapper(target); Type propertyType = wrapper.GetPropertyType("spouse.age"); Assert.AreEqual(typeof (int), propertyType); } [Test] public void SetValueOfCustomIndexerPropertyWithNonReadablePropertyInIndexedPath() { ObjectWrapper wrapper = GetWrapper(); Honey[] honeys = new NonReadableHoney[] {new NonReadableHoney(new string[] {"hsu", "feng"})}; wrapper.WrappedInstance = new Milk(honeys); Assert.Throws<NotWritablePropertyException>(() => wrapper.SetPropertyValue("Honeys[0][0]", "mei")); } [Test] public void SetPropertyThatRequiresTypeConversionWithNonConvertibleType() { ObjectWrapper wrapper = GetWrapper(); TestObject to = new TestObject(); wrapper.WrappedInstance = to; Assert.Throws<TypeMismatchException>(() => wrapper.SetPropertyValue("RealLawyer", "Noob")); } /// <summary> /// This test blows up because index is out of range. /// </summary> [Test] public void SetIndexedPropertyOnListThatsOutOfRange() { TestObject to = new TestObject(); ObjectWrapper wrapper = GetWrapper(to); to.Friends = new NoNullsList(); Assert.Throws<InvalidPropertyException>(() => wrapper.SetPropertyValue("Friends[5]", "Inheritance Tax")); } /// <summary> /// Tests that a property lookup such as <c>foo[0][1]['ben'][12]</c> is ok /// Well, rather it tests that its valid... 'cos man, that shoh ain't ok :D /// </summary> [Test] public void GetChainedIndexers() { Honey to = new Honey(new string[] {"wee", "jakey", "ned"}); ObjectWrapper wrapper = GetWrapper(to); Assert.AreEqual('j', wrapper.GetPropertyValue("AlsoKnownAs[1][0]")); } /// <summary> /// Test that passing a null value of the object to manipulate with the ObjectWrapper /// will throw a FatalPropertyException with the correct exception message. /// </summary> [Test] public void NullObject() { Assert.Throws<FatalObjectException>(() => new ObjectWrapper((object) null)); } [Test] public void InstantiateWithInterfaceType() { Assert.Throws<FatalObjectException>(() => new ObjectWrapper(typeof (IList))); } [Test] public void InstantiateWithAbstractType() { Assert.Throws<FatalObjectException>(() => new ObjectWrapper(typeof (AbstractObjectFactoryTests))); } [Test] public void InstantiateWithOkType() { IObjectWrapper wrapper = GetWrapper(typeof (TestObject)); Assert.IsNotNull(wrapper.WrappedInstance); } [Test] public void NestedProperties() { string doctorCompany = ""; string lawyerCompany = "Dr. Sueem"; TestObject to = new TestObject(); IObjectWrapper wrapper = GetWrapper(to); wrapper.SetPropertyValue("Doctor.Company", doctorCompany); wrapper.SetPropertyValue("Lawyer.Company", lawyerCompany); Assert.AreEqual(doctorCompany, to.Doctor.Company); Assert.AreEqual(lawyerCompany, to.Lawyer.Company); } [Test] public void GetterThrowsException() { GetterObject go = new GetterObject(); IObjectWrapper wrapper = GetWrapper(go); wrapper.SetPropertyValue("Name", "tom"); Assert.IsTrue(go.Name.Equals("tom"), "Expected name to be set to 'tom'"); } [Test] public void TryToReadTheValueOfAWriteOnlyProperty() { NoRead nr = new NoRead(); ObjectWrapper wrapper = GetWrapper(nr); Assert.Throws<NotReadablePropertyException>(() => wrapper.GetPropertyValue("Age")); } [Test] public void TryToReadAnIndexedValueFromANullProperty() { TestObject o = new TestObject(); o.Friends = null; ObjectWrapper wrapper = GetWrapper(o); Assert.Throws<NullValueInNestedPathException>(() => wrapper.GetPropertyValue("Friends[2]")); } /// <summary> /// Test that applying an empty MutablePropertyValues does not modify the object contents. /// </summary> [Test] public void EmptyPropertyValuesSet() { TestObject t = new TestObject(); int age = 50; string name = "Tony"; t.Age = age; t.Name = name; IObjectWrapper wrapper = GetWrapper(t); Assert.IsTrue(t.Age.Equals(age), "Age is not set correctly"); Assert.IsTrue(name.Equals(t.Name), "Name is not set correctly"); wrapper.SetPropertyValues(new MutablePropertyValues()); Assert.IsTrue(t.Age.Equals(age), "Age is not set correctly"); Assert.IsTrue(name.Equals(t.Name), "Name is not set correctly"); } /// <summary> /// Test basic ObjectWrapper functionality by setting properties using MutablePropertyValues. /// </summary> [Test] public void AllValid() { TestObject t = new TestObject(); string newName = "tony"; int newAge = 65; string newTouchy = "valid"; IObjectWrapper wrapper = GetWrapper(t); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.Add(new PropertyValue("Age", newAge)); pvs.Add(new PropertyValue("Name", newName)); pvs.Add(new PropertyValue("Touchy", newTouchy)); wrapper.SetPropertyValues(pvs); Assert.IsTrue(t.Name.Equals(newName), "Validly set property must stick"); Assert.IsTrue(t.Touchy.Equals(newTouchy), "Validly set property must stick"); Assert.IsTrue(t.Age == newAge, "Validly set property must stick"); } [Test] public void IndividualAllValid() { TestObject t = new TestObject(); String newName = "tony"; int newAge = 65; string newTouchy = "valid"; IObjectWrapper wrapper = GetWrapper(t); wrapper.SetPropertyValue("Age", newAge); wrapper.SetPropertyValue(new PropertyValue("Name", newName)); wrapper.SetPropertyValue(new PropertyValue("Touchy", newTouchy)); Assert.IsTrue(t.Name.Equals(newName), "Validly set property must stick"); Assert.IsTrue(t.Touchy.Equals(newTouchy), "Validly set property must stick"); Assert.IsTrue(t.Age == newAge, "Validly set property must stick"); } [Test] public void SettingAnInvalidValue() { TestObject t = new TestObject(); string newName = "tony"; try { IObjectWrapper wrapper = GetWrapper(t); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.Add(new PropertyValue("Age", "foobar")); pvs.Add(new PropertyValue("Name", newName)); wrapper.SetPropertyValues(pvs); Assert.Fail("Should throw exception when setting an invalid value"); } catch (PropertyAccessExceptionsException ex) { Assert.IsTrue(ex.ExceptionCount == 1, "Must contain 2 exceptions"); // Test validly set property matches Assert.IsTrue(t.Name.Equals(newName), "Validly set property must stick"); Assert.IsTrue(t.Age == 0, "Invalidly set property must retain old value"); } catch (Exception ex) { Assert.Fail( "Shouldn't throw exception other than PropertyAccessExceptions. Exception Message = " + ex.Message); } } [Test] public void ArrayToStringConversion() { TestObject t = new TestObject(); IObjectWrapper wrapper = GetWrapper(t); TypeConverterRegistry.RegisterConverter(typeof(string), new TestStringArrayConverter()); wrapper.SetPropertyValue("Name", new string[] {"a", "b"}); Assert.AreEqual("-a,b-", t.Name); } [Test] public void ArrayToArrayConversion() { IndexedTestObject to = new IndexedTestObject(); IObjectWrapper wrapper = GetWrapper(to); TypeConverterRegistry.RegisterConverter(typeof(TestObject), new TestObjectArrayConverter()); wrapper.SetPropertyValue("Array", new string[] {"a", "b"}); Assert.AreEqual("a", to.Array[0].Name); Assert.AreEqual("b", to.Array[1].Name); } [Test] public void PrimitiveArray() { PrimitiveArrayObject to = new PrimitiveArrayObject(); IObjectWrapper wrapper = GetWrapper(to); wrapper.SetPropertyValue("Array", new String[] {"1", "2"}); Assert.AreEqual(2, to.Array.Length); Assert.AreEqual(1, to.Array[0]); Assert.AreEqual(2, to.Array[1]); } [Test] public void PrimitiveArrayFromCommaDelimitedString() { PrimitiveArrayObject to = new PrimitiveArrayObject(); IObjectWrapper wrapper = GetWrapper(to); wrapper.SetPropertyValue("Array", "1,2"); Assert.AreEqual(2, to.Array.Length); Assert.AreEqual(1, to.Array[0]); Assert.AreEqual(2, to.Array[1]); } [Test] public void ObjectWrapperUpdates() { TestObject to = new TestObject("Rick", 2); int newAge = 33; ObjectWrapper wrapper = GetWrapper(to); to.Age = newAge; object owAge = wrapper.GetPropertyValue("Age"); Assert.IsTrue(owAge is Int32, "Age is an integer"); int owi = (int) owAge; Assert.IsTrue(owi == newAge, "Object wrapper must pick up changes"); } [Test] public void SetWrappedInstanceOfSameClass() { TestObject to = new TestObject(); IObjectWrapper wrapper = GetWrapper(to); to.Age = 11; TestObject to2 = new TestObject(); wrapper.WrappedInstance = to2; wrapper.SetPropertyValue("Age", 14); Assert.IsTrue(to2.Age == 14, "2nd changed"); Assert.IsTrue(to.Age == 11, "1st didn't change"); } [Test] public void SetWrappedInstanceOfDifferentClass() { ThrowsException tex = new ThrowsException(); ObjectWrapper wrapper = GetWrapper(tex); TestObject to2 = new TestObject(); wrapper.WrappedInstance = to2; wrapper.SetPropertyValue("Age", 14); Assert.IsTrue(to2.Age == 14); } [Test] public void TypeMismatch() { TestObject to = new TestObject(); IObjectWrapper wrapper = GetWrapper(to); Assert.Throws<TypeMismatchException>(() => wrapper.SetPropertyValue("Age", "foobar")); } [Test] public void EmptyValueForPrimitiveProperty() { TestObject to = new TestObject(); ObjectWrapper wrapper = GetWrapper(to); Assert.Throws<TypeMismatchException>(() => wrapper.SetPropertyValue("Age", "")); } [Test] public void GetProtectedPropertyValue() { TestObject foo = new TestObject(); IObjectWrapper wrapper = GetWrapper(foo); string happyPlace = (string) wrapper.GetPropertyValue("HappyPlace"); Assert.AreEqual(TestObject.DefaultHappyPlace, happyPlace, "Failed to read the value of a property with 'protected' access."); } [Test] public void SetProtectedPropertyValue() { TestObject foo = new TestObject(); IObjectWrapper wrapper = GetWrapper(foo); const string expectedHappyPlace = "The Rockies! Brrr..."; wrapper.SetPropertyValue(new PropertyValue("HappyPlace", expectedHappyPlace)); string happyPlace = (string) wrapper.GetPropertyValue("HappyPlace"); Assert.AreEqual(expectedHappyPlace, happyPlace, "Failed to read / write the value of a property with 'protected' access."); } [Test] public void GetPrivatePropertyValue() { TestObject foo = new TestObject(); IObjectWrapper wrapper = GetWrapper(foo); string[] contents = (string[]) wrapper.GetPropertyValue("SamsoniteSuitcase"); Assert.IsTrue(ArrayUtils.AreEqual(TestObject.DefaultContentsOfTheSuitcase, contents), "Failed to read the value of a property with 'private' access."); } [Test] public void SetPrivatePropertyValue() { TestObject foo = new TestObject(); IObjectWrapper wrapper = GetWrapper(foo); string[] expectedContents = new string[] {"Lloyd's Soul", "Harry's John Denver Records"}; wrapper.SetPropertyValue(new PropertyValue("SamsoniteSuitcase", expectedContents)); string[] contents = (string[]) wrapper.GetPropertyValue("SamsoniteSuitcase"); Assert.IsTrue(ArrayUtils.AreEqual(expectedContents, contents), "Failed to read / write the value of a property with 'private' access."); } [Test] public void GetNestedProperty() { ITestObject rod = new TestObject("rod", 31); ITestObject kerry = new TestObject("kerry", 35); rod.Spouse = kerry; kerry.Spouse = rod; IObjectWrapper wrapper = GetWrapper(rod); int KA = (int) wrapper.GetPropertyValue("Spouse.Age"); Assert.IsTrue(KA == 35, "Expected kerry's age to be 35"); int RA = (int) wrapper.GetPropertyValue("Spouse.Spouse.Age"); Assert.IsTrue(RA == 31, "Expected rod's age to be 31"); ITestObject spousesSpouse = (ITestObject) wrapper.GetPropertyValue("Spouse.Spouse"); Assert.IsTrue(rod == spousesSpouse, "spousesSpouse == initial point"); } [Test] public void GetNestedPropertyValueNullValue() { TestObject rod = new TestObject("rod", 31); rod.Doctor = new NestedTestObject(null); Assert.Throws<NullValueInNestedPathException>(() => GetWrapper(rod).GetPropertyValue("Doctor.Company.Length")); } [Test] public void SetNestedProperty() { ITestObject rod = new TestObject("rod", 31); ITestObject kerry = new TestObject("kerry", 0); IObjectWrapper wrapper = GetWrapper(rod); wrapper.SetPropertyValue("Spouse", kerry); Assert.AreEqual(rod.Spouse, kerry, "nested set did not work"); wrapper.SetPropertyValue("Spouse.Spouse", rod); Assert.AreEqual(rod, rod.Spouse.Spouse, "Nested set did not work."); wrapper.SetPropertyValue("Spouse.Age", 100); Assert.AreEqual(100, kerry.Age, "Nested setting of primitive property did not work."); } [Test] public void SetPropertyValue() { ITestObject bigby = new TestObject("Bigby", 4500); ITestObject snow = new TestObject("Snow", 2500); IObjectWrapper wrapper = GetWrapper(bigby); wrapper.SetPropertyValue("Spouse", snow); Assert.AreEqual(snow, bigby.Spouse); } [Test] public void SetIndexedPropertyValueOnUninitializedPath() { TestObject obj = new TestObject("Bill", 4500); IObjectWrapper wrapper = GetWrapper(obj); Assert.Throws<NullValueInNestedPathException>(() => wrapper.SetPropertyValue("hats [0]", "Hicks & Co")); } [Test] public void SetIndexedPropertyValueOnNonIndexableType() { TestObject obj = new TestObject("Bill", 4500); IObjectWrapper wrapper = GetWrapper(obj); Assert.Throws<InvalidPropertyException>(() => wrapper.SetPropertyValue("doctor [0]", "Hicks & Co")); } [Test] public void SetPrimitivePropertyToNullReference() { TestObject obj = new TestObject("Bill", 4500); IObjectWrapper wrapper = GetWrapper(obj); Assert.Throws<TypeMismatchException>(() => wrapper.SetPropertyValue("Age", null)); } [Test] public void SetPropertyValueIgnoresCase() { ITestObject bigby = new TestObject("Bigby", 4500); ITestObject snow = new TestObject("Snow", 2500); IObjectWrapper wrapper = GetWrapper(bigby); wrapper.SetPropertyValue("spouse", snow); Assert.AreEqual(snow, bigby.Spouse, "Property setting is not case insensitive with regard to the property name (and for CLS compliance it should be)."); } [Test] public void IntArrayProperty() { PropsTest pt = new PropsTest(); IObjectWrapper wrapper = GetWrapper(pt); wrapper.SetPropertyValue("IntArray", new int[] {4, 5, 2, 3}); Assert.IsTrue(pt.intArray.Length == 4, "intArray length = 4"); Assert.IsTrue(pt.intArray[0] == 4 && pt.intArray[1] == 5 && pt.intArray[2] == 2 && pt.intArray[3] == 3, "correct values"); wrapper.SetPropertyValue("IntArray", new String[] {"4", "5", "2", "3"}); Assert.IsTrue(pt.intArray.Length == 4, "intArray length = 4"); Assert.IsTrue(pt.intArray[0] == 4 && pt.intArray[1] == 5 && pt.intArray[2] == 2 && pt.intArray[3] == 3, "correct values"); wrapper.SetPropertyValue("IntArray", 1); Assert.IsTrue(pt.intArray.Length == 1, "intArray length = 1"); Assert.IsTrue(pt.intArray[0] == 1, "correct values"); wrapper.SetPropertyValue("IntArray", new String[] {"1"}); Assert.IsTrue(pt.intArray.Length == 1, "intArray length = 1"); Assert.IsTrue(pt.intArray[0] == 1, "correct values"); } [Test] public void NewWrappedInstancePropertyValuesGet() { ObjectWrapper wrapper = GetWrapper(); TestObject t = new TestObject("Tony", 50); wrapper.WrappedInstance = t; Assert.AreEqual(t.Age, wrapper.GetPropertyValue("Age"), "Object wrapper returns wrong property value"); TestObject u = new TestObject("Udo", 30); wrapper.WrappedInstance = u; Assert.AreEqual(u.Age, wrapper.GetPropertyValue("Age"), "Object wrapper returns cached property value"); } [Test] public void NewWrappedInstanceNestedPropertyValuesGet() { IObjectWrapper wrapper = GetWrapper(); TestObject t = new TestObject("Tony", 50); t.Spouse = new TestObject("Sue", 40); wrapper.WrappedInstance = t; Assert.AreEqual(t.Spouse.Age, wrapper.GetPropertyValue("Spouse.Age"), "Object wrapper returns wrong nested property value"); TestObject u = new TestObject("Udo", 30); u.Spouse = new TestObject("Vera", 20); wrapper.WrappedInstance = u; Assert.AreEqual(u.Spouse.Age, wrapper.GetPropertyValue("Spouse.Age"), "Object wrapper returns cached nested property value"); } [Test] public void StringArrayProperty() { PropsTest pt = new PropsTest(); ObjectWrapper wrapper = GetWrapper(pt); wrapper.SetPropertyValue("StringArray", "foo,fi,fi,fum"); Assert.IsTrue(pt.stringArray.Length == 4, "StringArray length = 4"); Assert.IsTrue( pt.stringArray[0].Equals("foo") && pt.stringArray[1].Equals("fi") && pt.stringArray[2].Equals("fi") && pt.stringArray[3].Equals("fum"), "in correct values of string array"); } #region Test for DateTime Properties internal class DateTimeTestObject { private DateTime _dt; public DateTime TriggerDateTime { get { return _dt; } set { _dt = value; } } } [Test] public void SetDateTimeProperty() { DateTimeTestObject o = new DateTimeTestObject(); ObjectWrapper wrapper = GetWrapper(o); wrapper.SetPropertyValue("TriggerDateTime", "1991-10-10"); Assert.AreEqual(1991, ((DateTime) wrapper.GetPropertyValue("TriggerDateTime")).Year); } #endregion #region Test for CultureInfo Properties internal class CultureTestObject { private CultureInfo _ci; public CultureInfo Cult { get { return _ci; } set { _ci = value; } } } [Test] public void SetCultureInfoProperty() { CultureTestObject o = new CultureTestObject(); ObjectWrapper wrapper = GetWrapper(o); wrapper.SetPropertyValue("Cult", "es-ES"); Assert.AreEqual("es-ES", ((CultureInfo) wrapper.GetPropertyValue("Cult")).Name); } #endregion #region Tests for URI Properties internal class URITestObject { private Uri _uri; public Uri ResourceIdentifier { get { return _uri; } set { _uri = value; } } } [Test] public void SetURIProperty() { URITestObject o = new URITestObject(); ObjectWrapper wrapper = GetWrapper(o); wrapper.SetPropertyValue("ResourceIdentifier", "http://www.springframework.net"); Assert.AreEqual("www.springframework.net", ((Uri) wrapper.GetPropertyValue("ResourceIdentifier")).Host); } #endregion #region Tests for Indexed Array Properties [Test] public void GetIndexedFromArrayProperty() { PrimitiveArrayObject to = new PrimitiveArrayObject(); IObjectWrapper wrapper = GetWrapper(to); to.Array = new int[] {1, 2, 3, 4, 5}; Assert.AreEqual(1, (int) wrapper.GetPropertyValue("Array[0]")); } [Test] public void GetIndexOutofRangeFromArrayProperty() { PrimitiveArrayObject to = new PrimitiveArrayObject(); IObjectWrapper wrapper = GetWrapper(to); to.Array = new int[] {1, 2, 3, 4, 5}; Assert.Throws<InvalidPropertyException>(() => wrapper.GetPropertyValue("Array[5]")); } [Test] public void SetIndexedFromArrayProperty() { PrimitiveArrayObject to = new PrimitiveArrayObject(); IObjectWrapper wrapper = GetWrapper(to); to.Array = new int[] {1, 2, 3, 4, 5}; wrapper.SetPropertyValue("Array[2]", 6); Assert.AreEqual(6, to.Array[2]); } [Test] public void SetIndexOutOfRangeFromArrayProperty() { PrimitiveArrayObject to = new PrimitiveArrayObject(); IObjectWrapper wrapper = GetWrapper(to); to.Array = new int[] {1, 2, 3, 4, 5}; Assert.Throws<InvalidPropertyException>(() => wrapper.SetPropertyValue("Array[5]", 6)); } /// <summary> /// Test that we bail when attempting to get an indexed property with some guff for the index /// </summary> [Test] public void GetIndexedPropertyValueWithGuffIndexFromArrayProperty() { PrimitiveArrayObject to = new PrimitiveArrayObject(); IObjectWrapper wrapper = GetWrapper(to); to.Array = new int[] {1, 2, 3, 4, 5}; Assert.Throws<InvalidPropertyException>(() => wrapper.GetPropertyValue("Array[HungerHurtsButStarvingWorks]")); } /// <summary> /// Test that we bail when attempting to get an indexed property with some guff for the index /// </summary> [Test] public void GetIndexedPropertyValueWithMissingIndexFromArrayProperty() { PrimitiveArrayObject to = new PrimitiveArrayObject(); IObjectWrapper wrapper = GetWrapper(to); to.Array = new int[] {1, 2, 3, 4, 5}; Assert.Throws<InvalidPropertyException>(() => wrapper.GetPropertyValue("Array[]")); } #endregion #region Tests for Indexed List Properties internal class ListTestObject { private IList _list; private ArrayList _arrayList; public IList List { get { return _list; } set { _list = value; } } public ArrayList ArrayList { get { return _arrayList; } set { _arrayList = value; } } } [Test] public void GetIndexedFromListProperty() { ListTestObject to = new ListTestObject(); IObjectWrapper wrapper = GetWrapper(to); to.List = new ArrayList(new int[] {1, 2, 3, 4, 5}); Assert.AreEqual(1, (int) wrapper.GetPropertyValue("List[0]")); } [Test] public void GetIndexedFromArrayListProperty() { ListTestObject to = new ListTestObject(); IObjectWrapper wrapper = GetWrapper(to); to.ArrayList = new ArrayList(new int[] {1, 2, 3, 4, 5}); Assert.AreEqual(1, (int) wrapper.GetPropertyValue("ArrayList[0]")); } [Test] public void GetIndexOutofRangeFromListProperty() { ListTestObject to = new ListTestObject(); IObjectWrapper wrapper = GetWrapper(to); to.List = new ArrayList(new int[] {1, 2, 3, 4, 5}); Assert.Throws<InvalidPropertyException>(() => wrapper.GetPropertyValue("List[5]")); } [Test] public void SetIndexedFromListProperty() { ListTestObject to = new ListTestObject(); IObjectWrapper wrapper = GetWrapper(to); to.List = new ArrayList(new int[] {1, 2, 3, 4, 5}); wrapper.SetPropertyValue("List[0]", 6); Assert.AreEqual(6, to.List[0]); } [Test] public void SetIndexedFromListPropertyUsingMixOfSingleAndDoubleQuotedDelimeters() { ListTestObject to = new ListTestObject(); IObjectWrapper wrapper = GetWrapper(to); to.List = new ArrayList(new int[] {1, 2, 3, 4, 5}); Assert.Throws<InvalidPropertyException>(() => wrapper.SetPropertyValue("List['0\"]", 6)); } [Test] public void SetIndexedFromListPropertyUsingNonNumericValueForTheIndex() { ListTestObject to = new ListTestObject(); IObjectWrapper wrapper = GetWrapper(to); to.List = new ArrayList(new int[] {1, 2, 3, 4, 5}); Assert.Throws<InvalidPropertyException>(() => wrapper.SetPropertyValue("List[bingo]", 6)); } [Test] public void SetIndexedFromListPropertyUsingEmptyValueForTheIndex() { ListTestObject to = new ListTestObject(); IObjectWrapper wrapper = GetWrapper(to); to.List = new ArrayList(new int[] {1, 2, 3, 4, 5}); Assert.Throws<InvalidPropertyException>(() => wrapper.SetPropertyValue("List[]", 6)); } [Test] [Ignore("Addition of elements to the list via index that is out of range is not supported anymore.")] public void SetIndexOutOfRangeFromListProperty() { ListTestObject to = new ListTestObject(); IObjectWrapper wrapper = GetWrapper(to); to.List = new ArrayList(new int[] {1, 2, 3, 4, 5}); wrapper.SetPropertyValue("List[6]", 6); Assert.AreEqual(6, to.List[6]); Assert.IsNull(to.List[5]); wrapper.SetPropertyValue("List[7]", 7); Assert.AreEqual(7, to.List[7]); } /// <summary> /// Test that we bail when attempting to get an indexed property with some guff for the index /// </summary> [Test] public void GetIndexedPropertyValueWithGuffIndexFromListProperty() { ListTestObject to = new ListTestObject(); IObjectWrapper wrapper = GetWrapper(to); to.List = new ArrayList(new int[] {1, 2, 3, 4, 5}); Assert.Throws<InvalidPropertyException>(() => wrapper.GetPropertyValue("List[HungerHurtsButStarvingWorks]")); } [Test] public void GetIndexedPropertyValueWithMissingIndexFromListProperty() { ListTestObject to = new ListTestObject(); IObjectWrapper wrapper = GetWrapper(to); to.List = new ArrayList(new int[] {1, 2, 3, 4, 5}); Assert.Throws<InvalidPropertyException>(() => wrapper.GetPropertyValue("List[]")); } #endregion #region Tests for Indexed Dictionary Properties internal class DictionaryTestObject { private IDictionary _dictionary; public IDictionary Dictionary { get { return _dictionary; } set { _dictionary = value; } } } [Test] public void GetIndexedFromDictionaryProperty() { DictionaryTestObject to = new DictionaryTestObject(); IObjectWrapper wrapper = GetWrapper(to); to.Dictionary = new Hashtable(); to.Dictionary.Add("key1", "value1"); Assert.AreEqual("value1", (string) wrapper.GetPropertyValue("Dictionary['key1']")); } [Test] public void GetIndexMissingFromDictionaryProperty() { DictionaryTestObject to = new DictionaryTestObject(); IObjectWrapper wrapper = GetWrapper(to); to.Dictionary = new Hashtable(); Assert.IsNull(wrapper.GetPropertyValue("Dictionary['notthere']")); } [Test] public void SetIndexedFromDictionaryProperty() { DictionaryTestObject to = new DictionaryTestObject(); IObjectWrapper wrapper = GetWrapper(to); to.Dictionary = new Hashtable(); wrapper.SetPropertyValue("Dictionary['key1']", "value1"); Assert.AreEqual("value1", to.Dictionary["key1"]); } [Test] public void SettingADictionaryPropertyJustAddsTheValuesToTheExistingDictionary() { TestObject to = new TestObject(); to.AddPeriodicElement("Hsu", "Feng"); to.AddPeriodicElement("Piao", "Jin"); ObjectWrapper wrapper = GetWrapper(to); IDictionary elements = new Hashtable(); elements.Add("Weekend", "News"); wrapper.SetPropertyValue("PeriodictabLE", elements); Assert.AreEqual(3, to.PeriodicTable.Count); } #endregion #region Tests for Indexed Set Properties internal class SetTestObject { private ISet _set; private HybridSet _aSet; public ISet Set { get { return _set; } set { _set = value; } } public HybridSet HybridSet { get { return _aSet; } set { _aSet = value; } } } [Test] public void SettingASetPropertyJustAddsTheValuesToTheExistingSet() { TestObject to = new TestObject(); to.AddComputerName("Atari 2900"); to.AddComputerName("JCN"); ObjectWrapper wrapper = GetWrapper(to); wrapper.SetPropertyValue("Computers", new HybridSet(new string[] {"Trusty SNES"})); Assert.AreEqual(3, to.Computers.Count); } [Test] public void GetIndexFromSetProperty() { SetTestObject to = new SetTestObject(); IObjectWrapper wrapper = GetWrapper(to); to.Set = new ListSet(new int[] { 1, 2, 3, 4, 5 }); Assert.Throws<InvalidPropertyException>(() => wrapper.GetPropertyValue("Set[1]")); } [Test] public void GetIndexOutofRangeFromSetProperty() { SetTestObject to = new SetTestObject(); IObjectWrapper wrapper = GetWrapper(to); to.Set = new ListSet(new int[] {1, 2, 3, 4, 5}); Assert.Throws<InvalidPropertyException>(() => wrapper.GetPropertyValue("Set[23]")); } /// <summary> /// Test that we bail when attempting to get an indexed property with some guff for the index /// </summary> [Test] public void GetIndexedPropertyValueWithGuffIndexFromSetProperty() { SetTestObject to = new SetTestObject(); IObjectWrapper wrapper = GetWrapper(to); to.Set = new ListSet(new int[] {1, 2, 3, 4, 5}); Assert.Throws<InvalidPropertyException>(() => wrapper.GetPropertyValue("Set[HungerHurtsButStarvingWorks]")); } [Test] public void GetIndexedPropertyValueWithMissingIndexFromSetProperty() { SetTestObject to = new SetTestObject(); IObjectWrapper wrapper = GetWrapper(to); to.Set = new ListSet(new int[] {1, 2, 3, 4, 5}); Assert.Throws<InvalidPropertyException>(() => wrapper.GetPropertyValue("Set[]")); } #endregion #region Test for Enumeration Properties internal class EnumTestObject { private FileMode FileModeEnum; public FileMode FileMode { get { return FileModeEnum; } set { FileModeEnum = value; } } } [Test] public void SetEnumProperty() { EnumTestObject o = new EnumTestObject(); ObjectWrapper wrapper = GetWrapper(o); wrapper.SetPropertyValue("FileMode", FileMode.Create); Assert.AreEqual(FileMode.Create, (FileMode) wrapper.GetPropertyValue("FileMode")); } #endregion [Test] public void SetTypePropertyWithString() { ObjectWithTypeProperty to = new ObjectWithTypeProperty(); IObjectWrapper wrapper = GetWrapper(to); wrapper.SetPropertyValue("Type", "System.DateTime"); Assert.AreEqual(typeof (DateTime), to.Type); } [Test] public void GetIndexedPropertyValueWithNonIndexedType() { TestObject to = new TestObject(); IObjectWrapper wrapper = GetWrapper(to); Assert.Throws<InvalidPropertyException>(() => wrapper.GetPropertyValue("FileMode[0]")); } [Test] public void SetPropertyValuesWithUnknownProperty() { TestObject to = new TestObject(); to.Doctor = null; ObjectWrapper wrapper = GetWrapper(to); Assert.Throws<NullValueInNestedPathException>(() => wrapper.SetPropertyValue("Doctor.Company", "Bingo")); } [Test] public void SetPropertyValuesFailsWhenSettingNonExistantProperty() { TestObject to = new TestObject(); ObjectWrapper wrapper = GetWrapper(to); MutablePropertyValues values = new MutablePropertyValues(); values.Add("JeepersCreepersWhereDidYaGetThosePeepers", "OhThisWeirdBatGuySoldEmToMe..."); values.Add("Age", 19); // the unknown and ridiculously named property should fail Assert.Throws<InvalidPropertyException>(() => wrapper.SetPropertyValues(values, false)); } [Test] public void SetPropertyValuesDoesNotFailWhenSettingNonExistantPropertyWithIgnorUnknownSetToTrue() { TestObject to = new TestObject(); ObjectWrapper wrapper = GetWrapper(to); MutablePropertyValues values = new MutablePropertyValues(); values.Add("Age", 19); values.Add("JeepersCreepersWhereDidYaGetThosePeepers", "OhThisWeirdBatGuySoldEmToMe..."); // the unknown and ridiculously named property should fail wrapper.SetPropertyValues(values, true); Assert.AreEqual(19, to.Age, "The single good property in the property values should have been set though..."); } [Test] public void SetPropertyValuesFailsWhenSettingReadOnlyProperty() { TestObject to = new TestObject(); ObjectWrapper wrapper = GetWrapper(to); MutablePropertyValues values = new MutablePropertyValues(); values.Add("ReadOnlyObjectNumber", 123); Assert.Throws<NotWritablePropertyException>(() => wrapper.SetPropertyValues(values, false)); } [Test] public void SetPropertyValuesDoesNotFailWhenSettingReadOnlyPropertyWithIgnorUnknownSetToTrue() { TestObject to = new TestObject(); ObjectWrapper wrapper = GetWrapper(to); MutablePropertyValues values = new MutablePropertyValues(); values.Add("ObjectNumber", 123); values.Add("Age", 19); wrapper.SetPropertyValues(values, true); Assert.AreEqual(19, to.Age, "The single good property in the property values should have been set though..."); } [Test] public void SetArrayPropertyValue() { string[] expected = new string[] {"Fedora", "Gacy", "Banjo"}; TestObject to = new TestObject(); ObjectWrapper wrapper = GetWrapper(to); wrapper.SetPropertyValue("Hats", expected); Assert.IsNotNull(to.Hats); Assert.AreEqual(expected.Length, to.Hats.Length); for (int i = 0; i < expected.Length; ++i) { Assert.AreEqual(expected[i], to.Hats[i]); } } [Test] public void TestToString() { ObjectWrapper wrapper = GetWrapper(); Assert.IsTrue(wrapper.ToString().IndexOf("Exception encountered") >= 0); wrapper.WrappedInstance = new WanPropsClass(); string expected = string.Format( "{0}: wrapping class [{1}]; IsWan={2}", wrapper.GetType().Name, wrapper.WrappedType.FullName, "{True}"); Assert.AreEqual(expected, wrapper.ToString()); } [Test] public void GetPropertyInfoWithNullArgument() { ObjectWrapper wrapper = GetWrapper(new TestObject()); Assert.Throws<FatalObjectException>(() => wrapper.GetPropertyInfo(null)); } [Test] public void GetPropertyInfoWithNonPropertyExpression() { ObjectWrapper wrapper = GetWrapper(new TestObject()); Assert.Throws<FatalReflectionException>(() => wrapper.GetPropertyInfo("2 + 2")); } [Test] public void GetPropertyInfoWithNonParsableExpression() { ObjectWrapper wrapper = GetWrapper(new TestObject()); Assert.Throws<FatalObjectException>(() => wrapper.GetPropertyInfo("[")); } [Test] public void GetNestedPropertyInfo() { RealNestedTestObject o = new RealNestedTestObject(); o.Datum = new TestObject(); o.Datum.Doctor = new NestedTestObject("Modlin"); ObjectWrapper wrapper = GetWrapper(o); PropertyInfo info = wrapper.GetPropertyInfo("Datum.Doctor.Company"); Assert.IsNotNull(info); } [Test(Description="SPRNET-198")] public void AmbiguousPropertyLookupIsHandledProperlyByLookingAtDerivedClassOnly() { ObjectWrapper wrapper = GetWrapper(new DerivedFoo()); wrapper.GetPropertyInfo("Bar"); } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion namespace System.Patterns.Caching { /// <summary> /// Represents a generic cache-based storage object. Provides an abstraction from the inherent caching mechanism /// provides by a given Application Type (WebApplication, etc) and the generic implementation used. Also /// provides a basic facade pattern over the implicit ASP.NET Caching mechanism. /// </summary> public partial class CacheEx { /// <summary> /// Provides <see cref="System.DateTime"/> instance to be used when no absolute expiration value to be set. /// </summary> public static readonly DateTime NoAbsoluteExpiration = DateTime.MaxValue; /// <summary> /// Provides <see cref="System.TimeSpan"/> instance to be used when no sliding expiration value to be set. /// </summary> public static readonly TimeSpan NoSlidingExpiration = TimeSpan.Zero; private static CacheProviderBase s_cacheProvider = new StaticCacheProvider(); //KernelFactory.s_configSection.CacheProvider; private string _salt; public static readonly CacheEx Default = new CacheEx(); public static readonly object s_lock = new object(); /// <summary> /// Initializes a new instance of the <see cref="Cache"/> class. /// </summary> internal CacheEx() : base() { } /// <summary> /// Initializes a new instance of the <see cref="Cache"/> class. /// </summary> /// <param name="salt">The salt.</param> internal CacheEx(string salt) : base() { _salt = salt; } public static void SetCacheProvider(Func<CacheProviderBase> cacheProvider) { lock (s_lock) { if (s_cacheProvider != null) s_cacheProvider.Dispose(); s_cacheProvider = (CacheProviderBase)cacheProvider(); } } /// <summary> /// Gets or sets the <see cref="System.Object"/> with the specified key. /// </summary> /// <value></value> public object this[string key] { get { return s_cacheProvider.Get(_salt == null ? key : _salt + key); } set { if (s_cacheProvider == null) throw new ArgumentNullException(); if (_salt != null) key = _salt + key; s_cacheProvider.Insert(key, value, null, DateTime.Now.AddMinutes(60), CacheEx.NoSlidingExpiration, CacheItemPriority.Normal, null); } } /// <summary> /// Adds the specified key. /// </summary> /// <param name="key">The key to use.</param> /// <param name="value">The value to add to cache.</param> /// <param name="dependency">The dependency object to use.</param> /// <param name="absoluteExpiration">The absolute expiration to use to define when the cache entry becomes invalid.</param> /// <param name="slidingExpiration">The sliding expiration to use to determine when an unused cache entry becomes invalid.</param> /// <param name="priority">The cache item priority to apply.</param> /// <param name="onRemoveCallback">The delegate to invoke when the item is removed from cache.</param> /// <returns></returns> public object Add(string key, object value, CacheDependency dependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback) { if (s_cacheProvider == null) throw new ArgumentNullException(); // ensure-dependency if (dependency != null) EnsureDependency(dependency); // add item return s_cacheProvider.Add((_salt == null ? key : _salt + key), value, dependency, absoluteExpiration, slidingExpiration, priority, onRemoveCallback); } /// <summary> /// Adds the value provided to cache using the information provided by the CacheCommand instance provided. /// </summary> /// <param name="cacheCommand">The cache command.</param> /// <param name="value">The value.</param> /// <returns></returns> public object Add(CacheCommand cacheCommand, object value) { if (cacheCommand == null) throw new ArgumentNullException("cacheCommand"); return AddInternal(cacheCommand.Key, cacheCommand, value); } /// <summary> /// Adds the value provided to cache using the information provided by the CacheCommand instance provided. /// </summary> /// <param name="key">The key to use.</param> /// <param name="cacheCommand">The cache command.</param> /// <param name="value">The value.</param> /// <returns></returns> internal object AddInternal(string key, CacheCommand cacheCommand, object value) { if (s_cacheProvider == null) throw new ArgumentNullException(); if (cacheCommand == null) throw new ArgumentNullException("cacheCommand"); // ensure-dependency var dependency = cacheCommand.Dependency; if (dependency != null) EnsureDependency(dependency); // add item var itemAddedCallback = cacheCommand.ItemAddedCallback; if (itemAddedCallback != null) itemAddedCallback(key, value); return s_cacheProvider.Add((_salt == null ? key : _salt + key), value, dependency, cacheCommand.AbsoluteExpiration, cacheCommand.SlidingExpiration, cacheCommand.Priority, cacheCommand.ItemRemovedCallback); } /// <summary> /// Ensures the dependency. /// </summary> /// <param name="dependency">The dependency.</param> private void EnsureDependency(CacheDependency dependency) { if (s_cacheProvider == null) throw new ArgumentNullException(); string[] cacheKeys = dependency.CacheKeys; if (cacheKeys != null) foreach (string cacheKey in cacheKeys) s_cacheProvider.Add(cacheKey, string.Empty, null, CacheEx.NoAbsoluteExpiration, CacheEx.NoSlidingExpiration, CacheItemPriority.Normal, null); } /// <summary> /// Adds the specified key. /// </summary> /// <param name="key">The key to use.</param> /// <param name="value">The value to add to cache.</param> /// <param name="dependency">The dependency object to use.</param> /// <param name="absoluteExpiration">The absolute expiration to use to define when the cache entry becomes invalid.</param> /// <param name="slidingExpiration">The sliding expiration to use to determine when an unused cache entry becomes invalid.</param> /// <param name="priority">The cache item priority to apply.</param> /// <param name="onRemoveCallback">The delegate to invoke when the item is removed from cache.</param> public void Insert(string key, object value, CacheDependency dependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback) { if (s_cacheProvider == null) throw new ArgumentNullException(); // ensure-dependency if (dependency != null) EnsureDependency(dependency); // add item s_cacheProvider.Insert((_salt == null ? key : _salt + key), value, dependency, absoluteExpiration, slidingExpiration, priority, onRemoveCallback); } /// <summary> /// Adds the value provided to cache using the information provided by the CacheCommand instance provided. /// </summary> /// <param name="cacheCommand">The cache command.</param> /// <param name="value">The value.</param> public void Insert(CacheCommand cacheCommand, object value) { if (cacheCommand == null) throw new ArgumentNullException("cacheCommand"); InsertInternal(cacheCommand.Key, cacheCommand, value); } /// <summary> /// Insert the value provided to cache using the information provided by the CacheCommand instance provided. /// </summary> /// <param name="key">The key to use.</param> /// <param name="cacheCommand">The cache command.</param> /// <param name="value">The value.</param> internal void InsertInternal(string key, CacheCommand cacheCommand, object value) { if (s_cacheProvider == null) throw new ArgumentNullException(); if (cacheCommand == null) throw new ArgumentNullException("cacheCommand"); // ensure-dependency var dependency = cacheCommand.Dependency; if (dependency != null) EnsureDependency(dependency); // add item var itemAddedCallback = cacheCommand.ItemAddedCallback; if (itemAddedCallback != null) itemAddedCallback(key, value); s_cacheProvider.Insert((_salt == null ? key : _salt + key), value, dependency, cacheCommand.AbsoluteExpiration, cacheCommand.SlidingExpiration, cacheCommand.Priority, cacheCommand.ItemRemovedCallback); } /// <summary> /// Removes the item from cache with the specific key. /// </summary> /// <param name="key">The cache item key.</param> /// <returns></returns> public object Remove(string key) { if (s_cacheProvider == null) throw new ArgumentNullException(); return s_cacheProvider.Remove(_salt == null ? key : _salt + key); } /// <summary> /// Removes the item from cached associated with the information contained within the provide CacheCommand instance. /// </summary> /// <param name="cacheCommand">The cache command.</param> /// <returns></returns> public object Remove(CacheCommand cacheCommand) { if (s_cacheProvider == null) throw new ArgumentNullException(); if (cacheCommand == null) throw new ArgumentNullException("cacheCommand"); return s_cacheProvider.Remove(_salt == null ? cacheCommand.Key : _salt + cacheCommand.Key); } public static CacheEx GetNamespace(object[] values) { if (values == null) throw new ArgumentNullException("values"); // add one additional item, so join ends with scope character. string[] valuesAsText = new string[values.Length + 1]; for (int valueIndex = 0; valueIndex < values.Length; valueIndex++) { object value = values[valueIndex]; valuesAsText[valueIndex] = (value != null ? "." + value.ToString() : string.Empty); } // set additional item to null incase declaration doesnt clear value valuesAsText[valuesAsText.Length - 1] = null; return new CacheEx(string.Join(CoreEx.Scope, valuesAsText)); } /// <summary> /// Touches the specified key. /// </summary> /// <param name="key">The key.</param> public void Touch(string key) { if (s_cacheProvider == null) throw new ArgumentNullException(); s_cacheProvider.Touch(key); } /// <summary> /// Touches the specified key array. /// </summary> /// <param name="keys">The keys.</param> public void Touch(params string[] keys) { if (s_cacheProvider == null) throw new ArgumentNullException(); foreach (string key in keys) s_cacheProvider.Touch(key); } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // ConfigurationSaveTest.cs // // Author: // Martin Baulig <[email protected]> // // Copyright (c) 2012 Xamarin Inc. (http://www.xamarin.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.IO; using System.Xml; using System.Xml.Schema; using System.Xml.XPath; using System.Text; using System.Reflection; using System.Globalization; using System.Configuration; using System.Collections.Generic; using SysConfig = System.Configuration.Configuration; using Xunit; namespace MonoTests.System.Configuration { using Util; public class ConfigurationSaveTest { #region Test Framework public abstract class ConfigProvider { public void Create(string filename) { if (File.Exists(filename)) File.Delete(filename); var settings = new XmlWriterSettings(); settings.Indent = true; using (var writer = XmlTextWriter.Create(filename, settings)) { writer.WriteStartElement("configuration"); WriteXml(writer); writer.WriteEndElement(); } } public abstract UserLevel Level { get; } public enum UserLevel { MachineAndExe, RoamingAndExe } public virtual SysConfig OpenConfig(string parentFile, string configFile) { ConfigurationUserLevel level; var map = new ExeConfigurationFileMap(); switch (Level) { case UserLevel.MachineAndExe: map.ExeConfigFilename = configFile; map.MachineConfigFilename = parentFile; level = ConfigurationUserLevel.None; break; case UserLevel.RoamingAndExe: map.RoamingUserConfigFilename = configFile; map.ExeConfigFilename = parentFile; level = ConfigurationUserLevel.PerUserRoaming; break; default: throw new InvalidOperationException(); } return ConfigurationManager.OpenMappedExeConfiguration(map, level); } protected abstract void WriteXml(XmlWriter writer); } public abstract class MachineConfigProvider : ConfigProvider { protected override void WriteXml(XmlWriter writer) { writer.WriteStartElement("configSections"); WriteSections(writer); writer.WriteEndElement(); WriteValues(writer); } public override UserLevel Level { get { return UserLevel.MachineAndExe; } } protected abstract void WriteSections(XmlWriter writer); protected abstract void WriteValues(XmlWriter writer); } class DefaultMachineConfig : MachineConfigProvider { protected override void WriteSections(XmlWriter writer) { writer.WriteStartElement("section"); writer.WriteAttributeString("name", "my"); writer.WriteAttributeString("type", typeof(MySection).AssemblyQualifiedName); writer.WriteAttributeString("allowLocation", "true"); writer.WriteAttributeString("allowDefinition", "Everywhere"); writer.WriteAttributeString("allowExeDefinition", "MachineToRoamingUser"); writer.WriteAttributeString("restartOnExternalChanges", "true"); writer.WriteAttributeString("requirePermission", "true"); writer.WriteEndElement(); } internal static void WriteConfigSections(XmlWriter writer) { var provider = new DefaultMachineConfig(); writer.WriteStartElement("configSections"); provider.WriteSections(writer); writer.WriteEndElement(); } protected override void WriteValues(XmlWriter writer) { writer.WriteStartElement("my"); writer.WriteEndElement(); } } class DefaultMachineConfig2 : MachineConfigProvider { protected override void WriteSections(XmlWriter writer) { writer.WriteStartElement("section"); writer.WriteAttributeString("name", "my2"); writer.WriteAttributeString("type", typeof(MySection2).AssemblyQualifiedName); writer.WriteAttributeString("allowLocation", "true"); writer.WriteAttributeString("allowDefinition", "Everywhere"); writer.WriteAttributeString("allowExeDefinition", "MachineToRoamingUser"); writer.WriteAttributeString("restartOnExternalChanges", "true"); writer.WriteAttributeString("requirePermission", "true"); writer.WriteEndElement(); } internal static void WriteConfigSections(XmlWriter writer) { var provider = new DefaultMachineConfig2(); writer.WriteStartElement("configSections"); provider.WriteSections(writer); writer.WriteEndElement(); } protected override void WriteValues(XmlWriter writer) { } } abstract class ParentProvider : ConfigProvider { protected override void WriteXml(XmlWriter writer) { DefaultMachineConfig.WriteConfigSections(writer); writer.WriteStartElement("my"); writer.WriteStartElement("test"); writer.WriteAttributeString("Hello", "29"); writer.WriteEndElement(); writer.WriteEndElement(); } } class RoamingAndExe : ParentProvider { public override UserLevel Level { get { return UserLevel.RoamingAndExe; } } } private delegate void TestFunction(SysConfig config, TestLabel label); private delegate void XmlCheckFunction(XPathNavigator nav, TestLabel label); private static void Run(string name, TestFunction func) { var label = new TestLabel(name); TestUtil.RunWithTempFile(filename => { var fileMap = new ExeConfigurationFileMap(); fileMap.ExeConfigFilename = filename; var config = ConfigurationManager.OpenMappedExeConfiguration( fileMap, ConfigurationUserLevel.None); func(config, label); }); } private static void Run<TConfig>(string name, TestFunction func) where TConfig : ConfigProvider, new() { Run<TConfig>(new TestLabel(name), func, null); } private static void Run<TConfig>(TestLabel label, TestFunction func) where TConfig : ConfigProvider, new() { Run<TConfig>(label, func, null); } private static void Run<TConfig>( string name, TestFunction func, XmlCheckFunction check) where TConfig : ConfigProvider, new() { Run<TConfig>(new TestLabel(name), func, check); } private static void Run<TConfig>( TestLabel label, TestFunction func, XmlCheckFunction check) where TConfig : ConfigProvider, new() { TestUtil.RunWithTempFiles((parent, filename) => { var provider = new TConfig(); provider.Create(parent); Assert.False(File.Exists(filename)); var config = provider.OpenConfig(parent, filename); Assert.False(File.Exists(filename)); try { label.EnterScope("config"); func(config, label); } finally { label.LeaveScope(); } if (check == null) return; var xml = new XmlDocument(); xml.Load(filename); var nav = xml.CreateNavigator().SelectSingleNode("/configuration"); try { label.EnterScope("xml"); check(nav, label); } finally { label.LeaveScope(); } }); } #endregion #region Assertion Helpers static void AssertNotModified(MySection my, TestLabel label) { label.EnterScope("modified"); Assert.NotNull(my); Assert.False(my.IsModified, label.Get()); Assert.NotNull(my.List); Assert.Equal(0, my.List.Collection.Count); Assert.False(my.List.IsModified, label.Get()); label.LeaveScope(); } static void AssertListElement(XPathNavigator nav, TestLabel label) { Assert.True(nav.HasChildren, label.Get()); var iter = nav.SelectChildren(XPathNodeType.Element); Assert.Equal(1, iter.Count); Assert.True(iter.MoveNext(), label.Get()); var my = iter.Current; label.EnterScope("my"); Assert.Equal("my", my.Name); Assert.False(my.HasAttributes, label.Get()); label.EnterScope("children"); Assert.True(my.HasChildren, label.Get()); var iter2 = my.SelectChildren(XPathNodeType.Element); Assert.Equal(1, iter2.Count); Assert.True(iter2.MoveNext(), label.Get()); var test = iter2.Current; label.EnterScope("test"); Assert.Equal("test", test.Name); Assert.False(test.HasChildren, label.Get()); Assert.True(test.HasAttributes, label.Get()); var attr = test.GetAttribute("Hello", string.Empty); Assert.Equal("29", attr); label.LeaveScope(); label.LeaveScope(); label.LeaveScope(); } #endregion #region Tests [Fact] public void DefaultValues() { Run<DefaultMachineConfig>("DefaultValues", (config, label) => { var my = config.Sections["my"] as MySection; AssertNotModified(my, label); label.EnterScope("file"); Assert.False(File.Exists(config.FilePath), label.Get()); config.Save(ConfigurationSaveMode.Minimal); Assert.False(File.Exists(config.FilePath), label.Get()); label.LeaveScope(); }); } [Fact] public void AddDefaultListElement() { Run<DefaultMachineConfig>("AddDefaultListElement", (config, label) => { var my = config.Sections["my"] as MySection; AssertNotModified(my, label); label.EnterScope("add"); var element = my.List.Collection.AddElement(); Assert.True(my.IsModified, label.Get()); Assert.True(my.List.IsModified, label.Get()); Assert.True(my.List.Collection.IsModified, label.Get()); Assert.False(element.IsModified, label.Get()); label.LeaveScope(); config.Save(ConfigurationSaveMode.Minimal); Assert.False(File.Exists(config.FilePath), label.Get()); }); } [Fact] public void AddDefaultListElement2() { Run<DefaultMachineConfig>("AddDefaultListElement2", (config, label) => { var my = config.Sections["my"] as MySection; AssertNotModified(my, label); label.EnterScope("add"); var element = my.List.Collection.AddElement(); Assert.True(my.IsModified, label.Get()); Assert.True(my.List.IsModified, label.Get()); Assert.True(my.List.Collection.IsModified, label.Get()); Assert.False(element.IsModified, label.Get()); label.LeaveScope(); config.Save(ConfigurationSaveMode.Modified); Assert.True(File.Exists(config.FilePath), label.Get()); }, (nav, label) => { Assert.True(nav.HasChildren, label.Get()); var iter = nav.SelectChildren(XPathNodeType.Element); Assert.Equal(1, iter.Count); Assert.True(iter.MoveNext(), label.Get()); var my = iter.Current; label.EnterScope("my"); Assert.Equal("my", my.Name); Assert.False(my.HasAttributes, label.Get()); Assert.False(my.HasChildren, label.Get()); label.LeaveScope(); }); } [Fact] public void AddDefaultListElement3() { Run<DefaultMachineConfig>("AddDefaultListElement3", (config, label) => { var my = config.Sections["my"] as MySection; AssertNotModified(my, label); label.EnterScope("add"); var element = my.List.Collection.AddElement(); Assert.True(my.IsModified, label.Get()); Assert.True(my.List.IsModified, label.Get()); Assert.True(my.List.Collection.IsModified, label.Get()); Assert.False(element.IsModified, label.Get()); label.LeaveScope(); config.Save(ConfigurationSaveMode.Full); Assert.True(File.Exists(config.FilePath), label.Get()); }, (nav, label) => { Assert.True(nav.HasChildren, label.Get()); var iter = nav.SelectChildren(XPathNodeType.Element); Assert.Equal(1, iter.Count); Assert.True(iter.MoveNext(), label.Get()); var my = iter.Current; label.EnterScope("my"); Assert.Equal("my", my.Name); Assert.False(my.HasAttributes, label.Get()); label.EnterScope("children"); Assert.True(my.HasChildren, label.Get()); var iter2 = my.SelectChildren(XPathNodeType.Element); Assert.Equal(2, iter2.Count); label.EnterScope("list"); var iter3 = my.Select("list/*"); Assert.Equal(1, iter3.Count); Assert.True(iter3.MoveNext(), label.Get()); var collection = iter3.Current; Assert.Equal("collection", collection.Name); Assert.False(collection.HasChildren, label.Get()); Assert.True(collection.HasAttributes, label.Get()); var hello = collection.GetAttribute("Hello", string.Empty); Assert.Equal("8", hello); var world = collection.GetAttribute("World", string.Empty); Assert.Equal("0", world); label.LeaveScope(); label.EnterScope("test"); var iter4 = my.Select("test"); Assert.Equal(1, iter4.Count); Assert.True(iter4.MoveNext(), label.Get()); var test = iter4.Current; Assert.Equal("test", test.Name); Assert.False(test.HasChildren, label.Get()); Assert.True(test.HasAttributes, label.Get()); var hello2 = test.GetAttribute("Hello", string.Empty); Assert.Equal("8", hello2); var world2 = test.GetAttribute("World", string.Empty); Assert.Equal("0", world2); label.LeaveScope(); label.LeaveScope(); label.LeaveScope(); }); } [Fact] public void AddListElement() { Run<DefaultMachineConfig>("AddListElement", (config, label) => { var my = config.Sections["my"] as MySection; AssertNotModified(my, label); my.Test.Hello = 29; label.EnterScope("file"); Assert.False(File.Exists(config.FilePath), label.Get()); config.Save(ConfigurationSaveMode.Minimal); Assert.True(File.Exists(config.FilePath), label.Get()); label.LeaveScope(); }, (nav, label) => { AssertListElement(nav, label); }); } [Fact] public void NotModifiedAfterSave() { Run<DefaultMachineConfig>("NotModifiedAfterSave", (config, label) => { var my = config.Sections["my"] as MySection; AssertNotModified(my, label); label.EnterScope("add"); var element = my.List.Collection.AddElement(); Assert.True(my.IsModified, label.Get()); Assert.True(my.List.IsModified, label.Get()); Assert.True(my.List.Collection.IsModified, label.Get()); Assert.False(element.IsModified, label.Get()); label.LeaveScope(); label.EnterScope("1st-save"); config.Save(ConfigurationSaveMode.Minimal); Assert.False(File.Exists(config.FilePath), label.Get()); config.Save(ConfigurationSaveMode.Modified); Assert.False(File.Exists(config.FilePath), label.Get()); label.LeaveScope(); label.EnterScope("modify"); element.Hello = 12; Assert.True(my.IsModified, label.Get()); Assert.True(my.List.IsModified, label.Get()); Assert.True(my.List.Collection.IsModified, label.Get()); Assert.True(element.IsModified, label.Get()); label.LeaveScope(); label.EnterScope("2nd-save"); config.Save(ConfigurationSaveMode.Modified); Assert.True(File.Exists(config.FilePath), label.Get()); Assert.False(my.IsModified, label.Get()); Assert.False(my.List.IsModified, label.Get()); Assert.False(my.List.Collection.IsModified, label.Get()); Assert.False(element.IsModified, label.Get()); label.LeaveScope(); // 2nd-save }); } [Fact] public void AddSection() { Run("AddSection", (config, label) => { Assert.Null(config.Sections["my"]); var my = new MySection(); config.Sections.Add("my2", my); config.Save(ConfigurationSaveMode.Full); Assert.True(File.Exists(config.FilePath), label.Get()); }); } [Fact] public void AddElement() { Run<DefaultMachineConfig>("AddElement", (config, label) => { var my = config.Sections["my"] as MySection; AssertNotModified(my, label); var element = my.List.DefaultCollection.AddElement(); element.Hello = 12; config.Save(ConfigurationSaveMode.Modified); label.EnterScope("file"); Assert.True(File.Exists(config.FilePath), "#c2"); label.LeaveScope(); }, (nav, label) => { Assert.True(nav.HasChildren, label.Get()); var iter = nav.SelectChildren(XPathNodeType.Element); Assert.Equal(1, iter.Count); Assert.True(iter.MoveNext(), label.Get()); var my = iter.Current; label.EnterScope("my"); Assert.Equal("my", my.Name); Assert.False(my.HasAttributes, label.Get()); Assert.True(my.HasChildren, label.Get()); label.EnterScope("children"); var iter2 = my.SelectChildren(XPathNodeType.Element); Assert.Equal(1, iter2.Count); Assert.True(iter2.MoveNext(), label.Get()); var list = iter2.Current; label.EnterScope("list"); Assert.Equal("list", list.Name); Assert.False(list.HasChildren, label.Get()); Assert.True(list.HasAttributes, label.Get()); var attr = list.GetAttribute("Hello", string.Empty); Assert.Equal("12", attr); label.LeaveScope(); label.LeaveScope(); label.LeaveScope(); }); } [Fact] public void ModifyListElement() { Run<RoamingAndExe>("ModifyListElement", (config, label) => { var my = config.Sections["my"] as MySection; AssertNotModified(my, label); my.Test.Hello = 29; label.EnterScope("file"); Assert.False(File.Exists(config.FilePath), label.Get()); config.Save(ConfigurationSaveMode.Minimal); Assert.False(File.Exists(config.FilePath), label.Get()); label.LeaveScope(); }); } [Fact] public void ModifyListElement2() { Run<RoamingAndExe>("ModifyListElement2", (config, label) => { var my = config.Sections["my"] as MySection; AssertNotModified(my, label); my.Test.Hello = 29; label.EnterScope("file"); Assert.False(File.Exists(config.FilePath), label.Get()); config.Save(ConfigurationSaveMode.Modified); Assert.True(File.Exists(config.FilePath), label.Get()); label.LeaveScope(); }, (nav, label) => { AssertListElement(nav, label); }); } [Fact] public void TestElementWithCollection() { Run<DefaultMachineConfig2>("TestElementWithCollection", (config, label) => { label.EnterScope("section"); var my2 = config.Sections["my2"] as MySection2; Assert.NotNull(my2); Assert.NotNull(my2.Test); Assert.NotNull(my2.Test.DefaultCollection); Assert.Equal(0, my2.Test.DefaultCollection.Count); label.LeaveScope(); my2.Test.DefaultCollection.AddElement(); my2.Element.Hello = 29; label.EnterScope("file"); Assert.False(File.Exists(config.FilePath), label.Get()); config.Save(ConfigurationSaveMode.Minimal); Assert.True(File.Exists(config.FilePath), label.Get()); label.LeaveScope(); }, (nav, label) => { Assert.True(nav.HasChildren, label.Get()); var iter = nav.SelectChildren(XPathNodeType.Element); Assert.Equal(1, iter.Count); Assert.True(iter.MoveNext(), label.Get()); var my = iter.Current; label.EnterScope("my2"); Assert.Equal("my2", my.Name); Assert.False(my.HasAttributes, label.Get()); Assert.True(my.HasChildren, label.Get()); label.EnterScope("children"); var iter2 = my.SelectChildren(XPathNodeType.Element); Assert.Equal(1, iter2.Count); Assert.True(iter2.MoveNext(), label.Get()); var element = iter2.Current; label.EnterScope("element"); Assert.Equal("element", element.Name); Assert.False(element.HasChildren, label.Get()); Assert.True(element.HasAttributes, label.Get()); var attr = element.GetAttribute("Hello", string.Empty); Assert.Equal("29", attr); label.LeaveScope(); label.LeaveScope(); label.LeaveScope(); }); } [Fact] public void TestElementWithCollection2() { Run<DefaultMachineConfig2>("TestElementWithCollection2", (config, label) => { label.EnterScope("section"); var my2 = config.Sections["my2"] as MySection2; Assert.NotNull(my2); Assert.NotNull(my2.Test); Assert.NotNull(my2.Test.DefaultCollection); Assert.Equal(0, my2.Test.DefaultCollection.Count); label.LeaveScope(); var element = my2.Test.DefaultCollection.AddElement(); var element2 = element.Test.DefaultCollection.AddElement(); element2.Hello = 1; label.EnterScope("file"); Assert.False(File.Exists(config.FilePath), label.Get()); config.Save(ConfigurationSaveMode.Minimal); Assert.True(File.Exists(config.FilePath), label.Get()); label.LeaveScope(); }, (nav, label) => { Assert.True(nav.HasChildren, label.Get()); var iter = nav.SelectChildren(XPathNodeType.Element); Assert.Equal(1, iter.Count); Assert.True(iter.MoveNext(), label.Get()); var my = iter.Current; label.EnterScope("my2"); Assert.Equal("my2", my.Name); Assert.False(my.HasAttributes, label.Get()); Assert.True(my.HasChildren, label.Get()); label.EnterScope("children"); var iter2 = my.SelectChildren(XPathNodeType.Element); Assert.Equal(1, iter2.Count); Assert.True(iter2.MoveNext(), label.Get()); var collection = iter2.Current; label.EnterScope("collection"); Assert.Equal("collection", collection.Name); Assert.True(collection.HasChildren, label.Get()); Assert.False(collection.HasAttributes, label.Get()); label.EnterScope("children"); var iter3 = collection.SelectChildren(XPathNodeType.Element); Assert.Equal(1, iter3.Count); Assert.True(iter3.MoveNext(), label.Get()); var element = iter3.Current; label.EnterScope("element"); Assert.Equal("test", element.Name); Assert.False(element.HasChildren, label.Get()); Assert.True(element.HasAttributes, label.Get()); var attr = element.GetAttribute("Hello", string.Empty); Assert.Equal("1", attr); label.LeaveScope(); label.LeaveScope(); label.LeaveScope(); label.LeaveScope(); label.LeaveScope(); }); } #endregion #region Configuration Classes public class MyElement : ConfigurationElement { [ConfigurationProperty("Hello", DefaultValue = 8)] public int Hello { get { return (int)base["Hello"]; } set { base["Hello"] = value; } } [ConfigurationProperty("World", IsRequired = false)] public int World { get { return (int)base["World"]; } set { base["World"] = value; } } new public bool IsModified { get { return base.IsModified(); } } } public class MyCollection<T> : ConfigurationElementCollection where T : ConfigurationElement, new() { #region implemented abstract members of ConfigurationElementCollection protected override ConfigurationElement CreateNewElement() { return new T(); } protected override object GetElementKey(ConfigurationElement element) { return ((T)element).GetHashCode(); } #endregion public override ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.BasicMap; } } public T AddElement() { var element = new T(); BaseAdd(element); return element; } public void RemoveElement(T element) { BaseRemove(GetElementKey(element)); } public new bool IsModified { get { return base.IsModified(); } } } public class MyCollectionElement<T> : ConfigurationElement where T : ConfigurationElement, new() { [ConfigurationProperty("", Options = ConfigurationPropertyOptions.IsDefaultCollection, IsDefaultCollection = true)] public MyCollection<T> DefaultCollection { get { return (MyCollection<T>)this[string.Empty]; } set { this[string.Empty] = value; } } [ConfigurationProperty("collection", Options = ConfigurationPropertyOptions.None)] public MyCollection<T> Collection { get { return (MyCollection<T>)this["collection"]; } set { this["collection"] = value; } } public new bool IsModified { get { return base.IsModified(); } } } public class MySection : ConfigurationSection { [ConfigurationProperty("list", Options = ConfigurationPropertyOptions.None)] public MyCollectionElement<MyElement> List { get { return (MyCollectionElement<MyElement>)this["list"]; } } [ConfigurationProperty("test", Options = ConfigurationPropertyOptions.None)] public MyElement Test { get { return (MyElement)this["test"]; } } new public bool IsModified { get { return base.IsModified(); } } } public class MyElementWithCollection : ConfigurationElement { [ConfigurationProperty("test")] public MyCollectionElement<MyElement> Test { get { return (MyCollectionElement<MyElement>)this["test"]; } } } public class MySection2 : ConfigurationSection { [ConfigurationProperty("collection", Options = ConfigurationPropertyOptions.None)] public MyCollectionElement<MyElementWithCollection> Test { get { return (MyCollectionElement<MyElementWithCollection>)this["collection"]; } } [ConfigurationProperty("element", Options = ConfigurationPropertyOptions.None)] public MyElement Element { get { return (MyElement)this["element"]; } } } public class MySectionGroup : ConfigurationSectionGroup { public MySection2 My2 { get { return (MySection2)Sections["my2"]; } } } #endregion } }
#region Header // // Copyright 2003-2019 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // #endregion // Header using System; using System.Diagnostics; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using Autodesk.Revit.DB; namespace RevitLookup.Snoop.Forms { /// <summary> /// Summary description for BindingMap form. /// </summary> public class Geometry : RevitLookup.Snoop.Forms.ObjTreeBase { protected Element m_elem = null; protected Autodesk.Revit.ApplicationServices.Application m_app = null; public Geometry( Autodesk.Revit.DB.Element elem, Autodesk.Revit.ApplicationServices.Application app ) { this.Text = "Element Geometry"; m_elem = elem; m_app = app; m_tvObjs.BeginUpdate(); AddObjectsToTree( elem, m_tvObjs.Nodes ); m_tvObjs.EndUpdate(); } protected void AddObjectsToTree( Element elem, TreeNodeCollection curNodes ) { Autodesk.Revit.DB.Options geomOp; TreeNode tmpNode; // add geometry with the View set to null. TreeNode rootNode1 = new TreeNode( "View = null" ); curNodes.Add( rootNode1 ); foreach( ViewDetailLevel viewDetailLevel in Enum.GetValues( typeof( ViewDetailLevel ) ) ) { tmpNode = new TreeNode( "Detail Level = " + viewDetailLevel.ToString() ); // IMPORTANT!!! Need to create options each time when you are // getting geometry. In other case, all the geometry you got at the // previous step will be owerriten according with the latest DetailLevel geomOp = m_app.Create.NewGeometryOptions(); geomOp.ComputeReferences = true; geomOp.DetailLevel = viewDetailLevel; tmpNode.Tag = elem.get_Geometry( geomOp ); rootNode1.Nodes.Add( tmpNode ); } // add model geometry including geometry objects not set as Visible. TreeNode rootNode = new TreeNode( "View = null - Including geometry objects not set as Visible" ); curNodes.Add( rootNode ); foreach( ViewDetailLevel viewDetailLevel in Enum.GetValues( typeof( ViewDetailLevel ) ) ) { tmpNode = new TreeNode( "Detail Level = " + viewDetailLevel.ToString() ); // IMPORTANT!!! Need to create options each time when you are // getting geometry. In other case, all the geometry you got at the // previous step will be owerriten according with the latest DetailLevel geomOp = m_app.Create.NewGeometryOptions(); geomOp.ComputeReferences = true; geomOp.IncludeNonVisibleObjects = true; geomOp.DetailLevel = viewDetailLevel; tmpNode.Tag = elem.get_Geometry( geomOp ); rootNode.Nodes.Add( tmpNode ); } // now add geometry with the View set to the current view if( elem.Document.ActiveView != null ) { Options geomOp2 = m_app.Create.NewGeometryOptions(); geomOp2.ComputeReferences = true; geomOp2.View = elem.Document.ActiveView; TreeNode rootNode2 = new TreeNode( "View = Document.ActiveView" ); rootNode2.Tag = elem.get_Geometry( geomOp2 ); curNodes.Add( rootNode2 ); // SOFiSTiK FS // add model geometry including geometry objects not set as Visible. { Autodesk.Revit.DB.Options opts = m_app.Create.NewGeometryOptions(); opts.ComputeReferences = true; opts.IncludeNonVisibleObjects = true; opts.View = elem.Document.ActiveView; rootNode = new TreeNode( "View = Document.ActiveView - Including geometry objects not set as Visible" ); curNodes.Add( rootNode ); rootNode.Tag = elem.get_Geometry( opts ); } } } new private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Geometry)); this.SuspendLayout(); // // m_tvObjs // this.m_tvObjs.LineColor = System.Drawing.Color.Black; // // Geometry // this.ClientSize = new System.Drawing.Size(800, 478); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "Geometry"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.ResumeLayout(false); this.PerformLayout(); } } //SOFiSTiK FS public class OriginalGeometry : RevitLookup.Snoop.Forms.ObjTreeBase { protected Element m_elem = null; protected Autodesk.Revit.ApplicationServices.Application m_app = null; public OriginalGeometry( Autodesk.Revit.DB.FamilyInstance elem, Autodesk.Revit.ApplicationServices.Application app ) { this.Text = "Element Original Geometry"; m_elem = elem; m_app = app; m_tvObjs.BeginUpdate(); AddObjectsToTree( elem, m_tvObjs.Nodes ); m_tvObjs.EndUpdate(); } protected void AddObjectsToTree( FamilyInstance elem, TreeNodeCollection curNodes ) { Autodesk.Revit.DB.Options geomOp = m_app.Create.NewGeometryOptions(); geomOp.ComputeReferences = false; // Not allowed for GetOriginalGeometry()! TreeNode tmpNode; // add geometry with the View set to null. TreeNode rootNode1 = new TreeNode( "View = null" ); curNodes.Add( rootNode1 ); tmpNode = new TreeNode( "Detail Level = Undefined" ); geomOp.DetailLevel = ViewDetailLevel.Undefined; tmpNode.Tag = elem.GetOriginalGeometry( geomOp ); rootNode1.Nodes.Add( tmpNode ); tmpNode = new TreeNode( "Detail Level = Coarse" ); geomOp.DetailLevel = ViewDetailLevel.Coarse; tmpNode.Tag = elem.GetOriginalGeometry( geomOp ); rootNode1.Nodes.Add( tmpNode ); tmpNode = new TreeNode( "Detail Level = Medium" ); geomOp.DetailLevel = ViewDetailLevel.Medium; tmpNode.Tag = elem.GetOriginalGeometry( geomOp ); rootNode1.Nodes.Add( tmpNode ); tmpNode = new TreeNode( "Detail Level = Fine" ); geomOp.DetailLevel = ViewDetailLevel.Fine; tmpNode.Tag = elem.GetOriginalGeometry( geomOp ); rootNode1.Nodes.Add( tmpNode ); // SOFiSTiK FS // add model geometry including geometry objects not set as Visible. { Autodesk.Revit.DB.Options opts = m_app.Create.NewGeometryOptions(); opts.ComputeReferences = false; // Not allowed for GetOriginalGeometry()!; opts.IncludeNonVisibleObjects = true; TreeNode rootNode = new TreeNode( "View = null - Including geometry objects not set as Visible" ); curNodes.Add( rootNode ); tmpNode = new TreeNode( "Detail Level = Undefined" ); opts.DetailLevel = ViewDetailLevel.Undefined; tmpNode.Tag = elem.GetOriginalGeometry( opts ); rootNode.Nodes.Add( tmpNode ); tmpNode = new TreeNode( "Detail Level = Coarse" ); opts.DetailLevel = ViewDetailLevel.Coarse; tmpNode.Tag = elem.GetOriginalGeometry( opts ); rootNode.Nodes.Add( tmpNode ); tmpNode = new TreeNode( "Detail Level = Medium" ); opts.DetailLevel = ViewDetailLevel.Medium; tmpNode.Tag = elem.GetOriginalGeometry( opts ); rootNode.Nodes.Add( tmpNode ); tmpNode = new TreeNode( "Detail Level = Fine" ); opts.DetailLevel = ViewDetailLevel.Fine; tmpNode.Tag = elem.GetOriginalGeometry( opts ); rootNode.Nodes.Add( tmpNode ); } // now add geometry with the View set to the current view if( elem.Document.ActiveView != null ) { Options geomOp2 = m_app.Create.NewGeometryOptions(); geomOp2.ComputeReferences = false; // Not allowed for GetOriginalGeometry()!; geomOp2.View = elem.Document.ActiveView; TreeNode rootNode2 = new TreeNode( "View = Document.ActiveView" ); rootNode2.Tag = elem.GetOriginalGeometry( geomOp2 ); curNodes.Add( rootNode2 ); // SOFiSTiK FS // add model geometry including geometry objects not set as Visible. { Autodesk.Revit.DB.Options opts = m_app.Create.NewGeometryOptions(); opts.ComputeReferences = false; // Not allowed for GetOriginalGeometry()!; opts.IncludeNonVisibleObjects = true; opts.View = elem.Document.ActiveView; TreeNode rootNode = new TreeNode( "View = Document.ActiveView - Including geometry objects not set as Visible" ); curNodes.Add( rootNode ); rootNode.Tag = elem.GetOriginalGeometry( opts ); } } } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Drawing; using ExcelLibrary.CompoundDocumentFormat; using ExcelLibrary.SpreadSheet; namespace ExcelLibrary.BinaryFileFormat { public class WorksheetDecoder { public static Worksheet Decode(Workbook book, Stream stream, SharedResource sharedResource) { Worksheet sheet = new Worksheet(); sheet.Book = book; List<Record> records = ReadRecords(stream, out sheet.Drawing); sheet.Cells = PopulateCells(records, sharedResource); sheet.Book.Records.AddRange(records); return sheet; } private static List<Record> ReadRecords(Stream stream, out MSODRAWING drawingRecord) { List<Record> records = new List<Record>(); drawingRecord = null; Record record = Record.Read(stream); Record last_record = record; Record last_formula_record = null; last_record.Decode(); if (record is BOF && ((BOF)record).StreamType == StreamType.Worksheet) { while (record.Type != RecordType.EOF) { if (record.Type == RecordType.CONTINUE) { last_record.ContinuedRecords.Add(record); } else { switch (record.Type) { case RecordType.STRING: // jetcat_au: use last_formula_record instead of last_record if (last_formula_record is FORMULA) { record.Decode(); (last_formula_record as FORMULA).StringRecord = record as STRING; } break; case RecordType.MSODRAWING: if (drawingRecord == null) { drawingRecord = record as MSODRAWING; records.Add(record); } else { drawingRecord.ContinuedRecords.Add(record); } break; default: records.Add(record); break; } // jetcat_au: see 4.8 Array Formulas and Shared Formulas if (record.Type == RecordType.FORMULA) { last_formula_record = record; } else if (record.Type != RecordType.SHRFMLA && record.Type != RecordType.ARRAY) { last_formula_record = null; } last_record = record; } record = Record.Read(stream); } records.Add(record); } return records; } private static CellCollection PopulateCells(List<Record> records, SharedResource sharedResource) { CellCollection cells = new CellCollection(); cells.SharedResource = sharedResource; foreach (Record record in records) { record.Decode(); switch (record.Type) { //case RecordType.DIMENSIONS: // DIMENSIONS dimensions = record as DIMENSIONS; // cells.FirstRowIndex = dimensions.FirstRow; // cells.FirstColIndex = dimensions.FirstColumn; // cells.LastRowIndex = dimensions.LastRow-1; // cells.LastColIndex = dimensions.LastColumn-1; // break; case RecordType.BOOLERR: BOOLERR boolerr = record as BOOLERR; cells.CreateCell(boolerr.RowIndex, boolerr.ColIndex, boolerr.GetValue(), boolerr.XFIndex); break; case RecordType.LABEL: LABEL label = record as LABEL; cells.CreateCell(label.RowIndex, label.ColIndex, label.Value, label.XFIndex); break; case RecordType.LABELSST: LABELSST labelsst = record as LABELSST; Cell cell = cells.CreateCell(labelsst.RowIndex, labelsst.ColIndex, sharedResource.GetStringFromSST(labelsst.SSTIndex), labelsst.XFIndex); cell.Style.RichTextFormat = sharedResource.SharedStringTable.RichTextFormatting[labelsst.SSTIndex]; break; case RecordType.NUMBER: NUMBER number = record as NUMBER; cells.CreateCell(number.RowIndex, number.ColIndex, number.Value, number.XFIndex); break; case RecordType.RK: RK rk = record as RK; cells.CreateCell(rk.RowIndex, rk.ColIndex, Record.DecodeRK(rk.Value), rk.XFIndex); break; case RecordType.MULRK: MULRK mulrk = record as MULRK; int row = mulrk.RowIndex; for (int col = mulrk.FirstColIndex; col <= mulrk.LastColIndex; col++) { int index = col - mulrk.FirstColIndex; object value = Record.DecodeRK(mulrk.RKList[index]); int XFindex = mulrk.XFList[index]; cells.CreateCell(row, col, value, XFindex); } break; case RecordType.FORMULA: FORMULA formula = record as FORMULA; cells.CreateCell(formula.RowIndex, formula.ColIndex, formula.DecodeResult(), formula.XFIndex); break; } } return cells; } /* * Page 171 of the OpenOffice documentation of the Excel File Format * * The font with index 4 is omitted in all BIFF versions. This means the first four fonts have zero-based indexes, * and the fifth font and all following fonts are referenced with one-based indexes. */ //public FONT getFontRecord(int index) private static FONT getFontRecord(SharedResource sharedResource, UInt16 index) { if (index >= 0 && index <= 3) { return sharedResource.Fonts[index]; } else if (index >= 5) { return sharedResource.Fonts[index - 1]; } else // index == 4 -> error { return null; } } /* * Sunil Shenoi, 8-25-2008 * * Assuming cell has a valid string vlaue, find the font record for a given characterIndex * into the stringValue of the cell */ public static FONT getFontForCharacter(Cell cell, UInt16 charIndex) { FONT f = null; int index = cell.Style.RichTextFormat.CharIndexes.BinarySearch(charIndex); List<UInt16> fontIndexList = cell.Style.RichTextFormat.FontIndexes; if (index >= 0) { // found the object, return the font record f = getFontRecord(cell.SharedResource, fontIndexList[index]); //Console.WriteLine("for charIndex={0}, fontIndex={1})", charIndex, fontIndexList[index]); //Console.WriteLine("Object: {0} found at [{1}]", o, index); } else { // would have been inserted before the returned value, so insert just before it if (~index == 0) { //f = getFontRecord(sheet,fontIndexList[0]); //Console.WriteLine("for charIndex={0}, fontIndex=CELL", charIndex); } else { f = getFontRecord(cell.SharedResource, fontIndexList[(~index) - 1]); //Console.WriteLine("for charIndex={0}, fontIndex={1})", charIndex, fontIndexList[(~index) - 1]); } //Console.WriteLine("Object: {0} not found. " // + "Next larger object found at [{1}].", o, ~index); } return f; } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Positioning.dll // Description: A library for managing GPS connections. // ******************************************************************************************************** // // The Original Code is from http://gps3.codeplex.com/ version 3.0 // // The Initial Developer of this original code is Jon Pearson. Submitted Oct. 21, 2010 by Ben Tombs (tidyup) // // Contributor(s): (Open source contributors should list themselves and their modifications here). // ------------------------------------------------------------------------------------------------------- // | Developer | Date | Comments // |--------------------------|------------|-------------------------------------------------------------- // | Tidyup (Ben Tombs) | 10/21/2010 | Original copy submitted from modified GPS.Net 3.0 // | Shade1974 (Ted Dunsford) | 10/22/2010 | Added file headers reviewed formatting with resharper. // ******************************************************************************************************** using System; using System.Text; namespace DotSpatial.Positioning { /// <summary> /// Represents the "recommended minimum" GPS sentence. /// </summary> public sealed class GprmcSentence : NmeaSentence, IPositionSentence, IUtcDateTimeSentence, IBearingSentence, ISpeedSentence, IMagneticVariationSentence, IFixStatusSentence { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="GprmcSentence"/> class. /// </summary> /// <param name="sentence">The sentence.</param> /// <param name="commandWord">The command word.</param> /// <param name="words">The words.</param> /// <param name="validChecksum">The valid checksum.</param> internal GprmcSentence(string sentence, string commandWord, string[] words, string validChecksum) : base(sentence, commandWord, words, validChecksum) { SetPropertiesFromSentence(); //correct this classes properties based on the sentence } /// <summary> /// Creates a GprmcSentence from the specified string. /// </summary> /// <param name="sentence">The sentence.</param> public GprmcSentence(string sentence) : base(sentence) { SetPropertiesFromSentence(); //correct this classes properties based on the sentence } /// <summary> /// Creates a GprmcSentence from the specified parameters. /// </summary> /// <param name="utcDateTime">The UTC date time.</param> /// <param name="isFixAcquired">if set to <c>true</c> [is fix acquired].</param> /// <param name="position">The position.</param> /// <param name="speed">The speed.</param> /// <param name="bearing">The bearing.</param> /// <param name="magneticVariation">The magnetic variation.</param> public GprmcSentence(DateTime utcDateTime, bool isFixAcquired, Position position, Speed speed, Azimuth bearing, Longitude magneticVariation) { // Use a string builder to create the sentence text StringBuilder builder = new StringBuilder(128); /* GPRMC sentences have the following format: * * $GPRMC, 040302.663, A, 3939.7, N, 10506.6, W, 0.27, 358.86, 200804, ,*1A */ // Append the command word, $GPRMC builder.Append("$GPRMC"); builder.Append(','); // Append the UTC time builder.Append(utcDateTime.Hour.ToString("0#", NmeaCultureInfo)); builder.Append(utcDateTime.Minute.ToString("0#", NmeaCultureInfo)); builder.Append(utcDateTime.Second.ToString("0#", NmeaCultureInfo)); builder.Append("."); builder.Append(utcDateTime.Millisecond.ToString("00#", NmeaCultureInfo)); builder.Append(','); // Write fix information builder.Append(isFixAcquired ? "A" : "V"); builder.Append(','); // Append the position // Append latitude in the format HHMM.MMMM. builder.Append(position.Latitude.ToString(LatitudeFormat, NmeaCultureInfo)); // Append Longitude in the format HHHMM.MMMM. builder.Append(position.Longitude.ToString(LongitudeFormat, NmeaCultureInfo)); // Append the speed (in knots) builder.Append(speed.ToKnots().ToString("v.v", NmeaCultureInfo)); builder.Append(','); // Append the bearing builder.Append(bearing.ToString("d.d", NmeaCultureInfo)); builder.Append(','); // Append UTC date builder.Append(utcDateTime.Day.ToString("0#", NmeaCultureInfo)); builder.Append(utcDateTime.Month.ToString("0#", NmeaCultureInfo)); // Append the year (year minus 2000) int year = utcDateTime.Year - 2000; builder.Append(year.ToString("0#", NmeaCultureInfo)); builder.Append(','); // Append magnetic variation builder.Append(Math.Abs(magneticVariation.DecimalDegrees).ToString("0.0", NmeaCultureInfo)); builder.Append(","); builder.Append(magneticVariation.Hemisphere == LongitudeHemisphere.West ? "W" : "E"); // Set this object's sentence Sentence = builder.ToString(); SetPropertiesFromSentence(); //correct this classes properties based on the sentence // Finally, append the checksum AppendChecksum(); } #endregion Constructors /// <summary> /// Corrects this classes properties after the base sentence was changed. /// </summary> private new void SetPropertiesFromSentence() { // Cache the sentence words string[] words = Words; int wordCount = words.Length; /* * $GPRMC Recommended minimum specific GPS/Transit data eg1. $GPRMC, 081836, A, 3751.65, S, 14507.36, E, 000.0, 360.0, 130998, 011.3, E*62 eg2. $GPRMC, 225446, A, 4916.45, N, 12311.12, W, 000.5, 054.7, 191194, 020.3, E*68 225446 Time of fix 22:54:46 UTC A Navigation receiver warning A = OK, V = warning 4916.45, N Latitude 49 deg. 16.45 min North 12311.12, W Longitude 123 deg. 11.12 min West 000.5 Speed over ground, Knots 054.7 Course Made Good, True 191194 Date of fix 19 November 1994 020.3, E Magnetic variation 20.3 deg East *68 mandatory checksum eg3. $GPRMC, 220516, A, 5133.82, N, 00042.24, W, 173.8, 231.8, 130694, 004.2, W*70 1 2 3 4 5 6 7 8 9 10 11 12 1 220516 Time Stamp 2 A validity - A-ok, V-invalid 3 5133.82 current Latitude 4 N North/South 5 00042.24 current Longitude 6 W East/West 7 173.8 Speed in knots 8 231.8 True course 9 130694 Date Stamp 10 004.2 Variation 11 W East/West 12 *70 checksum eg4. $GPRMC, hhmmss.ss, A, llll.ll, a, yyyyy.yy, a, x.x, x.x, ddmmyy, x.x, a*hh 1 = UTC of position fix 2 = Data status (V=navigation receiver warning) 3 = Latitude of fix 4 = N or S 5 = Longitude of fix 6 = E or W 7 = Speed over ground in knots 8 = Track made good in degrees True 9 = UT date 10 = Magnetic variation degrees (Easterly var. subtracts from true course) 11 = E or W 12 = Checksum */ FixStatus = ParseFixStatus(1); UtcDateTime = ParseUtcDateTime(0, 8); Position = ParsePosition(2, 3, 4, 5); Speed = ParseSpeed(6, SpeedUnit.Knots); Bearing = ParseAzimuth(7); // Do we have enough info for magnetic variation? if (wordCount >= 10 && words[9].Length != 0 && words[10].Length != 0) MagneticVariation = new Longitude(double.Parse(words[9], NmeaCultureInfo), words[10].Equals("E", StringComparison.Ordinal) ? LongitudeHemisphere.East : LongitudeHemisphere.West); else MagneticVariation = Longitude.Invalid; } #region Properties /// <summary> /// Represents an NMEA sentence which contains a position. /// </summary> public Position Position { get; private set; } /// <summary> /// Represents an NMEA sentence which contains date and time in UTC. /// </summary> public DateTime UtcDateTime { get; private set; } /// <summary> /// the Bearing /// </summary> public Azimuth Bearing { get; private set; } /// <summary> /// The Speed /// </summary> public Speed Speed { get; private set; } /// <summary> /// The Magnetic Variation /// </summary> public Longitude MagneticVariation { get; private set; } /// <summary> /// The Fix Status /// </summary> public FixStatus FixStatus { get; private set; } #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 Xunit; namespace System.Linq.Expressions.Tests { public static class ConstantArrayTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckBoolArrayConstantTest(bool useInterpreter) { foreach (bool[] value in new bool[][] { null, new bool[0], new bool[] { true, false }, new bool[100] }) { VerifyBoolArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckByteArrayConstantTest(bool useInterpreter) { foreach (byte[] value in new byte[][] { null, new byte[0], new byte[] { 0, 1, byte.MaxValue }, new byte[100] }) { VerifyByteArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckCustomArrayConstantTest(bool useInterpreter) { foreach (C[] value in new C[][] { null, new C[] { null, new C(), new D(), new D(0), new D(5) }, new C[10] }) { VerifyCustomArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckCharArrayConstantTest(bool useInterpreter) { foreach (char[] value in new char[][] { null, new char[0], new char[] { '\0', '\b', 'A', '\uffff' }, new char[100] }) { VerifyCharArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckCustom2ArrayConstantTest(bool useInterpreter) { foreach (D[] value in new D[][] { null, new D[] { null, new D(), new D(0), new D(5) }, new D[10] }) { VerifyCustom2ArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckDecimalArrayConstantTest(bool useInterpreter) { foreach (decimal[] value in new decimal[][] { null, new decimal[0], new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }, new decimal[100] }) { VerifyDecimalArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckDelegateArrayConstantTest(bool useInterpreter) { foreach (Delegate[] value in new Delegate[][] { null, new Delegate[0], new Delegate[] { null, (Func<object>)delegate () { return null; }, (Func<int, int>)delegate (int i) { return i + 1; }, (Action<object>)delegate { } }, new Delegate[100] }) { VerifyDelegateArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckDoubleArrayConstantTest(bool useInterpreter) { foreach (double[] value in new double[][] { null, new double[0], new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }, new double[100] }) { VerifyDoubleArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckEnumArrayConstantTest(bool useInterpreter) { foreach (E[] value in new E[][] { null, new E[0], new E[] { (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue }, new E[100] }) { VerifyEnumArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckEnumLongArrayConstantTest(bool useInterpreter) { foreach (El[] value in new El[][] { null, new El[0], new El[] { (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue }, new El[100] }) { VerifyEnumLongArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckFloatArrayConstantTest(bool useInterpreter) { foreach (float[] value in new float[][] { null, new float[0], new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }, new float[100] }) { VerifyFloatArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckFuncOfObjectConstantTest(bool useInterpreter) { foreach (Func<object>[] value in new Func<object>[][] { null, new Func<object>[0], new Func<object>[] { null, (Func<object>)delegate () { return null; } }, new Func<object>[100] }) { VerifyFuncOfObjectConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckInterfaceArrayConstantTest(bool useInterpreter) { foreach (I[] value in new I[][] { null, new I[0], new I[] { null, new C(), new D(), new D(0), new D(5) }, new I[100] }) { VerifyInterfaceArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckIEquatableOfCustomConstantTest(bool useInterpreter) { foreach (IEquatable<C>[] value in new IEquatable<C>[][] { null, new IEquatable<C>[0], new IEquatable<C>[] { null, new C(), new D(), new D(0), new D(5) }, new IEquatable<C>[100] }) { VerifyIEquatableOfCustomConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckIEquatableOfCustom2ConstantTest(bool useInterpreter) { foreach (IEquatable<D>[] value in new IEquatable<D>[][] { null, new IEquatable<D>[0], new IEquatable<D>[] { null, new D(), new D(0), new D(5) }, new IEquatable<D>[100] }) { VerifyIEquatableOfCustom2Constant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckIntArrayConstantTest(bool useInterpreter) { foreach (int[] value in new int[][] { null, new int[0], new int[] { 0, 1, -1, int.MinValue, int.MaxValue }, new int[100] }) { VerifyIntArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLongArrayConstantTest(bool useInterpreter) { foreach (long[] value in new long[][] { null, new long[0], new long[] { 0, 1, -1, long.MinValue, long.MaxValue }, new long[100] }) { VerifyLongArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckObjectArrayConstantTest(bool useInterpreter) { foreach (object[] value in new object[][] { null, new object[0], new object[] { null, new object(), new C(), new D(3) }, new object[100] }) { VerifyObjectArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckStructArrayConstantTest(bool useInterpreter) { foreach (S[] value in new S[][] { null, new S[] { default(S), new S() }, new S[10] }) { VerifyStructArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckSByteArrayConstantTest(bool useInterpreter) { foreach (sbyte[] value in new sbyte[][] { null, new sbyte[0], new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }, new sbyte[100] }) { VerifySByteArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckStructWithStringArrayConstantTest(bool useInterpreter) { foreach (Sc[] value in new Sc[][] { null, new Sc[0], new Sc[] { default(Sc), new Sc(), new Sc(null) }, new Sc[100] }) { VerifyStructWithStringArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckStructWithStringAndFieldArrayConstantTest(bool useInterpreter) { foreach (Scs[] value in new Scs[][] { null, new Scs[0], new Scs[] { default(Scs), new Scs(), new Scs(null, new S()) }, new Scs[100] }) { VerifyStructWithStringAndFieldArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckShortArrayConstantTest(bool useInterpreter) { foreach (short[] value in new short[][] { null, new short[0], new short[] { 0, 1, -1, short.MinValue, short.MaxValue }, new short[100] }) { VerifyShortArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckStructWithTwoValuesArrayConstantTest(bool useInterpreter) { foreach (Sp[] value in new Sp[][] { null, new Sp[0], new Sp[] { default(Sp), new Sp(), new Sp(5, 5.0) }, new Sp[100] }) { VerifyStructWithTwoValuesArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckStructWithValueArrayConstantTest(bool useInterpreter) { foreach (Ss[] value in new Ss[][] { null, new Ss[0], new Ss[] { default(Ss), new Ss(), new Ss(new S()) }, new Ss[100] }) { VerifyStructWithValueArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckStringArrayConstantTest(bool useInterpreter) { foreach (string[] value in new string[][] { null, new string[0], new string[] { null, "", "a", "foo" }, new string[100] }) { VerifyStringArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUIntArrayConstantTest(bool useInterpreter) { foreach (uint[] value in new uint[][] { null, new uint[0], new uint[] { 0, 1, uint.MaxValue }, new uint[100] }) { VerifyUIntArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckULongArrayConstantTest(bool useInterpreter) { foreach (ulong[] value in new ulong[][] { null, new ulong[0], new ulong[] { 0, 1, ulong.MaxValue }, new ulong[100] }) { VerifyULongArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUShortArrayConstantTest(bool useInterpreter) { foreach (ushort[] value in new ushort[][] { null, new ushort[0], new ushort[] { 0, 1, ushort.MaxValue }, new ushort[100] }) { VerifyUShortArrayConstant(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckGenericWithStructRestrictionWithEnumArrayConstantTest(bool useInterpreter) { CheckGenericWithStructRestrictionArrayConstantHelper<E>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckGenericWithStructRestrictionWithStructArrayConstantTest(bool useInterpreter) { CheckGenericWithStructRestrictionArrayConstantHelper<S>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckGenericWithStructRestrictionWithStructWithStringAndValueArrayConstantTest(bool useInterpreter) { CheckGenericWithStructRestrictionArrayConstantHelper<Scs>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckGenericWithCustomArrayTest(bool useInterpreter) { CheckGenericArrayHelper<C>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckGenericWithEnumArrayTest(bool useInterpreter) { CheckGenericArrayHelper<E>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckGenericWithObjectArrayTest(bool useInterpreter) { CheckGenericArrayHelper<object>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckGenericWithStructArrayTest(bool useInterpreter) { CheckGenericArrayHelper<S>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckGenericWithStructWithStringAndValueArrayTest(bool useInterpreter) { CheckGenericArrayHelper<Scs>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckGenericWithClassRestrictionWithCustomTest(bool useInterpreter) { CheckGenericWithClassRestrictionArrayHelper<C>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckGenericWithClassRestrictionWithObjectTest(bool useInterpreter) { CheckGenericWithClassRestrictionArrayHelper<object>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckGenericWithClassAndNewRestrictionWithCustomTest(bool useInterpreter) { CheckGenericWithClassAndNewRestrictionArrayHelper<C>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckGenericWithClassAndNewRestrictionWithObjectTest(bool useInterpreter) { CheckGenericWithClassAndNewRestrictionArrayHelper<object>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckGenericWithSubClassRestrictionTest(bool useInterpreter) { CheckGenericWithSubClassRestrictionHelper<C>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckGenericWithSubClassAndNewRestrictionTest(bool useInterpreter) { CheckGenericWithSubClassAndNewRestrictionHelper<C>(useInterpreter); } #endregion #region Generic helpers public static void CheckGenericWithStructRestrictionArrayConstantHelper<Ts>(bool useInterpreter) where Ts : struct { foreach (Ts[] value in new Ts[][] { null, new Ts[0], new Ts[] { default(Ts), new Ts() }, new Ts[100] }) { VerifyGenericArrayWithStructRestriction<Ts>(value, useInterpreter); } } public static void CheckGenericArrayHelper<T>(bool useInterpreter) { foreach (T[] value in new T[][] { null, new T[0], new T[] { default(T) }, new T[100] }) { VerifyGenericArray<T>(value, useInterpreter); } } public static void CheckGenericWithClassRestrictionArrayHelper<Tc>(bool useInterpreter) where Tc : class { foreach (Tc[] value in new Tc[][] { null, new Tc[0], new Tc[] { null, default(Tc) }, new Tc[100] }) { VerifyGenericWithClassRestrictionArray<Tc>(value, useInterpreter); } } public static void CheckGenericWithClassAndNewRestrictionArrayHelper<Tcn>(bool useInterpreter) where Tcn : class, new() { foreach (Tcn[] value in new Tcn[][] { null, new Tcn[0], new Tcn[] { null, default(Tcn), new Tcn() }, new Tcn[100] }) { VerifyGenericWithClassAndNewRestrictionArray<Tcn>(value, useInterpreter); } } public static void CheckGenericWithSubClassRestrictionHelper<TC>(bool useInterpreter) where TC : C { foreach (TC[] value in new TC[][] { null, new TC[0], new TC[] { null, default(TC), (TC)new C() }, new TC[100] }) { VerifyGenericWithSubClassRestrictionArray<TC>(value, useInterpreter); } } public static void CheckGenericWithSubClassAndNewRestrictionHelper<TCn>(bool useInterpreter) where TCn : C, new() { foreach (TCn[] value in new TCn[][] { null, new TCn[0], new TCn[] { null, default(TCn), new TCn(), (TCn)new C() }, new TCn[100] }) { VerifyGenericWithSubClassAndNewRestrictionArray<TCn>(value, useInterpreter); } } #endregion #region Test verifiers private static void VerifyBoolArrayConstant(bool[] value, bool useInterpreter) { Expression<Func<bool[]>> e = Expression.Lambda<Func<bool[]>>( Expression.Constant(value, typeof(bool[])), Enumerable.Empty<ParameterExpression>()); Func<bool[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyByteArrayConstant(byte[] value, bool useInterpreter) { Expression<Func<byte[]>> e = Expression.Lambda<Func<byte[]>>( Expression.Constant(value, typeof(byte[])), Enumerable.Empty<ParameterExpression>()); Func<byte[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyCustomArrayConstant(C[] value, bool useInterpreter) { Expression<Func<C[]>> e = Expression.Lambda<Func<C[]>>( Expression.Constant(value, typeof(C[])), Enumerable.Empty<ParameterExpression>()); Func<C[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyCharArrayConstant(char[] value, bool useInterpreter) { Expression<Func<char[]>> e = Expression.Lambda<Func<char[]>>( Expression.Constant(value, typeof(char[])), Enumerable.Empty<ParameterExpression>()); Func<char[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyCustom2ArrayConstant(D[] value, bool useInterpreter) { Expression<Func<D[]>> e = Expression.Lambda<Func<D[]>>( Expression.Constant(value, typeof(D[])), Enumerable.Empty<ParameterExpression>()); Func<D[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyDecimalArrayConstant(decimal[] value, bool useInterpreter) { Expression<Func<decimal[]>> e = Expression.Lambda<Func<decimal[]>>( Expression.Constant(value, typeof(decimal[])), Enumerable.Empty<ParameterExpression>()); Func<decimal[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyDelegateArrayConstant(Delegate[] value, bool useInterpreter) { Expression<Func<Delegate[]>> e = Expression.Lambda<Func<Delegate[]>>( Expression.Constant(value, typeof(Delegate[])), Enumerable.Empty<ParameterExpression>()); Func<Delegate[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyDoubleArrayConstant(double[] value, bool useInterpreter) { Expression<Func<double[]>> e = Expression.Lambda<Func<double[]>>( Expression.Constant(value, typeof(double[])), Enumerable.Empty<ParameterExpression>()); Func<double[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyEnumArrayConstant(E[] value, bool useInterpreter) { Expression<Func<E[]>> e = Expression.Lambda<Func<E[]>>( Expression.Constant(value, typeof(E[])), Enumerable.Empty<ParameterExpression>()); Func<E[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyEnumLongArrayConstant(El[] value, bool useInterpreter) { Expression<Func<El[]>> e = Expression.Lambda<Func<El[]>>( Expression.Constant(value, typeof(El[])), Enumerable.Empty<ParameterExpression>()); Func<El[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyFloatArrayConstant(float[] value, bool useInterpreter) { Expression<Func<float[]>> e = Expression.Lambda<Func<float[]>>( Expression.Constant(value, typeof(float[])), Enumerable.Empty<ParameterExpression>()); Func<float[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyFuncOfObjectConstant(Func<object>[] value, bool useInterpreter) { Expression<Func<Func<object>[]>> e = Expression.Lambda<Func<Func<object>[]>>( Expression.Constant(value, typeof(Func<object>[])), Enumerable.Empty<ParameterExpression>()); Func<Func<object>[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyInterfaceArrayConstant(I[] value, bool useInterpreter) { Expression<Func<I[]>> e = Expression.Lambda<Func<I[]>>( Expression.Constant(value, typeof(I[])), Enumerable.Empty<ParameterExpression>()); Func<I[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyIEquatableOfCustomConstant(IEquatable<C>[] value, bool useInterpreter) { Expression<Func<IEquatable<C>[]>> e = Expression.Lambda<Func<IEquatable<C>[]>>( Expression.Constant(value, typeof(IEquatable<C>[])), Enumerable.Empty<ParameterExpression>()); Func<IEquatable<C>[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyIEquatableOfCustom2Constant(IEquatable<D>[] value, bool useInterpreter) { Expression<Func<IEquatable<D>[]>> e = Expression.Lambda<Func<IEquatable<D>[]>>( Expression.Constant(value, typeof(IEquatable<D>[])), Enumerable.Empty<ParameterExpression>()); Func<IEquatable<D>[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyIntArrayConstant(int[] value, bool useInterpreter) { Expression<Func<int[]>> e = Expression.Lambda<Func<int[]>>( Expression.Constant(value, typeof(int[])), Enumerable.Empty<ParameterExpression>()); Func<int[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyLongArrayConstant(long[] value, bool useInterpreter) { Expression<Func<long[]>> e = Expression.Lambda<Func<long[]>>( Expression.Constant(value, typeof(long[])), Enumerable.Empty<ParameterExpression>()); Func<long[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyObjectArrayConstant(object[] value, bool useInterpreter) { Expression<Func<object[]>> e = Expression.Lambda<Func<object[]>>( Expression.Constant(value, typeof(object[])), Enumerable.Empty<ParameterExpression>()); Func<object[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyStructArrayConstant(S[] value, bool useInterpreter) { Expression<Func<S[]>> e = Expression.Lambda<Func<S[]>>( Expression.Constant(value, typeof(S[])), Enumerable.Empty<ParameterExpression>()); Func<S[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifySByteArrayConstant(sbyte[] value, bool useInterpreter) { Expression<Func<sbyte[]>> e = Expression.Lambda<Func<sbyte[]>>( Expression.Constant(value, typeof(sbyte[])), Enumerable.Empty<ParameterExpression>()); Func<sbyte[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyStructWithStringArrayConstant(Sc[] value, bool useInterpreter) { Expression<Func<Sc[]>> e = Expression.Lambda<Func<Sc[]>>( Expression.Constant(value, typeof(Sc[])), Enumerable.Empty<ParameterExpression>()); Func<Sc[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyStructWithStringAndFieldArrayConstant(Scs[] value, bool useInterpreter) { Expression<Func<Scs[]>> e = Expression.Lambda<Func<Scs[]>>( Expression.Constant(value, typeof(Scs[])), Enumerable.Empty<ParameterExpression>()); Func<Scs[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyShortArrayConstant(short[] value, bool useInterpreter) { Expression<Func<short[]>> e = Expression.Lambda<Func<short[]>>( Expression.Constant(value, typeof(short[])), Enumerable.Empty<ParameterExpression>()); Func<short[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyStructWithTwoValuesArrayConstant(Sp[] value, bool useInterpreter) { Expression<Func<Sp[]>> e = Expression.Lambda<Func<Sp[]>>( Expression.Constant(value, typeof(Sp[])), Enumerable.Empty<ParameterExpression>()); Func<Sp[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyStructWithValueArrayConstant(Ss[] value, bool useInterpreter) { Expression<Func<Ss[]>> e = Expression.Lambda<Func<Ss[]>>( Expression.Constant(value, typeof(Ss[])), Enumerable.Empty<ParameterExpression>()); Func<Ss[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyStringArrayConstant(string[] value, bool useInterpreter) { Expression<Func<string[]>> e = Expression.Lambda<Func<string[]>>( Expression.Constant(value, typeof(string[])), Enumerable.Empty<ParameterExpression>()); Func<string[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyUIntArrayConstant(uint[] value, bool useInterpreter) { Expression<Func<uint[]>> e = Expression.Lambda<Func<uint[]>>( Expression.Constant(value, typeof(uint[])), Enumerable.Empty<ParameterExpression>()); Func<uint[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyULongArrayConstant(ulong[] value, bool useInterpreter) { Expression<Func<ulong[]>> e = Expression.Lambda<Func<ulong[]>>( Expression.Constant(value, typeof(ulong[])), Enumerable.Empty<ParameterExpression>()); Func<ulong[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyUShortArrayConstant(ushort[] value, bool useInterpreter) { Expression<Func<ushort[]>> e = Expression.Lambda<Func<ushort[]>>( Expression.Constant(value, typeof(ushort[])), Enumerable.Empty<ParameterExpression>()); Func<ushort[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyGenericArrayWithStructRestriction<Ts>(Ts[] value, bool useInterpreter) where Ts : struct { Expression<Func<Ts[]>> e = Expression.Lambda<Func<Ts[]>>( Expression.Constant(value, typeof(Ts[])), Enumerable.Empty<ParameterExpression>()); Func<Ts[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyGenericArray<T>(T[] value, bool useInterpreter) { Expression<Func<T[]>> e = Expression.Lambda<Func<T[]>>( Expression.Constant(value, typeof(T[])), Enumerable.Empty<ParameterExpression>()); Func<T[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyGenericWithClassRestrictionArray<Tc>(Tc[] value, bool useInterpreter) where Tc : class { Expression<Func<Tc[]>> e = Expression.Lambda<Func<Tc[]>>( Expression.Constant(value, typeof(Tc[])), Enumerable.Empty<ParameterExpression>()); Func<Tc[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyGenericWithClassAndNewRestrictionArray<Tcn>(Tcn[] value, bool useInterpreter) where Tcn : class, new() { Expression<Func<Tcn[]>> e = Expression.Lambda<Func<Tcn[]>>( Expression.Constant(value, typeof(Tcn[])), Enumerable.Empty<ParameterExpression>()); Func<Tcn[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyGenericWithSubClassRestrictionArray<TC>(TC[] value, bool useInterpreter) where TC : C { Expression<Func<TC[]>> e = Expression.Lambda<Func<TC[]>>( Expression.Constant(value, typeof(TC[])), Enumerable.Empty<ParameterExpression>()); Func<TC[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } private static void VerifyGenericWithSubClassAndNewRestrictionArray<TCn>(TCn[] value, bool useInterpreter) where TCn : C, new() { Expression<Func<TCn[]>> e = Expression.Lambda<Func<TCn[]>>( Expression.Constant(value, typeof(TCn[])), Enumerable.Empty<ParameterExpression>()); Func<TCn[]> f = e.Compile(useInterpreter); Assert.Equal(value, f()); } #endregion } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Derivatives.Algo File: BasketBlackScholes.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Derivatives { using System; using System.Linq; using Ecng.Collections; using StockSharp.Algo.Positions; using StockSharp.BusinessEntities; using StockSharp.Messages; using StockSharp.Localization; /// <summary> /// Portfolio model for calculating the values of Greeks by the Black-Scholes formula. /// </summary> public class BasketBlackScholes : BlackScholes { /// <summary> /// The model for calculating Greeks values by the Black-Scholes formula based on the position. /// </summary> public class InnerModel { /// <summary> /// Initializes a new instance of the <see cref="InnerModel"/>. /// </summary> /// <param name="model">The model for calculating Greeks values by the Black-Scholes formula.</param> /// <param name="positionManager">The position manager.</param> public InnerModel(BlackScholes model, IPositionManager positionManager) { if (model == null) throw new ArgumentNullException(nameof(model)); if (positionManager == null) throw new ArgumentNullException(nameof(positionManager)); Model = model; PositionManager = positionManager; } /// <summary> /// The model for calculating Greeks values by the Black-Scholes formula. /// </summary> public BlackScholes Model { get; } /// <summary> /// The position manager. /// </summary> public IPositionManager PositionManager { get; } } /// <summary> /// The interface describing the internal models collection <see cref="BasketBlackScholes.InnerModels"/>. /// </summary> public interface IInnerModelList : ISynchronizedCollection<InnerModel> { /// <summary> /// To get the model for calculating Greeks values by the Black-Scholes formula for a particular option. /// </summary> /// <param name="option">Options contract.</param> /// <returns>The model. If the option is not registered, then <see langword="null" /> will be returned.</returns> InnerModel this[Security option] { get; } } private sealed class InnerModelList : CachedSynchronizedList<InnerModel>, IInnerModelList { private readonly BasketBlackScholes _parent; public InnerModelList(BasketBlackScholes parent) { if (parent == null) throw new ArgumentNullException(nameof(parent)); _parent = parent; } InnerModel IInnerModelList.this[Security option] { get { if (option == null) throw new ArgumentNullException(nameof(option)); return this.SyncGet(c => c.FirstOrDefault(i => i.Model.Option == option)); } } protected override bool OnAdding(InnerModel item) { item.Model.RoundDecimals = _parent.RoundDecimals; return base.OnAdding(item); } protected override bool OnInserting(int index, InnerModel item) { item.Model.RoundDecimals = _parent.RoundDecimals; return base.OnInserting(index, item); } } /// <summary> /// Initializes a new instance of the <see cref="BasketBlackScholes"/>. /// </summary> /// <param name="securityProvider">The provider of information about instruments.</param> /// <param name="dataProvider">The market data provider.</param> public BasketBlackScholes(ISecurityProvider securityProvider, IMarketDataProvider dataProvider) : base(securityProvider, dataProvider) { _innerModels = new InnerModelList(this); } private readonly InnerModelList _innerModels; /// <summary> /// Information about options. /// </summary> public IInnerModelList InnerModels => _innerModels; /// <summary> /// The position by the underlying asset. /// </summary> public IPositionManager UnderlyingAssetPosition { get; set; } /// <summary> /// Options contract. /// </summary> public override Security Option { get { throw new NotSupportedException(); } } private Security _underlyingAsset; /// <summary> /// Underlying asset. /// </summary> public override Security UnderlyingAsset { get { if (_underlyingAsset == null) { var info = _innerModels.SyncGet(c => c.FirstOrDefault()); if (info == null) throw new InvalidOperationException(LocalizedStrings.Str700); _underlyingAsset = info.Model.Option.GetAsset(SecurityProvider); } return _underlyingAsset; } } /// <summary> /// The number of decimal places at calculated values. The default is -1, which means no values rounding. /// </summary> public override int RoundDecimals { set { base.RoundDecimals = value; lock (_innerModels.SyncRoot) { _innerModels.ForEach(m => m.Model.RoundDecimals = value); } } } private decimal GetAssetPosition() { return (UnderlyingAssetPosition != null ? UnderlyingAssetPosition.Position : 0); } /// <summary> /// To calculate the option delta. /// </summary> /// <param name="currentTime">The current time.</param> /// <param name="deviation">The standard deviation. If it is not specified, then <see cref="BlackScholes.DefaultDeviation"/> is used.</param> /// <param name="assetPrice">The price of the underlying asset. If the price is not specified, then the last trade price getting from <see cref="BlackScholes.UnderlyingAsset"/>.</param> /// <returns>The option delta. If the value is equal to <see langword="null" />, then the value calculation currently is impossible.</returns> public override decimal? Delta(DateTimeOffset currentTime, decimal? deviation = null, decimal? assetPrice = null) { return ProcessOptions(bs => bs.Delta(currentTime, deviation, assetPrice)) + GetAssetPosition(); } /// <summary> /// To calculate the option gamma. /// </summary> /// <param name="currentTime">The current time.</param> /// <param name="deviation">The standard deviation. If it is not specified, then <see cref="BlackScholes.DefaultDeviation"/> is used.</param> /// <param name="assetPrice">The price of the underlying asset. If the price is not specified, then the last trade price getting from <see cref="BlackScholes.UnderlyingAsset"/>.</param> /// <returns>The option gamma. If the value is equal to <see langword="null" />, then the value calculation currently is impossible.</returns> public override decimal? Gamma(DateTimeOffset currentTime, decimal? deviation = null, decimal? assetPrice = null) { return ProcessOptions(bs => bs.Gamma(currentTime, deviation, assetPrice)); } /// <summary> /// To calculate the option vega. /// </summary> /// <param name="currentTime">The current time.</param> /// <param name="deviation">The standard deviation. If it is not specified, then <see cref="BlackScholes.DefaultDeviation"/> is used.</param> /// <param name="assetPrice">The price of the underlying asset. If the price is not specified, then the last trade price getting from <see cref="BlackScholes.UnderlyingAsset"/>.</param> /// <returns>The option vega. If the value is equal to <see langword="null" />, then the value calculation currently is impossible.</returns> public override decimal? Vega(DateTimeOffset currentTime, decimal? deviation = null, decimal? assetPrice = null) { return ProcessOptions(bs => bs.Vega(currentTime, deviation, assetPrice)); } /// <summary> /// To calculate the option theta. /// </summary> /// <param name="currentTime">The current time.</param> /// <param name="deviation">The standard deviation. If it is not specified, then <see cref="BlackScholes.DefaultDeviation"/> is used.</param> /// <param name="assetPrice">The price of the underlying asset. If the price is not specified, then the last trade price getting from <see cref="BlackScholes.UnderlyingAsset"/>.</param> /// <returns>The option theta. If the value is equal to <see langword="null" />, then the value calculation currently is impossible.</returns> public override decimal? Theta(DateTimeOffset currentTime, decimal? deviation = null, decimal? assetPrice = null) { return ProcessOptions(bs => bs.Theta(currentTime, deviation, assetPrice)); } /// <summary> /// To calculate the option rho. /// </summary> /// <param name="currentTime">The current time.</param> /// <param name="deviation">The standard deviation. If it is not specified, then <see cref="BlackScholes.DefaultDeviation"/> is used.</param> /// <param name="assetPrice">The price of the underlying asset. If the price is not specified, then the last trade price getting from <see cref="BlackScholes.UnderlyingAsset"/>.</param> /// <returns>The option rho. If the value is equal to <see langword="null" />, then the value calculation currently is impossible.</returns> public override decimal? Rho(DateTimeOffset currentTime, decimal? deviation = null, decimal? assetPrice = null) { return ProcessOptions(bs => bs.Rho(currentTime, deviation, assetPrice)); } /// <summary> /// To calculate the option premium. /// </summary> /// <param name="currentTime">The current time.</param> /// <param name="deviation">The standard deviation. If it is not specified, then <see cref="BlackScholes.DefaultDeviation"/> is used.</param> /// <param name="assetPrice">The price of the underlying asset. If the price is not specified, then the last trade price getting from <see cref="BlackScholes.UnderlyingAsset"/>.</param> /// <returns>The option premium. If the value is equal to <see langword="null" />, then the value calculation currently is impossible.</returns> public override decimal? Premium(DateTimeOffset currentTime, decimal? deviation = null, decimal? assetPrice = null) { return ProcessOptions(bs => bs.Premium(currentTime, deviation, assetPrice)); } /// <summary> /// To calculate the implied volatility. /// </summary> /// <param name="currentTime">The current time.</param> /// <param name="premium">The option premium.</param> /// <returns>The implied volatility. If the value is equal to <see langword="null" />, then the value calculation currently is impossible.</returns> public override decimal? ImpliedVolatility(DateTimeOffset currentTime, decimal premium) { return ProcessOptions(bs => bs.ImpliedVolatility(currentTime, premium), false); } /// <summary> /// To create the order book of volatility. /// </summary> /// <param name="currentTime">The current time.</param> /// <returns>The order book volatility.</returns> public override MarketDepth ImpliedVolatility(DateTimeOffset currentTime) { throw new NotSupportedException(); //return UnderlyingAsset.GetMarketDepth().ImpliedVolatility(this); } private decimal? ProcessOptions(Func<BlackScholes, decimal?> func, bool usePos = true) { return _innerModels.Cache.Sum(m => { var iv = (decimal?)DataProvider.GetSecurityValue(m.Model.Option, Level1Fields.ImpliedVolatility); return iv == null ? null : func(m.Model) * (usePos ? m.PositionManager.Position : 1); }); } } }
using System; using System.Diagnostics; namespace OTFontFile { /// <summary> /// Summary description for Table_ /// </summary> public class Table_OS2 : OTTable { /************************ * constructors */ public Table_OS2(OTTag tag, MBOBuffer buf) : base(tag, buf) { } /************************ * field offset values */ public enum FieldOffsets { version = 0, xAvgCharWidth = 2, usWeightClass = 4, usWidthClass = 6, fsType = 8, ySubscriptXSize = 10, ySubscriptYSize = 12, ySubscriptXOffset = 14, ySubscriptYOffset = 16, ySuperscriptXSize = 18, ySuperscriptYSize = 20, ySuperscriptXOffset = 22, ySuperscriptYOffset = 24, yStrikeoutSize = 26, yStrikeoutPosition = 28, sFamilyClass = 30, panose_byte1 = 32, panose_byte2 = 33, panose_byte3 = 34, panose_byte4 = 35, panose_byte5 = 36, panose_byte6 = 37, panose_byte7 = 38, panose_byte8 = 39, panose_byte9 = 40, panose_byte10 = 41, ulUnicodeRange1 = 42, ulUnicodeRange2 = 46, ulUnicodeRange3 = 50, ulUnicodeRange4 = 54, achVendID = 58, fsSelection = 62, usFirstCharIndex = 64, usLastCharIndex = 66, sTypoAscender = 68, sTypoDescender = 70, sTypoLineGap = 72, usWinAscent = 74, usWinDescent = 76, // version 0 specified through this field ulCodePageRange1 = 78, ulCodePageRange2 = 82, // version 1 specified through this field sxHeight = 86, sCapHeight = 88, usDefaultChar = 90, usBreakChar = 92, usMaxContext = 94 // version 2 and version 3 specified through this field } /************************ * property accessors */ public ushort version { get {return m_bufTable.GetUshort((uint)FieldOffsets.version);} } public short xAvgCharWidth { get {return m_bufTable.GetShort((uint)FieldOffsets.xAvgCharWidth);} } public ushort usWeightClass { get {return m_bufTable.GetUshort((uint)FieldOffsets.usWeightClass);} } public ushort usWidthClass { get {return m_bufTable.GetUshort((uint)FieldOffsets.usWidthClass);} } public ushort fsType { get {return m_bufTable.GetUshort((uint)FieldOffsets.fsType);} } public short ySubscriptXSize { get {return m_bufTable.GetShort((uint)FieldOffsets.ySubscriptXSize);} } public short ySubscriptYSize { get {return m_bufTable.GetShort((uint)FieldOffsets.ySubscriptYSize);} } public short ySubscriptXOffset { get {return m_bufTable.GetShort((uint)FieldOffsets.ySubscriptXOffset);} } public short ySubscriptYOffset { get {return m_bufTable.GetShort((uint)FieldOffsets.ySubscriptYOffset);} } public short ySuperscriptXSize { get {return m_bufTable.GetShort((uint)FieldOffsets.ySuperscriptXSize);} } public short ySuperscriptYSize { get {return m_bufTable.GetShort((uint)FieldOffsets.ySuperscriptYSize);} } public short ySuperscriptXOffset { get {return m_bufTable.GetShort((uint)FieldOffsets.ySuperscriptXOffset);} } public short ySuperscriptYOffset { get {return m_bufTable.GetShort((uint)FieldOffsets.ySuperscriptYOffset);} } public short yStrikeoutSize { get {return m_bufTable.GetShort((uint)FieldOffsets.yStrikeoutSize);} } public short yStrikeoutPosition { get {return m_bufTable.GetShort((uint)FieldOffsets.yStrikeoutPosition);} } public short sFamilyClass { get {return m_bufTable.GetShort((uint)FieldOffsets.sFamilyClass);} } public byte panose_byte1 { get {return m_bufTable.GetByte((uint)FieldOffsets.panose_byte1);} } public byte panose_byte2 { get {return m_bufTable.GetByte((uint)FieldOffsets.panose_byte2);} } public byte panose_byte3 { get {return m_bufTable.GetByte((uint)FieldOffsets.panose_byte3);} } public byte panose_byte4 { get {return m_bufTable.GetByte((uint)FieldOffsets.panose_byte4);} } public byte panose_byte5 { get {return m_bufTable.GetByte((uint)FieldOffsets.panose_byte5);} } public byte panose_byte6 { get {return m_bufTable.GetByte((uint)FieldOffsets.panose_byte6);} } public byte panose_byte7 { get {return m_bufTable.GetByte((uint)FieldOffsets.panose_byte7);} } public byte panose_byte8 { get {return m_bufTable.GetByte((uint)FieldOffsets.panose_byte8);} } public byte panose_byte9 { get {return m_bufTable.GetByte((uint)FieldOffsets.panose_byte9);} } public byte panose_byte10 { get {return m_bufTable.GetByte((uint)FieldOffsets.panose_byte10);} } public bool isUnicodeRangeBitSet( byte byBit ) { bool bResult = false; if( byBit > 127 ) { throw new ArgumentOutOfRangeException( "Valid Bit request are are to 127" ); } if( byBit < 32 ) { if( (ulUnicodeRange1 & 1<<byBit) != 0 ) { bResult = true; } } else if( byBit < 64 ) { if( (ulUnicodeRange2 & 1<<(byBit - 32)) != 0 ) { bResult = true; } } else if( byBit < 96 ) { if( (ulUnicodeRange3 & 1<<(byBit - 64)) != 0 ) { bResult = true; } } else { if( (ulUnicodeRange4 & 1<<(byBit - 96)) != 0 ) { bResult = true; } } return bResult; } public uint ulUnicodeRange1 { get {return m_bufTable.GetUint((uint)FieldOffsets.ulUnicodeRange1);} } public uint ulUnicodeRange2 { get {return m_bufTable.GetUint((uint)FieldOffsets.ulUnicodeRange2);} } public uint ulUnicodeRange3 { get {return m_bufTable.GetUint((uint)FieldOffsets.ulUnicodeRange3);} } public uint ulUnicodeRange4 { get {return m_bufTable.GetUint((uint)FieldOffsets.ulUnicodeRange4);} } public byte[] achVendID { get { byte[] fourBytes = new byte[4]; System.Buffer.BlockCopy(m_bufTable.GetBuffer(), (int)FieldOffsets.achVendID, fourBytes, 0, 4); return fourBytes; } } public ushort fsSelection { get {return m_bufTable.GetUshort((uint)FieldOffsets.fsSelection);} } public ushort usFirstCharIndex { get {return m_bufTable.GetUshort((uint)FieldOffsets.usFirstCharIndex);} } public ushort usLastCharIndex { get {return m_bufTable.GetUshort((uint)FieldOffsets.usLastCharIndex);} } public short sTypoAscender { get {return m_bufTable.GetShort((uint)FieldOffsets.sTypoAscender);} } public short sTypoDescender { get {return m_bufTable.GetShort((uint)FieldOffsets.sTypoDescender);} } public short sTypoLineGap { get {return m_bufTable.GetShort((uint)FieldOffsets.sTypoLineGap);} } public ushort usWinAscent { get {return m_bufTable.GetUshort((uint)FieldOffsets.usWinAscent);} } public ushort usWinDescent { get {return m_bufTable.GetUshort((uint)FieldOffsets.usWinDescent);} } public uint ulCodePageRange1 { get { if( version < 0x0001 ) { throw new InvalidOperationException(); } return m_bufTable.GetUint((uint)FieldOffsets.ulCodePageRange1); } } public uint ulCodePageRange2 { get { if( version < 0x0001 ) { throw new InvalidOperationException(); } return m_bufTable.GetUint((uint)FieldOffsets.ulCodePageRange2); } } public short sxHeight { get { if( version < 0x0002 ) { throw new InvalidOperationException(); } return m_bufTable.GetShort((uint)FieldOffsets.sxHeight); } } public short sCapHeight { get { if( version < 0x0002 ) { throw new InvalidOperationException(); } return m_bufTable.GetShort((uint)FieldOffsets.sCapHeight); } } public ushort usDefaultChar { get { if( version < 0x0002 ) { throw new InvalidOperationException(); } return m_bufTable.GetUshort((uint)FieldOffsets.usDefaultChar); } } public ushort usBreakChar { get { if( version < 0x0002 ) { throw new InvalidOperationException(); } return m_bufTable.GetUshort((uint)FieldOffsets.usBreakChar); } } public ushort usMaxContext { get { if( version < 0x0002 ) { throw new InvalidOperationException(); } return m_bufTable.GetUshort((uint)FieldOffsets.usMaxContext); } } /************************ * DataCache class */ public override DataCache GetCache() { if (m_cache == null) { m_cache = new OS2_cache(this); } return m_cache; } public class OS2_cache : DataCache { protected ushort m_version; protected short m_xAvgCharWidth; protected ushort m_usWeightClass; protected ushort m_usWidthClass; protected ushort m_fsType; protected short m_ySubscriptXSize; protected short m_ySubscriptYSize; protected short m_ySubscriptXOffset; protected short m_ySubscriptYOffset; protected short m_ySuperscriptXSize; protected short m_ySuperscriptYSize; protected short m_ySuperscriptXOffset; protected short m_ySuperscriptYOffset; protected short m_yStrikeoutSize; protected short m_yStrikeoutPosition; protected short m_sFamilyClass; protected byte m_panose_byte1; protected byte m_panose_byte2; protected byte m_panose_byte3; protected byte m_panose_byte4; protected byte m_panose_byte5; protected byte m_panose_byte6; protected byte m_panose_byte7; protected byte m_panose_byte8; protected byte m_panose_byte9; protected byte m_panose_byte10; protected uint m_ulUnicodeRange1; protected uint m_ulUnicodeRange2; protected uint m_ulUnicodeRange3; protected uint m_ulUnicodeRange4; protected byte[] m_achVendID; protected ushort m_fsSelection; protected ushort m_usFirstCharIndex; protected ushort m_usLastCharIndex; protected short m_sTypoAscender; protected short m_sTypoDescender; protected short m_sTypoLineGap; protected ushort m_usWinAscent; protected ushort m_usWinDescent; protected uint m_ulCodePageRange1; protected uint m_ulCodePageRange2; protected short m_sxHeight; protected short m_sCapHeight; protected ushort m_usDefaultChar; protected ushort m_usBreakChar; protected ushort m_usMaxContext; // constructor public OS2_cache(Table_OS2 OwnerTable) { // copy the data from the owner table's MBOBuffer // and store it in the cache variables m_version = OwnerTable.version; m_xAvgCharWidth = OwnerTable.xAvgCharWidth; m_usWeightClass = OwnerTable.usWeightClass; m_usWidthClass = OwnerTable.usWidthClass; m_fsType = OwnerTable.fsType; m_ySubscriptXSize = OwnerTable.ySubscriptXSize; m_ySubscriptYSize = OwnerTable.ySubscriptYSize; m_ySubscriptXOffset = OwnerTable.ySubscriptXOffset; m_ySubscriptYOffset = OwnerTable.ySubscriptYOffset; m_ySuperscriptXSize = OwnerTable.ySuperscriptXSize; m_ySuperscriptYSize = OwnerTable.ySuperscriptYSize; m_ySuperscriptXOffset = OwnerTable.ySuperscriptXOffset; m_ySuperscriptYOffset = OwnerTable.ySuperscriptYOffset; m_yStrikeoutSize = OwnerTable.yStrikeoutSize; m_yStrikeoutPosition = OwnerTable.yStrikeoutPosition; m_sFamilyClass = OwnerTable.sFamilyClass; m_panose_byte1 = OwnerTable.panose_byte1; m_panose_byte2 = OwnerTable.panose_byte2; m_panose_byte3 = OwnerTable.panose_byte3; m_panose_byte4 = OwnerTable.panose_byte4; m_panose_byte5 = OwnerTable.panose_byte5; m_panose_byte6 = OwnerTable.panose_byte6; m_panose_byte7 = OwnerTable.panose_byte7; m_panose_byte8 = OwnerTable.panose_byte8; m_panose_byte9 = OwnerTable.panose_byte9; m_panose_byte10 = OwnerTable.panose_byte10; m_ulUnicodeRange1 = OwnerTable.ulUnicodeRange1; m_ulUnicodeRange2 = OwnerTable.ulUnicodeRange2; m_ulUnicodeRange3 = OwnerTable.ulUnicodeRange3; m_ulUnicodeRange4 = OwnerTable.ulUnicodeRange4; m_achVendID = OwnerTable.achVendID; m_fsSelection = OwnerTable.fsSelection; m_usFirstCharIndex = OwnerTable.usFirstCharIndex; m_usLastCharIndex = OwnerTable.usLastCharIndex; m_sTypoAscender = OwnerTable.sTypoAscender; m_sTypoDescender = OwnerTable.sTypoDescender; m_sTypoLineGap = OwnerTable.sTypoLineGap; m_usWinAscent = OwnerTable.usWinAscent; m_usWinDescent = OwnerTable.usWinDescent; if( version > 0x000 ) { m_ulCodePageRange1 = OwnerTable.ulCodePageRange1; m_ulCodePageRange2 = OwnerTable.ulCodePageRange2; if( version > 0x001 ) // version 2 and 3 { m_sxHeight = OwnerTable.sxHeight; m_sCapHeight = OwnerTable.sCapHeight; m_usDefaultChar = OwnerTable.usDefaultChar; m_usBreakChar = OwnerTable.usBreakChar; m_usMaxContext = OwnerTable.usMaxContext; } } } /************************ * property accessors */ public ushort version { get { return m_version; } set { m_version = value; m_bDirty = true; } } public short xAvgCharWidth { get { return m_xAvgCharWidth; } set { m_xAvgCharWidth = value; m_bDirty = true; } } public ushort usWeightClass { get { return m_usWeightClass; } set { m_usWeightClass = value; m_bDirty = true; } } public ushort usWidthClass { get { return m_usWidthClass; } set { m_usWidthClass = value; m_bDirty = true; } } public ushort fsType { get { return m_fsType; } set { m_fsType = value; m_bDirty = true; } } public short ySubscriptXSize { get { return m_ySubscriptXSize; } set { m_ySubscriptXSize = value; m_bDirty = true; } } public short ySubscriptYSize { get { return m_ySubscriptYSize; } set { m_ySubscriptYSize = value; m_bDirty = true; } } public short ySubscriptXOffset { get { return m_ySubscriptXOffset; } set { m_ySubscriptXOffset = value; m_bDirty = true; } } public short ySubscriptYOffset { get { return m_ySubscriptYOffset; } set { m_ySubscriptYOffset = value; m_bDirty = true; } } public short ySuperscriptXSize { get { return m_ySuperscriptXSize; } set { m_ySuperscriptXSize = value; m_bDirty = true; } } public short ySuperscriptYSize { get { return m_ySuperscriptYSize; } set { m_ySuperscriptYSize = value; m_bDirty = true; } } public short ySuperscriptXOffset { get { return m_ySuperscriptXOffset; } set { m_ySuperscriptXOffset = value; m_bDirty = true; } } public short ySuperscriptYOffset { get { return m_ySuperscriptYOffset; } set { m_ySuperscriptYOffset = value; m_bDirty = true; } } public short yStrikeoutSize { get { return m_yStrikeoutSize; } set { m_yStrikeoutSize = value; m_bDirty = true; } } public short yStrikeoutPosition { get { return m_yStrikeoutPosition; } set { m_yStrikeoutPosition = value; m_bDirty = true; } } public short sFamilyClass { get { return m_sFamilyClass; } set { m_sFamilyClass = value; m_bDirty = true; } } public byte panose_byte1 { get { return m_panose_byte1; } set { m_panose_byte1 = value; m_bDirty = true; } } public byte panose_byte2 { get { return m_panose_byte2; } set { m_panose_byte2 = value; m_bDirty = true; } } public byte panose_byte3 { get { return m_panose_byte3; } set { m_panose_byte3 = value; m_bDirty = true; } } public byte panose_byte4 { get { return m_panose_byte4; } set { m_panose_byte4 = value; m_bDirty = true; } } public byte panose_byte5 { get { return m_panose_byte5; } set { m_panose_byte5 = value; m_bDirty = true; } } public byte panose_byte6 { get { return m_panose_byte6; } set { m_panose_byte6 = value; m_bDirty = true; } } public byte panose_byte7 { get { return m_panose_byte7; } set { m_panose_byte7 = value; m_bDirty = true; } } public byte panose_byte8 { get { return m_panose_byte8; } set { m_panose_byte8 = value; m_bDirty = true; } } public byte panose_byte9 { get { return m_panose_byte9; } set { m_panose_byte9 = value; m_bDirty = true; } } public byte panose_byte10 { get { return m_panose_byte10; } set { m_panose_byte10 = value; m_bDirty = true; } } public uint ulUnicodeRange1 { get { return m_ulUnicodeRange1; } set { m_ulUnicodeRange1 = value; m_bDirty = true; } } public uint ulUnicodeRange2 { get { return m_ulUnicodeRange2; } set { m_ulUnicodeRange2 = value; m_bDirty = true; } } public uint ulUnicodeRange3 { get { return m_ulUnicodeRange3; } set { m_ulUnicodeRange3 = value; m_bDirty = true; } } public uint ulUnicodeRange4 { get { return m_ulUnicodeRange4; } set { m_ulUnicodeRange4 = value; m_bDirty = true; } } public byte[] achVendID { get { return m_achVendID; } set { byte[] fourByte; fourByte = value; if( value.Length != 4 ) { throw new ApplicationException( "Only a four byte array is applicable" ); } m_achVendID = value; m_bDirty = true; } } public ushort fsSelection { get { return m_fsSelection; } set { m_fsSelection = value; m_bDirty = true; } } public ushort usFirstCharIndex { get { return m_usFirstCharIndex; } set { m_usFirstCharIndex = value; m_bDirty = true; } } public ushort usLastCharIndex { get { return m_usLastCharIndex; } set { m_usLastCharIndex = value; m_bDirty = true; } } public short sTypoAscender { get { return m_sTypoAscender; } set { m_sTypoAscender = value; m_bDirty = true; } } public short sTypoDescender { get { return m_sTypoDescender; } set { m_sTypoDescender = value; m_bDirty = true; } } public short sTypoLineGap { get { return m_sTypoLineGap; } set { m_sTypoLineGap = value; m_bDirty = true; } } public ushort usWinAscent { get { return m_usWinAscent; } set { m_usWinAscent = value; m_bDirty = true; } } public ushort usWinDescent { get { return m_usWinDescent; } set { m_usWinDescent = value; m_bDirty = true; } } public uint ulCodePageRange1 { get { if( m_version < 0x0001 ) { throw new InvalidOperationException(); } return m_ulCodePageRange1; } set { if( m_version < 0x0001 ) { throw new InvalidOperationException(); } m_ulCodePageRange1 = value; m_bDirty = true; } } public uint ulCodePageRange2 { get { if( m_version < 0x0001 ) { throw new InvalidOperationException(); } return m_ulCodePageRange2; } set { if( m_version < 0x0001 ) { throw new InvalidOperationException(); } m_ulCodePageRange2 = value; m_bDirty = true; } } public short sxHeight { get { if( m_version < 0x0002 ) { throw new InvalidOperationException(); } return m_sxHeight; } set { if( m_version < 0x0002 ) { throw new InvalidOperationException(); } m_sxHeight = value; m_bDirty = true; } } public short sCapHeight { get { if( m_version < 0x0002 ) { throw new InvalidOperationException(); } return m_sCapHeight; } set { if( m_version < 0x0002 ) { throw new InvalidOperationException(); } m_sCapHeight = value; m_bDirty = true; } } public ushort usDefaultChar { get { if( m_version < 0x0002 ) { throw new InvalidOperationException(); } return m_usDefaultChar; } set { if( m_version < 0x0002 ) { throw new InvalidOperationException(); } m_usDefaultChar = value; m_bDirty = true; } } public ushort usBreakChar { get { if( m_version < 0x0002 ) { throw new InvalidOperationException(); } return m_usBreakChar; } set { if( m_version < 0x0002 ) { throw new InvalidOperationException(); } m_usBreakChar = value; m_bDirty = true; } } public ushort usMaxContext { get { if( m_version < 0x0002 ) { throw new InvalidOperationException(); } return m_usMaxContext; } set { if( m_version < 0x0002 ) { throw new InvalidOperationException(); } m_usMaxContext = value; m_bDirty = true; } } public override OTTable GenerateTable() { MBOBuffer newbuf; switch( m_version ) { case 0x0000: newbuf = new MBOBuffer( 78 ); break; case 0x0001: newbuf = new MBOBuffer( 86 ); break; case 0x0002: newbuf = new MBOBuffer( 96 ); break; case 0x0003: goto case 0x0002; default: goto case 0x0002; // version 3 is default } newbuf.SetUshort( m_version, (uint)Table_OS2.FieldOffsets.version ); newbuf.SetShort( m_xAvgCharWidth, (uint)Table_OS2.FieldOffsets.xAvgCharWidth ); newbuf.SetUshort( m_usWeightClass, (uint)Table_OS2.FieldOffsets.usWeightClass ); newbuf.SetUshort( m_usWidthClass, (uint)Table_OS2.FieldOffsets.usWidthClass ); newbuf.SetUshort( m_fsType, (uint)Table_OS2.FieldOffsets.fsType ); newbuf.SetShort( m_ySubscriptXSize, (uint)Table_OS2.FieldOffsets.ySubscriptXSize ); newbuf.SetShort( m_ySubscriptYSize, (uint)Table_OS2.FieldOffsets.ySubscriptYSize ); newbuf.SetShort( m_ySubscriptXOffset, (uint)Table_OS2.FieldOffsets.ySubscriptXOffset ); newbuf.SetShort( m_ySubscriptYOffset, (uint)Table_OS2.FieldOffsets.ySubscriptYOffset ); newbuf.SetShort( m_ySuperscriptXSize, (uint)Table_OS2.FieldOffsets.ySuperscriptXSize ); newbuf.SetShort( m_ySuperscriptYSize, (uint)Table_OS2.FieldOffsets.ySuperscriptYSize ); newbuf.SetShort( m_ySuperscriptXOffset, (uint)Table_OS2.FieldOffsets.ySuperscriptXOffset ); newbuf.SetShort( m_ySuperscriptYOffset, (uint)Table_OS2.FieldOffsets.ySuperscriptYOffset ); newbuf.SetShort( m_yStrikeoutSize, (uint)Table_OS2.FieldOffsets.yStrikeoutSize ); newbuf.SetShort( m_yStrikeoutPosition, (uint)Table_OS2.FieldOffsets.yStrikeoutPosition ); newbuf.SetShort( m_sFamilyClass, (uint)Table_OS2.FieldOffsets.sFamilyClass ); newbuf.SetByte( m_panose_byte1, (uint)Table_OS2.FieldOffsets.panose_byte1 ); newbuf.SetByte( m_panose_byte2, (uint)Table_OS2.FieldOffsets.panose_byte2 ); newbuf.SetByte( m_panose_byte3, (uint)Table_OS2.FieldOffsets.panose_byte3 ); newbuf.SetByte( m_panose_byte4, (uint)Table_OS2.FieldOffsets.panose_byte4 ); newbuf.SetByte( m_panose_byte5, (uint)Table_OS2.FieldOffsets.panose_byte5 ); newbuf.SetByte( m_panose_byte6, (uint)Table_OS2.FieldOffsets.panose_byte6 ); newbuf.SetByte( m_panose_byte7, (uint)Table_OS2.FieldOffsets.panose_byte7 ); newbuf.SetByte( m_panose_byte8, (uint)Table_OS2.FieldOffsets.panose_byte8 ); newbuf.SetByte( m_panose_byte9, (uint)Table_OS2.FieldOffsets.panose_byte9 ); newbuf.SetByte( m_panose_byte10, (uint)Table_OS2.FieldOffsets.panose_byte10 ); newbuf.SetUint( m_ulUnicodeRange1, (uint)Table_OS2.FieldOffsets.ulUnicodeRange1 ); newbuf.SetUint( m_ulUnicodeRange2, (uint)Table_OS2.FieldOffsets.ulUnicodeRange2 ); newbuf.SetUint( m_ulUnicodeRange3, (uint)Table_OS2.FieldOffsets.ulUnicodeRange3 ); newbuf.SetUint( m_ulUnicodeRange4, (uint)Table_OS2.FieldOffsets.ulUnicodeRange4 ); for( int i = 0; i < 4; i++ ) { newbuf.SetByte( m_achVendID[i], (uint)(Table_OS2.FieldOffsets.achVendID + i)); } newbuf.SetUshort( m_fsSelection, (uint)Table_OS2.FieldOffsets.fsSelection ); newbuf.SetUshort( m_usFirstCharIndex, (uint)Table_OS2.FieldOffsets.usFirstCharIndex ); newbuf.SetUshort( m_usLastCharIndex, (uint)Table_OS2.FieldOffsets.usLastCharIndex ); newbuf.SetShort( m_sTypoAscender, (uint)Table_OS2.FieldOffsets.sTypoAscender ); newbuf.SetShort( m_sTypoDescender, (uint)Table_OS2.FieldOffsets.sTypoDescender ); newbuf.SetShort( m_sTypoLineGap, (uint)Table_OS2.FieldOffsets.sTypoLineGap ); newbuf.SetUshort( m_usWinAscent, (uint)Table_OS2.FieldOffsets.usWinAscent ); newbuf.SetUshort( m_usWinDescent, (uint)Table_OS2.FieldOffsets.usWinDescent ); // version 1.0 if( version > 0x000 ) { newbuf.SetUint( m_ulCodePageRange1, (uint)Table_OS2.FieldOffsets.ulCodePageRange1 ); newbuf.SetUint( m_ulCodePageRange2, (uint)Table_OS2.FieldOffsets.ulCodePageRange2 ); // vewrsion 2 & 3 if( version > 0x001 ) { newbuf.SetShort( m_sxHeight, (uint)Table_OS2.FieldOffsets.sxHeight ); newbuf.SetShort( m_sCapHeight, (uint)Table_OS2.FieldOffsets.sCapHeight ); newbuf.SetUshort( m_usDefaultChar, (uint)Table_OS2.FieldOffsets.usDefaultChar ); newbuf.SetUshort( m_usBreakChar, (uint)Table_OS2.FieldOffsets.usBreakChar ); newbuf.SetUshort( m_usMaxContext, (uint)Table_OS2.FieldOffsets.usMaxContext ); } } // put the buffer into a Table_maxp object and return it Table_OS2 OS2Table = new Table_OS2("OS/2", newbuf); return OS2Table; } } } }
//----------------------------------------------------------------------------- // // <copyright file="PackageRelationship.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // This is a class for representing a PackageRelationship. This is a part of the // MMCF Packaging Layer. // // History: // 01/03/2004: SarjanaS: Initial creation. // 03/17/2004: BruceMac: Initial implementation or PackageRelationship methods // //----------------------------------------------------------------------------- using System; using System.Collections; using System.Xml; using System.Windows; // For Exception strings - SRID using System.Text; // for StringBuilder using System.Diagnostics; // for Debug.Assert using MS.Internal; // for Invariant.Assert using MS.Internal.WindowsBase; namespace System.IO.Packaging { /// <summary> /// This class is used to express a relationship between a source and a target part. /// The only way to create a PackageRelationship, is to call the PackagePart.CreateRelationship() /// or Package.CreateRelationship(). A relationship is owned by a part or by the package itself. /// If the source part is deleted all the relationships it owns are also deleted. /// A target of the relationship need not be present. </summary> public class PackageRelationship { //------------------------------------------------------ // // Public Constructors // //------------------------------------------------------ // None //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties /// <summary> /// This is a reference to the parent PackagePart to which this relationship belongs. /// </summary> /// <value>Uri</value> public Uri SourceUri { get { if (_source == null) return PackUriHelper.PackageRootUri; else return _source.Uri; } } /// <summary> /// Uri of the TargetPart, that this relationship points to. /// </summary> /// <value></value> public Uri TargetUri { get { return _targetUri; } } /// <summary> /// Type of the relationship - used to uniquely define the role of the relationship /// </summary> /// <value></value> public string RelationshipType { get { return _relationshipType; } } /// <summary> /// Enumeration value indicating the interpretations of the "base" of the target uri. /// </summary> /// <value></value> public TargetMode TargetMode { get { return _targetMode; } } /// <summary> /// PackageRelationship's identifier. Unique across relationships for the given source. /// </summary> /// <value>String</value> public String Id { get { return _id; } } /// <summary> /// PackageRelationship's owning Package object. /// </summary> /// <value>Package</value> public Package Package { get { return _package; } } #endregion Public Properties //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ // None //------------------------------------------------------ // // Public Events // //------------------------------------------------------ // None //------------------------------------------------------ // // Internal Constructors // //------------------------------------------------------ #region Internal Constructor /// <summary> /// PackageRelationship constructor /// </summary> /// <param name="package">Owning Package object for this relationship</param> /// <param name="sourcePart">owning part - will be null if the owner is the container</param> /// <param name="targetUri">target of relationship</param> /// <param name="targetMode">enum specifying the interpretation of the base uri for the target uri</param> /// <param name="relationshipType">type name</param> /// <param name="id">unique identifier</param> internal PackageRelationship(Package package, PackagePart sourcePart, Uri targetUri, TargetMode targetMode, string relationshipType, string id) { //sourcePart can be null to represent that the relationships are at the package level if (package == null) throw new ArgumentNullException("package"); if (targetUri == null) throw new ArgumentNullException("targetUri"); if (relationshipType == null) throw new ArgumentNullException("relationshipType"); if (id == null) throw new ArgumentNullException("id"); // The ID is guaranteed to be an XML ID by the caller (InternalRelationshipCollection). // The following check is a precaution against future bug introductions. #if DEBUG try { // An XSD ID is an NCName that is unique. We can't check uniqueness at this level. XmlConvert.VerifyNCName(id); } catch(XmlException exception) { throw new XmlException(SR.Get(SRID.NotAValidXmlIdString, id), exception); } #endif // Additional check - don't accept absolute Uri's if targetMode is Internal. Debug.Assert((targetMode == TargetMode.External || !targetUri.IsAbsoluteUri), "PackageRelationship target must be relative if the TargetMode is Internal"); // Additional check - Verify if the Enum value is valid Debug.Assert ((targetMode >= TargetMode.Internal || targetMode <= TargetMode.External), "TargetMode enum value is out of Range"); // Look for empty string or string with just spaces Debug.Assert(relationshipType.Trim() != String.Empty, "RelationshipType cannot be empty string or a string with just spaces"); _package = package; _source = sourcePart; _targetUri = targetUri; _relationshipType = relationshipType; _targetMode = targetMode; _id = id; } #endregion Internal Constructor //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties internal static Uri ContainerRelationshipPartName { get { return _containerRelationshipPartName; } } // Property used in streaming production to be able to keep the set // of all properties that have been created in memory while knowing // which remain to be written to XML. internal bool Saved { get { return _saved; } set { _saved = value; } } #endregion Internal Properties //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ // None //------------------------------------------------------ // // Internal Events // //------------------------------------------------------ // None //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ // None //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Members private Package _package; private PackagePart _source; private Uri _targetUri; private string _relationshipType; private TargetMode _targetMode; private String _id; private bool _saved = false; private static readonly Uri _containerRelationshipPartName = PackUriHelper.CreatePartUri(new Uri("/_rels/.rels", UriKind.Relative)); #endregion Private Members } }
/* Copyright (c) 2004-2009 Krzysztof Ostrowski. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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 "AS IS" BY THE ABOVE COPYRIGHT HOLDER(S) AND ALL OTHER CONTRIBUTORS 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 ABOVE COPYRIGHT HOLDER(S) OR ANY OTHER CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; namespace QS.Fx.Base { public sealed class Event : IEvent { public Event(ContextCallback callback, object context, SynchronizationOption option) { this.callback = callback; this.context = context; this.option = option; } public Event(ContextCallback callback, object context) : this(callback, context, SynchronizationOption.Synchronous | SynchronizationOption.Singlethreaded) { } public Event(ContextCallback callback) : this(callback, null, SynchronizationOption.Synchronous | SynchronizationOption.Singlethreaded) { } private ContextCallback callback; private object context; private IEvent next; private SynchronizationOption option; #region IEvent Members void IEvent.Handle() { callback(context); } IEvent IEvent.Next { get { return this.next; } set { this.next = value; } } SynchronizationOption IEvent.SynchronizationOption { get { return this.option; } } #endregion } public sealed class Event<C> : IEvent { public Event(ContextCallback<C> callback, C context, SynchronizationOption option) { this.callback = callback; this.context = context; this.option = option; } public Event(ContextCallback<C> callback, C context) : this(callback, context, SynchronizationOption.Synchronous | SynchronizationOption.Singlethreaded) { } private ContextCallback<C> callback; private C context; private IEvent next; private SynchronizationOption option; #region IEvent Members void IEvent.Handle() { callback(context); } IEvent IEvent.Next { get { return this.next; } set { this.next = value; } } SynchronizationOption IEvent.SynchronizationOption { get { return this.option; } } #endregion } public sealed class Event<C1, C2> : IEvent { public Event(ContextCallback<C1, C2> callback, C1 context1, C2 context2, SynchronizationOption option) { this.callback = callback; this.context1 = context1; this.context2 = context2; this.option = option; } public Event(ContextCallback<C1, C2> callback, C1 context1, C2 context2) : this(callback, context1, context2, SynchronizationOption.Synchronous | SynchronizationOption.Singlethreaded) { } private ContextCallback<C1, C2> callback; private C1 context1; private C2 context2; private IEvent next; private SynchronizationOption option; #region IEvent Members void IEvent.Handle() { callback(context1, context2); } IEvent IEvent.Next { get { return this.next; } set { this.next = value; } } SynchronizationOption IEvent.SynchronizationOption { get { return this.option; } } #endregion } public sealed class Event<C1, C2, C3> : IEvent { public Event(ContextCallback<C1, C2, C3> callback, C1 context1, C2 context2, C3 context3, SynchronizationOption option) { this.callback = callback; this.context1 = context1; this.context2 = context2; this.context3 = context3; this.option = option; } public Event(ContextCallback<C1, C2, C3> callback, C1 context1, C2 context2, C3 context3) : this(callback, context1, context2, context3, SynchronizationOption.Synchronous | SynchronizationOption.Singlethreaded) { } private ContextCallback<C1, C2, C3> callback; private C1 context1; private C2 context2; private C3 context3; private IEvent next; private SynchronizationOption option; #region IEvent Members void IEvent.Handle() { callback(context1, context2, context3); } IEvent IEvent.Next { get { return this.next; } set { this.next = value; } } SynchronizationOption IEvent.SynchronizationOption { get { return this.option; } } #endregion } }
/* * KinectModelController.cs - Handles rotating the bones of a model to match * rotations derived from the bone positions given by the kinect * * Developed by Peter Kinney -- 6/30/2011 * */ using UnityEngine; using System; using System.Collections; public class KinectModelControllerV2 : MonoBehaviour { //Assignments for a bitmask to control which bones to look at and which to ignore public enum BoneMask { None = 0x0, //EMPTY = 0x1, Spine = 0x2, Shoulder_Center = 0x4, Head = 0x8, Shoulder_Left = 0x10, Elbow_Left = 0x20, Wrist_Left = 0x40, Hand_Left = 0x80, Shoulder_Right = 0x100, Elbow_Right = 0x200, Wrist_Right = 0x400, Hand_Right = 0x800, Hips = 0x1000, Knee_Left = 0x2000, Ankle_Left = 0x4000, Foot_Left = 0x8000, //EMPTY = 0x10000, Knee_Right = 0x20000, Ankle_Right = 0x40000, Foot_Right = 0x80000, All = 0xEFFFE, Torso = 0x1000000 | Spine | Shoulder_Center | Head, //the leading bit is used to force the ordering in the editor Left_Arm = 0x1000000 | Shoulder_Left | Elbow_Left | Wrist_Left | Hand_Left, Right_Arm = 0x1000000 | Shoulder_Right | Elbow_Right | Wrist_Right | Hand_Right, Left_Leg = 0x1000000 | Hips | Knee_Left | Ankle_Left | Foot_Left, Right_Leg = 0x1000000 | Hips | Knee_Right | Ankle_Right | Foot_Right, R_Arm_Chest = Right_Arm | Spine, No_Feet = All & ~(Foot_Left | Foot_Right), Upper_Body = Torso | Left_Arm | Right_Arm } public SkeletonWrapper sw; public GameObject Hip_Center; public GameObject Spine; public GameObject Shoulder_Center; public GameObject Head; public GameObject Collar_Left; public GameObject Shoulder_Left; public GameObject Elbow_Left; public GameObject Wrist_Left; public GameObject Hand_Left; public GameObject Fingers_Left; //unused public GameObject Collar_Right; public GameObject Shoulder_Right; public GameObject Elbow_Right; public GameObject Wrist_Right; public GameObject Hand_Right; public GameObject Fingers_Right; //unused public GameObject Hip_Override; public GameObject Hip_Left; public GameObject Knee_Left; public GameObject Ankle_Left; public GameObject Foot_Left; public GameObject Hip_Right; public GameObject Knee_Right; public GameObject Ankle_Right; public GameObject Foot_Right; public int player; public BoneMask Mask = BoneMask.All; public bool animated; public float blendWeight = 1; private GameObject[] _bones; //internal handle for the bones of the model private uint _nullMask = 0x0; private Quaternion[] _baseRotation; //starting orientation of the joints private Vector3[] _boneDir; //in the bone's local space, the direction of the bones private Vector3[] _boneUp; //in the bone's local space, the up vector of the bone private Vector3 _hipRight; //right vector of the hips private Vector3 _chestRight; //right vectory of the chest // Use this for initialization void Start () { //store bones in a list for easier access, everything except Hip_Center will be one //higher than the corresponding Kinect.NuiSkeletonPositionIndex (because of the hip_override) _bones = new GameObject[(int)Kinect.NuiSkeletonPositionIndex.Count + 5] { null, Hip_Center, Spine, Shoulder_Center, Collar_Left, Shoulder_Left, Elbow_Left, Wrist_Left, Collar_Right, Shoulder_Right, Elbow_Right, Wrist_Right, Hip_Override, Hip_Left, Knee_Left, Ankle_Left, null, Hip_Right, Knee_Right, Ankle_Right, //extra joints to determine the direction of some bones Head, Hand_Left, Hand_Right, Foot_Left, Foot_Right}; //determine which bones are not available for(int ii = 0; ii < _bones.Length; ii++) { if(_bones[ii] == null) { _nullMask |= (uint)(1 << ii); } } //store the base rotations and bone directions (in bone-local space) _baseRotation = new Quaternion[(int)Kinect.NuiSkeletonPositionIndex.Count]; _boneDir = new Vector3[(int)Kinect.NuiSkeletonPositionIndex.Count]; //first save the special rotations for the hip and spine _hipRight = Hip_Right.transform.position - Hip_Left.transform.position; _hipRight = Hip_Override.transform.InverseTransformDirection(_hipRight); _chestRight = Shoulder_Right.transform.position - Shoulder_Left.transform.position; _chestRight = Spine.transform.InverseTransformDirection(_chestRight); //get direction of all other bones for( int ii = 0; ii < (int)Kinect.NuiSkeletonPositionIndex.Count; ii++) { if((_nullMask & (uint)(1 << ii)) <= 0) { //save initial rotation _baseRotation[ii] = _bones[ii].transform.localRotation; //if the bone is the end of a limb, get direction from this bone to one of the extras (hand or foot). if(ii % 4 == 3 && ((_nullMask & (uint)(1 << (ii/4) + (int)Kinect.NuiSkeletonPositionIndex.Count)) <= 0)) { _boneDir[ii] = _bones[(ii/4) + (int)Kinect.NuiSkeletonPositionIndex.Count].transform.position - _bones[ii].transform.position; } //if the bone is the hip_override (at boneindex Hip_Left, get direction from average of left and right hips else if(ii == (int)Kinect.NuiSkeletonPositionIndex.HipLeft && Hip_Left != null && Hip_Right != null) { _boneDir[ii] = ((Hip_Right.transform.position + Hip_Left.transform.position) / 2F) - Hip_Override.transform.position; } //otherwise, get the vector from this bone to the next. else if((_nullMask & (uint)(1 << ii+1)) <= 0) { _boneDir[ii] = _bones[ii+1].transform.position - _bones[ii].transform.position; } else { continue; } //Since the spine of the kinect data is ~40 degrees back from the hip, //check what angle the spine is at and rotate the saved direction back to match the data if(ii == (int)Kinect.NuiSkeletonPositionIndex.Spine) { float angle = Vector3.Angle(transform.up, _boneDir[ii]); {//YuYuYouEr Modified for Kinect V2 //_boneDir[ii] = Quaternion.AngleAxis(-40 + angle,transform.right) * _boneDir[ii]; _boneDir[ii] = Quaternion.AngleAxis(0 + angle, transform.right) * _boneDir[ii]; } } //transform the direction into local space. _boneDir[ii] = _bones[ii].transform.InverseTransformDirection(_boneDir[ii]); } } //make _chestRight orthogonal to the direction of the spine. _chestRight -= Vector3.Project(_chestRight, _boneDir[(int)Kinect.NuiSkeletonPositionIndex.Spine]); //make _hipRight orthogonal to the direction of the hip override Vector3.OrthoNormalize(ref _boneDir[(int)Kinect.NuiSkeletonPositionIndex.HipLeft],ref _hipRight); } void Update () { //update the data from the kinect if necessary if(sw.pollSkeleton()){ for( int ii = 0; ii < (int)Kinect.NuiSkeletonPositionIndex.Count; ii++) { if( ((uint)Mask & (uint)(1 << ii) ) > 0 && (_nullMask & (uint)(1 << ii)) <= 0 ) { RotateJoint(ii); } } } } void RotateJoint(int bone) { //if blendWeight is 0 there is no need to compute the rotations if( blendWeight <= 0 ){ return; } Vector3 upDir = new Vector3(); Vector3 rightDir = new Vector3(); if(bone == (int)Kinect.NuiSkeletonPositionIndex.Spine) { upDir = ((Hip_Left.transform.position + Hip_Right.transform.position) / 2F) - Hip_Override.transform.position; rightDir = Hip_Right.transform.position - Hip_Left.transform.position; } //if the model is not animated, reset rotations to fix twisted joints if(!animated){_bones[bone].transform.localRotation = _baseRotation[bone];} //if the required bone data from the kinect isn't available, return if( sw.boneState[player,bone] == Kinect.NuiSkeletonPositionTrackingState.NotTracked) { return; } //get the target direction of the bone in world space //for the majority of bone it's bone - 1 to bone, but Hip_Override and the outside //shoulders are determined differently. Vector3 dir = _boneDir[bone]; Vector3 target; //if bone % 4 == 0 then it is either an outside shoulder or the hip override if(bone % 4 == 0) { //hip override is at Hip_Left if(bone == (int)Kinect.NuiSkeletonPositionIndex.HipLeft) { //target = vector from hip_center to average of hips left and right target = ((sw.bonePos[player,(int)Kinect.NuiSkeletonPositionIndex.HipLeft] + sw.bonePos[player,(int)Kinect.NuiSkeletonPositionIndex.HipRight]) / 2F) - sw.bonePos[player,(int)Kinect.NuiSkeletonPositionIndex.HipCenter]; } //otherwise it is one of the shoulders else { //target = vector from shoulder_center to bone target = sw.bonePos[player,bone] - sw.bonePos[player,(int)Kinect.NuiSkeletonPositionIndex.ShoulderCenter]; } } else { //target = vector from previous bone to bone target = sw.bonePos[player,bone] - sw.bonePos[player,bone-1]; } //transform it into bone-local space (independant of the transform of the controller) target = transform.TransformDirection(target); target = _bones[bone].transform.InverseTransformDirection(target); //create a rotation that rotates dir into target Quaternion quat = Quaternion.FromToRotation(dir,target); //if bone is the spine, add in the rotation along the spine if(bone == (int)Kinect.NuiSkeletonPositionIndex.Spine) { //rotate the chest so that it faces forward (determined by the shoulders) dir = _chestRight; target = sw.bonePos[player,(int)Kinect.NuiSkeletonPositionIndex.ShoulderRight] - sw.bonePos[player,(int)Kinect.NuiSkeletonPositionIndex.ShoulderLeft]; target = transform.TransformDirection(target); target = _bones[bone].transform.InverseTransformDirection(target); target -= Vector3.Project(target,_boneDir[bone]); quat *= Quaternion.FromToRotation(dir,target); } //if bone is the hip override, add in the rotation along the hips else if(bone == (int)Kinect.NuiSkeletonPositionIndex.HipLeft) { //rotate the hips so they face forward (determined by the hips) dir = _hipRight; target = sw.bonePos[player,(int)Kinect.NuiSkeletonPositionIndex.HipRight] - sw.bonePos[player,(int)Kinect.NuiSkeletonPositionIndex.HipLeft]; target = transform.TransformDirection(target); target = _bones[bone].transform.InverseTransformDirection(target); target -= Vector3.Project(target,_boneDir[bone]); quat *= Quaternion.FromToRotation(dir,target); } //reduce the effect of the rotation using the blend parameter quat = Quaternion.Lerp(Quaternion.identity, quat, blendWeight); //apply the rotation to the local rotation of the bone _bones[bone].transform.localRotation = _bones[bone].transform.localRotation * quat; if(bone == (int)Kinect.NuiSkeletonPositionIndex.Spine) { restoreBone(_bones[(int)Kinect.NuiSkeletonPositionIndex.HipLeft],_boneDir[(int)Kinect.NuiSkeletonPositionIndex.HipLeft],upDir); restoreBone(_bones[(int)Kinect.NuiSkeletonPositionIndex.HipLeft],_hipRight,rightDir); } return; } void restoreBone(GameObject bone,Vector3 dir, Vector3 target) { //transform target into bone-local space (independant of the transform of the controller) //target = transform.TransformDirection(target); target = bone.transform.InverseTransformDirection(target); //create a rotation that rotates dir into target Quaternion quat = Quaternion.FromToRotation(dir,target); bone.transform.localRotation *= quat; } }
// Copyright 2017 Google Inc. 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 // // 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. using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using UnityEngine; namespace TiltBrushToolkit { [Serializable] public sealed class Gltf1Root : GltfRootBase { public Dictionary<string, Gltf1Buffer> buffers; public Dictionary<string, Gltf1Accessor> accessors; public Dictionary<string, Gltf1BufferView> bufferViews; public Dictionary<string, Gltf1Mesh> meshes; public Dictionary<string, Gltf1Shader> shaders; public Dictionary<string, Gltf1Program> programs; public Dictionary<string, Gltf1Technique> techniques; public Dictionary<string, Gltf1Image> images; public Dictionary<string, Gltf1Texture> textures; public Dictionary<string, Gltf1Material> materials; public Dictionary<string, Gltf1Node> nodes; public Dictionary<string, Gltf1Scene> scenes; public string scene; private bool disposed; [JsonIgnore] public Gltf1Scene scenePtr; public override GltfSceneBase ScenePtr { get { return scenePtr; } } public override IEnumerable<GltfImageBase> Images { get { if (images == null) { return new GltfImageBase[0]; } return images.Values.Cast<GltfImageBase>(); } } public override IEnumerable<GltfTextureBase> Textures { get { if (textures == null) { return new GltfTextureBase[0]; } return textures.Values.Cast<GltfTextureBase>(); } } public override IEnumerable<GltfMaterialBase> Materials { get { if (materials == null) { return new GltfMaterialBase[0]; } return materials.Values.Cast<GltfMaterialBase>(); } } public override IEnumerable<GltfMeshBase> Meshes { get { if (meshes == null) { return new GltfMeshBase[0]; } return meshes.Values.Cast<GltfMeshBase>(); } } // Disposable pattern, with Dispose(void) and Dispose(bool), as recommended by: // https://docs.microsoft.com/en-us/dotnet/api/system.idisposable protected override void Dispose(bool disposing) { if (disposed) return; // Already disposed. if (disposing && buffers != null) { foreach (var buffer in buffers.Values) { if (buffer != null && buffer.data != null) { buffer.data.Dispose(); } } } disposed = true; base.Dispose(disposing); } /// Map glTFid values (ie, string names) names to the objects they refer to public override void Dereference(bool isGlb, IUriLoader uriLoader = null) { // "dereference" all the names scenePtr = scenes[scene]; foreach (var pair in buffers) { pair.Value.gltfId = pair.Key; Gltf1Buffer buffer = pair.Value; if (uriLoader != null) { Debug.Assert(buffer.type == "arraybuffer"); // The .glb binary chunk is indicated by the id "binary_glTF", which must lack a uri // It's an error for other buffers to lack URIs. if (pair.Key == "binary_glTF") { Debug.Assert(buffer.uri == null); } else { Debug.Assert(buffer.uri != null); } buffer.data = uriLoader.Load(buffer.uri); } } foreach (var pair in accessors) { pair.Value.gltfId = pair.Key; pair.Value.bufferViewPtr = bufferViews[pair.Value.bufferView]; } foreach (var pair in bufferViews) { pair.Value.gltfId = pair.Key; pair.Value.bufferPtr = buffers[pair.Value.buffer]; } foreach (var pair in meshes) { pair.Value.gltfId = pair.Key; foreach (var prim in pair.Value.primitives) { prim.attributePtrs = prim.attributes.ToDictionary( elt => elt.Key, elt => accessors[elt.Value]); prim.indicesPtr = accessors[prim.indices]; prim.materialPtr = materials[prim.material]; } } if (shaders != null) { foreach (var pair in shaders) { pair.Value.gltfId = pair.Key; } } if (programs != null) { foreach (var pair in programs) { pair.Value.gltfId = pair.Key; var program = pair.Value; if (program.vertexShader != null) { program.vertexShaderPtr = shaders[program.vertexShader]; } if (program.fragmentShader != null) { program.fragmentShaderPtr = shaders[program.fragmentShader]; } } } if (techniques != null) { foreach (var pair in techniques) { pair.Value.gltfId = pair.Key; var technique = pair.Value; if (technique.program != null) { technique.programPtr = programs[technique.program]; } } } if (images != null) { foreach (var pair in images) { pair.Value.gltfId = pair.Key; } foreach (var pair in textures) { pair.Value.gltfId = pair.Key; var texture = pair.Value; if (texture.source != null) { texture.sourcePtr = images[texture.source]; } } } if (materials != null) { foreach (var pair in materials) { pair.Value.gltfId = pair.Key; var material = pair.Value; if (material.technique != null) { material.techniquePtr = techniques[material.technique]; } if (material.values != null) { if (material.values.BaseColorTex != null) { material.values.BaseColorTexPtr = textures[material.values.BaseColorTex]; } } } } foreach (var pair in nodes) { pair.Value.gltfId = pair.Key; var node = pair.Value; if (node.meshes != null) { node.meshPtrs = node.meshes.Select(id => meshes[id]).ToList(); } if (node.children != null) { node.childPtrs = node.children.Select(id => nodes[id]).ToList(); } } foreach (var pair in scenes) { pair.Value.gltfId = pair.Key; var scene2 = pair.Value; if (scene2.nodes != null) { scene2.nodePtrs = scene2.nodes.Select(name => nodes[name]).ToList(); } } } } [Serializable] public class Gltf1Buffer : GltfBufferBase { public string type; [JsonIgnore] public string gltfId; } [Serializable] public class Gltf1Accessor : GltfAccessorBase { public string bufferView; [JsonIgnore] public string gltfId; [JsonIgnore] public Gltf1BufferView bufferViewPtr; public override GltfBufferViewBase BufferViewPtr { get { return bufferViewPtr; } } } [Serializable] public class Gltf1BufferView : GltfBufferViewBase { public string buffer; [JsonIgnore] public string gltfId; [JsonIgnore] public Gltf1Buffer bufferPtr; public override GltfBufferBase BufferPtr { get { return bufferPtr; } } } [Serializable] public class Gltf1Primitive : GltfPrimitiveBase { public Dictionary<string, string> attributes; public string indices; public string material; [JsonIgnore] public Dictionary<string, Gltf1Accessor> attributePtrs; [JsonIgnore] public Gltf1Accessor indicesPtr; [JsonIgnore] public Gltf1Material materialPtr; public override GltfMaterialBase MaterialPtr { get { return materialPtr; } } public override GltfAccessorBase IndicesPtr { get { return indicesPtr; } } public override GltfAccessorBase GetAttributePtr(string attributeName) { return attributePtrs[attributeName]; } public override void ReplaceAttribute(string original, string replacement) { attributes[replacement] = attributes[original]; attributePtrs[replacement] = attributePtrs[original]; attributes.Remove(original); attributePtrs.Remove(original); } public override HashSet<string> GetAttributeNames() { return new HashSet<string>(attributePtrs.Keys); } } [Serializable] public class Gltf1Shader { public const int kFragmentShader = 35632; public const int kVertexShader = 35633; [JsonIgnore] public string gltfId; public string uri; public int type; } [Serializable] public class Gltf1Program { public string vertexShader; // index into shaders[] public string fragmentShader; // index into shaders[] [JsonIgnore] public string gltfId; [JsonIgnore] public Gltf1Shader vertexShaderPtr; [JsonIgnore] public Gltf1Shader fragmentShaderPtr; } [Serializable] public class Gltf1Technique { public string program; // index into programs[] public Dictionary<string, string> extras; [JsonIgnore] public string gltfId; [JsonIgnore] public Gltf1Program programPtr; } [Serializable] public class Gltf1Image : GltfImageBase { [JsonIgnore] public string gltfId; } [Serializable] public class Gltf1Texture : GltfTextureBase { [JsonIgnore] public string gltfId; public string source; // index into images[] [JsonIgnore] public Gltf1Image sourcePtr; public override object GltfId { get { return gltfId; } } public override GltfImageBase SourcePtr { get { return sourcePtr; } } } [Serializable] public class TiltBrushGltf1PbrValues { public Color? BaseColorFactor; public float? MetallicFactor; public float? RoughnessFactor; public string BaseColorTex; // index into textures[] // If you add more texture references here, update Gltf1Material.ReferencedTextures [JsonIgnore] public Gltf1Texture BaseColorTexPtr; } [Serializable] public class Gltf1Material : GltfMaterialBase { public string technique; // Since glTF1 is dying, there is no real reason to try and be generic about "values". // Instead, parse only those values we need in order to duplicate glTF2-pbr-like // functionality. Even this is not generic, as it assumes the pbr-like material // was created by Tilt Brush, using its Materials' names. // public Dict<string, JObject> values; public TiltBrushGltf1PbrValues values; [JsonIgnore] public string gltfId; [JsonIgnore] public Gltf1Technique techniquePtr; public override Dictionary<string,string> TechniqueExtras { get { return techniquePtr != null ? techniquePtr.extras : null; } } public override IEnumerable<GltfTextureBase> ReferencedTextures { get { if (values != null) { if (values.BaseColorTexPtr != null) { yield return values.BaseColorTexPtr; } } } } } [Serializable] public class Gltf1Mesh : GltfMeshBase { public List<Gltf1Primitive> primitives; [JsonIgnore] public string gltfId; public override IEnumerable<GltfPrimitiveBase> Primitives { get { foreach (Gltf1Primitive prim in primitives) { yield return prim; } } } public override int PrimitiveCount { get { return primitives.Count(); } } public override GltfPrimitiveBase GetPrimitiveAt(int i) { return primitives[i]; } } [Serializable] public class Gltf1Node : GltfNodeBase { public List<string> children; public List<string> meshes; [JsonIgnore] public string gltfId; [JsonIgnore] public List<Gltf1Mesh> meshPtrs; [JsonIgnore] public List<Gltf1Node> childPtrs; // Returns the mesh if there is only one mesh associated with this node. // Raises InvalidOperationException if there are multiple meshes. // glTF 1 allows this; glTF 2 does not. // // Safe to use if the source is glTF 2, or if you know a priori that the // generator doesn't use multiple nodes per mesh. public override GltfMeshBase Mesh { get { if (meshPtrs == null) { return null; } else if (meshPtrs.Count == 0) { return null; } else if (meshPtrs.Count == 1) { return meshPtrs[0]; } else { throw new InvalidOperationException("Multiple meshes"); } } } public override IEnumerable<GltfNodeBase> Children { get { if (childPtrs == null) yield break; foreach (Gltf1Node node in childPtrs) { yield return node; } } } } [Serializable] public class Gltf1Scene : GltfSceneBase { public List<string> nodes; [JsonIgnore] public string gltfId; [JsonIgnore] public List<Gltf1Node> nodePtrs; public override IEnumerable<GltfNodeBase> Nodes { get { foreach (Gltf1Node node in nodePtrs) { yield return node; } } } } }
// <copyright file="FtpStateMachine.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using FubarDev.FtpServer.Features; using JetBrains.Annotations; namespace FubarDev.FtpServer { /// <summary> /// A base class for a state machine that's triggered by FTP commands. /// </summary> /// <typeparam name="TStatus">The status type.</typeparam> public abstract class FtpStateMachine<TStatus> : IFtpStateMachine<TStatus> where TStatus : Enum { private readonly IReadOnlyDictionary<TStatus, IReadOnlyCollection<Transition>> _transitions; private readonly TStatus _initialStatus; private IReadOnlyCollection<Transition> _possibleTransitions; /// <summary> /// Initializes a new instance of the <see cref="FtpStateMachine{TStatus}"/> class. /// </summary> /// <param name="connection">The FTP connection.</param> /// <param name="transitions">The supported transitions.</param> /// <param name="initialStatus">The initial status.</param> protected FtpStateMachine( IFtpConnection connection, IEnumerable<Transition> transitions, TStatus initialStatus) { Connection = connection; _initialStatus = initialStatus; _transitions = transitions .ToLookup(x => x.Source) .ToDictionary(x => x.Key, x => (IReadOnlyCollection<Transition>)x.ToList()); Status = initialStatus; _possibleTransitions = GetPossibleTransitions(initialStatus); } /// <summary> /// Gets the current status. /// </summary> public TStatus Status { get; private set; } /// <summary> /// Gets the connection this state machine belongs to. /// </summary> public IFtpConnection Connection { get; } /// <summary> /// Resets the state machine to the initial status. /// </summary> public virtual void Reset() { SetStatus(_initialStatus); } /// <summary> /// Executes the given FTP command. /// </summary> /// <param name="ftpCommand">The FTP command to execute.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The task returning the response.</returns> public async Task<IFtpResponse?> ExecuteAsync(FtpCommand ftpCommand, CancellationToken cancellationToken = default) { var commandTransitions = _possibleTransitions .Where(x => x.IsMatch(ftpCommand.Name)) .ToList(); if (commandTransitions.Count == 0) { return new FtpResponse(503, T("Bad sequence of commands")); } var response = await ExecuteCommandAsync(ftpCommand, cancellationToken) .ConfigureAwait(false); if (response == null) { return new FtpResponse(421, T("Service not available")); } var foundStatus = commandTransitions.SingleOrDefault(x => x.IsMatch(ftpCommand.Name, response.Code)); if (foundStatus == null) { return new FtpResponse(421, T("Service not available")); } SetStatus(foundStatus.Target); // Ugh ... this is a hack, but I have to fix this later. if (response is FtpResponse ftpResponse && ftpResponse.Message == null) { return null; } return response; } /// <summary> /// Execute the command. All status checks are already done. /// </summary> /// <param name="ftpCommand">The FTP command to execute.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The task returning the response.</returns> protected abstract Task<IFtpResponse?> ExecuteCommandAsync(FtpCommand ftpCommand, CancellationToken cancellationToken = default); /// <summary> /// Called when the status was updated. /// </summary> /// <param name="from">The previous status.</param> /// <param name="to">The new status.</param> protected virtual void OnStatusChanged(TStatus from, TStatus to) { } /// <summary> /// Sets the status to a new value. /// </summary> /// <param name="status">The new status value.</param> protected void SetStatus(TStatus status) { _possibleTransitions = GetPossibleTransitions(status); var oldStatus = Status; Status = status; if (!oldStatus.Equals(status)) { OnStatusChanged(oldStatus, status); } } /// <summary> /// Get all possible transitions for a given status. /// </summary> /// <param name="status">The status value to get the transitions for.</param> /// <returns>The possible transitions for the given status.</returns> protected IReadOnlyCollection<Transition> GetPossibleTransitions(TStatus status) { if (_transitions.TryGetValue(status, out var statusTransitions)) { return statusTransitions; } return Array.Empty<Transition>(); } /// <summary> /// Translates a message using the current catalog of the active connection. /// </summary> /// <param name="message">The message to translate.</param> /// <returns>The translated message.</returns> protected string T(string message) { return Connection.Features.Get<ILocalizationFeature>().Catalog.GetString(message); } /// <summary> /// Translates a message using the current catalog of the active connection. /// </summary> /// <param name="message">The message to translate.</param> /// <param name="args">The format arguments.</param> /// <returns>The translated message.</returns> [StringFormatMethod("message")] protected string T(string message, params object[] args) { return Connection.Features.Get<ILocalizationFeature>().Catalog.GetString(message, args); } /// <summary> /// A class representing a transition. /// </summary> protected class Transition { private readonly Func<int, bool> _isCodeMatchFunc; private readonly Func<string, bool> _isCommandMatchFunc; /// <summary> /// Initializes a new instance of the <see cref="Transition"/> class. /// </summary> /// <param name="source">The source status.</param> /// <param name="target">The target status.</param> /// <param name="command">The trigger command.</param> /// <param name="resultCode">The expected FTP code.</param> public Transition(TStatus source, TStatus target, string command, SecurityActionResult resultCode) : this(source, target, command, code => code == (int)resultCode) { } /// <summary> /// Initializes a new instance of the <see cref="Transition"/> class. /// </summary> /// <remarks> /// The <paramref name="hundredsRange"/> is multiplied by 100 to get the FTP code range. /// </remarks> /// <param name="source">The source status.</param> /// <param name="target">The target status.</param> /// <param name="command">The trigger command.</param> /// <param name="hundredsRange">The hundreds range.</param> public Transition(TStatus source, TStatus target, string command, int hundredsRange) : this(source, target, command, code => code >= (hundredsRange * 100) && code < (hundredsRange + 1) * 100) { if (hundredsRange > 9) { throw new ArgumentOutOfRangeException(nameof(hundredsRange), "The value must be below 10."); } } /// <summary> /// Initializes a new instance of the <see cref="Transition"/> class. /// </summary> /// <param name="source">The source status.</param> /// <param name="target">The target status.</param> /// <param name="command">The trigger command.</param> /// <param name="isCodeMatch">A function to test if the code triggers this transition.</param> public Transition(TStatus source, TStatus target, string command, Func<int, bool> isCodeMatch) { Source = source; Target = target; _isCommandMatchFunc = cmd => string.Equals(command, cmd.Trim(), StringComparison.OrdinalIgnoreCase); _isCodeMatchFunc = isCodeMatch; } /// <summary> /// Gets the source status. /// </summary> public TStatus Source { get; } /// <summary> /// Gets the target status. /// </summary> public TStatus Target { get; } /// <summary> /// Returns <see langword="true"/> when this transition might be triggered by the given <paramref name="command"/>. /// </summary> /// <param name="command">The command to test for.</param> /// <returns><see langword="true"/> when this transition might be triggered by the given <paramref name="command"/>.</returns> public bool IsMatch(string command) => _isCommandMatchFunc(command); /// <summary> /// Returns <see langword="true"/> when this transition will be triggered by the given <paramref name="command"/> and <paramref name="code"/>. /// </summary> /// <param name="command">The command to test for.</param> /// <param name="code">The code to test for.</param> /// <returns><see langword="true"/> when this transition will be triggered by the given <paramref name="command"/> and <paramref name="code"/>.</returns> public bool IsMatch(string command, int code) => _isCommandMatchFunc(command) && _isCodeMatchFunc(code); } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Runtime.Serialization; using System.Security.Permissions; using OpenMetaverse; using OpenSim.Framework; namespace OpenSim.Region.Framework.Scenes { public delegate bool BoolDelegate(); public abstract class EntityBase : ISceneEntity { /// <summary> /// The scene to which this entity belongs /// </summary> public Scene Scene { get { return m_scene; } } protected Scene m_scene; protected UUID m_uuid; public virtual UUID UUID { get { return m_uuid; } set { m_uuid = value; } } protected string m_name; /// <summary> /// The name of this entity /// </summary> public virtual string Name { get { return m_name; } set { m_name = value; } } /// <summary> /// Signals whether this entity was in a scene but has since been removed from it. /// </summary> public bool IsDeleted { get { return m_isDeleted; } } protected bool m_isDeleted; public class PositionInfo { public Vector3 m_pos; public SceneObjectPart m_parent; public Vector3 m_parentPos; public PositionInfo() { Clear(); } public PositionInfo(Vector3 pos, SceneObjectPart parent, Vector3 parentPos) { Set(pos, parent, parentPos); } public PositionInfo(PositionInfo info) { Set(info); } public void Set(PositionInfo info) { lock (this) { m_pos = info.m_pos; m_parentPos = info.m_parentPos; m_parent = info.m_parent; } } public void Set(Vector3 pos, SceneObjectPart parent, Vector3 parentPos) { lock (this) { m_pos = pos; m_parentPos = parentPos; m_parent = parent; } } public void SetPosition(float x, float y, float z) { lock (this) { m_pos.X = x; m_pos.Y = y; m_pos.Z = z; } } public void Clear() { lock (this) { m_pos = Vector3.Zero; m_parentPos = Vector3.Zero; m_parent = null; } } public Object Clone() { lock (this) { return MemberwiseClone(); } } public Vector3 Position { get { lock (this) { return new Vector3(m_pos); } } set { lock (this) { m_pos = value; } } } public SceneObjectPart Parent { get { lock (this) { return m_parent; } } set { lock (this) { m_parent = value; } } } internal void SetPosition(Vector3 pos) { m_pos = pos; } }; protected PositionInfo m_posInfo; // Don't use getter/setter methods, make it obvious these are method function calls, not members, take a snapshot with GET, don't use .Position, etc. public PositionInfo GetPosInfo() { lock (m_posInfo) { return (PositionInfo)m_posInfo.Clone(); } } public void SetPosInfo(PositionInfo info) { lock (m_posInfo) { m_posInfo.m_pos = info.m_pos; m_posInfo.m_parentPos = info.m_parentPos; m_posInfo.m_parent = info.m_parent; } } public bool PosInfoLockedCall(BoolDelegate func) { lock (m_posInfo) return func(); } /// <summary> /// /// </summary> public virtual Vector3 AbsolutePosition { get { lock (m_posInfo) { return m_posInfo.Position; } } set { lock (m_posInfo) { m_posInfo.Position = value; } } } protected Vector3 m_rotationalvelocity; protected Quaternion m_rotation = new Quaternion(0f, 0f, 1f, 0f); public virtual Quaternion Rotation { get { return m_rotation; } set { m_rotation = value; } } protected uint m_localId; public virtual uint LocalId { get { return m_localId; } set { m_localId = value; } } /// <summary> /// Creates a new Entity (should not occur on it's own) /// </summary> public EntityBase() { m_uuid = UUID.Zero; m_posInfo = new PositionInfo(); Rotation = Quaternion.Identity; m_name = "(basic entity)"; m_rotationalvelocity = Vector3.Zero; } /// <summary> /// /// </summary> public abstract void UpdateMovement(); /// <summary> /// Performs any updates that need to be done at each frame, as opposed to immediately. /// These included scheduled updates and updates that occur due to physics processing. /// </summary> public abstract void Update(); /// <summary> /// Copies the entity /// </summary> /// <returns></returns> public virtual EntityBase Copy() { return (EntityBase) MemberwiseClone(); } public abstract void SetText(string text, Vector3 color, double alpha); } //Nested Classes public class EntityIntersection { public Vector3 ipoint = new Vector3(0, 0, 0); public Vector3 normal = new Vector3(0, 0, 0); public Vector3 AAfaceNormal = new Vector3(0, 0, 0); public int face = -1; public bool HitTF = false; public SceneObjectPart obj; public float distance = 0; public EntityIntersection() { } public EntityIntersection(Vector3 _ipoint, Vector3 _normal, bool _HitTF) { ipoint = _ipoint; normal = _normal; HitTF = _HitTF; } } }
// // LastfmRequest.cs // // Authors: // Bertrand Lorentz <[email protected]> // // Copyright (C) 2009 Bertrand Lorentz // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Web; using Hyena; using Hyena.Json; namespace Lastfm { public enum RequestType { Read, SessionRequest, // Needs the signature, but we don't have the session key yet AuthenticatedRead, Write } public enum ResponseFormat { Json, Raw } public class LastfmRequest { private const string API_ROOT = "http://ws.audioscrobbler.com/2.0/"; private Dictionary<string, string> parameters = new Dictionary<string, string> (); private Stream response_stream; public LastfmRequest () {} public LastfmRequest (string method) : this (method, RequestType.Read, ResponseFormat.Json) {} public LastfmRequest (string method, RequestType request_type, ResponseFormat response_format) { this.method = method; this.request_type = request_type; this.response_format = response_format; } private string method; public string Method { get; set; } private RequestType request_type; public RequestType RequestType { get; set; } private ResponseFormat response_format; public ResponseFormat ResponseFormat { get; set; } public void AddParameter (string param_name, string param_value) { parameters.Add (param_name, param_value); } public Stream GetResponseStream () { return response_stream; } public void Send () { if (method == null) { throw new InvalidOperationException ("The method name should be set"); } if (response_format == ResponseFormat.Json) { AddParameter ("format", "json"); } else if (response_format == ResponseFormat.Raw) { AddParameter ("raw", "true"); } if (request_type == RequestType.Write) { response_stream = Post (API_ROOT, BuildPostData ()); } else { response_stream = Get (BuildGetUrl ()); } } public JsonObject GetResponseObject () { Deserializer deserializer = new Deserializer (response_stream); object obj = deserializer.Deserialize (); JsonObject json_obj = obj as Hyena.Json.JsonObject; if (json_obj == null) { throw new ApplicationException ("Lastfm invalid response : not a JSON object"); } return json_obj; } public StationError GetError () { StationError error = StationError.None; string response; using (StreamReader sr = new StreamReader (response_stream)) { response = sr.ReadToEnd (); } if (response.Contains ("<lfm status=\"failed\">")) { // XML reply indicates an error Match match = Regex.Match (response, "<error code=\"(\\d+)\">"); if (match.Success) { error = (StationError) Int32.Parse (match.Value); Log.WarningFormat ("Lastfm error {0}", error); } else { error = StationError.Unknown; } } if (response_format == ResponseFormat.Json && response.Contains ("\"error\":")) { // JSON reply indicates an error Deserializer deserializer = new Deserializer (response); JsonObject json = deserializer.Deserialize () as JsonObject; if (json != null && json.ContainsKey ("error")) { error = (StationError) json["error"]; Log.WarningFormat ("Lastfm error {0} : {1}", error, (string)json["message"]); } } return error; } private string BuildGetUrl () { if (request_type == RequestType.AuthenticatedRead) { parameters.Add ("sk", LastfmCore.Account.SessionKey); } StringBuilder url = new StringBuilder (API_ROOT); url.AppendFormat ("?method={0}", method); url.AppendFormat ("&api_key={0}", LastfmCore.ApiKey); foreach (KeyValuePair<string, string> param in parameters) { url.AppendFormat ("&{0}={1}", param.Key, Uri.EscapeDataString (param.Value)); } if (request_type == RequestType.AuthenticatedRead || request_type == RequestType.SessionRequest) { url.AppendFormat ("&api_sig={0}", GetSignature ()); } return url.ToString (); } private string BuildPostData () { parameters.Add ("sk", LastfmCore.Account.SessionKey); StringBuilder data = new StringBuilder (); data.AppendFormat ("method={0}", method); data.AppendFormat ("&api_key={0}", LastfmCore.ApiKey); foreach (KeyValuePair<string, string> param in parameters) { data.AppendFormat ("&{0}={1}", param.Key, Uri.EscapeDataString (param.Value)); } data.AppendFormat ("&api_sig={0}", GetSignature ()); return data.ToString (); } private string GetSignature () { SortedDictionary<string, string> sorted_params = new SortedDictionary<string, string> (parameters); if (!sorted_params.ContainsKey ("api_key")) { sorted_params.Add ("api_key", LastfmCore.ApiKey); } if (!sorted_params.ContainsKey ("method")) { sorted_params.Add ("method", method); } StringBuilder signature = new StringBuilder (); foreach (KeyValuePair<string, string> parm in sorted_params) { if (parm.Key.Equals ("format")) { continue; } signature.Append (parm.Key); signature.Append (parm.Value); } signature.Append (LastfmCore.ApiSecret); return Hyena.CryptoUtil.Md5Encode (signature.ToString (), Encoding.UTF8); } #region HTTP helpers private Stream Get (string uri) { return Get (uri, null); } private Stream Get (string uri, string accept) { HttpWebRequest request = (HttpWebRequest) WebRequest.Create (uri); if (accept != null) { request.Accept = accept; } request.UserAgent = LastfmCore.UserAgent; request.Timeout = 10000; request.KeepAlive = false; request.AllowAutoRedirect = true; HttpWebResponse response = (HttpWebResponse) request.GetResponse (); return response.GetResponseStream (); } private Stream Post (string uri, string data) { // Do not trust docs : it doesn't work if parameters are in the request body HttpWebRequest request = (HttpWebRequest) WebRequest.Create (String.Concat (uri, "?", data)); request.UserAgent = LastfmCore.UserAgent; request.Timeout = 10000; request.Method = "POST"; request.KeepAlive = false; request.ContentType = "application/x-www-form-urlencoded"; HttpWebResponse response = null; try { response = (HttpWebResponse) request.GetResponse (); } catch (WebException e) { Log.DebugException (e); response = (HttpWebResponse)e.Response; } return response.GetResponseStream (); } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Hyak.Common; using Microsoft.Azure.Gallery; namespace Microsoft.Azure.Gallery { public partial class GalleryItem { private IList<Artifact> _artifacts; /// <summary> /// Optional. Gets or sets gallery item artifacts. /// </summary> public IList<Artifact> Artifacts { get { return this._artifacts; } set { this._artifacts = value; } } private IList<string> _categories; /// <summary> /// Optional. Gets or sets gallery item category identifiers. /// </summary> public IList<string> Categories { get { return this._categories; } set { this._categories = value; } } private string _description; /// <summary> /// Optional. Gets or sets gallery item description. /// </summary> public string Description { get { return this._description; } set { this._description = value; } } private string _displayName; /// <summary> /// Optional. Gets or sets gallery item display name. /// </summary> public string DisplayName { get { return this._displayName; } set { this._displayName = value; } } private IList<Filter> _filters; /// <summary> /// Optional. Gets or sets gallery item filters. /// </summary> public IList<Filter> Filters { get { return this._filters; } set { this._filters = value; } } private IDictionary<string, string> _iconFileUris; /// <summary> /// Optional. Gets or sets gallery item screenshot Uris /// </summary> public IDictionary<string, string> IconFileUris { get { return this._iconFileUris; } set { this._iconFileUris = value; } } private string _identity; /// <summary> /// Optional. Gets or sets gallery item identity. /// </summary> public string Identity { get { return this._identity; } set { this._identity = value; } } private IList<Link> _links; /// <summary> /// Optional. Gets or sets gallery item links. /// </summary> public IList<Link> Links { get { return this._links; } set { this._links = value; } } private string _longSummary; /// <summary> /// Optional. Gets or sets gallery item long summary. /// </summary> public string LongSummary { get { return this._longSummary; } set { this._longSummary = value; } } private MarketingMaterial _marketingMaterial; /// <summary> /// Optional. Gets or sets gallery item marketing information. /// </summary> public MarketingMaterial MarketingMaterial { get { return this._marketingMaterial; } set { this._marketingMaterial = value; } } private IDictionary<string, string> _metadata; /// <summary> /// Optional. Gets or sets gallery item metadata. /// </summary> public IDictionary<string, string> Metadata { get { return this._metadata; } set { this._metadata = value; } } private string _name; /// <summary> /// Optional. Gets or sets gallery item name. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private IList<Product> _products; /// <summary> /// Optional. Gets or sets gallery item product definition. /// </summary> public IList<Product> Products { get { return this._products; } set { this._products = value; } } private IDictionary<string, string> _properties; /// <summary> /// Optional. Gets or sets gallery item user visible properties. /// </summary> public IDictionary<string, string> Properties { get { return this._properties; } set { this._properties = value; } } private string _publisher; /// <summary> /// Optional. Gets or sets gallery item publisher. /// </summary> public string Publisher { get { return this._publisher; } set { this._publisher = value; } } private string _publisherDisplayName; /// <summary> /// Optional. Gets or sets gallery item publisher display name. /// </summary> public string PublisherDisplayName { get { return this._publisherDisplayName; } set { this._publisherDisplayName = value; } } private IList<string> _screenshotUris; /// <summary> /// Optional. Gets or sets gallery item screenshot Uris /// </summary> public IList<string> ScreenshotUris { get { return this._screenshotUris; } set { this._screenshotUris = value; } } private string _summary; /// <summary> /// Optional. Gets or sets gallery item summary. /// </summary> public string Summary { get { return this._summary; } set { this._summary = value; } } private string _uiDefinitionUri; /// <summary> /// Optional. Gets or sets Azure Portal Uder Interface Definition /// artificat Uri. /// </summary> public string UiDefinitionUri { get { return this._uiDefinitionUri; } set { this._uiDefinitionUri = value; } } private string _version; /// <summary> /// Optional. Gets or sets gallery item version. /// </summary> public string Version { get { return this._version; } set { this._version = value; } } /// <summary> /// Initializes a new instance of the GalleryItem class. /// </summary> public GalleryItem() { this.Artifacts = new LazyList<Artifact>(); this.Categories = new LazyList<string>(); this.Filters = new LazyList<Filter>(); this.IconFileUris = new LazyDictionary<string, string>(); this.Links = new LazyList<Link>(); this.Metadata = new LazyDictionary<string, string>(); this.Products = new LazyList<Product>(); this.Properties = new LazyDictionary<string, string>(); this.ScreenshotUris = new LazyList<string>(); } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections.Generic; using System.Xml; using System.Management.Automation.Internal; namespace Microsoft.PowerShell.Commands.Internal.Format { /// <summary> /// class to load the XML document into data structures. /// It encapsulates the file format specific code /// </summary> internal sealed partial class TypeInfoDataBaseLoader : XmlLoaderBase { private ControlBase LoadTableControl(XmlNode controlNode) { using (this.StackFrame(controlNode)) { TableControlBody tableBody = new TableControlBody(); bool headersNodeFound = false; // cardinality 0..1 bool rowEntriesNodeFound = false; // cardinality 1 bool hideHeadersNodeFound = false; // cardinality 0..1 bool autosizeNodeFound = false; // cardinality 0..1 foreach (XmlNode n in controlNode.ChildNodes) { if (MatchNodeName(n, XmlTags.HideTableHeadersNode)) { if (hideHeadersNodeFound) { this.ProcessDuplicateNode(n); return null; // fatal error } hideHeadersNodeFound = true; if (!this.ReadBooleanNode(n, out tableBody.header.hideHeader)) { return null; //fatal error } } else if (MatchNodeName(n, XmlTags.AutoSizeNode)) { if (autosizeNodeFound) { this.ProcessDuplicateNode(n); return null; // fatal error } autosizeNodeFound = true; bool tempVal; if (!this.ReadBooleanNode(n, out tempVal)) { return null; // fatal error } tableBody.autosize = tempVal; } else if (MatchNodeName(n, XmlTags.TableHeadersNode)) { if (headersNodeFound) { this.ProcessDuplicateNode(n); return null; // fatal error } headersNodeFound = true; // now read the columns header section LoadHeadersSection(tableBody, n); if (tableBody.header.columnHeaderDefinitionList == null) { // if we have an empty list, it means there was a failure return null; // fatal error } } else if (MatchNodeName(n, XmlTags.TableRowEntriesNode)) { if (rowEntriesNodeFound) { this.ProcessDuplicateNode(n); return null; // fatal error } rowEntriesNodeFound = true; // now read the columns section LoadRowEntriesSection(tableBody, n); if (tableBody.defaultDefinition == null) { return null; // fatal error } } else { this.ProcessUnknownNode(n); } } if (!rowEntriesNodeFound) { this.ReportMissingNode(XmlTags.TableRowEntriesNode); return null; // fatal error } // CHECK: verify consistency of headers and row entries if (tableBody.header.columnHeaderDefinitionList.Count != 0) { // CHECK: if there are headers in the list, their number has to match // the default row definition intem count if (tableBody.header.columnHeaderDefinitionList.Count != tableBody.defaultDefinition.rowItemDefinitionList.Count) { //Error at XPath {0} in file {1}: Header item count = {2} does not match default row item count = {3}. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.IncorrectHeaderItemCount, ComputeCurrentXPath(), FilePath, tableBody.header.columnHeaderDefinitionList.Count, tableBody.defaultDefinition.rowItemDefinitionList.Count)); return null; // fatal error } } // CHECK: if there are alternative row definitions, they should have the same # of items if (tableBody.optionalDefinitionList.Count != 0) { int k = 0; foreach (TableRowDefinition trd in tableBody.optionalDefinitionList) { if (trd.rowItemDefinitionList.Count != tableBody.defaultDefinition.rowItemDefinitionList.Count) { //Error at XPath {0} in file {1}: Row item count = {2} on alternative set #{3} does not match default row item count = {4}. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.IncorrectRowItemCount, ComputeCurrentXPath(), FilePath, trd.rowItemDefinitionList.Count, tableBody.defaultDefinition.rowItemDefinitionList.Count, k + 1)); return null; // fatal error } k++; } } return tableBody; } } private void LoadHeadersSection(TableControlBody tableBody, XmlNode headersNode) { using (this.StackFrame(headersNode)) { int columnIndex = 0; foreach (XmlNode n in headersNode.ChildNodes) { if (MatchNodeName(n, XmlTags.TableColumnHeaderNode)) { TableColumnHeaderDefinition chd = LoadColumnHeaderDefinition(n, columnIndex++); if (chd != null) tableBody.header.columnHeaderDefinitionList.Add(chd); else { //Error at XPath {0} in file {1}: Column header definition is invalid; all headers are discarded. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.InvalidColumnHeader, ComputeCurrentXPath(), FilePath)); tableBody.header.columnHeaderDefinitionList = null; return; // fatal error } } else { this.ProcessUnknownNode(n); } } // NOTICE: the list can be empty if no entries were found } } private TableColumnHeaderDefinition LoadColumnHeaderDefinition(XmlNode columnHeaderNode, int index) { using (this.StackFrame(columnHeaderNode, index)) { TableColumnHeaderDefinition chd = new TableColumnHeaderDefinition(); bool labelNodeFound = false; // cardinality 0..1 bool widthNodeFound = false; // cardinality 0..1 bool alignmentNodeFound = false; // cardinality 0..1 foreach (XmlNode n in columnHeaderNode.ChildNodes) { if (MatchNodeNameWithAttributes(n, XmlTags.LabelNode)) { if (labelNodeFound) { this.ProcessDuplicateNode(n); return null; // fatal error } labelNodeFound = true; chd.label = LoadLabel(n); if (chd.label == null) { return null; // fatal error } } else if (MatchNodeName(n, XmlTags.WidthNode)) { if (widthNodeFound) { this.ProcessDuplicateNode(n); return null; // fatal error } widthNodeFound = true; int wVal; if (ReadPositiveIntegerValue(n, out wVal)) { chd.width = wVal; } else { //Error at XPath {0} in file {1}: Invalid {2} value. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.InvalidNodeValue, ComputeCurrentXPath(), FilePath, XmlTags.WidthNode)); return null; //fatal error } } else if (MatchNodeName(n, XmlTags.AlignmentNode)) { if (alignmentNodeFound) { this.ProcessDuplicateNode(n); return null; // fatal error } alignmentNodeFound = true; if (!LoadAlignmentValue(n, out chd.alignment)) { return null; // fatal error } } else { this.ProcessUnknownNode(n); } } // foreach return chd; } // using } private bool ReadPositiveIntegerValue(XmlNode n, out int val) { val = -1; string text = GetMandatoryInnerText(n); if (text == null) return false; bool isInteger = int.TryParse(text, out val); if (!isInteger || val <= 0) { //Error at XPath {0} in file {1}: A positive integer is expected. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.ExpectPositiveInteger, ComputeCurrentXPath(), FilePath)); return false; } return true; } private bool LoadAlignmentValue(XmlNode n, out int alignmentValue) { alignmentValue = TextAlignment.Undefined; string alignmentString = GetMandatoryInnerText(n); if (alignmentString == null) { return false; // fatal error } if (string.Equals(n.InnerText, XMLStringValues.AligmentLeft, StringComparison.OrdinalIgnoreCase)) { alignmentValue = TextAlignment.Left; } else if (string.Equals(n.InnerText, XMLStringValues.AligmentRight, StringComparison.OrdinalIgnoreCase)) { alignmentValue = TextAlignment.Right; } else if (string.Equals(n.InnerText, XMLStringValues.AligmentCenter, StringComparison.OrdinalIgnoreCase)) { alignmentValue = TextAlignment.Center; } else { //Error at XPath {0} in file {1}: "{2}" is not an valid alignment value. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.InvalidAlignmentValue, ComputeCurrentXPath(), FilePath, alignmentString)); return false; // fatal error } return true; } private void LoadRowEntriesSection(TableControlBody tableBody, XmlNode rowEntriesNode) { using (this.StackFrame(rowEntriesNode)) { int rowEntryIndex = 0; foreach (XmlNode n in rowEntriesNode.ChildNodes) { if (MatchNodeName(n, XmlTags.TableRowEntryNode)) { TableRowDefinition trd = LoadRowEntryDefinition(n, rowEntryIndex++); if (trd == null) { //Error at XPath {0} in file {1}: {2} failed to load. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.LoadTagFailed, ComputeCurrentXPath(), FilePath, XmlTags.TableRowEntryNode)); tableBody.defaultDefinition = null; return; // fatal error } // determine if we have a default entry and if it's already set if (trd.appliesTo == null) { if (tableBody.defaultDefinition == null) { tableBody.defaultDefinition = trd; } else { //Error at XPath {0} in file {1}: There cannot be more than one default {2}. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.TooManyDefaultShapeEntry, ComputeCurrentXPath(), FilePath, XmlTags.TableRowEntryNode)); tableBody.defaultDefinition = null; return; // fatal error } } else { tableBody.optionalDefinitionList.Add(trd); } } else { this.ProcessUnknownNode(n); } } if (tableBody.defaultDefinition == null) { //Error at XPath {0} in file {1}: There must be at least one default {2}. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NoDefaultShapeEntry, ComputeCurrentXPath(), FilePath, XmlTags.TableRowEntryNode)); } } } private TableRowDefinition LoadRowEntryDefinition(XmlNode rowEntryNode, int index) { using (this.StackFrame(rowEntryNode, index)) { bool appliesToNodeFound = false; // cardinality 0..1 bool columnEntriesNodeFound = false; // cardinality 1 bool multiLineFound = false; // cardinality 0..1 TableRowDefinition trd = new TableRowDefinition(); foreach (XmlNode n in rowEntryNode.ChildNodes) { if (MatchNodeName(n, XmlTags.EntrySelectedByNode)) { if (appliesToNodeFound) { this.ProcessDuplicateNode(n); return null; // fatal error } appliesToNodeFound = true; // optional section trd.appliesTo = LoadAppliesToSection(n, true); } else if (MatchNodeName(n, XmlTags.TableColumnItemsNode)) { if (columnEntriesNodeFound) { this.ProcessDuplicateNode(n); return null; //fatal } LoadColumnEntries(n, trd); if (trd.rowItemDefinitionList == null) { return null; // fatal error } } else if (MatchNodeName(n, XmlTags.MultiLineNode)) { if (multiLineFound) { this.ProcessDuplicateNode(n); return null; //fatal } multiLineFound = true; if (!this.ReadBooleanNode(n, out trd.multiLine)) { return null; //fatal error } } else { this.ProcessUnknownNode(n); } } return trd; } } private void LoadColumnEntries(XmlNode columnEntriesNode, TableRowDefinition trd) { using (this.StackFrame(columnEntriesNode)) { int columnEntryIndex = 0; foreach (XmlNode n in columnEntriesNode.ChildNodes) { if (MatchNodeName(n, XmlTags.TableColumnItemNode)) { TableRowItemDefinition rid = LoadColumnEntry(n, columnEntryIndex++); if (rid != null) { trd.rowItemDefinitionList.Add(rid); } else { // we failed one entry: fatal error to percolate up // remove all the entries trd.rowItemDefinitionList = null; return; // fatal error } } else { this.ProcessUnknownNode(n); } } } } private TableRowItemDefinition LoadColumnEntry(XmlNode columnEntryNode, int index) { using (this.StackFrame(columnEntryNode, index)) { // process Mshexpression, format string and text token ViewEntryNodeMatch match = new ViewEntryNodeMatch(this); List<XmlNode> unprocessedNodes = new List<XmlNode>(); if (!match.ProcessExpressionDirectives(columnEntryNode, unprocessedNodes)) { return null; // fatal error } TableRowItemDefinition rid = new TableRowItemDefinition(); // process the remaining nodes bool alignmentNodeFound = false; // cardinality 0..1 foreach (XmlNode n in unprocessedNodes) { if (MatchNodeName(n, XmlTags.AlignmentNode)) { if (alignmentNodeFound) { this.ProcessDuplicateNode(n); return null; // fatal error } alignmentNodeFound = true; if (!LoadAlignmentValue(n, out rid.alignment)) { return null; // fatal error } } else { this.ProcessUnknownNode(n); } } // finally build the item to return // add either the text token or the MshExpression with optional format string if (match.TextToken != null) { rid.formatTokenList.Add(match.TextToken); } else if (match.Expression != null) { FieldPropertyToken fpt = new FieldPropertyToken(); fpt.expression = match.Expression; fpt.fieldFormattingDirective.formatString = match.FormatString; rid.formatTokenList.Add(fpt); } return rid; } // using } } }
// 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.Diagnostics; using Microsoft.DiaSymReader; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal static class PdbHelpers { /// <remarks> /// Test helper. /// </remarks> internal static void GetAllScopes(this ISymUnmanagedMethod method, ArrayBuilder<ISymUnmanagedScope> builder) { var unused = ArrayBuilder<ISymUnmanagedScope>.GetInstance(); GetAllScopes(method, builder, unused, offset: -1, isScopeEndInclusive: false); unused.Free(); } internal static void GetAllScopes( this ISymUnmanagedMethod method, ArrayBuilder<ISymUnmanagedScope> allScopes, ArrayBuilder<ISymUnmanagedScope> containingScopes, int offset, bool isScopeEndInclusive) { GetAllScopes(method.GetRootScope(), allScopes, containingScopes, offset, isScopeEndInclusive); } private static void GetAllScopes( ISymUnmanagedScope root, ArrayBuilder<ISymUnmanagedScope> allScopes, ArrayBuilder<ISymUnmanagedScope> containingScopes, int offset, bool isScopeEndInclusive) { var stack = ArrayBuilder<ISymUnmanagedScope>.GetInstance(); stack.Push(root); while (stack.Any()) { var scope = stack.Pop(); allScopes.Add(scope); if (offset >= 0 && scope.IsInScope(offset, isScopeEndInclusive)) { containingScopes.Add(scope); } foreach (var nested in scope.GetScopes()) { stack.Push(nested); } } stack.Free(); } /// <summary> /// Translates the value of a constant returned by <see cref="ISymUnmanagedConstant.GetValue(out object)"/> to a <see cref="ConstantValue"/>. /// </summary> public static ConstantValue GetConstantValue(ITypeSymbol type, object symValue) { Debug.Assert(type.TypeKind != TypeKind.Enum); short shortValue; switch (type.SpecialType) { case SpecialType.System_Boolean: if (!(symValue is short)) { return ConstantValue.Bad; } return ConstantValue.Create((short)symValue != 0); case SpecialType.System_Byte: if (!(symValue is short)) { return ConstantValue.Bad; } shortValue = (short)symValue; if (unchecked((byte)shortValue) != shortValue) { return ConstantValue.Bad; } return ConstantValue.Create((byte)shortValue); case SpecialType.System_SByte: if (!(symValue is short)) { return ConstantValue.Bad; } shortValue = (short)symValue; if (unchecked((sbyte)shortValue) != shortValue) { return ConstantValue.Bad; } return ConstantValue.Create((sbyte)shortValue); case SpecialType.System_Int16: if (!(symValue is short)) { return ConstantValue.Bad; } return ConstantValue.Create((short)symValue); case SpecialType.System_Char: if (!(symValue is ushort)) { return ConstantValue.Bad; } return ConstantValue.Create((char)(ushort)symValue); case SpecialType.System_UInt16: if (!(symValue is ushort)) { return ConstantValue.Bad; } return ConstantValue.Create((ushort)symValue); case SpecialType.System_Int32: if (!(symValue is int)) { return ConstantValue.Bad; } return ConstantValue.Create((int)symValue); case SpecialType.System_UInt32: if (!(symValue is uint)) { return ConstantValue.Bad; } return ConstantValue.Create((uint)symValue); case SpecialType.System_Int64: if (!(symValue is long)) { return ConstantValue.Bad; } return ConstantValue.Create((long)symValue); case SpecialType.System_UInt64: if (!(symValue is ulong)) { return ConstantValue.Bad; } return ConstantValue.Create((ulong)symValue); case SpecialType.System_Single: if (!(symValue is float)) { return ConstantValue.Bad; } return ConstantValue.Create((float)symValue); case SpecialType.System_Double: if (!(symValue is double)) { return ConstantValue.Bad; } return ConstantValue.Create((double)symValue); case SpecialType.System_String: if (symValue is int && (int)symValue == 0) { return ConstantValue.Null; } if (symValue == null) { return ConstantValue.Create(string.Empty); } var str = symValue as string; if (str == null) { return ConstantValue.Bad; } return ConstantValue.Create(str); case SpecialType.System_Object: if (symValue is int && (int)symValue == 0) { return ConstantValue.Null; } return ConstantValue.Bad; case SpecialType.System_Decimal: if (!(symValue is decimal)) { return ConstantValue.Bad; } return ConstantValue.Create((decimal)symValue); case SpecialType.System_DateTime: if (!(symValue is double)) { return ConstantValue.Bad; } return ConstantValue.Create(DateTimeUtilities.ToDateTime((double)symValue)); case SpecialType.None: if (type.IsReferenceType) { if (symValue is int && (int)symValue == 0) { return ConstantValue.Null; } return ConstantValue.Bad; } return ConstantValue.Bad; default: return ConstantValue.Bad; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Text; using System.Threading; using System.Windows.Forms; using SIL.Email; using SIL.Reporting; using System.Runtime.InteropServices; namespace SIL.Windows.Forms.Reporting { /// <summary> /// Display exception reporting dialog. /// NOTE: It is recommended to call one of Palaso.Reporting.ErrorReport.Report(Non)Fatal* /// methods instead of instantiating this class. /// </summary> public class ExceptionReportingDialog : Form { #region Local structs private struct ExceptionReportingData { public ExceptionReportingData(string message, string messageBeforeStack, Exception error, StackTrace stackTrace, Form owningForm, int threadId) { Message = message; MessageBeforeStack = messageBeforeStack; Error = error; StackTrace = stackTrace; OwningForm = owningForm; ThreadId = threadId; } public string Message; public string MessageBeforeStack; public Exception Error; public Form OwningForm; public StackTrace StackTrace; public int ThreadId; } #endregion #region Member variables private Label label3; private TextBox _details; private TextBox _pleaseHelpText; private TextBox m_reproduce; private bool _isLethal; private Button _sendAndCloseButton; private TextBox _notificationText; private TextBox textBox1; private ComboBox _methodCombo; private Button _privacyNoticeButton; private Label _emailAddress; private static bool s_doIgnoreReport; /// <summary> /// Stack with exception data. /// </summary> /// <remarks>When an exception occurs on a background thread ideally it should be handled /// by the application. However, not all applications are always implemented to do it /// that way, so we need a safe fall back that doesn't pop up a dialog from a (non-UI) /// background thread. /// /// This implementation creates a control on the UI thread /// (WinFormsExceptionHandler.ControlOnUIThread) in order to be able to check /// if invoke is required. When an exception occurs on a background thread we push the /// exception data to an exception data stack and try to invoke the exception dialog on /// the UI thread. In case that the UI thread already shows an exception dialog we skip /// the exception (similar to the behavior we already have when we get an exception on /// the UI thread while displaying the exception dialog). Otherwise we display the /// exception dialog, appending the messages from the exception data stack.</remarks> private static Stack<ExceptionReportingData> s_reportDataStack = new Stack<ExceptionReportingData>(); #endregion protected ExceptionReportingDialog(bool isLethal) { _isLethal = isLethal; } #region IDisposable override /// <summary> /// Check to see if the object has been disposed. /// All public Properties and Methods should call this /// before doing anything else. /// </summary> public void CheckDisposed() { if (IsDisposed) { throw new ObjectDisposedException(String.Format("'{0}' in use after being disposed.", GetType().Name)); } } /// <summary> /// Executes in two distinct scenarios. /// /// 1. If disposing is true, the method has been called directly /// or indirectly by a user's code via the Dispose method. /// Both managed and unmanaged resources can be disposed. /// /// 2. If disposing is false, the method has been called by the /// runtime from inside the finalizer and you should not reference (access) /// other managed objects, as they already have been garbage collected. /// Only unmanaged resources can be disposed. /// </summary> /// <param name="disposing"></param> /// <remarks> /// If any exceptions are thrown, that is fine. /// If the method is being done in a finalizer, it will be ignored. /// If it is thrown by client code calling Dispose, /// it needs to be handled by fixing the bug. /// /// If subclasses override this method, they should call the base implementation. /// </remarks> protected override void Dispose(bool disposing) { //Debug.WriteLineIf(!disposing, "****************** " + GetType().Name + " 'disposing' is false. ******************"); // Must not be run more than once. if (IsDisposed) { return; } if (disposing) { // Dispose managed resources here. } // Dispose unmanaged resources here, whether disposing is true or false. base.Dispose(disposing); } #endregion IDisposable override #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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ExceptionReportingDialog)); this.m_reproduce = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this._details = new System.Windows.Forms.TextBox(); this._sendAndCloseButton = new System.Windows.Forms.Button(); this._pleaseHelpText = new System.Windows.Forms.TextBox(); this._notificationText = new System.Windows.Forms.TextBox(); this.textBox1 = new System.Windows.Forms.TextBox(); this._methodCombo = new System.Windows.Forms.ComboBox(); this._privacyNoticeButton = new System.Windows.Forms.Button(); this._emailAddress = new System.Windows.Forms.Label(); this.SuspendLayout(); // // m_reproduce // this.m_reproduce.AcceptsReturn = true; this.m_reproduce.AcceptsTab = true; resources.ApplyResources(this.m_reproduce, "m_reproduce"); this.m_reproduce.Name = "m_reproduce"; // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // _details // resources.ApplyResources(this._details, "_details"); this._details.BackColor = System.Drawing.SystemColors.ControlLightLight; this._details.Name = "_details"; this._details.ReadOnly = true; // // _sendAndCloseButton // resources.ApplyResources(this._sendAndCloseButton, "_sendAndCloseButton"); this._sendAndCloseButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this._sendAndCloseButton.Name = "_sendAndCloseButton"; this._sendAndCloseButton.Click += new System.EventHandler(this.btnClose_Click); // // _pleaseHelpText // resources.ApplyResources(this._pleaseHelpText, "_pleaseHelpText"); this._pleaseHelpText.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this._pleaseHelpText.BorderStyle = System.Windows.Forms.BorderStyle.None; this._pleaseHelpText.ForeColor = System.Drawing.Color.Black; this._pleaseHelpText.Name = "_pleaseHelpText"; this._pleaseHelpText.ReadOnly = true; // // _notificationText // resources.ApplyResources(this._notificationText, "_notificationText"); this._notificationText.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this._notificationText.BorderStyle = System.Windows.Forms.BorderStyle.None; this._notificationText.ForeColor = System.Drawing.Color.Black; this._notificationText.Name = "_notificationText"; this._notificationText.ReadOnly = true; // // textBox1 // resources.ApplyResources(this.textBox1, "textBox1"); this.textBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.textBox1.ForeColor = System.Drawing.Color.Black; this.textBox1.Name = "textBox1"; this.textBox1.ReadOnly = true; // // _methodCombo // resources.ApplyResources(this._methodCombo, "_methodCombo"); this._methodCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this._methodCombo.FormattingEnabled = true; this._methodCombo.Name = "_methodCombo"; this._methodCombo.SelectedIndexChanged += new System.EventHandler(this._methodCombo_SelectedIndexChanged); // // _privacyNoticeButton // resources.ApplyResources(this._privacyNoticeButton, "_privacyNoticeButton"); this._privacyNoticeButton.Image = global::SIL.Windows.Forms.Properties.Resources.spy16x16; this._privacyNoticeButton.Name = "_privacyNoticeButton"; this._privacyNoticeButton.UseVisualStyleBackColor = true; this._privacyNoticeButton.Click += new System.EventHandler(this._privacyNoticeButton_Click); // // _emailAddress // resources.ApplyResources(this._emailAddress, "_emailAddress"); this._emailAddress.ForeColor = System.Drawing.Color.DimGray; this._emailAddress.Name = "_emailAddress"; // // ExceptionReportingDialog // this.AcceptButton = this._sendAndCloseButton; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.ControlBox = false; this.Controls.Add(this._emailAddress); this.Controls.Add(this._privacyNoticeButton); this.Controls.Add(this._methodCombo); this.Controls.Add(this.textBox1); this.Controls.Add(this.m_reproduce); this.Controls.Add(this._notificationText); this.Controls.Add(this._pleaseHelpText); this.Controls.Add(this._details); this.Controls.Add(this.label3); this.Controls.Add(this._sendAndCloseButton); this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ExceptionReportingDialog"; this.TopMost = true; this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.ExceptionReportingDialog_KeyPress); this.ResumeLayout(false); this.PerformLayout(); } private void SetupMethodCombo() { _methodCombo.Items.Clear(); _methodCombo.Items.Add(new ReportingMethod("Send using my email program", "&Email", "mapiWithPopup", SendViaEmail)); _methodCombo.Items.Add(new ReportingMethod("Copy to clipboard", "&Copy", "clipboard", PutOnClipboard)); } class ReportingMethod { private readonly string _label; public readonly string CloseButtonLabel; public readonly string Id; public readonly Func<bool> Method; public ReportingMethod(string label, string closeButtonLabel, string id, Func<bool> method) { _label = label; CloseButtonLabel = closeButtonLabel; Id = id; Method = method; } public override string ToString() { return _label; } } #endregion /// ------------------------------------------------------------------------------------ /// <summary> /// show a dialog or output to the error log, as appropriate. /// </summary> /// <param name="error">the exception you want to report</param> /// ------------------------------------------------------------------------------------ internal static void ReportException(Exception error) { ReportException(error, null); } /// <summary> /// /// </summary> /// <param name="error"></param> /// <param name="parent"></param> internal static void ReportException(Exception error, Form parent) { ReportException(error, null, true); } /// ------------------------------------------------------------------------------------ /// <summary> /// show a dialog or output to the error log, as appropriate. /// </summary> /// <param name="error">the exception you want to report</param> /// <param name="parent">the parent form that this error belongs to (i.e. the form /// show modally on)</param> /// ------------------------------------------------------------------------------------ /// <param name="isLethal"></param> internal static void ReportException(Exception error, Form parent, bool isLethal) { if (s_doIgnoreReport) { lock (s_reportDataStack) { s_reportDataStack.Push(new ExceptionReportingData(null, null, error, null, parent, Thread.CurrentThread.ManagedThreadId)); } return; // ignore message if we are showing from a previous error } using (ExceptionReportingDialog dlg = new ExceptionReportingDialog(isLethal)) { dlg.Report(error, parent); } } internal static void ReportMessage(string message, StackTrace stack, bool isLethal) { if (s_doIgnoreReport) { lock (s_reportDataStack) { s_reportDataStack.Push(new ExceptionReportingData(message, null, null, stack, null, Thread.CurrentThread.ManagedThreadId)); } return; // ignore message if we are showing from a previous error } using (ExceptionReportingDialog dlg = new ExceptionReportingDialog(isLethal)) { dlg.Report(message, string.Empty, stack, null); } } internal static void ReportMessage(string message, Exception error, bool isLethal) { if (s_doIgnoreReport) { lock (s_reportDataStack) { s_reportDataStack.Push(new ExceptionReportingData(message, null, error, null, null, Thread.CurrentThread.ManagedThreadId)); } return; // ignore message if we are showing from a previous error } using (ExceptionReportingDialog dlg = new ExceptionReportingDialog(isLethal)) { dlg.Report(message, null, error,null); } } protected void GatherData() { _details.Text += Environment.NewLine + "To Reproduce: " + m_reproduce.Text + Environment.NewLine; } public void Report(Exception error, Form owningForm) { Report(null,null, error, owningForm); } public void Report(string message, string messageBeforeStack, Exception error, Form owningForm) { lock (s_reportDataStack) { s_reportDataStack.Push(new ExceptionReportingData(message, messageBeforeStack, error, null, owningForm, Thread.CurrentThread.ManagedThreadId)); } if (WinFormsExceptionHandler.InvokeRequired) { // we got called from a background thread. WinFormsExceptionHandler.ControlOnUIThread.Invoke( new Action(ReportInternal)); return; } ReportInternal(); } public void Report(string message, string messageBeforeStack, StackTrace stackTrace, Form owningForm) { lock (s_reportDataStack) { s_reportDataStack.Push(new ExceptionReportingData(message, messageBeforeStack, null, stackTrace, owningForm, Thread.CurrentThread.ManagedThreadId)); } if (WinFormsExceptionHandler.InvokeRequired) { // we got called from a background thread. WinFormsExceptionHandler.ControlOnUIThread.Invoke( new Action(ReportInternal)); return; } ReportInternal(); } private void ReportInternal() { // This method will/should always be called on the UI thread Debug.Assert(!WinFormsExceptionHandler.InvokeRequired); ExceptionReportingData reportingData; lock (s_reportDataStack) { if (s_reportDataStack.Count <= 0) return; reportingData = s_reportDataStack.Pop(); } ReportExceptionToAnalytics(reportingData); if (s_doIgnoreReport) return; // ignore message if we are showing from a previous error PrepareDialog(); if(!string.IsNullOrEmpty(reportingData.Message)) _notificationText.Text = reportingData.Message; var bldr = new StringBuilder(); var innerMostException = FormatMessage(bldr, reportingData); bldr.Append(AddMessagesFromBackgroundThreads()); _details.Text += bldr.ToString(); Debug.WriteLine(_details.Text); var error = reportingData.Error; if (error != null) { if (innerMostException != null) { error = innerMostException; } try { Logger.WriteEvent("Got exception " + error.GetType().Name); } catch (Exception err) { //We have more than one report of dieing while logging an exception. _details.Text += "****Could not write to log (" + err.Message + ")" + Environment.NewLine; _details.Text += "Was trying to log the exception: " + error.Message + Environment.NewLine; _details.Text += "Recent events:" + Environment.NewLine; _details.Text += Logger.MinorEventsLog; } } else { try { Logger.WriteEvent("Got error message " + reportingData.Message); } catch (Exception err) { //We have more than one report of dieing while logging an exception. _details.Text += "****Could not write to log (" + err.Message + ")" + Environment.NewLine; } } ShowReportDialogIfAppropriate(reportingData.OwningForm); } private static void ReportExceptionToAnalytics(ExceptionReportingData reportingData) { try { if (!string.IsNullOrEmpty(reportingData.Message)) UsageReporter.ReportExceptionString(reportingData.Message); else if (reportingData.Error != null) UsageReporter.ReportException(reportingData.Error); } catch { //swallow } } private static string AddMessagesFromBackgroundThreads() { var bldr = new StringBuilder(); for (bool messageOnStack = AddNextMessageFromStack(bldr); messageOnStack;) messageOnStack = AddNextMessageFromStack(bldr); return bldr.ToString(); } private static bool AddNextMessageFromStack(StringBuilder bldr) { ExceptionReportingData data; lock (s_reportDataStack) { if (s_reportDataStack.Count <= 0) return false; data = s_reportDataStack.Pop(); } ReportExceptionToAnalytics(data); bldr.AppendLine("---------------------------------"); bldr.AppendFormat("The following exception occurred on a different thread ({0}) at about the same time:", data.ThreadId); bldr.AppendLine(); bldr.AppendLine(); FormatMessage(bldr, data); return true; } private static Exception FormatMessage(StringBuilder bldr, ExceptionReportingData data) { if (!string.IsNullOrEmpty(data.Message)) { bldr.Append("Message (not an exception): "); bldr.AppendLine(data.Message); bldr.AppendLine(); } if (!string.IsNullOrEmpty(data.MessageBeforeStack)) { bldr.AppendLine(data.MessageBeforeStack); } if (data.Error != null) { Exception innerMostException = null; bldr.Append(ErrorReport.GetHiearchicalExceptionInfo(data.Error, ref innerMostException)); //if the exception had inner exceptions, show the inner-most exception first, since that is usually the one //we want the developer to read. if (innerMostException != null) { var oldText = bldr.ToString(); bldr.Clear(); bldr.AppendLine("Inner-most exception:"); bldr.AppendLine(ErrorReport.GetExceptionText(innerMostException)); bldr.AppendLine(); bldr.AppendLine("Full, hierarchical exception contents:"); bldr.Append(oldText); } AddErrorReportingPropertiesToDetails(bldr); return innerMostException; } if (data.StackTrace != null) { bldr.AppendLine("--Stack--"); bldr.AppendLine(data.StackTrace.ToString()); } return null; } private static void AddErrorReportingPropertiesToDetails(StringBuilder bldr) { bldr.AppendLine(); bldr.AppendLine("--Error Reporting Properties--"); foreach (string label in ErrorReport.Properties.Keys) { bldr.Append(label); bldr.Append(": "); bldr.AppendLine(ErrorReport.Properties[label]); } bldr.AppendLine(); bldr.AppendLine("--Log--"); try { bldr.Append(Logger.LogText); } catch (Exception err) { //We have more than one report of dieing while logging an exception. bldr.AppendLine("****Could not read from log: " + err.Message); } } private void PrepareDialog() { CheckDisposed(); Font = SystemFonts.MessageBoxFont; // // Required for Windows Form Designer support // InitializeComponent(); _emailAddress.Text = ErrorReport.EmailAddress; SetupMethodCombo(); foreach (ReportingMethod method in _methodCombo.Items) { if (ErrorReportSettings.Default.ReportingMethod == method.Id) { SelectedMethod = method; break; } } if (!_isLethal) { BackColor = Color.FromArgb(255, 255, 192); //yellow _notificationText.Text = "Take Courage. It'll work out."; _notificationText.BackColor = BackColor; _pleaseHelpText.BackColor = BackColor; textBox1.BackColor = BackColor; } SetupCloseButtonText(); } private void ShowReportDialogIfAppropriate(Form owningForm) { if (ErrorReport.IsOkToInteractWithUser) { s_doIgnoreReport = true; ShowDialog(owningForm); s_doIgnoreReport = false; } else //the test environment already prohibits dialogs but will save the contents of assertions in some log. { Debug.Fail(_details.Text); } } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// ------------------------------------------------------------------------------------ private void btnClose_Click(object sender, EventArgs e) { ErrorReportSettings.Default.ReportingMethod = ((ReportingMethod) (_methodCombo.SelectedItem)).Id; ErrorReportSettings.Default.Save(); if (ModifierKeys.Equals(Keys.Shift)) { return; } GatherData(); // Clipboard.SetDataObject(_details.Text, true); if (SelectedMethod.Method()) { CloseUp(); } else { PutOnClipboard(); CloseUp(); } } private bool PutOnClipboard() { if (ErrorReport.EmailAddress != null) { _details.Text = String.Format("Please e-mail this to {0} {1}", ErrorReport.EmailAddress, _details.Text); } #if MONO try { // Workaround for Xamarin bug #4959. Eberhard had a mono fix for that bug // but it doesn't work with FW (or Palaso) -- he couldn't figure out why not. // This is a dirty hack but at least it works :-) var clipboardAtom = gdk_atom_intern("CLIPBOARD", true); var clipboard = gtk_clipboard_get(clipboardAtom); if (clipboard != IntPtr.Zero) { gtk_clipboard_set_text(clipboard, _details.Text, -1); gtk_clipboard_store(clipboard); } } catch { // ignore any errors - most likely because gtk isn't installed? return false; } #else Clipboard.SetDataObject(_details.Text, true); #endif return true; } #if MONO // Workaround for Xamarin bug #4959 [DllImport("libgdk-x11-2.0")] internal extern static IntPtr gdk_atom_intern(string atomName, bool onlyIfExists); [DllImport("libgtk-x11-2.0")] internal extern static IntPtr gtk_clipboard_get(IntPtr atom); [DllImport("libgtk-x11-2.0")] internal extern static void gtk_clipboard_store(IntPtr clipboard); [DllImport("libgtk-x11-2.0")] internal extern static void gtk_clipboard_set_text(IntPtr clipboard, [MarshalAs(UnmanagedType.LPStr)] string text, int len); #endif private bool SendViaEmail() { try { var emailProvider = EmailProviderFactory.PreferredEmailProvider(); var emailMessage = emailProvider.CreateMessage(); emailMessage.To.Add(ErrorReport.EmailAddress); emailMessage.Subject = ErrorReport.EmailSubject; emailMessage.Body = _details.Text; if (emailMessage.Send(emailProvider)) { CloseUp(); return true; } } catch (Exception) { //swallow it and go to the alternate method } try { //EmailMessage msg = new EmailMessage(); // This currently does not work. The main issue seems to be the length of the error report. mailto // apparently has some limit on the length of the message, and we are exceeding that. var emailProvider = EmailProviderFactory.PreferredEmailProvider(); var emailMessage = emailProvider.CreateMessage(); emailMessage.To.Add(ErrorReport.EmailAddress); emailMessage.Subject = ErrorReport.EmailSubject; if (Environment.OSVersion.Platform == PlatformID.Unix) { emailMessage.Body = _details.Text; } else { PutOnClipboard(); emailMessage.Body = "<Details of the crash have been copied to the clipboard. Please paste them here>"; } if (emailMessage.Send(emailProvider)) { CloseUp(); return true; } } catch (Exception error) { PutOnClipboard(); ErrorReport.NotifyUserOfProblem(error, "This program wasn't able to get your email program, if you have one, to send the error message. " + "The contents of the error message has been placed on your Clipboard."); return false; } return false; } private void CloseUp() { if (!_isLethal || ModifierKeys.Equals(Keys.Shift)) { try { Logger.WriteEvent("Error Dialog: Continuing..."); } catch (Exception) { //really can't handle an embedded error related to logging } Close(); return; } try { Logger.WriteEvent("Error Dialog: Exiting..."); } catch (Exception) { //really can't handle an embedded error related to logging } Process.GetCurrentProcess().Kill(); } /// ------------------------------------------------------------------------------------ /// <summary> /// Shows the attempt to continue label if the shift key is pressed /// </summary> /// <param name="e"></param> /// ------------------------------------------------------------------------------------ protected override void OnKeyDown(KeyEventArgs e) { if (e.KeyCode == Keys.ShiftKey && Visible) { _sendAndCloseButton.Text = "Continue"; } base.OnKeyDown(e); } /// ------------------------------------------------------------------------------------ /// <summary> /// Hides the attempt to continue label if the shift key is pressed /// </summary> /// <param name="e"></param> /// ------------------------------------------------------------------------------------ protected override void OnKeyUp(KeyEventArgs e) { if (e.KeyCode == Keys.ShiftKey && Visible) { SetupCloseButtonText(); } base.OnKeyUp(e); } private void OnJustExit_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { CloseUp(); } private void _methodCombo_SelectedIndexChanged(object sender, EventArgs e) { SetupCloseButtonText(); } private void SetupCloseButtonText() { _sendAndCloseButton.Text = SelectedMethod.CloseButtonLabel; if (!_isLethal) { // _dontSendEmailLink.Text = "Don't Send Email"; } else { _sendAndCloseButton.Text += " and Exit"; } } private ReportingMethod SelectedMethod { get { return ((ReportingMethod) _methodCombo.SelectedItem); } set { _methodCombo.SelectedItem = value; } } public static string PrivacyNotice = @"If you don't care who reads your bug report, you can skip this notice. When you submit a crash report or other issue, the contents of your email go in our issue tracking system, ""jira"", which is available via the web at http://jira.palaso.org/issues. This is the normal way to handle issues in an open-source project. Our issue-tracking system is not searchable by those without an account. Therefore, someone searching via Google will not find your bug reports. However, anyone can make an account and then read what you sent us. So if you have something private to say, please send it to one of the developers privately with a note that you don't want the issue in our issue tracking system. If need be, we'll make some kind of sanitized place-holder for your issue so that we don't lose it. "; private void _privacyNoticeButton_Click(object sender, EventArgs e) { MessageBox.Show(PrivacyNotice, "Privacy Notice"); } private void ExceptionReportingDialog_KeyPress(object sender, KeyPressEventArgs e) { if(e.KeyChar== 27)//ESCAPE { CloseUp(); } } } }
using System; using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.DependencyInjection; using Umbraco.Cms.Core; using Umbraco.Cms.Core.DependencyInjection; using Umbraco.Cms.Core.Security; using Umbraco.Cms.Web.BackOffice.Middleware; using Umbraco.Cms.Web.BackOffice.Security; using Umbraco.Cms.Web.Common.Authorization; using Umbraco.Cms.Web.Common.Security; using Umbraco.Cms.Core.Actions; using Umbraco.Cms.Core.Notifications; using Umbraco.Cms.Web.BackOffice.Authorization; using Umbraco.Cms.Web.Common.Middleware; namespace Umbraco.Extensions { /// <summary> /// Extension methods for <see cref="IUmbracoBuilder"/> for the Umbraco back office /// </summary> public static partial class UmbracoBuilderExtensions { /// <summary> /// Adds Umbraco back office authentication requirements /// </summary> public static IUmbracoBuilder AddBackOfficeAuthentication(this IUmbracoBuilder builder) { builder.Services // This just creates a builder, nothing more .AddAuthentication() // Add our custom schemes which are cookie handlers .AddCookie(Constants.Security.BackOfficeAuthenticationType) .AddCookie(Constants.Security.BackOfficeExternalAuthenticationType, o => { o.Cookie.Name = Constants.Security.BackOfficeExternalAuthenticationType; o.ExpireTimeSpan = TimeSpan.FromMinutes(5); }) // Although we don't natively support this, we add it anyways so that if end-users implement the required logic // they don't have to worry about manually adding this scheme or modifying the sign in manager .AddCookie(Constants.Security.BackOfficeTwoFactorAuthenticationType, o => { o.Cookie.Name = Constants.Security.BackOfficeTwoFactorAuthenticationType; o.ExpireTimeSpan = TimeSpan.FromMinutes(5); }); builder.Services.ConfigureOptions<ConfigureBackOfficeCookieOptions>(); builder.Services.AddSingleton<BackOfficeExternalLoginProviderErrorMiddleware>(); builder.Services.AddUnique<IBackOfficeAntiforgery, BackOfficeAntiforgery>(); builder.Services.AddUnique<IPasswordChanger<BackOfficeIdentityUser>, PasswordChanger<BackOfficeIdentityUser>>(); builder.Services.AddUnique<IPasswordChanger<MemberIdentityUser>, PasswordChanger<MemberIdentityUser>>(); builder.AddNotificationHandler<UserLoginSuccessNotification, BackOfficeUserManagerAuditer>(); builder.AddNotificationHandler<UserLogoutSuccessNotification, BackOfficeUserManagerAuditer>(); builder.AddNotificationHandler<UserLoginFailedNotification, BackOfficeUserManagerAuditer>(); builder.AddNotificationHandler<UserForgotPasswordRequestedNotification, BackOfficeUserManagerAuditer>(); builder.AddNotificationHandler<UserForgotPasswordChangedNotification, BackOfficeUserManagerAuditer>(); builder.AddNotificationHandler<UserPasswordChangedNotification, BackOfficeUserManagerAuditer>(); builder.AddNotificationHandler<UserPasswordResetNotification, BackOfficeUserManagerAuditer>(); return builder; } /// <summary> /// Adds Umbraco back office authorization policies /// </summary> public static IUmbracoBuilder AddBackOfficeAuthorizationPolicies(this IUmbracoBuilder builder, string backOfficeAuthenticationScheme = Constants.Security.BackOfficeAuthenticationType) { builder.AddBackOfficeAuthorizationPoliciesInternal(backOfficeAuthenticationScheme); builder.Services.AddSingleton<IAuthorizationHandler, FeatureAuthorizeHandler>(); builder.Services.AddAuthorization(options => options.AddPolicy(AuthorizationPolicies.UmbracoFeatureEnabled, policy => policy.Requirements.Add(new FeatureAuthorizeRequirement()))); return builder; } /// <summary> /// Add authorization handlers and policies /// </summary> private static void AddBackOfficeAuthorizationPoliciesInternal(this IUmbracoBuilder builder, string backOfficeAuthenticationScheme = Constants.Security.BackOfficeAuthenticationType) { // NOTE: Even though we are registering these handlers globally they will only actually execute their logic for // any auth defining a matching requirement and scheme. builder.Services.AddSingleton<IAuthorizationHandler, BackOfficeHandler>(); builder.Services.AddSingleton<IAuthorizationHandler, TreeHandler>(); builder.Services.AddSingleton<IAuthorizationHandler, SectionHandler>(); builder.Services.AddSingleton<IAuthorizationHandler, AdminUsersHandler>(); builder.Services.AddSingleton<IAuthorizationHandler, UserGroupHandler>(); builder.Services.AddSingleton<IAuthorizationHandler, ContentPermissionsQueryStringHandler>(); builder.Services.AddSingleton<IAuthorizationHandler, ContentPermissionsResourceHandler>(); builder.Services.AddSingleton<IAuthorizationHandler, ContentPermissionsPublishBranchHandler>(); builder.Services.AddSingleton<IAuthorizationHandler, MediaPermissionsResourceHandler>(); builder.Services.AddSingleton<IAuthorizationHandler, MediaPermissionsQueryStringHandler>(); builder.Services.AddSingleton<IAuthorizationHandler, DenyLocalLoginHandler>(); builder.Services.AddAuthorization(o => CreatePolicies(o, backOfficeAuthenticationScheme)); } private static void CreatePolicies(AuthorizationOptions options, string backOfficeAuthenticationScheme) { options.AddPolicy(AuthorizationPolicies.MediaPermissionByResource, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new MediaPermissionsResourceRequirement()); }); options.AddPolicy(AuthorizationPolicies.MediaPermissionPathById, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new MediaPermissionsQueryStringRequirement("id")); }); options.AddPolicy(AuthorizationPolicies.ContentPermissionByResource, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new ContentPermissionsResourceRequirement()); }); options.AddPolicy(AuthorizationPolicies.ContentPermissionEmptyRecycleBin, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new ContentPermissionsQueryStringRequirement(Constants.System.RecycleBinContent, ActionDelete.ActionLetter)); }); options.AddPolicy(AuthorizationPolicies.ContentPermissionAdministrationById, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new ContentPermissionsQueryStringRequirement(ActionRights.ActionLetter)); policy.Requirements.Add(new ContentPermissionsQueryStringRequirement(ActionRights.ActionLetter, "contentId")); }); options.AddPolicy(AuthorizationPolicies.ContentPermissionProtectById, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new ContentPermissionsQueryStringRequirement(ActionProtect.ActionLetter)); policy.Requirements.Add(new ContentPermissionsQueryStringRequirement(ActionProtect.ActionLetter, "contentId")); }); options.AddPolicy(AuthorizationPolicies.ContentPermissionRollbackById, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new ContentPermissionsQueryStringRequirement(ActionRollback.ActionLetter)); policy.Requirements.Add(new ContentPermissionsQueryStringRequirement(ActionRollback.ActionLetter, "contentId")); }); options.AddPolicy(AuthorizationPolicies.ContentPermissionPublishById, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new ContentPermissionsQueryStringRequirement(ActionPublish.ActionLetter)); }); options.AddPolicy(AuthorizationPolicies.ContentPermissionBrowseById, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new ContentPermissionsQueryStringRequirement(ActionBrowse.ActionLetter)); policy.Requirements.Add(new ContentPermissionsQueryStringRequirement(ActionBrowse.ActionLetter, "contentId")); }); options.AddPolicy(AuthorizationPolicies.ContentPermissionDeleteById, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new ContentPermissionsQueryStringRequirement(ActionDelete.ActionLetter)); }); options.AddPolicy(AuthorizationPolicies.BackOfficeAccess, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new BackOfficeRequirement()); }); options.AddPolicy(AuthorizationPolicies.BackOfficeAccessWithoutApproval, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new BackOfficeRequirement(false)); }); options.AddPolicy(AuthorizationPolicies.AdminUserEditsRequireAdmin, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new AdminUsersRequirement()); policy.Requirements.Add(new AdminUsersRequirement("userIds")); }); options.AddPolicy(AuthorizationPolicies.UserBelongsToUserGroupInRequest, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new UserGroupRequirement()); policy.Requirements.Add(new UserGroupRequirement("userGroupIds")); }); options.AddPolicy(AuthorizationPolicies.DenyLocalLoginIfConfigured, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new DenyLocalLoginRequirement()); }); options.AddPolicy(AuthorizationPolicies.SectionAccessContent, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new SectionRequirement(Constants.Applications.Content)); }); options.AddPolicy(AuthorizationPolicies.SectionAccessContentOrMedia, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new SectionRequirement(Constants.Applications.Content, Constants.Applications.Media)); }); options.AddPolicy(AuthorizationPolicies.SectionAccessUsers, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new SectionRequirement(Constants.Applications.Users)); }); options.AddPolicy(AuthorizationPolicies.SectionAccessForTinyMce, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new SectionRequirement( Constants.Applications.Content, Constants.Applications.Media, Constants.Applications.Members)); }); options.AddPolicy(AuthorizationPolicies.SectionAccessMedia, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new SectionRequirement(Constants.Applications.Media)); }); options.AddPolicy(AuthorizationPolicies.SectionAccessMembers, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new SectionRequirement(Constants.Applications.Members)); }); options.AddPolicy(AuthorizationPolicies.SectionAccessPackages, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new SectionRequirement(Constants.Applications.Packages)); }); options.AddPolicy(AuthorizationPolicies.SectionAccessSettings, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new SectionRequirement(Constants.Applications.Settings)); }); // We will not allow the tree to render unless the user has access to any of the sections that the tree gets rendered // this is not ideal but until we change permissions to be tree based (not section) there's not much else we can do here. options.AddPolicy(AuthorizationPolicies.SectionAccessForContentTree, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new SectionRequirement( Constants.Applications.Content, Constants.Applications.Media, Constants.Applications.Users, Constants.Applications.Settings, Constants.Applications.Packages, Constants.Applications.Members)); }); options.AddPolicy(AuthorizationPolicies.SectionAccessForMediaTree, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new SectionRequirement( Constants.Applications.Content, Constants.Applications.Media, Constants.Applications.Users, Constants.Applications.Settings, Constants.Applications.Packages, Constants.Applications.Members)); }); options.AddPolicy(AuthorizationPolicies.SectionAccessForMemberTree, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new SectionRequirement( Constants.Applications.Content, Constants.Applications.Media, Constants.Applications.Members)); }); // Permission is granted to this policy if the user has access to any of these sections: Content, media, settings, developer, members options.AddPolicy(AuthorizationPolicies.SectionAccessForDataTypeReading, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new SectionRequirement( Constants.Applications.Content, Constants.Applications.Media, Constants.Applications.Members, Constants.Applications.Settings, Constants.Applications.Packages)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessDocuments, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.Content)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessUsers, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.Users)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessPartialViews, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.PartialViews)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessPartialViewMacros, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.PartialViewMacros)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessPackages, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.Packages)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessLogs, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.LogViewer)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessDataTypes, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.DataTypes)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessTemplates, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.Templates)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessMemberTypes, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.MemberTypes)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessRelationTypes, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.RelationTypes)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessDocumentTypes, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.DocumentTypes)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessMemberGroups, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.MemberGroups)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessMediaTypes, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.MediaTypes)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessMacros, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.Macros)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessLanguages, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.Languages)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessDictionary, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.Dictionary)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessDictionaryOrTemplates, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.Dictionary, Constants.Trees.Templates)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessDocumentsOrDocumentTypes, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.DocumentTypes, Constants.Trees.Content)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessMediaOrMediaTypes, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.MediaTypes, Constants.Trees.Media)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessMembersOrMemberTypes, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.MemberTypes, Constants.Trees.Members)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessAnySchemaTypes, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement(Constants.Trees.DataTypes, Constants.Trees.DocumentTypes, Constants.Trees.MediaTypes, Constants.Trees.MemberTypes)); }); options.AddPolicy(AuthorizationPolicies.TreeAccessAnyContentOrTypes, policy => { policy.AuthenticationSchemes.Add(backOfficeAuthenticationScheme); policy.Requirements.Add(new TreeRequirement( Constants.Trees.DocumentTypes, Constants.Trees.Content, Constants.Trees.MediaTypes, Constants.Trees.Media, Constants.Trees.MemberTypes, Constants.Trees.Members)); }); } } }
//------------------------------------------------------------------------------ // <copyright file="ProcessModelSection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Configuration { using System; using System.Xml; using System.Configuration; using System.Collections.Specialized; using System.Collections; using System.Globalization; using System.IO; using System.Text; using System.ComponentModel; using System.Web.Util; using System.Security.Permissions; /* <!-- processModel Attributes: enable="[true|false]" - Enable processModel timeout="[Infinite | HH:MM:SS] - Total life of process, once expired process is shutdown and a new process is created idleTimeout="[Infinite | HH:MM:SS]" - Total idle life of process, once expired process is automatically shutdown shutdownTimeout="[Infinite | HH:MM:SS]" - Time process is given to shutdown gracefully before being killed requestLimit="[Infinite | number]" - Total number of requests to serve before process is shutdown requestQueueLimit="[Infinite | number]" - Number of queued requests allowed before requests are rejected restartQueueLimit="[Infinite | number]" - Number of requests kept in queue while process is restarting memoryLimit="[number]" - Represents percentage of physical memory process is allowed to use before process is recycled webGarden="[true|false]" - Determines whether a process should be affinitized with a particular CPU cpuMask="[bit mask]" - Controls number of available CPUs available for ASP.NET processes (webGarden must be set to true) userName="[user]" - Windows user to run the process as. Special users: "SYSTEM": run as localsystem (high privilege admin) account. "machine": run as low privilege user account named "ASPNET". Other users: If domain is not specified, current machine name is assumed to be the domain name. password="[AutoGenerate | password]" - Password of windows user. For special users (SYSTEM and machine), specify "AutoGenerate". logLevel="[All|None|Errors]" - Event types logged to the event log clientConnectedCheck="[HH:MM:SS]" - Time a request is left in the queue before ASP.NET does a client connected check comAuthenticationLevel="[Default|None|Connect|Call|Pkt|PktIntegrity|PktPrivacy]" - Level of authentication for DCOM security comImpersonationLevel="[Default|Anonymous|Identify|Impersonate|Delegate]" - Authentication level for COM security responseDeadlockInterval="[Infinite | HH:MM:SS]" - For deadlock detection, timeout for responses when there are executing requests. maxWorkerThreads="[number]" - Maximum number of worker threads per CPU in the thread pool maxIoThreads="[number]" - Maximum number of IO threads per CPU in the thread pool serverErrorMessageFile="[filename]" - Customization for "Server Unavailable" message maxAppDomains="[number]" - Maximum allowed number of app domain in one process When ASP.NET is running under IIS 6 in native mode, the IIS 6 process model is used and most settings in this section are ignored. Please use the IIS administrative UI to configure things like process identity and cycling for the IIS worker process for the desired application --> <processModel enable="true" timeout="Infinite" idleTimeout="Infinite" shutdownTimeout="00:00:05" requestLimit="Infinite" requestQueueLimit="5000" restartQueueLimit="10" memoryLimit="60" webGarden="false" cpuMask="0xffffffff" userName="machine" password="AutoGenerate" logLevel="Errors" clientConnectedCheck="00:00:05" comAuthenticationLevel="Connect" comImpersonationLevel="Impersonate" responseDeadlockInterval="00:03:00" maxWorkerThreads="20" maxIoThreads="20" maxAppDomains="2000" /> */ public sealed class ProcessModelSection : ConfigurationSection { private const int DefaultMaxThreadsPerCPU = 100; private static readonly ConfigurationElementProperty s_elemProperty = new ConfigurationElementProperty(new CallbackValidator(typeof(ProcessModelSection), Validate)); internal static TimeSpan DefaultClientConnectedCheck = new TimeSpan(0, 0, 5); private static ConfigurationPropertyCollection _properties; private static readonly ConfigurationProperty _propEnable = new ConfigurationProperty("enable", typeof(bool), true, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propTimeout = new ConfigurationProperty("timeout", typeof(TimeSpan), TimeSpan.MaxValue, StdValidatorsAndConverters.InfiniteTimeSpanConverter, null, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propIdleTimeout = new ConfigurationProperty("idleTimeout", typeof(TimeSpan), TimeSpan.MaxValue, StdValidatorsAndConverters.InfiniteTimeSpanConverter, null, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propShutdownTimeout = new ConfigurationProperty("shutdownTimeout", typeof(TimeSpan), TimeSpan.FromSeconds(5), StdValidatorsAndConverters.InfiniteTimeSpanConverter, StdValidatorsAndConverters.PositiveTimeSpanValidator, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propRequestLimit = new ConfigurationProperty("requestLimit", typeof(int), int.MaxValue, new InfiniteIntConverter(), StdValidatorsAndConverters.PositiveIntegerValidator, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propRequestQueueLimit = new ConfigurationProperty("requestQueueLimit", typeof(int), 5000, new InfiniteIntConverter(), StdValidatorsAndConverters.PositiveIntegerValidator, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propRestartQueueLimit = new ConfigurationProperty("restartQueueLimit", typeof(int), 10, new InfiniteIntConverter(), StdValidatorsAndConverters.PositiveIntegerValidator, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propMemoryLimit = new ConfigurationProperty("memoryLimit", typeof(int), 60, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propWebGarden = new ConfigurationProperty("webGarden", typeof(bool), false, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propCpuMask = new ConfigurationProperty("cpuMask", typeof(string), "0xffffffff", ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propUserName = new ConfigurationProperty("userName", typeof(string), "machine", ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propPassword = new ConfigurationProperty("password", typeof(string), "AutoGenerate", ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propLogLevel = new ConfigurationProperty("logLevel", typeof(ProcessModelLogLevel), ProcessModelLogLevel.Errors, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propClientConnectedCheck = new ConfigurationProperty("clientConnectedCheck", typeof(TimeSpan), DefaultClientConnectedCheck, StdValidatorsAndConverters.InfiniteTimeSpanConverter, null, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propComAuthenticationLevel = new ConfigurationProperty("comAuthenticationLevel", typeof(ProcessModelComAuthenticationLevel), ProcessModelComAuthenticationLevel.Connect, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propComImpersonationLevel = new ConfigurationProperty("comImpersonationLevel", typeof(ProcessModelComImpersonationLevel), ProcessModelComImpersonationLevel.Impersonate, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propResponseDeadlockInterval = new ConfigurationProperty("responseDeadlockInterval", typeof(TimeSpan), TimeSpan.FromMinutes(3), StdValidatorsAndConverters.InfiniteTimeSpanConverter, StdValidatorsAndConverters.PositiveTimeSpanValidator, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propResponseRestartDeadlockInterval = new ConfigurationProperty("responseRestartDeadlockInterval", typeof(TimeSpan), TimeSpan.FromMinutes(3), StdValidatorsAndConverters.InfiniteTimeSpanConverter, null, ConfigurationPropertyOptions.None); // NOTE the AutoConfig default value is different then the value shipped in Machine.config // This is because the Whidbey value is supposed to be true, but if the user removes the value // it should act like pre whidbey behavior which did not have autoconfig. private static readonly ConfigurationProperty _propAutoConfig = new ConfigurationProperty("autoConfig", typeof(bool), false, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propMaxWorkerThreads = new ConfigurationProperty("maxWorkerThreads", typeof(int), DefaultMaxThreadsPerCPU, null, new IntegerValidator(1, int.MaxValue - 1), ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propMaxIOThreads = new ConfigurationProperty("maxIoThreads", typeof(int), DefaultMaxThreadsPerCPU, null, new IntegerValidator(1, int.MaxValue - 1), ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propMinWorkerThreads = new ConfigurationProperty("minWorkerThreads", typeof(int), 1, null, new IntegerValidator(1, int.MaxValue - 1), ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propMinIOThreads = new ConfigurationProperty("minIoThreads", typeof(int), 1, null, new IntegerValidator(1, int.MaxValue - 1), ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propServerErrorMessageFile = new ConfigurationProperty("serverErrorMessageFile", typeof(string), String.Empty, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propPingFrequency = new ConfigurationProperty("pingFrequency", typeof(TimeSpan), TimeSpan.MaxValue, StdValidatorsAndConverters.InfiniteTimeSpanConverter, null, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propPingTimeout = new ConfigurationProperty("pingTimeout", typeof(TimeSpan), TimeSpan.MaxValue, StdValidatorsAndConverters.InfiniteTimeSpanConverter, null, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propMaxAppDomains = new ConfigurationProperty("maxAppDomains", typeof(int), 2000, null, new IntegerValidator(1, int.MaxValue - 1), ConfigurationPropertyOptions.None); private static int cpuCount; internal const string sectionName = "system.web/processModel"; static ProcessModelSection() { // Property initialization _properties = new ConfigurationPropertyCollection(); _properties.Add(_propEnable); _properties.Add(_propTimeout); _properties.Add(_propIdleTimeout); _properties.Add(_propShutdownTimeout); _properties.Add(_propRequestLimit); _properties.Add(_propRequestQueueLimit); _properties.Add(_propRestartQueueLimit); _properties.Add(_propMemoryLimit); _properties.Add(_propWebGarden); _properties.Add(_propCpuMask); _properties.Add(_propUserName); _properties.Add(_propPassword); _properties.Add(_propLogLevel); _properties.Add(_propClientConnectedCheck); _properties.Add(_propComAuthenticationLevel); _properties.Add(_propComImpersonationLevel); _properties.Add(_propResponseDeadlockInterval); _properties.Add(_propResponseRestartDeadlockInterval); _properties.Add(_propAutoConfig); _properties.Add(_propMaxWorkerThreads); _properties.Add(_propMaxIOThreads); _properties.Add(_propMinWorkerThreads); _properties.Add(_propMinIOThreads); _properties.Add(_propServerErrorMessageFile); _properties.Add(_propPingFrequency); _properties.Add(_propPingTimeout); _properties.Add(_propMaxAppDomains); cpuCount = SystemInfo.GetNumProcessCPUs(); } public ProcessModelSection() { } protected override ConfigurationPropertyCollection Properties { get { return _properties; } } [ConfigurationProperty("enable", DefaultValue = true)] public bool Enable { get { return (bool)base[_propEnable]; } set { base[_propEnable] = value; } } [ConfigurationProperty("timeout", DefaultValue = TimeSpanValidatorAttribute.TimeSpanMaxValue)] [TypeConverter(typeof(InfiniteTimeSpanConverter))] public TimeSpan Timeout { get { return (TimeSpan)base[_propTimeout]; } set { base[_propTimeout] = value; } } [ConfigurationProperty("idleTimeout", DefaultValue = TimeSpanValidatorAttribute.TimeSpanMaxValue)] [TypeConverter(typeof(InfiniteTimeSpanConverter))] public TimeSpan IdleTimeout { get { return (TimeSpan)base[_propIdleTimeout]; } set { base[_propIdleTimeout] = value; } } [ConfigurationProperty("shutdownTimeout", DefaultValue = "00:00:05")] [TypeConverter(typeof(InfiniteTimeSpanConverter))] [TimeSpanValidator(MinValueString="00:00:00", MaxValueString=TimeSpanValidatorAttribute.TimeSpanMaxValue)] public TimeSpan ShutdownTimeout { get { return (TimeSpan)base[_propShutdownTimeout]; } set { base[_propShutdownTimeout] = value; } } [ConfigurationProperty("requestLimit", DefaultValue = int.MaxValue)] [TypeConverter(typeof(InfiniteIntConverter))] [IntegerValidator(MinValue = 0)] public int RequestLimit { get { return (int)base[_propRequestLimit]; } set { base[_propRequestLimit] = value; } } [ConfigurationProperty("requestQueueLimit", DefaultValue = 5000)] [TypeConverter(typeof(InfiniteIntConverter))] [IntegerValidator(MinValue = 0)] public int RequestQueueLimit { get { return (int)base[_propRequestQueueLimit]; } set { base[_propRequestQueueLimit] = value; } } [ConfigurationProperty("restartQueueLimit", DefaultValue = 10)] [TypeConverter(typeof(InfiniteIntConverter))] [IntegerValidator(MinValue = 0)] public int RestartQueueLimit { get { return (int)base[_propRestartQueueLimit]; } set { base[_propRestartQueueLimit] = value; } } [ConfigurationProperty("memoryLimit", DefaultValue = 60)] public int MemoryLimit { get { return (int)base[_propMemoryLimit]; } set { base[_propMemoryLimit] = value; } } [ConfigurationProperty("webGarden", DefaultValue = false)] public bool WebGarden { get { return (bool)base[_propWebGarden]; } set { base[_propWebGarden] = value; } } [ConfigurationProperty("cpuMask", DefaultValue = "0xffffffff")] public int CpuMask { get { return (int)Convert.ToInt32((string)base[_propCpuMask], 16); } set { base[_propCpuMask] = "0x" + Convert.ToString(value, 16); } } [ConfigurationProperty("userName", DefaultValue = "machine")] public string UserName { get { return (string)base[_propUserName]; } set { base[_propUserName] = value; } } [ConfigurationProperty("password", DefaultValue = "AutoGenerate")] public string Password { get { return (string)base[_propPassword]; } set { base[_propPassword] = value; } } [ConfigurationProperty("logLevel", DefaultValue = ProcessModelLogLevel.Errors)] public ProcessModelLogLevel LogLevel { get { return (ProcessModelLogLevel)base[_propLogLevel]; } set { base[_propLogLevel] = value; } } [ConfigurationProperty("clientConnectedCheck", DefaultValue = "00:00:05")] [TypeConverter(typeof(InfiniteTimeSpanConverter))] public TimeSpan ClientConnectedCheck { get { return (TimeSpan)base[_propClientConnectedCheck]; } set { base[_propClientConnectedCheck] = value; } } [ConfigurationProperty("comAuthenticationLevel", DefaultValue = ProcessModelComAuthenticationLevel.Connect)] public ProcessModelComAuthenticationLevel ComAuthenticationLevel { get { return (ProcessModelComAuthenticationLevel)base[_propComAuthenticationLevel]; } set { base[_propComAuthenticationLevel] = value; } } [ConfigurationProperty("comImpersonationLevel", DefaultValue = ProcessModelComImpersonationLevel.Impersonate)] public ProcessModelComImpersonationLevel ComImpersonationLevel { get { return (ProcessModelComImpersonationLevel)base[_propComImpersonationLevel]; } set { base[_propComImpersonationLevel] = value; } } [ConfigurationProperty("responseDeadlockInterval", DefaultValue = "00:03:00")] [TypeConverter(typeof(InfiniteTimeSpanConverter))] [TimeSpanValidator(MinValueString="00:00:00", MaxValueString=TimeSpanValidatorAttribute.TimeSpanMaxValue)] public TimeSpan ResponseDeadlockInterval { get { return (TimeSpan)base[_propResponseDeadlockInterval]; } set { base[_propResponseDeadlockInterval] = value; } } [ConfigurationProperty("responseRestartDeadlockInterval", DefaultValue = "00:03:00")] [TypeConverter(typeof(InfiniteTimeSpanConverter))] public TimeSpan ResponseRestartDeadlockInterval { get { return (TimeSpan)base[_propResponseRestartDeadlockInterval]; } set { base[_propResponseRestartDeadlockInterval] = value; } } // NOTE the AutoConfig default value is different then the value shipped in Machine.config // This is because the Whidbey value is supposed to be true, but if the user removes the value // it should act like pre whidbey behavior which did not have autoconfig. [ConfigurationProperty("autoConfig", DefaultValue = false)] public bool AutoConfig { get { return (bool)base[_propAutoConfig]; } set { base[_propAutoConfig] = value; } } [ConfigurationProperty("maxWorkerThreads", DefaultValue = 20)] [IntegerValidator(MinValue = 1, MaxValue = int.MaxValue - 1)] public int MaxWorkerThreads { get { return (int)base[_propMaxWorkerThreads]; } set { base[_propMaxWorkerThreads] = value; } } [ConfigurationProperty("maxIoThreads", DefaultValue = 20)] [IntegerValidator(MinValue = 1, MaxValue = int.MaxValue - 1)] public int MaxIOThreads { get { return (int)base[_propMaxIOThreads]; } set { base[_propMaxIOThreads] = value; } } [ConfigurationProperty("minWorkerThreads", DefaultValue = 1)] [IntegerValidator(MinValue = 1, MaxValue = int.MaxValue - 1)] public int MinWorkerThreads { get { return (int)base[_propMinWorkerThreads]; } set { base[_propMinWorkerThreads] = value; } } [ConfigurationProperty("minIoThreads", DefaultValue = 1)] [IntegerValidator(MinValue = 1, MaxValue = int.MaxValue - 1)] public int MinIOThreads { get { return (int)base[_propMinIOThreads]; } set { base[_propMinIOThreads] = value; } } [ConfigurationProperty("serverErrorMessageFile", DefaultValue = "")] public string ServerErrorMessageFile { get { return (string)base[_propServerErrorMessageFile]; } set { base[_propServerErrorMessageFile] = value; } } [ConfigurationProperty("pingFrequency", DefaultValue = TimeSpanValidatorAttribute.TimeSpanMaxValue)] [TypeConverter(typeof(InfiniteTimeSpanConverter))] public TimeSpan PingFrequency { get { return (TimeSpan)base[_propPingFrequency]; } set { base[_propPingFrequency] = value; } } [ConfigurationProperty("pingTimeout", DefaultValue = TimeSpanValidatorAttribute.TimeSpanMaxValue)] [TypeConverter(typeof(InfiniteTimeSpanConverter))] public TimeSpan PingTimeout { get { return (TimeSpan)base[_propPingTimeout]; } set { base[_propPingTimeout] = value; } } [ConfigurationProperty("maxAppDomains", DefaultValue = 2000)] [IntegerValidator(MinValue = 1, MaxValue = int.MaxValue - 1)] public int MaxAppDomains { get { return (int)base[_propMaxAppDomains]; } set { base[_propMaxAppDomains] = value; } } internal int CpuCount { get { return cpuCount; } } internal int DefaultMaxWorkerThreadsForAutoConfig { get { return DefaultMaxThreadsPerCPU * cpuCount; } } internal int DefaultMaxIoThreadsForAutoConfig { get { return DefaultMaxThreadsPerCPU * cpuCount; } } internal int MaxWorkerThreadsTimesCpuCount { get { return MaxWorkerThreads * cpuCount; } } internal int MaxIoThreadsTimesCpuCount { get { return MaxIOThreads * cpuCount; } } internal int MinWorkerThreadsTimesCpuCount { get { return MinWorkerThreads * cpuCount; } } internal int MinIoThreadsTimesCpuCount { get { return MinIOThreads * cpuCount; } } protected override ConfigurationElementProperty ElementProperty { get { return s_elemProperty; } } private static void Validate(object value) { if (value == null) { throw new ArgumentNullException("value"); } ProcessModelSection elem = (ProcessModelSection)value; int val = -1; try { val = elem.CpuMask; } catch { throw new ConfigurationErrorsException( SR.GetString(SR.Invalid_non_zero_hexadecimal_attribute, "cpuMask"), elem.ElementInformation.Properties["cpuMask"].Source, elem.ElementInformation.Properties["cpuMask"].LineNumber); } if (val == 0) { throw new ConfigurationErrorsException( SR.GetString(SR.Invalid_non_zero_hexadecimal_attribute, "cpuMask"), elem.ElementInformation.Properties["cpuMask"].Source, elem.ElementInformation.Properties["cpuMask"].LineNumber); } } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Model\EntityType.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type Group. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public partial class Group : DirectoryObject { /// <summary> /// Gets or sets classification. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "classification", Required = Newtonsoft.Json.Required.Default)] public string Classification { get; set; } /// <summary> /// Gets or sets description. /// An optional description for the group. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "description", Required = Newtonsoft.Json.Required.Default)] public string Description { get; set; } /// <summary> /// Gets or sets display name. /// The display name for the group. This property is required when a group is created and it cannot be cleared during updates. Supports $filter and $orderby. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "displayName", Required = Newtonsoft.Json.Required.Default)] public string DisplayName { get; set; } /// <summary> /// Gets or sets group types. /// Specifies the type of group to create. Possible values are Unified to create an Office 365 group, or DynamicMembership for dynamic groups. For all other group types, like security-enabled groups and email-enabled security groups, do not set this property. Supports $filter. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "groupTypes", Required = Newtonsoft.Json.Required.Default)] public IEnumerable<string> GroupTypes { get; set; } /// <summary> /// Gets or sets mail. /// The SMTP address for the group, for example, "[email protected]". Read-only. Supports $filter. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "mail", Required = Newtonsoft.Json.Required.Default)] public string Mail { get; set; } /// <summary> /// Gets or sets mail enabled. /// Specifies whether the group is mail-enabled. If the securityEnabled property is also true, the group is a mail-enabled security group; otherwise, the group is a Microsoft Exchange distribution group. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "mailEnabled", Required = Newtonsoft.Json.Required.Default)] public bool? MailEnabled { get; set; } /// <summary> /// Gets or sets mail nickname. /// The mail alias for the group. This property must be specified when a group is created. Supports $filter. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "mailNickname", Required = Newtonsoft.Json.Required.Default)] public string MailNickname { get; set; } /// <summary> /// Gets or sets on premises last sync date time. /// Indicates the last time at which the group was synced with the on-premises directory.The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 would look like this: '2014-01-01T00:00:00Z'. Read-only. Supports $filter. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "onPremisesLastSyncDateTime", Required = Newtonsoft.Json.Required.Default)] public DateTimeOffset? OnPremisesLastSyncDateTime { get; set; } /// <summary> /// Gets or sets on premises security identifier. /// Contains the on-premises security identifier (SID) for the group that was synchronized from on-premises to the cloud. Read-only. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "onPremisesSecurityIdentifier", Required = Newtonsoft.Json.Required.Default)] public string OnPremisesSecurityIdentifier { get; set; } /// <summary> /// Gets or sets on premises sync enabled. /// true if this group is synced from an on-premises directory; false if this group was originally synced from an on-premises directory but is no longer synced; null if this object has never been synced from an on-premises directory (default). Read-only. Supports $filter. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "onPremisesSyncEnabled", Required = Newtonsoft.Json.Required.Default)] public bool? OnPremisesSyncEnabled { get; set; } /// <summary> /// Gets or sets proxy addresses. /// The any operator is required for filter expressions on multi-valued properties. Read-only. Not nullable. Supports $filter. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "proxyAddresses", Required = Newtonsoft.Json.Required.Default)] public IEnumerable<string> ProxyAddresses { get; set; } /// <summary> /// Gets or sets security enabled. /// Specifies whether the group is a security group. If the mailEnabled property is also true, the group is a mail-enabled security group; otherwise it is a security group. Must be false for Office 365 groups. Supports $filter. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "securityEnabled", Required = Newtonsoft.Json.Required.Default)] public bool? SecurityEnabled { get; set; } /// <summary> /// Gets or sets visibility. /// Specifies the visibility of an Office 365 group. Possible values are: Private, Public, or empty (which is interpreted as Public). /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "visibility", Required = Newtonsoft.Json.Required.Default)] public string Visibility { get; set; } /// <summary> /// Gets or sets allow external senders. /// Default is false. Indicates if people external to the organization can send messages to the group. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "allowExternalSenders", Required = Newtonsoft.Json.Required.Default)] public bool? AllowExternalSenders { get; set; } /// <summary> /// Gets or sets auto subscribe new members. /// Default is false. Indicates if new members added to the group will be auto-subscribed to receive email notifications. You can set this property in a PATCH request for the group; do not set it in the initial POST request that creates the group. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "autoSubscribeNewMembers", Required = Newtonsoft.Json.Required.Default)] public bool? AutoSubscribeNewMembers { get; set; } /// <summary> /// Gets or sets is subscribed by mail. /// Default value is true. Indicates whether the current user is subscribed to receive email conversations. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "isSubscribedByMail", Required = Newtonsoft.Json.Required.Default)] public bool? IsSubscribedByMail { get; set; } /// <summary> /// Gets or sets unseen count. /// Count of posts that the current user has not seen since his last visit. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "unseenCount", Required = Newtonsoft.Json.Required.Default)] public Int32? UnseenCount { get; set; } /// <summary> /// Gets or sets members. /// Users and groups that are members of this group. HTTP Methods: GET (supported for all groups), POST (supported for Office 365 groups, security groups and mail-enabled security groups), DELETE (supported for Office 365 groups and security groups) Nullable. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "members", Required = Newtonsoft.Json.Required.Default)] public IGroupMembersCollectionWithReferencesPage Members { get; set; } /// <summary> /// Gets or sets member of. /// Groups that this group is a member of. HTTP Methods: GET (supported for all groups). Read-only. Nullable. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "memberOf", Required = Newtonsoft.Json.Required.Default)] public IGroupMemberOfCollectionWithReferencesPage MemberOf { get; set; } /// <summary> /// Gets or sets created on behalf of. /// The user (or application) that created the group. NOTE: This is not set if the user is an administrator. Read-only. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "createdOnBehalfOf", Required = Newtonsoft.Json.Required.Default)] public DirectoryObject CreatedOnBehalfOf { get; set; } /// <summary> /// Gets or sets owners. /// The owners of the group. The owners are a set of non-admin users who are allowed to modify this object. Limited to 10 owners. HTTP Methods: GET (supported for all groups), POST (supported for Office 365 groups, security groups and mail-enabled security groups), DELETE (supported for Office 365 groups and security groups). Nullable. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "owners", Required = Newtonsoft.Json.Required.Default)] public IGroupOwnersCollectionWithReferencesPage Owners { get; set; } /// <summary> /// Gets or sets settings. /// Read-only. Nullable. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "settings", Required = Newtonsoft.Json.Required.Default)] public IGroupSettingsCollectionPage Settings { get; set; } /// <summary> /// Gets or sets extensions. /// The collection of open extensions defined for the group. Read-only. Nullable. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "extensions", Required = Newtonsoft.Json.Required.Default)] public IGroupExtensionsCollectionPage Extensions { get; set; } /// <summary> /// Gets or sets threads. /// The group's conversation threads. Nullable. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "threads", Required = Newtonsoft.Json.Required.Default)] public IGroupThreadsCollectionPage Threads { get; set; } /// <summary> /// Gets or sets calendar. /// The group's calendar. Read-only. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "calendar", Required = Newtonsoft.Json.Required.Default)] public Calendar Calendar { get; set; } /// <summary> /// Gets or sets calendar view. /// The calendar view for the calendar. Read-only. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "calendarView", Required = Newtonsoft.Json.Required.Default)] public IGroupCalendarViewCollectionPage CalendarView { get; set; } /// <summary> /// Gets or sets events. /// The group's calendar events. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "events", Required = Newtonsoft.Json.Required.Default)] public IGroupEventsCollectionPage Events { get; set; } /// <summary> /// Gets or sets conversations. /// The group's conversations. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "conversations", Required = Newtonsoft.Json.Required.Default)] public IGroupConversationsCollectionPage Conversations { get; set; } /// <summary> /// Gets or sets photo. /// The group's profile photo /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "photo", Required = Newtonsoft.Json.Required.Default)] public ProfilePhoto Photo { get; set; } /// <summary> /// Gets or sets photos. /// The profile photos owned by the group. Read-only. Nullable. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "photos", Required = Newtonsoft.Json.Required.Default)] public IGroupPhotosCollectionPage Photos { get; set; } /// <summary> /// Gets or sets accepted senders. /// The list of users or groups that are allowed to create post's or calendar events in this group. If this list is non-empty then only users or groups listed here are allowed to post. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "acceptedSenders", Required = Newtonsoft.Json.Required.Default)] public IGroupAcceptedSendersCollectionPage AcceptedSenders { get; set; } /// <summary> /// Gets or sets rejected senders. /// The list of users or groups that are not allowed to create posts or calendar events in this group. Nullable /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "rejectedSenders", Required = Newtonsoft.Json.Required.Default)] public IGroupRejectedSendersCollectionPage RejectedSenders { get; set; } /// <summary> /// Gets or sets drive. /// The group's drive. Read-only. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "drive", Required = Newtonsoft.Json.Required.Default)] public Drive Drive { get; set; } /// <summary> /// Gets or sets drives. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "drives", Required = Newtonsoft.Json.Required.Default)] public IGroupDrivesCollectionPage Drives { get; set; } /// <summary> /// Gets or sets sites. /// The list of SharePoint sites in this group. Access the default site with /sites/root. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "sites", Required = Newtonsoft.Json.Required.Default)] public IGroupSitesCollectionPage Sites { get; set; } /// <summary> /// Gets or sets planner. /// Entry-point to Planner resource that might exist for a Unified Group. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "planner", Required = Newtonsoft.Json.Required.Default)] public PlannerGroup Planner { get; set; } /// <summary> /// Gets or sets onenote. /// Read-only. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "onenote", Required = Newtonsoft.Json.Required.Default)] public Onenote Onenote { get; set; } } }
// 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 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Store { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.DataLake; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for TrustedIdProvidersOperations. /// </summary> public static partial class TrustedIdProvidersOperationsExtensions { /// <summary> /// Creates or updates the specified trusted identity provider. During update, /// the trusted identity provider with the specified name will be replaced with /// this new provider /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to add or replace the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider. This is used for differentiation /// of providers in the account. /// </param> /// <param name='parameters'> /// Parameters supplied to create or replace the trusted identity provider. /// </param> public static TrustedIdProvider CreateOrUpdate(this ITrustedIdProvidersOperations operations, string resourceGroupName, string accountName, string trustedIdProviderName, TrustedIdProvider parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, accountName, trustedIdProviderName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates the specified trusted identity provider. During update, /// the trusted identity provider with the specified name will be replaced with /// this new provider /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to add or replace the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider. This is used for differentiation /// of providers in the account. /// </param> /// <param name='parameters'> /// Parameters supplied to create or replace the trusted identity provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<TrustedIdProvider> CreateOrUpdateAsync(this ITrustedIdProvidersOperations operations, string resourceGroupName, string accountName, string trustedIdProviderName, TrustedIdProvider parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, accountName, trustedIdProviderName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the specified trusted identity provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to which to update the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider. This is used for differentiation /// of providers in the account. /// </param> /// <param name='parameters'> /// Parameters supplied to update the trusted identity provider. /// </param> public static TrustedIdProvider Update(this ITrustedIdProvidersOperations operations, string resourceGroupName, string accountName, string trustedIdProviderName, UpdateTrustedIdProviderParameters parameters = default(UpdateTrustedIdProviderParameters)) { return operations.UpdateAsync(resourceGroupName, accountName, trustedIdProviderName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Updates the specified trusted identity provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to which to update the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider. This is used for differentiation /// of providers in the account. /// </param> /// <param name='parameters'> /// Parameters supplied to update the trusted identity provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<TrustedIdProvider> UpdateAsync(this ITrustedIdProvidersOperations operations, string resourceGroupName, string accountName, string trustedIdProviderName, UpdateTrustedIdProviderParameters parameters = default(UpdateTrustedIdProviderParameters), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, accountName, trustedIdProviderName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified trusted identity provider from the specified Data /// Lake Store account /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to delete the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider to delete. /// </param> public static void Delete(this ITrustedIdProvidersOperations operations, string resourceGroupName, string accountName, string trustedIdProviderName) { operations.DeleteAsync(resourceGroupName, accountName, trustedIdProviderName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified trusted identity provider from the specified Data /// Lake Store account /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to delete the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider to delete. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this ITrustedIdProvidersOperations operations, string resourceGroupName, string accountName, string trustedIdProviderName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, trustedIdProviderName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets the specified Data Lake Store trusted identity provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider to retrieve. /// </param> public static TrustedIdProvider Get(this ITrustedIdProvidersOperations operations, string resourceGroupName, string accountName, string trustedIdProviderName) { return operations.GetAsync(resourceGroupName, accountName, trustedIdProviderName).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified Data Lake Store trusted identity provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider to retrieve. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<TrustedIdProvider> GetAsync(this ITrustedIdProvidersOperations operations, string resourceGroupName, string accountName, string trustedIdProviderName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, accountName, trustedIdProviderName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the Data Lake Store trusted identity providers within the specified /// Data Lake Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the trusted /// identity providers. /// </param> public static IPage<TrustedIdProvider> ListByAccount(this ITrustedIdProvidersOperations operations, string resourceGroupName, string accountName) { return operations.ListByAccountAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Lists the Data Lake Store trusted identity providers within the specified /// Data Lake Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the trusted /// identity providers. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<TrustedIdProvider>> ListByAccountAsync(this ITrustedIdProvidersOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAccountWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the Data Lake Store trusted identity providers within the specified /// Data Lake Store account. /// </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<TrustedIdProvider> ListByAccountNext(this ITrustedIdProvidersOperations operations, string nextPageLink) { return operations.ListByAccountNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists the Data Lake Store trusted identity providers within the specified /// Data Lake Store account. /// </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<TrustedIdProvider>> ListByAccountNextAsync(this ITrustedIdProvidersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAccountNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.IO { /* * This class is used to access a contiguous block of memory, likely outside * the GC heap (or pinned in place in the GC heap, but a MemoryStream may * make more sense in those cases). It's great if you have a pointer and * a length for a section of memory mapped in by someone else and you don't * want to copy this into the GC heap. UnmanagedMemoryStream assumes these * two things: * * 1) All the memory in the specified block is readable or writable, * depending on the values you pass to the constructor. * 2) The lifetime of the block of memory is at least as long as the lifetime * of the UnmanagedMemoryStream. * 3) You clean up the memory when appropriate. The UnmanagedMemoryStream * currently will do NOTHING to free this memory. * 4) All calls to Write and WriteByte may not be threadsafe currently. * * It may become necessary to add in some sort of * DeallocationMode enum, specifying whether we unmap a section of memory, * call free, run a user-provided delegate to free the memory, etc. * We'll suggest user write a subclass of UnmanagedMemoryStream that uses * a SafeHandle subclass to hold onto the memory. * */ /// <summary> /// Stream over a memory pointer or over a SafeBuffer /// </summary> public class UnmanagedMemoryStream : Stream { private SafeBuffer _buffer; private unsafe byte* _mem; private long _length; private long _capacity; private long _position; private long _offset; private FileAccess _access; private bool _isOpen; private Task<Int32> _lastReadTask; // The last successful task returned from ReadAsync /// <summary> /// Creates a closed stream. /// </summary> // Needed for subclasses that need to map a file, etc. protected UnmanagedMemoryStream() { unsafe { _mem = null; } _isOpen = false; } /// <summary> /// Creates a stream over a SafeBuffer. /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="length"></param> public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length) { Initialize(buffer, offset, length, FileAccess.Read); } /// <summary> /// Creates a stream over a SafeBuffer. /// </summary> public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access) { Initialize(buffer, offset, length, access); } /// <summary> /// Subclasses must call this method (or the other overload) to properly initialize all instance fields. /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="length"></param> /// <param name="access"></param> protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.ByteLength < (ulong)(offset + length)) { throw new ArgumentException(SR.Argument_InvalidSafeBufferOffLen); } if (access < FileAccess.Read || access > FileAccess.ReadWrite) { throw new ArgumentOutOfRangeException(nameof(access)); } Contract.EndContractBlock(); if (_isOpen) { throw new InvalidOperationException(SR.InvalidOperation_CalledTwice); } // check for wraparound unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { buffer.AcquirePointer(ref pointer); if ((pointer + offset + length) < pointer) { throw new ArgumentException(SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround); } } finally { if (pointer != null) { buffer.ReleasePointer(); } } } _offset = offset; _buffer = buffer; _length = length; _capacity = length; _access = access; _isOpen = true; } /// <summary> /// Creates a stream over a byte*. /// </summary> [CLSCompliant(false)] public unsafe UnmanagedMemoryStream(byte* pointer, long length) { Initialize(pointer, length, length, FileAccess.Read); } /// <summary> /// Creates a stream over a byte*. /// </summary> [CLSCompliant(false)] public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access) { Initialize(pointer, length, capacity, access); } /// <summary> /// Subclasses must call this method (or the other overload) to properly initialize all instance fields. /// </summary> [CLSCompliant(false)] protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access) { if (pointer == null) throw new ArgumentNullException(nameof(pointer)); if (length < 0 || capacity < 0) throw new ArgumentOutOfRangeException((length < 0) ? nameof(length) : nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum); if (length > capacity) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_LengthGreaterThanCapacity); Contract.EndContractBlock(); // Check for wraparound. if (((byte*)((long)pointer + capacity)) < pointer) throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround); if (access < FileAccess.Read || access > FileAccess.ReadWrite) throw new ArgumentOutOfRangeException(nameof(access), SR.ArgumentOutOfRange_Enum); if (_isOpen) throw new InvalidOperationException(SR.InvalidOperation_CalledTwice); _mem = pointer; _offset = 0; _length = length; _capacity = capacity; _access = access; _isOpen = true; } /// <summary> /// Returns true if the stream can be read; otherwise returns false. /// </summary> public override bool CanRead { [Pure] get { return _isOpen && (_access & FileAccess.Read) != 0; } } /// <summary> /// Returns true if the stream can seek; otherwise returns false. /// </summary> public override bool CanSeek { [Pure] get { return _isOpen; } } /// <summary> /// Returns true if the stream can be written to; otherwise returns false. /// </summary> public override bool CanWrite { [Pure] get { return _isOpen && (_access & FileAccess.Write) != 0; } } /// <summary> /// Closes the stream. The stream's memory needs to be dealt with separately. /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { _isOpen = false; unsafe { _mem = null; } // Stream allocates WaitHandles for async calls. So for correctness // call base.Dispose(disposing) for better perf, avoiding waiting // for the finalizers to run on those types. base.Dispose(disposing); } /// <summary> /// Since it's a memory stream, this method does nothing. /// </summary> public override void Flush() { if (!_isOpen) throw Error.GetStreamIsClosed(); } /// <summary> /// Since it's a memory stream, this method does nothing specific. /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> public override Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); try { Flush(); return Task.CompletedTask; } catch (Exception ex) { return Task.FromException(ex); } } /// <summary> /// Number of bytes in the stream. /// </summary> public override long Length { get { if (!_isOpen) throw Error.GetStreamIsClosed(); return Interlocked.Read(ref _length); } } /// <summary> /// Number of bytes that can be written to the stream. /// </summary> public long Capacity { get { if (!_isOpen) throw Error.GetStreamIsClosed(); return _capacity; } } /// <summary> /// ReadByte will read byte at the Position in the stream /// </summary> public override long Position { get { if (!CanSeek) throw Error.GetStreamIsClosed(); Contract.EndContractBlock(); return Interlocked.Read(ref _position); } set { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); if (!CanSeek) throw Error.GetStreamIsClosed(); Contract.EndContractBlock(); Interlocked.Exchange(ref _position, value); } } /// <summary> /// Pointer to memory at the current Position in the stream. /// </summary> [CLSCompliant(false)] public unsafe byte* PositionPointer { get { if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer); if (!_isOpen) throw Error.GetStreamIsClosed(); // Use a temp to avoid a race long pos = Interlocked.Read(ref _position); if (pos > _capacity) throw new IndexOutOfRangeException(SR.IndexOutOfRange_UMSPosition); byte* ptr = _mem + pos; return ptr; } set { if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer); if (!_isOpen) throw Error.GetStreamIsClosed(); if (value < _mem) throw new IOException(SR.IO_SeekBeforeBegin); long newPosition = (long)value - (long)_mem; if (newPosition < 0) throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_UnmanagedMemStreamLength); Interlocked.Exchange(ref _position, newPosition); } } /// <summary> /// Reads bytes from stream and puts them into the buffer /// </summary> /// <param name="buffer">Buffer to read the bytes to.</param> /// <param name="offset">Starting index in the buffer.</param> /// <param name="count">Maximum number of bytes to read.</param> /// <returns>Number of bytes actually read.</returns> public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); return ReadCore(new Span<byte>(buffer, offset, count)); } public override int Read(Span<byte> destination) { if (GetType() == typeof(UnmanagedMemoryStream)) { return ReadCore(destination); } else { // UnmanagedMemoryStream is not sealed, and a derived type may have overridden Read(byte[], int, int) prior // to this Read(Span<byte>) overload being introduced. In that case, this Read(Span<byte>) overload // should use the behavior of Read(byte[],int,int) overload. return base.Read(destination); } } internal int ReadCore(Span<byte> destination) { if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanRead) throw Error.GetReadNotSupported(); // Use a local variable to avoid a race where another thread // changes our position after we decide we can read some bytes. long pos = Interlocked.Read(ref _position); long len = Interlocked.Read(ref _length); long n = Math.Min(len - pos, destination.Length); if (n <= 0) { return 0; } int nInt = (int)n; // Safe because n <= count, which is an Int32 if (nInt < 0) { return 0; // _position could be beyond EOF } Debug.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1. unsafe { fixed (byte* pBuffer = &destination.DangerousGetPinnableReference()) { if (_buffer != null) { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); Buffer.Memcpy(pBuffer, pointer + pos + _offset, nInt); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } else { Buffer.Memcpy(pBuffer, _mem + pos, nInt); } } } Interlocked.Exchange(ref _position, pos + n); return nInt; } /// <summary> /// Reads bytes from stream and puts them into the buffer /// </summary> /// <param name="buffer">Buffer to read the bytes to.</param> /// <param name="offset">Starting index in the buffer.</param> /// <param name="count">Maximum number of bytes to read.</param> /// <param name="cancellationToken">Token that can be used to cancel this operation.</param> /// <returns>Task that can be used to access the number of bytes actually read.</returns> public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // contract validation copied from Read(...) if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<Int32>(cancellationToken); try { Int32 n = Read(buffer, offset, count); Task<Int32> t = _lastReadTask; return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<Int32>(n)); } catch (Exception ex) { Debug.Assert(!(ex is OperationCanceledException)); return Task.FromException<Int32>(ex); } } /// <summary> /// Returns the byte at the stream current Position and advances the Position. /// </summary> /// <returns></returns> public override int ReadByte() { if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanRead) throw Error.GetReadNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); if (pos >= len) return -1; Interlocked.Exchange(ref _position, pos + 1); int result; if (_buffer != null) { unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); result = *(pointer + pos + _offset); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { result = _mem[pos]; } } return result; } /// <summary> /// Advanced the Position to specific location in the stream. /// </summary> /// <param name="offset">Offset from the loc parameter.</param> /// <param name="loc">Origin for the offset parameter.</param> /// <returns></returns> public override long Seek(long offset, SeekOrigin loc) { if (!_isOpen) throw Error.GetStreamIsClosed(); switch (loc) { case SeekOrigin.Begin: if (offset < 0) throw new IOException(SR.IO_SeekBeforeBegin); Interlocked.Exchange(ref _position, offset); break; case SeekOrigin.Current: long pos = Interlocked.Read(ref _position); if (offset + pos < 0) throw new IOException(SR.IO_SeekBeforeBegin); Interlocked.Exchange(ref _position, offset + pos); break; case SeekOrigin.End: long len = Interlocked.Read(ref _length); if (len + offset < 0) throw new IOException(SR.IO_SeekBeforeBegin); Interlocked.Exchange(ref _position, len + offset); break; default: throw new ArgumentException(SR.Argument_InvalidSeekOrigin); } long finalPos = Interlocked.Read(ref _position); Debug.Assert(finalPos >= 0, "_position >= 0"); return finalPos; } /// <summary> /// Sets the Length of the stream. /// </summary> /// <param name="value"></param> public override void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer); if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanWrite) throw Error.GetWriteNotSupported(); if (value > _capacity) throw new IOException(SR.IO_FixedCapacity); long pos = Interlocked.Read(ref _position); long len = Interlocked.Read(ref _length); if (value > len) { unsafe { Buffer.ZeroMemory(_mem + len, value - len); } } Interlocked.Exchange(ref _length, value); if (pos > value) { Interlocked.Exchange(ref _position, value); } } /// <summary> /// Writes buffer into the stream /// </summary> /// <param name="buffer">Buffer that will be written.</param> /// <param name="offset">Starting index in the buffer.</param> /// <param name="count">Number of bytes to write.</param> public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); WriteCore(new Span<byte>(buffer, offset, count)); } public override void Write(ReadOnlySpan<byte> source) { if (GetType() == typeof(UnmanagedMemoryStream)) { WriteCore(source); } else { // UnmanagedMemoryStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior // to this Write(Span<byte>) overload being introduced. In that case, this Write(Span<byte>) overload // should use the behavior of Write(byte[],int,int) overload. base.Write(source); } } internal unsafe void WriteCore(ReadOnlySpan<byte> source) { if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanWrite) throw Error.GetWriteNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); long n = pos + source.Length; // Check for overflow if (n < 0) { throw new IOException(SR.IO_StreamTooLong); } if (n > _capacity) { throw new NotSupportedException(SR.IO_FixedCapacity); } if (_buffer == null) { // Check to see whether we are now expanding the stream and must // zero any memory in the middle. if (pos > len) { Buffer.ZeroMemory(_mem + len, pos - len); } // set length after zeroing memory to avoid race condition of accessing unzeroed memory if (n > len) { Interlocked.Exchange(ref _length, n); } } fixed (byte* pBuffer = &source.DangerousGetPinnableReference()) { if (_buffer != null) { long bytesLeft = _capacity - pos; if (bytesLeft < source.Length) { throw new ArgumentException(SR.Arg_BufferTooSmall); } byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); Buffer.Memcpy(pointer + pos + _offset, pBuffer, source.Length); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } else { Buffer.Memcpy(_mem + pos, pBuffer, source.Length); } } Interlocked.Exchange(ref _position, n); return; } /// <summary> /// Writes buffer into the stream. The operation completes synchronously. /// </summary> /// <param name="buffer">Buffer that will be written.</param> /// <param name="offset">Starting index in the buffer.</param> /// <param name="count">Number of bytes to write.</param> /// <param name="cancellationToken">Token that can be used to cancel the operation.</param> /// <returns>Task that can be awaited </returns> public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // contract validation copied from Write(..) if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); try { Write(buffer, offset, count); return Task.CompletedTask; } catch (Exception ex) { Debug.Assert(!(ex is OperationCanceledException)); return Task.FromException(ex); } } /// <summary> /// Writes a byte to the stream and advances the current Position. /// </summary> /// <param name="value"></param> public override void WriteByte(byte value) { if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanWrite) throw Error.GetWriteNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); long n = pos + 1; if (pos >= len) { // Check for overflow if (n < 0) throw new IOException(SR.IO_StreamTooLong); if (n > _capacity) throw new NotSupportedException(SR.IO_FixedCapacity); // Check to see whether we are now expanding the stream and must // zero any memory in the middle. // don't do if created from SafeBuffer if (_buffer == null) { if (pos > len) { unsafe { Buffer.ZeroMemory(_mem + len, pos - len); } } // set length after zeroing memory to avoid race condition of accessing unzeroed memory Interlocked.Exchange(ref _length, n); } } if (_buffer != null) { unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); *(pointer + pos + _offset) = value; } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { _mem[pos] = value; } } Interlocked.Exchange(ref _position, n); } } }
// // Copyright (c) 2008-2019 the Urho3D project. // Copyright (c) 2017-2020 the rbfx project. // // 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.Runtime.InteropServices; namespace Urho3DNet { /// %Sphere in three-dimensional space. [StructLayout(LayoutKind.Sequential)] public struct Sphere : IEquatable<Sphere> { /// Construct from center and radius. public Sphere(in Vector3? center=null, float radius=float.NegativeInfinity) { Center = center.GetValueOrDefault(Vector3.Zero); Radius = radius; } /// Construct from an array of vertices. public Sphere(Vector3[] vertices) { Center = Vector3.Zero; Radius = 0; Define(vertices); } /// Construct from a bounding box. public Sphere(in BoundingBox box) { Center = Vector3.Zero; Radius = 0; Define(box); } // /// Construct from a frustum. // public Sphere(in Frustum frustum) // { // Center = Vector3.Zero; // Radius = 0; // Define(frustum); // } // /// Construct from a polyhedron. // public Sphere(in Polyhedron poly) // { // Center = Vector3.Zero; // Radius = 0; // Define(poly); // } /// Test for equality with another sphere. public static bool operator ==(in Sphere lhs, in Sphere rhs) { return lhs.Equals(rhs); } /// Test for inequality with another sphere. public static bool operator !=(in Sphere lhs, in Sphere rhs) { return !lhs.Equals(rhs); } /// Define from another sphere. public void Define(in Sphere sphere) { Define(sphere.Center, sphere.Radius); } /// Define from center and radius. public void Define(in Vector3 center, float radius) { Center = center; Radius = radius; } /// Define from an array of vertices. public void Define(Vector3[] vertices) { if (vertices.Length < 1) return; Clear(); Merge(vertices); } /// Define from a bounding box. public void Define(in BoundingBox box) { Vector3 min = box.Min; Vector3 max = box.Max; Clear(); Merge(min); Merge(new Vector3(max.X, min.Y, min.Z)); Merge(new Vector3(min.X, max.Y, min.Z)); Merge(new Vector3(max.X, max.Y, min.Z)); Merge(new Vector3(min.X, min.Y, max.Z)); Merge(new Vector3(max.X, min.Y, max.Z)); Merge(new Vector3(min.X, max.Y, max.Z)); Merge(max); } /// Define from a frustum. // public void Define(in Frustum frustum) // { // Define(frustum.Vertices); // } // /// Define from a polyhedron. // public void Define(in Polyhedron poly) // { // Clear(); // Merge(poly); // } /// Merge a point. public void Merge(in Vector3 point) { if (Radius < 0.0f) { Center = point; Radius = 0.0f; return; } Vector3 offset = point - Center; float dist = offset.Length; if (dist > Radius) { float half = (dist - Radius) * 0.5f; Radius += half; Center += (half / dist) * offset; } } /// Merge an array of vertices. public void Merge(Vector3[] vertices) { foreach (var vert in vertices) Merge(vert); } /// Merge a bounding box. public void Merge(in BoundingBox box) { Vector3 min = box.Min; Vector3 max = box.Max; Merge(min); Merge(new Vector3(max.X, min.Y, min.Z)); Merge(new Vector3(min.X, max.Y, min.Z)); Merge(new Vector3(max.X, max.Y, min.Z)); Merge(new Vector3(min.X, min.Y, max.Z)); Merge(new Vector3(max.X, min.Y, max.Z)); Merge(new Vector3(min.X, max.Y, max.Z)); Merge(max); } /// Merge a frustum. // public void Merge(in Frustum frustum) // { // Merge(frustum.Vertices); // } // /// Merge a polyhedron. // public void Merge(in Polyhedron poly) // { // for (unsigned i = 0; i < poly.faces_.Size(); ++i) // { // const ea::vector<Vector3>& face = poly.faces_[i]; // if (!face.Empty()) // Merge(&face[0], face.Size()); // } // } /// Merge a sphere. public void Merge(in Sphere sphere) { if (Radius < 0.0f) { Center = sphere.Center; Radius = sphere.Radius; return; } Vector3 offset = sphere.Center - Center; float dist = offset.Length; // If sphere fits inside, do nothing if (dist + sphere.Radius < Radius) return; // If we fit inside the other sphere, become it if (dist + Radius < sphere.Radius) { Center = sphere.Center; Radius = sphere.Radius; } else { Vector3 NormalizedOffset = offset / dist; Vector3 min = Center - Radius * NormalizedOffset; Vector3 max = sphere.Center + sphere.Radius * NormalizedOffset; Center = (min + max) * 0.5f; Radius = (max - Center).Length; } } /// Clear to undefined state. public void Clear() { Center = Vector3.Zero; Radius = float.NegativeInfinity; } /// Return true if this sphere is defined via a previous call to Define() or Merge(). public bool Defined() { return Radius >= 0.0f; } /// Test if a point is inside. public Intersection IsInside(in Vector3 point) { float distSquared = (point - Center).LengthSquared; if (distSquared < Radius * Radius) return Intersection.Inside; else return Intersection.Outside; } /// Test if another sphere is inside, outside or intersects. public Intersection IsInside(in Sphere sphere) { float dist = (sphere.Center - Center).Length; if (dist >= sphere.Radius + Radius) return Intersection.Outside; else if (dist + sphere.Radius < Radius) return Intersection.Inside; else return Intersection.Intersects; } /// Test if another sphere is (partially) inside or outside. public Intersection IsInsideFast(in Sphere sphere) { float distSquared = (sphere.Center - Center).LengthSquared; float combined = sphere.Radius + Radius; if (distSquared >= combined * combined) return Intersection.Outside; else return Intersection.Inside; } /// Test if a bounding box is inside, outside or intersects. public Intersection IsInside(in BoundingBox box) { float radiusSquared = Radius * Radius; float distSquared = 0; float temp; Vector3 min = box.Min; Vector3 max = box.Max; if (Center.X < min.X) { temp = Center.X - min.X; distSquared += temp * temp; } else if (Center.X > max.X) { temp = Center.X - max.X; distSquared += temp * temp; } if (Center.Y < min.Y) { temp = Center.Y - min.Y; distSquared += temp * temp; } else if (Center.Y > max.Y) { temp = Center.Y - max.Y; distSquared += temp * temp; } if (Center.Z < min.Z) { temp = Center.Z - min.Z; distSquared += temp * temp; } else if (Center.Z > max.Z) { temp = Center.Z - max.Z; distSquared += temp * temp; } if (distSquared >= radiusSquared) return Intersection.Outside; min -= Center; max -= Center; Vector3 tempVec = min; // - - - if (tempVec.LengthSquared >= radiusSquared) return Intersection.Intersects; tempVec.X = max.X; // + - - if (tempVec.LengthSquared >= radiusSquared) return Intersection.Intersects; tempVec.Y = max.Y; // + + - if (tempVec.LengthSquared >= radiusSquared) return Intersection.Intersects; tempVec.X = min.X; // - + - if (tempVec.LengthSquared >= radiusSquared) return Intersection.Intersects; tempVec.Z = max.Z; // - + + if (tempVec.LengthSquared >= radiusSquared) return Intersection.Intersects; tempVec.Y = min.Y; // - - + if (tempVec.LengthSquared >= radiusSquared) return Intersection.Intersects; tempVec.X = max.X; // + - + if (tempVec.LengthSquared >= radiusSquared) return Intersection.Intersects; tempVec.Y = max.Y; // + + + if (tempVec.LengthSquared >= radiusSquared) return Intersection.Intersects; return Intersection.Inside; } /// Test if a bounding box is (partially) inside or outside. public Intersection IsInsideFast(in BoundingBox box) { float radiusSquared = Radius * Radius; float distSquared = 0; float temp; Vector3 min = box.Min; Vector3 max = box.Max; if (Center.X < min.X) { temp = Center.X - min.X; distSquared += temp * temp; } else if (Center.X > max.X) { temp = Center.X - max.X; distSquared += temp * temp; } if (Center.Y < min.Y) { temp = Center.Y - min.Y; distSquared += temp * temp; } else if (Center.Y > max.Y) { temp = Center.Y - max.Y; distSquared += temp * temp; } if (Center.Z < min.Z) { temp = Center.Z - min.Z; distSquared += temp * temp; } else if (Center.Z > max.Z) { temp = Center.Z - max.Z; distSquared += temp * temp; } if (distSquared >= radiusSquared) return Intersection.Outside; else return Intersection.Inside; } /// Return distance of a point to the surface, or 0 if inside. public float Distance(in Vector3 point) { return Math.Max((point - Center).Length - Radius, 0.0f); } /// Return point on the sphere relative to sphere position. public Vector3 GetLocalPoint(float theta, float phi) { return new Vector3( (float) (Radius * Math.Sin(theta) * Math.Sin(phi)), (float) (Radius * Math.Cos(phi)), (float) (Radius * Math.Cos(theta) * Math.Sin(phi)) ); } /// Return point on the sphere. public Vector3 GetPoint(float theta, float phi) { return Center + GetLocalPoint(theta, phi); } /// Sphere center. public Vector3 Center; /// Sphere radius. public float Radius; public bool Equals(Sphere other) { return Center.Equals(other.Center) && Radius.Equals(other.Radius); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is Sphere other && Equals(other); } public override int GetHashCode() { unchecked { return (Center.GetHashCode() * 397) ^ Radius.GetHashCode(); } } } }
using System; using System.Collections.Generic; using System.Linq; using MvcContrib.UI.Grid; using NUnit.Framework; namespace MvcContrib.UnitTests.UI.Grid { [TestFixture] public class ColumnBuilderTester { private ColumnBuilder<Person> _builder; [SetUp] public void Setup() { _builder = new ColumnBuilder<Person>(); } [Test] public void Should_define_columns() { _builder.For(x => x.Name); _builder.For(x => x.DateOfBirth); _builder.Count().ShouldEqual(2); } [Test] public void Should_infer_column_name_from_lambda() { _builder.For(x => x.Name); _builder.Single().Name.ShouldEqual("Name"); } [Test] public void Should_infer_column_displayname_from_lambda() { _builder.For(x => x.Name); _builder.Single().DisplayName.ShouldEqual("Name"); } [Test] public void Shold_build_column_with_name() { _builder.For(x => x.Name).Named("foo"); _builder.Single().Name.ShouldEqual("Name"); } [Test] public void Should_build_column_with_displayname() { _builder.For(x => x.Name).Named("foo"); _builder.Single().DisplayName.ShouldEqual("foo"); } [Test] public void Name_should_be_null_if_no_name_specified_and_not_MemberExpression() { _builder.For(x => 1); _builder.Single().Name.ShouldBeNull(); } [Test] public void DisplayName_should_be_null_if_no_name_specified_and_not_MemberExpression() { _builder.For(x => 1); _builder.Single().DisplayName.ShouldBeNull(); } [Test] public void DisplayName_should_be_split_pascal_case() { _builder.For(x => x.DateOfBirth); _builder.Single().DisplayName.ShouldEqual("Date Of Birth"); } [Test] public void Name_should_not_be_split_pascal_case() { _builder.For(x => x.DateOfBirth); _builder.Single().Name.ShouldEqual("DateOfBirth"); } [Test] public void DisplayName_should_not_be_split_if_DoNotSplit_specified() { _builder.For(x => x.DateOfBirth).DoNotSplit(); _builder.Single().DisplayName.ShouldEqual("DateOfBirth"); } [Test] public void DisplayName_should_not_be_split_when_explicit_name_specified() { _builder.For(x => x.Id).Named("FOO"); _builder.Single().DisplayName.ShouldEqual("FOO"); } [Test] public void Should_obtain_value() { _builder.For(x => x.Name); _builder.Single().GetValue(new Person { Name = "Jeremy" }).ShouldEqual("Jeremy"); } [Test] public void Should_format_item() { _builder.For(x => x.Name).Format("{0}_TEST"); _builder.Single().GetValue(new Person{Name="Jeremy"}).ShouldEqual("Jeremy_TEST"); } [Test] public void Should_not_return_value_when_CellCondition_returns_false() { _builder.For(x => x.Name).CellCondition(x => false); _builder.Single().GetValue(new Person(){Name = "Jeremy"}).ShouldBeNull(); } [Test] public void Column_should_not_be_visible() { _builder.For(x => x.Name).Visible(false); _builder.Single().Visible.ShouldBeFalse(); } [Test] public void Should_html_encode_output() { _builder.For(x => x.Name); _builder.Single().GetValue(new Person{Name = "<script>"}).ShouldEqual("&lt;script&gt;"); } [Test] public void Should_not_html_encode_output() { _builder.For(x => x.Name).Encode(false); _builder.Single().GetValue(new Person{Name = "<script>"}).ShouldEqual("<script>"); } [Test] public void Should_specify_header_attributes() { var attrs = new Dictionary<string, object> { { "foo", "bar" } }; _builder.For(x => x.Name).HeaderAttributes(attrs); _builder.Single().HeaderAttributes["foo"].ShouldEqual("bar"); } [Test] public void Should_specify_header_attributes_using_lambdas() { _builder.For(x => x.Name).HeaderAttributes(foo => "bar"); _builder.Single().HeaderAttributes["foo"].ShouldEqual("bar"); } [Test] public void Should_add_column() { ((ICollection<GridColumn<Person>>)_builder).Add(new GridColumn<Person>(x => null, null, null)); _builder.Count().ShouldEqual(1); } [Test] public void Should_clear() { _builder.For(x => x.Name); ((ICollection<GridColumn<Person>>)_builder).Clear(); _builder.Count().ShouldEqual(0); } [Test] public void Should_contain_column() { var column = _builder.For(x => x.Name) as GridColumn<Person>; ((ICollection<GridColumn<Person>>)_builder).Contains(column).ShouldBeTrue(); } [Test] public void Should_copy_to_array() { var array = new GridColumn<Person>[1]; var col = _builder.For(x => x.Name); ((ICollection<GridColumn<Person>>)_builder).CopyTo(array, 0); array[0].ShouldBeTheSameAs(col); } [Test] public void Should_remove_column() { var column = (GridColumn<Person>) _builder.For(x => x.Name); ((ICollection<GridColumn<Person>>)_builder).Remove(column); _builder.Count().ShouldEqual(0); } [Test] public void Should_count_columns() { _builder.For(x => x.Name); ((ICollection<GridColumn<Person>>)_builder).Count.ShouldEqual(1); } [Test] public void Should_not_be_readonly() { ((ICollection<GridColumn<Person>>)_builder).IsReadOnly.ShouldBeFalse(); } [Test] public void ColumnType_should_return_the_Type_of_the_property_referenced_by_the_column() { _builder.For(x => x.DateOfBirth); _builder.Single().ColumnType.ShouldEqual(typeof(DateTime)); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { /// <summary> /// The pattern matcher is thread-safe. However, it maintains an internal cache of /// information as it is used. Therefore, you should not keep it around forever and should get /// and release the matcher appropriately once you no longer need it. /// Also, while the pattern matcher is culture aware, it uses the culture specified in the /// constructor. /// </summary> internal sealed class PatternMatcher { // First we break up the pattern given by dots. Each portion of the pattern between the // dots is a 'Segment'. The 'Segment' contains information about the entire section of // text between the dots, as well as information about any individual 'Words' that we // can break the segment into. private struct Segment { // Information about the entire piece of text between the dots. For example, if the // text between the dots is 'GetKeyword', then TotalTextChunk.Text will be 'GetKeyword' and // TotalTextChunk.CharacterSpans will correspond to 'G', 'et', 'K' and 'eyword'. public readonly TextChunk TotalTextChunk; // Information about the subwords compromising the total word. For example, if the // text between the dots is 'GetKeyword', then the subwords will be 'Get' and 'Keyword' // Those individual words will have CharacterSpans of ('G' and 'et') and ('K' and 'eyword') // respectively. public readonly TextChunk[] SubWordTextChunks; public Segment(string text, bool verbatimIdentifierPrefixIsWordCharacter) { this.TotalTextChunk = new TextChunk(text); this.SubWordTextChunks = BreakPatternIntoTextChunks(text, verbatimIdentifierPrefixIsWordCharacter); } public bool IsInvalid => this.SubWordTextChunks.Length == 0; private static int CountTextChunks(string pattern, bool verbatimIdentifierPrefixIsWordCharacter) { int count = 0; int wordLength = 0; for (int i = 0; i < pattern.Length; i++) { if (IsWordChar(pattern[i], verbatimIdentifierPrefixIsWordCharacter)) { wordLength++; } else { if (wordLength > 0) { count++; wordLength = 0; } } } if (wordLength > 0) { count++; } return count; } private static TextChunk[] BreakPatternIntoTextChunks(string pattern, bool verbatimIdentifierPrefixIsWordCharacter) { int partCount = CountTextChunks(pattern, verbatimIdentifierPrefixIsWordCharacter); if (partCount == 0) { return SpecializedCollections.EmptyArray<TextChunk>(); } var result = new TextChunk[partCount]; int resultIndex = 0; int wordStart = 0; int wordLength = 0; for (int i = 0; i < pattern.Length; i++) { var ch = pattern[i]; if (IsWordChar(ch, verbatimIdentifierPrefixIsWordCharacter)) { if (wordLength++ == 0) { wordStart = i; } } else { if (wordLength > 0) { result[resultIndex++] = new TextChunk(pattern.Substring(wordStart, wordLength)); wordLength = 0; } } } if (wordLength > 0) { result[resultIndex++] = new TextChunk(pattern.Substring(wordStart, wordLength)); } return result; } } // Information about a chunk of text from the pattern. The chunk is a piece of text, with // cached information about the character spans within in. Character spans separate out // capitalized runs and lowercase runs. i.e. if you have AAbb, then there will be two // character spans, one for AA and one for BB. private struct TextChunk { public readonly string Text; public readonly StringBreaks CharacterSpans; public TextChunk(string text) { this.Text = text; this.CharacterSpans = StringBreaker.BreakIntoCharacterParts(text); } } private static readonly char[] s_dotCharacterArray = new[] { '.' }; private readonly object _gate = new object(); private readonly bool _invalidPattern; private readonly Segment _fullPatternSegment; private readonly Segment[] _dotSeparatedSegments; private readonly Dictionary<string, StringBreaks> _stringToWordSpans = new Dictionary<string, StringBreaks>(); private readonly Func<string, StringBreaks> _breakIntoWordSpans = StringBreaker.BreakIntoWordParts; // PERF: Cache the culture's compareInfo to avoid the overhead of asking for them repeatedly in inner loops private readonly CompareInfo _compareInfo; /// <summary> /// Construct a new PatternMatcher using the calling thread's culture for string searching and comparison. /// </summary> public PatternMatcher(string pattern, bool verbatimIdentifierPrefixIsWordCharacter = false) : this(pattern, CultureInfo.CurrentCulture, verbatimIdentifierPrefixIsWordCharacter) { } /// <summary> /// Construct a new PatternMatcher using the specified culture. /// </summary> /// <param name="pattern">The pattern to make the pattern matcher for.</param> /// <param name="culture">The culture to use for string searching and comparison.</param> /// <param name="verbatimIdentifierPrefixIsWordCharacter">Whether to consider "@" as a word character</param> public PatternMatcher(string pattern, CultureInfo culture, bool verbatimIdentifierPrefixIsWordCharacter) { pattern = pattern.Trim(); _compareInfo = culture.CompareInfo; _fullPatternSegment = new Segment(pattern, verbatimIdentifierPrefixIsWordCharacter); _dotSeparatedSegments = pattern.Split(s_dotCharacterArray, StringSplitOptions.RemoveEmptyEntries) .Select(text => new Segment(text.Trim(), verbatimIdentifierPrefixIsWordCharacter)) .ToArray(); _invalidPattern = _dotSeparatedSegments.Length == 0 || _dotSeparatedSegments.Any(s => s.IsInvalid); } public bool IsDottedPattern => _dotSeparatedSegments.Length > 1; private bool SkipMatch(string candidate) { return _invalidPattern || string.IsNullOrWhiteSpace(candidate); } /// <summary> /// Determines if a given candidate string matches under a multiple word query text, as you /// would find in features like Navigate To. /// </summary> /// <param name="candidate">The word being tested.</param> /// <returns>If this was a match, a set of match types that occurred while matching the /// patterns. If it was not a match, it returns null.</returns> public IEnumerable<PatternMatch> GetMatches(string candidate) { if (SkipMatch(candidate)) { return null; } return MatchSegment(candidate, _fullPatternSegment); } public IEnumerable<PatternMatch> GetMatchesForLastSegmentOfPattern(string candidate) { if (SkipMatch(candidate)) { return null; } return MatchSegment(candidate, _dotSeparatedSegments.Last()); } /// <summary> /// Matches a pattern against a candidate, and an optional dotted container for the /// candidate. If the container is provided, and the pattern itself contains dots, then /// the pattern will be tested against the candidate and container. Specifically, /// the part of the pattern after the last dot will be tested against the candidate. If /// a match occurs there, then the remaining dot-separated portions of the pattern will /// be tested against every successive portion of the container from right to left. /// /// i.e. if you have a pattern of "Con.WL" and the candidate is "WriteLine" with a /// dotted container of "System.Console", then "WL" will be tested against "WriteLine". /// With a match found there, "Con" will then be tested against "Console". /// </summary> public IEnumerable<PatternMatch> GetMatches(string candidate, string dottedContainer) { if (SkipMatch(candidate)) { return null; } // First, check that the last part of the dot separated pattern matches the name of the // candidate. If not, then there's no point in proceeding and doing the more // expensive work. var candidateMatch = MatchSegment(candidate, _dotSeparatedSegments.Last()); if (candidateMatch == null) { return null; } dottedContainer = dottedContainer ?? string.Empty; var containerParts = dottedContainer.Split(s_dotCharacterArray, StringSplitOptions.RemoveEmptyEntries); // -1 because the last part was checked against the name, and only the rest // of the parts are checked against the container. if (_dotSeparatedSegments.Length - 1 > containerParts.Length) { // There weren't enough container parts to match against the pattern parts. // So this definitely doesn't match. return null; } // So far so good. Now break up the container for the candidate and check if all // the dotted parts match up correctly. var totalMatch = candidateMatch.ToList(); for (int i = _dotSeparatedSegments.Length - 2, j = containerParts.Length - 1; i >= 0; i--, j--) { var segment = _dotSeparatedSegments[i]; var containerName = containerParts[j]; var containerMatch = MatchSegment(containerName, segment); if (containerMatch == null) { // This container didn't match the pattern piece. So there's no match at all. return null; } totalMatch.AddRange(containerMatch); } // Success, this symbol's full name matched against the dotted name the user was asking // about. return totalMatch; } /// <summary> /// Determines if a given candidate string matches under a multiple word query text, as you /// would find in features like Navigate To. /// </summary> /// <remarks> /// PERF: This is slightly faster and uses less memory than <see cref="GetMatches(string)"/> /// so, unless you need to know the full set of matches, use this version. /// </remarks> /// <param name="candidate">The word being tested.</param> /// <returns>If this was a match, the first element of the set of match types that occurred while matching the /// patterns. If it was not a match, it returns null.</returns> public PatternMatch? GetFirstMatch(string candidate) { if (SkipMatch(candidate)) { return null; } PatternMatch[] ignored; return MatchSegment(candidate, _fullPatternSegment, wantAllMatches: false, allMatches: out ignored); } private StringBreaks GetWordSpans(string word) { lock (_gate) { return _stringToWordSpans.GetOrAdd(word, _breakIntoWordSpans); } } internal PatternMatch? MatchSingleWordPattern_ForTestingOnly(string candidate) { return MatchTextChunk(candidate, _fullPatternSegment.TotalTextChunk, punctuationStripped: false); } private static bool ContainsUpperCaseLetter(string pattern) { // Expansion of "foreach(char ch in pattern)" to avoid a CharEnumerator allocation for (int i = 0; i < pattern.Length; i++) { if (char.IsUpper(pattern[i])) { return true; } } return false; } private PatternMatch? MatchTextChunk(string candidate, TextChunk chunk, bool punctuationStripped) { int index = _compareInfo.IndexOf(candidate, chunk.Text, CompareOptions.IgnoreCase); if (index == 0) { if (chunk.Text.Length == candidate.Length) { // a) Check if the part matches the candidate entirely, in an case insensitive or // sensitive manner. If it does, return that there was an exact match. return new PatternMatch(PatternMatchKind.Exact, punctuationStripped, isCaseSensitive: candidate == chunk.Text); } else { // b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive // manner. If it does, return that there was a prefix match. return new PatternMatch(PatternMatchKind.Prefix, punctuationStripped, isCaseSensitive: _compareInfo.IsPrefix(candidate, chunk.Text)); } } var isLowercase = !ContainsUpperCaseLetter(chunk.Text); if (isLowercase) { if (index > 0) { // c) If the part is entirely lowercase, then check if it is contained anywhere in the // candidate in a case insensitive manner. If so, return that there was a substring // match. // // Note: We only have a substring match if the lowercase part is prefix match of some // word part. That way we don't match something like 'Class' when the user types 'a'. // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). var wordSpans = GetWordSpans(candidate); for(int i = 0; i < wordSpans.Count; i++) { var span = wordSpans[i]; if (PartStartsWith(candidate, span, chunk.Text, CompareOptions.IgnoreCase)) { return new PatternMatch(PatternMatchKind.Substring, punctuationStripped, isCaseSensitive: PartStartsWith(candidate, span, chunk.Text, CompareOptions.None)); } } } } else { // d) If the part was not entirely lowercase, then check if it is contained in the // candidate in a case *sensitive* manner. If so, return that there was a substring // match. if (_compareInfo.IndexOf(candidate, chunk.Text) > 0) { return new PatternMatch(PatternMatchKind.Substring, punctuationStripped, isCaseSensitive: true); } } if (!isLowercase) { // e) If the part was not entirely lowercase, then attempt a camel cased match as well. if (chunk.CharacterSpans.Count > 0) { var candidateParts = GetWordSpans(candidate); var camelCaseWeight = TryCamelCaseMatch(candidate, candidateParts, chunk, CompareOptions.None); if (camelCaseWeight.HasValue) { return new PatternMatch(PatternMatchKind.CamelCase, punctuationStripped, isCaseSensitive: true, camelCaseWeight: camelCaseWeight); } camelCaseWeight = TryCamelCaseMatch(candidate, candidateParts, chunk, CompareOptions.IgnoreCase); if (camelCaseWeight.HasValue) { return new PatternMatch(PatternMatchKind.CamelCase, punctuationStripped, isCaseSensitive: false, camelCaseWeight: camelCaseWeight); } } } if (isLowercase) { // f) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries? // We could check every character boundary start of the candidate for the pattern. However, that's // an m * n operation in the wost case. Instead, find the first instance of the pattern // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to // filter the list based on a substring that starts on a capital letter and also with a lowercase one. // (Pattern: fogbar, Candidate: quuxfogbarFogBar). if (chunk.Text.Length < candidate.Length) { if (index != -1 && char.IsUpper(candidate[index])) { return new PatternMatch(PatternMatchKind.Substring, punctuationStripped, isCaseSensitive: false); } } } return null; } private static bool ContainsSpaceOrAsterisk(string text) { for (int i = 0; i < text.Length; i++) { char ch = text[i]; if (ch == ' ' || ch == '*') { return true; } } return false; } private IEnumerable<PatternMatch> MatchSegment(string candidate, Segment segment) { PatternMatch[] matches; var singleMatch = MatchSegment(candidate, segment, wantAllMatches: true, allMatches: out matches); if (singleMatch.HasValue) { return SpecializedCollections.SingletonEnumerable(singleMatch.Value); } return matches; } /// <summary> /// Internal helper for MatchPatternInternal /// </summary> /// <remarks> /// PERF: Designed to minimize allocations in common cases. /// If there's no match, then null is returned. /// If there's a single match, or the caller only wants the first match, then it is returned (as a Nullable) /// If there are multiple matches, and the caller wants them all, then a List is allocated. /// </remarks> /// <param name="candidate">The word being tested.</param> /// <param name="segment">The segment of the pattern to check against the candidate.</param> /// <param name="wantAllMatches">Does the caller want all matches or just the first?</param> /// <param name="allMatches">If <paramref name="wantAllMatches"/> is true, and there's more than one match, then the list of all matches.</param> /// <returns>If there's only one match, then the return value is that match. Otherwise it is null.</returns> private PatternMatch? MatchSegment(string candidate, Segment segment, bool wantAllMatches, out PatternMatch[] allMatches) { allMatches = null; // First check if the segment matches as is. This is also useful if the segment contains // characters we would normally strip when splitting into parts that we also may want to // match in the candidate. For example if the segment is "@int" and the candidate is // "@int", then that will show up as an exact match here. // // Note: if the segment contains a space or an asterisk then we must assume that it's a // multi-word segment. if (!ContainsSpaceOrAsterisk(segment.TotalTextChunk.Text)) { var match = MatchTextChunk(candidate, segment.TotalTextChunk, punctuationStripped: false); if (match != null) { return match; } } // The logic for pattern matching is now as follows: // // 1) Break the segment passed in into words. Breaking is rather simple and a // good way to think about it that if gives you all the individual alphanumeric words // of the pattern. // // 2) For each word try to match the word against the candidate value. // // 3) Matching is as follows: // // a) Check if the word matches the candidate entirely, in an case insensitive or // sensitive manner. If it does, return that there was an exact match. // // b) Check if the word is a prefix of the candidate, in a case insensitive or // sensitive manner. If it does, return that there was a prefix match. // // c) If the word is entirely lowercase, then check if it is contained anywhere in the // candidate in a case insensitive manner. If so, return that there was a substring // match. // // Note: We only have a substring match if the lowercase part is prefix match of // some word part. That way we don't match something like 'Class' when the user // types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with // 'a'). // // d) If the word was not entirely lowercase, then check if it is contained in the // candidate in a case *sensitive* manner. If so, return that there was a substring // match. // // e) If the word was not entirely lowercase, then attempt a camel cased match as // well. // // f) The word is all lower case. Is it a case insensitive substring of the candidate starting // on a part boundary of the candidate? // // Only if all words have some sort of match is the pattern considered matched. var subWordTextChunks = segment.SubWordTextChunks; PatternMatch[] matches = null; for (int i = 0; i < subWordTextChunks.Length; i++) { var subWordTextChunk = subWordTextChunks[i]; // Try to match the candidate with this word var result = MatchTextChunk(candidate, subWordTextChunk, punctuationStripped: true); if (result == null) { return null; } if (!wantAllMatches || subWordTextChunks.Length == 1) { // Stop at the first word return result; } matches = matches ?? new PatternMatch[subWordTextChunks.Length]; matches[i] = result.Value; } allMatches = matches; return null; } private static bool IsWordChar(char ch, bool verbatimIdentifierPrefixIsWordCharacter) { return char.IsLetterOrDigit(ch) || ch == '_' || (verbatimIdentifierPrefixIsWordCharacter && ch == '@'); } /// <summary> /// Do the two 'parts' match? i.e. Does the candidate part start with the pattern part? /// </summary> /// <param name="candidate">The candidate text</param> /// <param name="candidatePart">The span within the <paramref name="candidate"/> text</param> /// <param name="pattern">The pattern text</param> /// <param name="patternPart">The span within the <paramref name="pattern"/> text</param> /// <param name="compareOptions">Options for doing the comparison (case sensitive or not)</param> /// <returns>True if the span identified by <paramref name="candidatePart"/> within <paramref name="candidate"/> starts with /// the span identified by <paramref name="patternPart"/> within <paramref name="pattern"/>.</returns> private bool PartStartsWith(string candidate, TextSpan candidatePart, string pattern, TextSpan patternPart, CompareOptions compareOptions) { if (patternPart.Length > candidatePart.Length) { // Pattern part is longer than the candidate part. There can never be a match. return false; } return _compareInfo.Compare(candidate, candidatePart.Start, patternPart.Length, pattern, patternPart.Start, patternPart.Length, compareOptions) == 0; } /// <summary> /// Does the given part start with the given pattern? /// </summary> /// <param name="candidate">The candidate text</param> /// <param name="candidatePart">The span within the <paramref name="candidate"/> text</param> /// <param name="pattern">The pattern text</param> /// <param name="compareOptions">Options for doing the comparison (case sensitive or not)</param> /// <returns>True if the span identified by <paramref name="candidatePart"/> within <paramref name="candidate"/> starts with <paramref name="pattern"/></returns> private bool PartStartsWith(string candidate, TextSpan candidatePart, string pattern, CompareOptions compareOptions) { return PartStartsWith(candidate, candidatePart, pattern, new TextSpan(0, pattern.Length), compareOptions); } private int? TryCamelCaseMatch(string candidate, StringBreaks candidateParts, TextChunk chunk, CompareOptions compareOption) { var chunkCharacterSpans = chunk.CharacterSpans; // Note: we may have more pattern parts than candidate parts. This is because multiple // pattern parts may match a candidate part. For example "SiUI" against "SimpleUI". // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U // and I will both match in UI. int currentCandidate = 0; int currentChunkSpan = 0; int? firstMatch = null; bool? contiguous = null; while (true) { // Let's consider our termination cases if (currentChunkSpan == chunkCharacterSpans.Count) { Contract.Requires(firstMatch.HasValue); Contract.Requires(contiguous.HasValue); // We did match! We shall assign a weight to this int weight = 0; // Was this contiguous? if (contiguous.Value) { weight += 1; } // Did we start at the beginning of the candidate? if (firstMatch.Value == 0) { weight += 2; } return weight; } else if (currentCandidate == candidateParts.Count) { // No match, since we still have more of the pattern to hit return null; } var candidatePart = candidateParts[currentCandidate]; bool gotOneMatchThisCandidate = false; // Consider the case of matching SiUI against SimpleUIElement. The candidate parts // will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si' // against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to // still keep matching pattern parts against that candidate part. for (; currentChunkSpan < chunkCharacterSpans.Count; currentChunkSpan++) { var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan]; if (gotOneMatchThisCandidate) { // We've already gotten one pattern part match in this candidate. We will // only continue trying to consumer pattern parts if the last part and this // part are both upper case. if (!char.IsUpper(chunk.Text[chunkCharacterSpans[currentChunkSpan - 1].Start]) || !char.IsUpper(chunk.Text[chunkCharacterSpans[currentChunkSpan].Start])) { break; } } if (!PartStartsWith(candidate, candidatePart, chunk.Text, chunkCharacterSpan, compareOption)) { break; } gotOneMatchThisCandidate = true; firstMatch = firstMatch ?? currentCandidate; // If we were contiguous, then keep that value. If we weren't, then keep that // value. If we don't know, then set the value to 'true' as an initial match is // obviously contiguous. contiguous = contiguous ?? true; candidatePart = new TextSpan(candidatePart.Start + chunkCharacterSpan.Length, candidatePart.Length - chunkCharacterSpan.Length); } // Check if we matched anything at all. If we didn't, then we need to unset the // contiguous bit if we currently had it set. // If we haven't set the bit yet, then that means we haven't matched anything so // far, and we don't want to change that. if (!gotOneMatchThisCandidate && contiguous.HasValue) { contiguous = false; } // Move onto the next candidate. currentCandidate++; } } } }
/* * Copyright (C) 2016-2020. Autumn Beauchesne. All rights reserved. * Author: Autumn Beauchesne * Date: 8 May 2018 * * File: SimpleSpline.cs * Purpose: Quadratic bezier curve. */ #if UNITY_EDITOR || DEVELOPMENT_BUILD #define DEVELOPMENT #endif using System; using UnityEngine; namespace BeauRoutine.Splines { /// <summary> /// Quadratic Bezier curve. Contains start, end, and a single control point. /// </summary> [Serializable] public class SimpleSpline : ISpline { private struct PreciseSegment { public float Marker; public float Length; } #region Inspector [SerializeField] private Vector3 m_Start = default(Vector3); [SerializeField] private Vector3 m_End = default(Vector3); [SerializeField] private Vector3 m_Control = default(Vector3); #endregion // Inspector private Action<ISpline> m_OnUpdated; private object m_StartUserData; private object m_EndUserData; private float m_Distance; private float m_PreciseDistance; private int m_PreciseSegmentCount; private PreciseSegment[] m_PreciseSegmentData; private bool m_Dirty; public SimpleSpline(Vector3 inStart, Vector3 inEnd, Vector3 inControl) { m_Start = inStart; m_End = inEnd; m_Control = inControl; m_Distance = 0; m_PreciseDistance = 0; m_Dirty = true; m_StartUserData = m_EndUserData = null; m_PreciseSegmentCount = SplineMath.DistancePrecision; } public SimpleSpline(Vector2 inStart, Vector2 inEnd, Vector2 inControl) { m_Start = inStart; m_End = inEnd; m_Control = inControl; m_Distance = 0; m_PreciseDistance = 0; m_Dirty = true; m_StartUserData = m_EndUserData = null; m_PreciseSegmentCount = SplineMath.DistancePrecision; } #region Construction /// <summary> /// Starting point of the spline. /// </summary> public Vector3 Start { get { return m_Start; } set { if (m_Start != value) { m_Start = value; m_Dirty = true; } } } /// <summary> /// Ending point of the spline. /// </summary> public Vector3 End { get { return m_End; } set { if (m_End != value) { m_End = value; m_Dirty = true; } } } /// <summary> /// Spline control point. /// </summary> public Vector3 Control { get { return m_Control; } set { if (m_Control != value) { m_Control = value; m_Dirty = true; } } } #endregion // Construction #region ISpline #region Basic Info public SplineType GetSplineType() { return SplineType.SimpleSpline; } public bool IsLooped() { return false; } public float GetDistance() { if (m_Dirty) Process(); return m_PreciseDistance; } public float GetDirectDistance() { if (m_Dirty) Process(); return m_Distance; } #endregion // Basic Info #region Vertex Info public int GetVertexCount() { return 2; } public Vector3 GetVertex(int inIndex) { #if DEVELOPMENT if (inIndex < 0 || inIndex > 1) throw new ArgumentOutOfRangeException("inIndex"); #endif // DEVELOPMENT return (inIndex == 0 ? m_Start : m_End); } public void SetVertex(int inIndex, Vector3 inVertex) { #if DEVELOPMENT if (inIndex < 0 || inIndex > 1) throw new ArgumentOutOfRangeException("inIndex"); #endif // DEVELOPMENT if (inIndex == 0) m_Start = inVertex; else m_End = inVertex; m_Dirty = true; } public object GetVertexUserData(int inIndex) { #if DEVELOPMENT if (inIndex < 0 || inIndex > 1) throw new ArgumentOutOfRangeException("inIndex"); #endif // DEVELOPMENT return (inIndex == 0 ? m_StartUserData : m_EndUserData); } public void SetVertexUserData(int inIndex, object inUserData) { #if DEVELOPMENT if (inIndex < 0 || inIndex > 1) throw new ArgumentOutOfRangeException("inIndex"); #endif // DEVELOPMENT if (inIndex == 0) m_StartUserData = inUserData; else m_EndUserData = inUserData; } public int GetControlCount() { return 1; } public Vector3 GetControlPoint(int inIndex) { #if DEVELOPMENT if (inIndex != 0) throw new ArgumentOutOfRangeException("inIndex"); #endif // DEVELOPMENT return m_Control; } public void SetControlPoint(int inIndex, Vector3 inVertex) { #if DEVELOPMENT if (inIndex != 0) throw new ArgumentOutOfRangeException("inIndex"); #endif // DEVELOPMENT m_Control = inVertex; m_Dirty = true; } #endregion // Vertex Info #region Evaluation public float TransformPercent(float inPercent, SplineLerp inLerpMethod) { if (m_Dirty) Process(); if (inPercent == 0 || inPercent == 1) return inPercent; switch(inLerpMethod) { case SplineLerp.Vertex: case SplineLerp.Direct: default: { return inPercent; } case SplineLerp.Precise: { int segCount = m_PreciseSegmentCount; for (int i = segCount - 1; i > 0; --i) { if (m_PreciseSegmentData[i].Marker <= inPercent) { float lerp = (inPercent - m_PreciseSegmentData[i].Marker) / m_PreciseSegmentData[i].Length; return (i + lerp) / segCount; } } // If this fails, use the starting node { float lerp = inPercent / m_PreciseSegmentData[0].Length; return (lerp) / segCount; } } } } public float InvTransformPercent(float inPercent, SplineLerp inLerpMethod) { if (m_Dirty) Process(); if (inPercent == 0 || inPercent == 1) return inPercent; switch(inLerpMethod) { case SplineLerp.Vertex: case SplineLerp.Direct: default: { return inPercent; } case SplineLerp.Precise: { float vertAF = inPercent * m_PreciseSegmentCount; int vertA = (int)vertAF; if (vertA < 0) vertA = 0; else if (vertA >= m_PreciseSegmentData.Length) vertA = m_PreciseSegmentData.Length - 1; float interpolation = vertAF - vertA; return m_PreciseSegmentData[vertA].Marker + interpolation * m_PreciseSegmentData[vertA].Length; } } } public Vector3 GetPoint(float inPercent, Curve inSegmentCurve = Curve.Linear) { if (m_Dirty) Process(); return SplineMath.Quadratic(m_Start, m_Control, m_End, inSegmentCurve.Evaluate(inPercent)); } public Vector3 GetDirection(float inPercent, Curve inSegmentCurve = Curve.Linear) { if (m_Dirty) Process(); float p = inSegmentCurve.Evaluate(inPercent); Vector3 dir = SplineMath.QuadraticDerivative(m_Start, m_Control, m_End, p); dir.Normalize(); return dir; } public void GetSegment(float inPercent, out SplineSegment outSegment) { outSegment.Interpolation = inPercent; outSegment.VertexA = 0; outSegment.VertexB = 1; } #endregion // Evaluation #region Operations public bool Process() { if (!m_Dirty) return false; m_Distance = Vector3.Distance(m_Start, m_End); float preciseDist = 0; float segmentDist = 0; Vector3 prev = m_Start; Vector3 next; if (m_PreciseSegmentCount < 1) m_PreciseSegmentCount = 1; Array.Resize(ref m_PreciseSegmentData, Mathf.NextPowerOfTwo(m_PreciseSegmentCount)); for (int i = 0; i < m_PreciseSegmentCount; ++i) { next = SplineMath.Quadratic(m_Start, m_Control, m_End, (float)(i + 1) / m_PreciseSegmentCount); segmentDist = Vector3.Distance(prev, next); m_PreciseSegmentData[i].Marker = preciseDist; m_PreciseSegmentData[i].Length = segmentDist; preciseDist += segmentDist; prev = next; } m_PreciseDistance = preciseDist; float invPreciseDist = 1f / preciseDist; for (int i = 0; i < m_PreciseSegmentCount; ++i) { m_PreciseSegmentData[i].Marker *= invPreciseDist; m_PreciseSegmentData[i].Length *= invPreciseDist; } m_Dirty = false; if (m_OnUpdated != null) m_OnUpdated(this); return true; } public Action<ISpline> OnUpdated { get { return m_OnUpdated; } set { m_OnUpdated = value; } } #endregion // Operations #endregion // ISpline } }
using System; using CoreGraphics; using CoreGraphics; using UIKit; namespace MonoCross.Touch { internal enum MGCornersPosition { LeadingVertical, // top of screen for a left/right split. TrailingVertical, // bottom of screen for a left/right split. LeadingHorizontal, // left of screen for a top/bottom split. TrailingHorizontal // right of screen for a top/bottom split. } class MGSplitCornersView : UIView { internal float CornerRadius { get; set; } internal MGCornersPosition CornersPosition { get; set; } internal UIColor CornerBackgroundColor { get; set; } private MGSplitViewController _splitViewController = null; internal MGSplitCornersView () { ContentMode = UIViewContentMode.Redraw; UserInteractionEnabled = false; Opaque = false; BackgroundColor = UIColor.Clear; CornerRadius = 0; // actual value is set by the splitViewController. CornersPosition = MGCornersPosition.LeadingVertical; } float DegreesToRadians(float degrees) { // Converts degrees to radians. return degrees * ((float)Math.PI / 180); } float RadiansToDegrees(float radians) { // Converts radians to degrees. return radians * (180 / (float)Math.PI); } void DrawRect(CGRect rect) { // Draw two appropriate corners, with cornerBackgroundColor behind them. if (CornerRadius > 0) { nfloat maxX = Bounds.GetMaxX(); nfloat maxY = Bounds.GetMaxY(); UIBezierPath path = UIBezierPath.Create(); CGPoint pt = CGPoint.Empty; switch (CornersPosition) { case MGCornersPosition.LeadingVertical: // top of screen for a left/right split path.MoveTo(pt); pt.Y += CornerRadius; path.AppendPath(UIBezierPath.FromArc(pt, CornerRadius, DegreesToRadians(90), 0, true)); pt.X += CornerRadius; pt.Y -= CornerRadius; path.AddLineTo(pt); path.AddLineTo(CGPoint.Empty); path.ClosePath(); pt.X = maxX - CornerRadius; pt.Y = 0; path.MoveTo(pt); pt.Y = maxY; path.AddLineTo(pt); pt.X += CornerRadius; path.AppendPath(UIBezierPath.FromArc(pt, CornerRadius, DegreesToRadians(180), DegreesToRadians(90), true)); pt.Y -= CornerRadius; path.AddLineTo(pt); pt.X -= CornerRadius; path.AddLineTo(pt); path.ClosePath(); break; case MGCornersPosition.TrailingVertical: // bottom of screen for a left/right split pt.Y = maxY; path.MoveTo(pt); pt.Y -= CornerRadius; path.AppendPath(UIBezierPath.FromArc(pt, CornerRadius, DegreesToRadians(270), DegreesToRadians(360), false)); pt.X += CornerRadius; pt.Y += CornerRadius; path.AddLineTo(pt); pt.X -= CornerRadius; path.AddLineTo(pt); path.ClosePath(); pt.X = maxX - CornerRadius; pt.Y = maxY; path.MoveTo(pt); pt.Y -= CornerRadius; path.AddLineTo(pt); pt.X += CornerRadius; path.AppendPath(UIBezierPath.FromArc(pt, CornerRadius, DegreesToRadians(180), DegreesToRadians(270), false)); pt.Y += CornerRadius; path.AddLineTo(pt); pt.X -= CornerRadius; path.AddLineTo(pt); path.ClosePath(); break; case MGCornersPosition.LeadingHorizontal: // left of screen for a top/bottom split pt.X = 0; pt.Y = CornerRadius; path.MoveTo(pt); pt.Y -= CornerRadius; path.AddLineTo(pt); pt.X += CornerRadius; path.AppendPath(UIBezierPath.FromArc(pt, CornerRadius, DegreesToRadians(180), DegreesToRadians(270), false)); pt.Y += CornerRadius; path.AddLineTo(pt); pt.X -= CornerRadius; path.AddLineTo(pt); path.ClosePath(); pt.X = 0; pt.Y = maxY - CornerRadius; path.MoveTo(pt); pt.Y = maxY; path.AddLineTo(pt); pt.X += CornerRadius; path.AppendPath(UIBezierPath.FromArc(pt, CornerRadius, DegreesToRadians(180), DegreesToRadians(90), true)); pt.Y -= CornerRadius; path.AddLineTo(pt); pt.X -= CornerRadius; path.AddLineTo(pt); path.ClosePath(); break; case MGCornersPosition.TrailingHorizontal: // right of screen for a top/bottom split pt.Y = CornerRadius; path.MoveTo(pt); pt.Y -= CornerRadius; path.AppendPath(UIBezierPath.FromArc(pt, CornerRadius, DegreesToRadians(270), DegreesToRadians(360), false)); pt.X += CornerRadius; pt.Y += CornerRadius; path.AddLineTo(pt); pt.X -= CornerRadius; path.AddLineTo(pt); path.ClosePath(); pt.Y = maxY - CornerRadius; path.MoveTo(pt); pt.Y += CornerRadius; path.AppendPath(UIBezierPath.FromArc(pt, CornerRadius, DegreesToRadians(90), 0, true)); pt.X += CornerRadius; pt.Y -= CornerRadius; path.AddLineTo(pt); pt.X -= CornerRadius; path.AddLineTo(pt); path.ClosePath(); break; default: break; } CornerBackgroundColor.SetColor(); path.Fill(); } } public void SetCornerRadius(float newRadius) { if (newRadius != CornerRadius) { CornerRadius = newRadius; SetNeedsDisplay(); } } public void SetSplitViewController(MGSplitViewController controller) { if (controller != _splitViewController) { _splitViewController = controller; SetNeedsDisplay(); } } public void SetCornersPosition(MGCornersPosition pos) { if (CornersPosition != pos) { CornersPosition = pos; SetNeedsDisplay(); } } public void SetCornerBackgroundColor(UIColor color) { if (color != CornerBackgroundColor) { CornerBackgroundColor = color; SetNeedsDisplay(); } } } }
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 TestApi.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>(); } /// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and 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)) { 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="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <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, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [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) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.IO; using System.Web; using Microsoft.IdentityModel.Protocols.WSFederation; using Microsoft.Xrm.Client; using Microsoft.Xrm.Client.Diagnostics; using Microsoft.Xrm.Portal.IdentityModel.Configuration; using Microsoft.Xrm.Portal.IdentityModel.Web.Modules; using Microsoft.Xrm.Portal.Web; using Microsoft.Xrm.Portal.Web.Security; using Microsoft.Xrm.Portal.Web.Security.LiveId; namespace Microsoft.Xrm.Portal.IdentityModel.Web.Handlers { public class LiveIdAccountTransferHandler : IHttpHandler { private class Message : WSFederationMessage { public Message(Uri baseUrl) : base(baseUrl, WSFederationConstants.Actions.SignIn) { Parameters.Clear(); } public override void Write(TextWriter writer) { } } #region Constructors public LiveIdAccountTransferHandler() : this(FederationCrmConfigurationManager.GetUserRegistrationSettings()) { } public LiveIdAccountTransferHandler(IUserRegistrationSettings registrationSettings) { RegistrationSettings = registrationSettings; } #endregion private static readonly string _className = typeof(LiveIdAccountTransferHandler).FullName; private static readonly WindowsLiveLogin _windowsLiveLogin = new WindowsLiveLogin(true); public virtual IUserRegistrationSettings RegistrationSettings { get; private set; } protected string LiveIdTokenKey { get { return SelectRegistrationSetting(setting => setting.LiveIdTokenKey, "live-id-token"); } } protected string ReturnUrlKey { get { return SelectRegistrationSetting(setting => setting.ReturnUrlKey, "returnurl"); } } protected string ResultCodeKey { get { return SelectRegistrationSetting(setting => setting.ResultCodeKey, "result-code"); } } protected string DefaultReturnPath { get { return SelectRegistrationSetting(setting => setting.DefaultReturnPath, "~/"); } } public virtual string AccountTransferPath { get { return SelectRegistrationSetting(setting => setting.AccountTransferPath, DefaultReturnPath); } } public virtual string UnregisteredUserPath { get { return SelectRegistrationSetting(setting => setting.UnregisteredUserPath, DefaultReturnPath); } } public virtual string RegistrationPath { get { return SelectRegistrationSetting(setting => setting.RegistrationPath, DefaultReturnPath); } } protected string ErrorPath { get { return SelectRegistrationSetting(setting => setting.ErrorPath, DefaultReturnPath); } } private string SelectRegistrationSetting(Func<IUserRegistrationSettings, string> selector, string defaultValue) { return SelectSetting(RegistrationSettings, selector, defaultValue); } private static string SelectSetting<T>(T setting, Func<T, string> selector, string defaultValue) where T : class { return setting != null ? selector(setting) ?? defaultValue : defaultValue; } /// <summary> /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler" /> instance. /// </summary> /// <returns> /// true if the <see cref="T:System.Web.IHttpHandler" /> instance is reusable; otherwise, false. /// </returns> public bool IsReusable { get { return false; } } /// <summary> /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler" /> interface. /// </summary> /// <param name="context">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests. </param> public void ProcessRequest(HttpContext context) { try { TryHandleSignInResponse(context); } catch (Exception exception) { if (!TryHandleException(context, exception)) { throw new FederationAuthenticationException("Federated sign-in error.", exception); } } } /// <summary> /// Set the Live ID cookie and redirect to the login destination or the registration destination. /// </summary> protected virtual bool TryHandleSignInResponse(HttpContext context) { var user = _windowsLiveLogin.ProcessLogin(context.Request.Form); TraceInformation("TryHandleSignInResponse", "user.Id={0}", user.Id); if (LiveIdMembershipProvider.Current.ValidateUser(user.Id, user.Id)) { if (RegistrationSettings != null && !string.IsNullOrEmpty(RegistrationSettings.AccountTransferPath)) { // go to the account transfer page TraceInformation("TryHandleSignInResponse", "accountTransferPath={0}", AccountTransferPath); return TryHandleAccountTransferPageRedirect(context); } // go straight to ACS return TryHandleImmediateAcsRedirect(context); } // invalid user account return TryHandleUnregisteredUser(context); } public virtual bool TryHandleAccountTransferPageRedirect(HttpContext context) { var transferUri = GetReturnUri(context, AccountTransferPath); TraceInformation("TryHandleAccountTransferPageRedirect", "transferUri={0}", transferUri); var message = new Message(transferUri); message.Parameters.Add(LiveIdTokenKey, context.Request["stoken"]); message.Parameters.Add(ReturnUrlKey, context.Request[ReturnUrlKey]); var post = message.WriteFormPost(); context.Response.Write(post); return true; } public virtual bool TryHandleImmediateAcsRedirect(HttpContext context) { var signInContext = new Dictionary<string, string> { { LiveIdTokenKey, context.Request["stoken"] }, { ReturnUrlKey, context.Request[ReturnUrlKey] }, }; var fam = new CrmFederationAuthenticationModule(context); var signInUrl = fam.GetSignInRequestUrl(signInContext); TraceInformation("TryHandleImmediateAcsRedirect", "signInUrl={0}", signInUrl); context.RedirectAndEndResponse(signInUrl); return true; } public virtual bool TryHandleUnregisteredUser(HttpContext context) { // redirect to the unregistered page var returnPath = RegistrationSettings != null && !string.IsNullOrEmpty(RegistrationSettings.UnregisteredUserPath) ? UnregisteredUserPath : "{0}{1}{2}={3}".FormatWith(RegistrationPath, RegistrationPath.Contains("?") ? "&" : "?", ResultCodeKey, "unregistered"); TraceInformation("TryHandleException", "returnPath={0}", returnPath); context.RedirectAndEndResponse(returnPath); return true; } public virtual bool TryHandleException(HttpContext context, Exception exception) { // redirect to the error page if it is specified if (RegistrationSettings != null && !string.IsNullOrEmpty(RegistrationSettings.ErrorPath)) { var returnPath = ErrorPath; TraceInformation("TryHandleException", "returnPath={0}", returnPath); context.RedirectAndEndResponse(returnPath); return true; } return false; } protected static Uri GetReturnUri(HttpContext context, string path) { var baseUri = context.Request.Url.GetLeftPart(UriPartial.Authority); var returnPath = VirtualPathUtility.ToAbsolute(path); return new Uri(baseUri + returnPath); } private static void TraceInformation(string memberName, string format, params object[] args) { Tracing.FrameworkInformation(_className, memberName, format, args); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.Versioning; using Microsoft.Build.Shared; using Microsoft.Build.Framework; namespace Microsoft.Build.Tasks { /// <summary> /// A reference to an assembly along with information about resolution. /// </summary> sealed internal class Reference { /// <summary> /// dictionary where ITaskItem.ItemSpec (a string) is the key and ITaskItem is the value. /// A hash table is used to remove duplicates. /// All source items that inspired this reference (possibly indirectly through a dependency chain). /// </summary> private Dictionary<string, ITaskItem> _sourceItems = new Dictionary<string, ITaskItem>(StringComparer.OrdinalIgnoreCase); /// <summary> /// A list of unique dependencies. /// </summary> private HashSet<Reference> _dependees = new HashSet<Reference>(); /// <summary> /// Hashset of Reference which depend on this reference /// A list of unique dependencies. /// </summary> private HashSet<Reference> _dependencies = new HashSet<Reference>(); /// <summary> /// Scatter files associated with this reference. /// </summary> private string[] _scatterFiles = Array.Empty<string>(); /// <summary> /// Any errors that occurred while resolving or finding dependencies on this item. /// </summary> private List<Exception> _errors = new List<Exception>(); /// <summary> /// Contains any file extension that are related to this file. Pdbs and xmls are related. /// This is an extension string starting with "." /// </summary> private List<string> _relatedFileExtensions = new List<string>(); /// <summary> /// Contains satellite files for this reference. /// This file path is relative to the location of the reference. /// </summary> private List<string> _satelliteFiles = new List<string>(); /// <summary> /// Contains serialization assembly files for this reference. /// This file path is relative to the location of the reference. /// </summary> private List<string> _serializationAssemblyFiles = new List<string>(); /// <summary> /// AssemblyNames of references that lost collision conflicts with this reference. /// </summary> private List<AssemblyNameExtension> _conflictVictims = new List<AssemblyNameExtension>(); /// <summary> /// These are the versions (type UnificationVersion) that were unified from. /// </summary> private Dictionary<string, UnificationVersion> _preUnificationVersions = new Dictionary<string, UnificationVersion>(StringComparer.OrdinalIgnoreCase); /// <summary> /// The original source item, as passed into the task that is directly associated /// with this reference. This only applies to "primary" references. /// </summary> private ITaskItem _primarySourceItem; /// <summary> /// The full path to the assembly. If this is "", then that means that this reference /// has not been resolved. /// </summary> private string _fullPath = String.Empty; /// <summary> /// The directory that this reference lives in. /// </summary> private string _directoryName = String.Empty; /// <summary> /// The reference's filename without extension. /// </summary> private string _fileNameWithoutExtension = String.Empty; /// <summary> /// The full path to the file name but without the extension. /// </summary> private string _fullPathWithoutExtension = String.Empty; /// <summary> /// The list of expected extensions. /// </summary> private List<string> _expectedExtensions; /// <summary> /// Is the file a managed winmd file. That means it has both windows runtime and CLR in the imageruntime string. /// </summary> private bool _isManagedWinMDFile; /// <summary> /// The imageruntime version for this reference. /// </summary> private string _imageRuntimeVersion; /// <summary> /// Set containing the names the reference was remapped from /// </summary> private HashSet<AssemblyRemapping> _remappedAssemblyNames = new HashSet<AssemblyRemapping>(); /// <summary> /// Delegate to determine if the file is a winmd file or not /// </summary> private IsWinMDFile _isWinMDFile; /// <summary> /// Delegate to check to see if the file exists on disk /// </summary> private FileExists _fileExists; /// <summary> /// Delegate to get the imageruntime version from a file. /// </summary> private GetAssemblyRuntimeVersion _getRuntimeVersion; internal Reference(IsWinMDFile isWinMDFile, FileExists fileExists, GetAssemblyRuntimeVersion getRuntimeVersion) { _isWinMDFile = isWinMDFile; _fileExists = fileExists; _getRuntimeVersion = getRuntimeVersion; } /// <summary> /// Add items that caused (possibly indirectly through a dependency chain) this Reference. /// </summary> internal void AddSourceItem(ITaskItem sourceItem) { string itemSpec = sourceItem.ItemSpec; if (!_sourceItems.ContainsKey(itemSpec)) { _sourceItems[itemSpec] = sourceItem; PropagateSourceItems(sourceItem); } } /// <summary> /// Add items that caused (possibly indirectly through a dependency chain) this Reference. /// </summary> internal void AddSourceItems(IEnumerable<ITaskItem> sourceItemsToAdd) { foreach (ITaskItem sourceItem in sourceItemsToAdd) { AddSourceItem(sourceItem); } } /// <summary> /// We have had our source item list updated, we need to propagate this change to any of our dependencies so they have the new information. /// </summary> internal void PropagateSourceItems(ITaskItem sourceItem) { if (_dependencies != null) { foreach (Reference dependency in _dependencies) { dependency.AddSourceItem(sourceItem); } } } /// <summary> /// Get the source items for this reference. /// This is collection of ITaskItems. /// </summary> internal ICollection<ITaskItem> GetSourceItems() { return _sourceItems.Values; } /// <summary> /// Add a reference which this reference depends on /// </summary> internal void AddDependency(Reference dependency) { if (!_dependencies.Contains(dependency)) { _dependencies.Add(dependency); } } /// <summary> /// Add a reference that caused (possibly indirectly through a dependency chain) this Reference. /// </summary> internal void AddDependee(Reference dependee) { Debug.Assert(dependee.FullPath.Length > 0, "Cannot add dependee that doesn't have a full name. This should have already been resolved."); dependee.AddDependency(this); if (!_dependees.Contains(dependee)) { _dependees.Add(dependee); // When a new dependee is added, this is a new place where a reference might be resolved. // Reset this item so it will be re-resolved if possible. if (IsUnresolvable) { _errors = new List<Exception>(); AssembliesConsideredAndRejected = new List<ResolutionSearchLocation>(); } } } /// <summary> /// A dependee may be removed because it or its dependee's are in the black list /// </summary> internal void RemoveDependee(Reference dependeeToRemove) { _dependees.Remove(dependeeToRemove); } /// <summary> /// A dependency may be removed because it may not be referenced any more due this reference being in the black list or being removed due to it depending on something in the black list /// </summary> internal void RemoveDependency(Reference dependencyToRemove) { _dependencies.Remove(dependencyToRemove); } /// <summary> /// Get the dependee references for this reference. /// This is collection of References. /// </summary> internal HashSet<Reference> GetDependees() { return _dependees; } /// <summary> /// Scatter files associated with this assembly. /// </summary> /// <value></value> internal void AttachScatterFiles(string[] scatterFilesToAttach) { if (scatterFilesToAttach == null || scatterFilesToAttach.Length == 0) { _scatterFiles = Array.Empty<string>(); } else { _scatterFiles = scatterFilesToAttach; } } /// <summary> /// Scatter files associated with this assembly. /// </summary> /// <returns></returns> internal string[] GetScatterFiles() { return _scatterFiles; } /// <summary> /// Set one expected extension for this reference. /// </summary> internal void SetExecutableExtension(string extension) { if (_expectedExtensions == null) { _expectedExtensions = new List<string>(); } else { _expectedExtensions.Clear(); } if (extension.Length > 0 && extension[0] != '.') { extension = '.' + extension; } _expectedExtensions.Add(extension); } /// <summary> /// Get the list of expected extensions. /// </summary> internal string[] GetExecutableExtensions(string[] allowedAssemblyExtensions) { if (_expectedExtensions == null) { // Use the default. return allowedAssemblyExtensions; } return _expectedExtensions.ToArray(); } /// <summary> /// Whether the name needs to match exactly or just the simple name part needs to match. /// </summary> /// <value></value> internal bool WantSpecificVersion { get; private set; } = true; /// <summary> /// Whether types need to be embedded into the target assembly /// </summary> /// <value></value> internal bool EmbedInteropTypes { get; set; } = false; /// <summary> /// This will be true if the user requested a specific file. We know this when the file was resolved /// by hintpath or if it was resolve as a raw file name for example. /// </summary> internal bool UserRequestedSpecificFile { get; set; } = false; /// <summary> /// The version number of this reference /// </summary> internal Version ReferenceVersion { get; set; } = null; /// <summary> /// True if the assembly was found to be in the GAC. /// </summary> internal bool? FoundInGac { get; private set; } /// <summary> /// True if the assembly was resolved through the GAC. Otherwise, false. /// </summary> internal bool ResolvedFromGac { get { return string.Equals(ResolvedSearchPath, AssemblyResolutionConstants.gacSentinel, StringComparison.OrdinalIgnoreCase); } } /// <summary> /// Set of properties for this reference used to log why this reference could not be resolved. /// </summary> internal ExclusionListProperties ExclusionListLoggingProperties { get; } = new ExclusionListProperties(); /// <summary> /// Determines if a given reference or its parent primary references have specific version metadata set to true. /// If anyParentHasMetadata is set to true then we will return true if any parent primary reference has the specific version metadata set to true, /// if the value is false we will return true ONLY if all parent primary references have the metadata set to true. /// </summary> internal bool CheckForSpecificVersionMetadataOnParentsReference(bool anyParentHasMetadata) { bool hasSpecificVersionMetadata = false; // We are our own parent, therefore the specific version metadata is what ever is passed into as wantspecificVersion for this reference. // this saves us from having to read the metadata from our item again. if (IsPrimary) { hasSpecificVersionMetadata = WantSpecificVersion; } else { // Go through all of the primary items which lead to this dependency, if they all have specificVersion set to true then // hasSpecificVersionMetadata will be true. If any item has the metadata set to false or not set then the value will be false. foreach (ITaskItem item in GetSourceItems()) { hasSpecificVersionMetadata = MetadataConversionUtilities.TryConvertItemMetadataToBool(item, ItemMetadataNames.specificVersion); // Break if one of the primary references has specific version false or not set if (anyParentHasMetadata == hasSpecificVersionMetadata) { break; } } } return hasSpecificVersionMetadata; } /// <summary> /// Add a dependency or resolution error to this reference's list of errors. /// </summary> /// <param name="e">The error.</param> internal void AddError(Exception e) { if (e is BadImageReferenceException) { IsBadImage = true; } _errors.Add(e); } /// <summary> /// Return the list of dependency or resolution errors for this item. /// </summary> /// <returns>The collection of resolution errors.</returns> internal List<Exception> GetErrors() { return _errors; } /// <summary> /// Add a new related file to this reference. /// Related files always live in the same directory as the reference. /// Examples include, MyAssembly.pdb and MyAssembly.xml /// </summary> /// <param name="filenameExtension">This is the filename extension.</param> internal void AddRelatedFileExtension(string filenameExtension) { #if DEBUG Debug.Assert(filenameExtension[0]=='.', "Expected extension to start with '.'"); #endif _relatedFileExtensions.Add(filenameExtension); } /// <summary> /// Return the list of related files for this item. /// </summary> /// <returns>The collection of related file extensions.</returns> internal List<string> GetRelatedFileExtensions() { return _relatedFileExtensions; } /// <summary> /// Add a new satellite file /// </summary> /// <param name="filename">This is the filename relative the this reference.</param> internal void AddSatelliteFile(string filename) { #if DEBUG Debug.Assert(!Path.IsPathRooted(filename), "Satellite path should be relative to the current reference."); #endif _satelliteFiles.Add(filename); } /// <summary> /// Add a new serialization assembly file. /// </summary> /// <param name="filename">This is the filename relative the this reference.</param> internal void AddSerializationAssemblyFile(string filename) { #if DEBUG Debug.Assert(!Path.IsPathRooted(filename), "Serialization assembly path should be relative to the current reference."); #endif _serializationAssemblyFiles.Add(filename); } /// <summary> /// Return the list of satellite files for this item. /// </summary> /// <returns>The collection of satellit files.</returns> internal List<string> GetSatelliteFiles() { return _satelliteFiles; } /// <summary> /// Return the list of serialization assembly files for this item. /// </summary> /// <returns>The collection of serialization assembly files.</returns> internal List<string> GetSerializationAssemblyFiles() { return _serializationAssemblyFiles; } /// <summary> /// The full path to the assembly. If this is "", then that means that this reference /// has not been resolved. /// </summary> /// <value>The full path to this assembly.</value> internal string FullPath { get { return _fullPath; } set { if (_fullPath != value) { _fullPath = value; _fullPathWithoutExtension = null; _fileNameWithoutExtension = null; _directoryName = null; if (string.IsNullOrEmpty(_fullPath)) { _scatterFiles = Array.Empty<string>(); _satelliteFiles = new List<string>(); _serializationAssemblyFiles = new List<string>(); AssembliesConsideredAndRejected = new List<ResolutionSearchLocation>(); ResolvedSearchPath = String.Empty; _preUnificationVersions = new Dictionary<string, UnificationVersion>(StringComparer.OrdinalIgnoreCase); IsBadImage = false; DependenciesFound = false; UserRequestedSpecificFile = false; IsWinMDFile = false; } else if (NativeMethodsShared.IsWindows) { IsWinMDFile = _isWinMDFile(_fullPath, _getRuntimeVersion, _fileExists, out _imageRuntimeVersion, out _isManagedWinMDFile); } } } } internal void NormalizeFullPath() { _fullPath = FileUtilities.NormalizePath(_fullPath); _fullPathWithoutExtension = null; _directoryName = null; } /// <summary> /// The directory that this assembly lives in. /// </summary> internal string DirectoryName { get { if ((string.IsNullOrEmpty(_directoryName)) && (!string.IsNullOrEmpty(_fullPath))) { _directoryName = Path.GetDirectoryName(_fullPath); if (_directoryName.Length == 0) { _directoryName = "."; } } return _directoryName; } } /// <summary> /// The file name without extension. /// </summary> /// <value></value> internal string FileNameWithoutExtension { get { if ((string.IsNullOrEmpty(_fileNameWithoutExtension)) && (!string.IsNullOrEmpty(_fullPath))) { _fileNameWithoutExtension = Path.GetFileNameWithoutExtension(_fullPath); } return _fileNameWithoutExtension; } } /// <summary> /// The full path to the assembly but without an extension on the file namee /// </summary> internal string FullPathWithoutExtension { get { if ((string.IsNullOrEmpty(_fullPathWithoutExtension)) && (!string.IsNullOrEmpty(_fullPath))) { _fullPathWithoutExtension = Path.Combine(DirectoryName, FileNameWithoutExtension); } return _fullPathWithoutExtension; } } /// <summary> /// This is the HintPath from the source item. This is used to resolve the assembly. /// </summary> /// <value>The hint path to this assembly.</value> internal string HintPath { get; set; } = ""; /// <summary> /// This is the key that was passed in to the reference through the &lt;AssemblyFolderKey&gt; metadata. /// </summary> /// <value>The &lt;AssemblyFolderKey&gt; value.</value> internal string AssemblyFolderKey { get; set; } = String.Empty; /// <summary> /// Whether this assembly came from the project. If 'false' then this reference was deduced /// through the reference resolution process. /// </summary> /// <value>'true' if this reference is a primary assembly.</value> internal bool IsPrimary { get; private set; } = false; /// <summary> /// Whether or not this reference will be installed on the target machine. /// </summary> internal bool IsPrerequisite { set; get; } = false; /// <summary> /// Whether or not this reference is a redist root. /// </summary> internal bool? IsRedistRoot { set; get; } = null; /// <summary> /// The redist name for this reference (if any) /// </summary> internal string RedistName { set; get; } = null; /// <summary> /// The original source item, as passed into the task that is directly associated /// with this reference. This only applies to "primary" references. /// </summary> internal ITaskItem PrimarySourceItem { get { ErrorUtilities.VerifyThrow( !(IsPrimary && _primarySourceItem == null), "A primary reference must have a primary source item."); ErrorUtilities.VerifyThrow( IsPrimary || _primarySourceItem == null, "Only a primary reference can have a primary source item."); return _primarySourceItem; } } /// <summary> /// If 'true' then the path that this item points to is known to be a bad image. /// This item shouldn't be passed to compilers and so forth. /// </summary> /// <value>'true' if this reference points to a bad image.</value> internal bool IsBadImage { get; private set; } = false; /// <summary> /// If true, then this item conflicted with another item and lost. /// </summary> internal bool IsConflictVictim { get { return ConflictVictorName != null; } } /// <summary> /// Add a conflict victim to this reference /// </summary> internal void AddConflictVictim(AssemblyNameExtension victim) { _conflictVictims.Add(victim); } /// <summary> /// Return the list of conflict victims. /// </summary> internal List<AssemblyNameExtension> GetConflictVictims() { return _conflictVictims; } /// <summary> /// The name of the assembly that won over this reference. /// </summary> internal AssemblyNameExtension ConflictVictorName { get; set; } = null; /// <summary> /// The reason why this reference lost to another reference. /// </summary> internal ConflictLossReason ConflictLossExplanation { get; set; } = ConflictLossReason.DidntLose; /// <summary> /// Is the file a WinMDFile. /// </summary> internal bool IsWinMDFile { get; set; } /// <summary> /// Is the file a Managed. /// </summary> internal bool IsManagedWinMDFile { get { return _isManagedWinMDFile; } set { _isManagedWinMDFile = value; } } /// <summary> /// For winmd files there may be an implementation file sitting beside the winmd called the assemblyName.dll /// We need to attach a piece of metadata to if this is the case. /// </summary> public string ImplementationAssembly { get; set; } /// <summary> /// ImageRuntime Information /// </summary> internal string ImageRuntime { get { return _imageRuntimeVersion; } set { _imageRuntimeVersion = value; } } /// <summary> /// Return the list of versions that this reference is unified from. /// </summary> internal List<UnificationVersion> GetPreUnificationVersions() { return new List<UnificationVersion>(_preUnificationVersions.Values); } /// <summary> /// Return the list of versions that this reference is unified from. /// </summary> internal HashSet<AssemblyRemapping> RemappedAssemblyNames() { return _remappedAssemblyNames; } /// <summary> /// Add a new version number for a version of this reference /// </summary> internal void AddPreUnificationVersion(String referencePath, Version version, UnificationReason reason) { string key = referencePath + version.ToString() + reason.ToString(); // Only add a reference, version, and reason once. UnificationVersion unificationVersion; if (!_preUnificationVersions.TryGetValue(key, out unificationVersion)) { unificationVersion = new UnificationVersion(); unificationVersion.referenceFullPath = referencePath; unificationVersion.version = version; unificationVersion.reason = reason; _preUnificationVersions[key] = unificationVersion; } } /// <summary> /// Add the AssemblyNames name we were remapped from /// </summary> internal void AddRemapping(AssemblyNameExtension remappedFrom, AssemblyNameExtension remappedTo) { ErrorUtilities.VerifyThrow(remappedFrom.Immutable, " Remapped from is NOT immutable"); ErrorUtilities.VerifyThrow(remappedTo.Immutable, " Remapped to is NOT immutable"); _remappedAssemblyNames.Add(new AssemblyRemapping(remappedFrom, remappedTo)); } /// <summary> /// Whether or not this reference is unified from a different version or versions. /// </summary> internal bool IsUnified { get { return _preUnificationVersions.Count != 0; } } /// <summary> /// Whether this reference should be copied to the local 'bin' dir or not and the reason this flag /// was set that way. /// </summary> /// <value>The current copy-local state.</value> internal CopyLocalState CopyLocal { get; private set; } = CopyLocalState.Undecided; /// <summary> /// Whether the reference should be CopyLocal. For the reason, see CopyLocalState. /// </summary> /// <value>'true' if this reference should be copied.</value> internal bool IsCopyLocal { get { return CopyLocalStateUtility.IsCopyLocal(CopyLocal); } } /// <summary> /// Whether this reference has already been resolved. /// Resolved means that the actual filename of the assembly has been found. /// </summary> /// <value>'true' if this reference has been resolved.</value> internal bool IsResolved { get { return _fullPath.Length > 0; } } /// <summary> /// Whether this reference can't be resolve. /// References are usually unresolvable because they weren't found anywhere in the defined search paths. /// </summary> /// <value>'true' if this reference is unresolvable.</value> internal bool IsUnresolvable { // If there are any resolution errors then this reference is unresolvable. get { return !IsResolved && _errors.Count > 0; } } /// <summary> /// Whether or not we still need to find dependencies for this reference. /// </summary> internal bool DependenciesFound { get; set; } = false; /// <summary> /// If the reference has an SDK name metadata this will contain that string. /// </summary> internal string SDKName { get; private set; } = String.Empty; /// <summary> /// Add some records to the table of assemblies that were considered and then rejected. /// </summary> internal void AddAssembliesConsideredAndRejected(List<ResolutionSearchLocation> assembliesConsideredAndRejectedToAdd) { AssembliesConsideredAndRejected.AddRange(assembliesConsideredAndRejectedToAdd); } /// <summary> /// Returns a collection of strings. Each string is the full path to an assembly that was /// considered for resolution but then rejected because it wasn't a complete match. /// </summary> internal List<ResolutionSearchLocation> AssembliesConsideredAndRejected { get; private set; } = new List<ResolutionSearchLocation>(); /// <summary> /// The searchpath location that the reference was found at. /// </summary> internal string ResolvedSearchPath { get; set; } = String.Empty; /// <summary> /// FrameworkName attribute on this reference /// </summary> internal FrameworkName FrameworkNameAttribute { get; set; } /// <summary> /// Indicates that the reference is primary and has ExternallyResolved=true metadata to denote that /// it was resolved by an external system (commonly from nuget). Such a system has already provided a /// resolved closure as primary references and therefore we can skip the expensive closure walk. /// </summary> internal bool ExternallyResolved { get; private set; } /// <summary> /// Make this reference an assembly that is a dependency of 'sourceReference' /// /// For example, if 'sourceReference' is MyAssembly.dll then a dependent assembly file /// might be en\MyAssembly.resources.dll /// /// Assembly references do not have their own dependencies, therefore they are /// </summary> /// <param name="sourceReference">The source reference that this reference will be dependent on</param> internal void MakeDependentAssemblyReference(Reference sourceReference) { CopyLocal = CopyLocalState.Undecided; // This is a true dependency, so its not primary. IsPrimary = false; // This is an assembly file, so we'll need to find dependencies later. DependenciesFound = false; // Dependencies must always be specific version. WantSpecificVersion = true; // Add source items from the original item. AddSourceItems(sourceReference.GetSourceItems()); // Add dependees AddDependee(sourceReference); } /// <summary> /// Make this reference a primary assembly reference. /// This is a refrence that is an assembly and is primary. /// </summary> /// <param name="sourceItem">The source item.</param> /// <param name="wantSpecificVersionValue">Whether the version needs to match exactly or loosely.</param> /// <param name="executableExtension">The filename extension that the resulting assembly must have.</param> internal void MakePrimaryAssemblyReference ( ITaskItem sourceItem, bool wantSpecificVersionValue, string executableExtension ) { CopyLocal = CopyLocalState.Undecided; // This is a primary reference. IsPrimary = true; // This is the source item (from the list passed into the task) that // originally created this reference. _primarySourceItem = sourceItem; SDKName = sourceItem.GetMetadata("SDKName"); if (!string.IsNullOrEmpty(executableExtension)) { // Set the expected extension. SetExecutableExtension(executableExtension); } // The specific version indicator. WantSpecificVersion = wantSpecificVersionValue; // This is an assembly file, so we'll need to find dependencies later. DependenciesFound = false; ExternallyResolved = MetadataConversionUtilities.TryConvertItemMetadataToBool(sourceItem, "ExternallyResolved"); // Add source items from the original item. AddSourceItem(sourceItem); } /// <summary> /// Determine whether the given assembly is an FX assembly. /// </summary> /// <param name="fullPath">The full path to the assembly.</param> /// <param name="frameworkPaths">The path to the frameworks.</param> /// <returns>True if this is a frameworks assembly.</returns> internal static bool IsFrameworkFile(string fullPath, string[] frameworkPaths) { if (frameworkPaths != null) { foreach (string frameworkPath in frameworkPaths) { if ( String.Compare ( frameworkPath, 0, fullPath, 0, frameworkPath.Length, StringComparison.OrdinalIgnoreCase ) == 0 ) { return true; } } } return false; } /// <summary> /// Figure out the what the CopyLocal state of given assembly should be. /// </summary> /// <param name="assemblyName">The name of the assembly.</param> /// <param name="frameworkPaths">The framework paths.</param> /// <param name="targetProcessorArchitecture">Like x86 or IA64\AMD64.</param> /// <param name="getRuntimeVersion">Delegate to get runtime version.</param> /// <param name="targetedRuntimeVersion">The targeted runtime version.</param> /// <param name="fileExists">Delegate to check if a file exists.</param> /// <param name="getAssemblyPathInGac">Delegate to get the path to an assembly in the system GAC.</param> /// <param name="copyLocalDependenciesWhenParentReferenceInGac">if set to true, copy local dependencies when only parent reference in gac.</param> /// <param name="doNotCopyLocalIfInGac">If set to true, do not copy local a reference that exists in the GAC (legacy behavior).</param> /// <param name="referenceTable">The reference table.</param> internal void SetFinalCopyLocalState ( AssemblyNameExtension assemblyName, string[] frameworkPaths, ProcessorArchitecture targetProcessorArchitecture, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntimeVersion, FileExists fileExists, GetAssemblyPathInGac getAssemblyPathInGac, bool copyLocalDependenciesWhenParentReferenceInGac, bool doNotCopyLocalIfInGac, ReferenceTable referenceTable ) { // If this item was unresolvable, then copy-local is false. if (IsUnresolvable) { CopyLocal = CopyLocalState.NoBecauseUnresolved; return; } if (EmbedInteropTypes) { CopyLocal = CopyLocalState.NoBecauseEmbedded; return; } // If this item was a conflict victim, then it should not be copy-local. if (IsConflictVictim) { CopyLocal = CopyLocalState.NoBecauseConflictVictim; return; } // If this is a primary reference then see if there's a Private metadata on the source item if (IsPrimary) { bool found; bool result = MetadataConversionUtilities.TryConvertItemMetadataToBool ( PrimarySourceItem, ItemMetadataNames.privateMetadata, out found ); if (found) { CopyLocal = result ? CopyLocalState.YesBecauseReferenceItemHadMetadata : CopyLocalState.NoBecauseReferenceItemHadMetadata; return; } } else { // This is a dependency. If any primary reference that lead to this dependency // has Private=false, then this dependency should false too. bool privateTrueFound = false; bool privateFalseFound = false; foreach (ITaskItem item in _sourceItems.Values) { bool found; bool result = MetadataConversionUtilities.TryConvertItemMetadataToBool ( item, ItemMetadataNames.privateMetadata, out found ); if (found) { if (result) { privateTrueFound = true; // Once we hit this once we know there will be no modification to CopyLocal state. // so we can immediately... break; } else { privateFalseFound = true; } } } if (privateFalseFound && !privateTrueFound) { CopyLocal = CopyLocalState.NoBecauseReferenceItemHadMetadata; return; } } // If the item was determined to be an prereq assembly. if (IsPrerequisite && !UserRequestedSpecificFile) { CopyLocal = CopyLocalState.NoBecausePrerequisite; return; } // Items in the frameworks directory shouldn't be copy-local if (IsFrameworkFile(_fullPath, frameworkPaths)) { CopyLocal = CopyLocalState.NoBecauseFrameworkFile; return; } // We are a dependency, check to see if all of our parent references have come from the GAC if (!IsPrimary && !copyLocalDependenciesWhenParentReferenceInGac) { // Did we discover a parent reference which was not found in the GAC bool foundSourceItemNotInGac = false; // Go through all of the parent source items and check to see if they were found in the GAC foreach (string key in _sourceItems.Keys) { AssemblyNameExtension primaryAssemblyName = referenceTable.GetReferenceFromItemSpec(key); Reference primaryReference = referenceTable.GetReference(primaryAssemblyName); if (doNotCopyLocalIfInGac) { // Legacy behavior, don't copy local if the assembly is in the GAC at all if (!primaryReference.FoundInGac.HasValue) { primaryReference.FoundInGac = !string.IsNullOrEmpty(getAssemblyPathInGac(primaryAssemblyName, targetProcessorArchitecture, getRuntimeVersion, targetedRuntimeVersion, fileExists, true, false)); } if (!primaryReference.FoundInGac.Value) { foundSourceItemNotInGac = true; break; } } else { if (!primaryReference.ResolvedFromGac) { foundSourceItemNotInGac = true; break; } } } // All parent source items were found in the GAC. if (!foundSourceItemNotInGac) { CopyLocal = CopyLocalState.NoBecauseParentReferencesFoundInGAC; return; } } if (doNotCopyLocalIfInGac) { // Legacy behavior, don't copy local if the assembly is in the GAC at all if (!FoundInGac.HasValue) { FoundInGac = !string.IsNullOrEmpty(getAssemblyPathInGac(assemblyName, targetProcessorArchitecture, getRuntimeVersion, targetedRuntimeVersion, fileExists, true, false)); } if (FoundInGac.Value) { CopyLocal = CopyLocalState.NoBecauseReferenceFoundInGAC; return; } } if (ResolvedFromGac) { CopyLocal = CopyLocalState.NoBecauseReferenceResolvedFromGAC; return; } // It was resolved locally, so copy it. CopyLocal = CopyLocalState.YesBecauseOfHeuristic; } /// <summary> /// Produce a string representation. /// </summary> public override string ToString() { if (IsResolved) { return FullPath; } return "*Unresolved*"; } /// <summary> /// There are a number of properties which are set when we generate exclusion lists and it is useful to have this information on the references so that /// the correct reasons can be logged for these references being in the black list. /// </summary> internal class ExclusionListProperties { /// <summary> /// Is this reference in an exclusion list /// </summary> internal bool IsInExclusionList { get; set; } /// <summary> /// What is the highest version of this assembly in the current redist list /// </summary> internal Version HighestVersionInRedist { get; set; } /// <summary> /// What is the highest versioned redist list on the machine /// </summary> internal string HighestRedistListMonkier { get; set; } /// <summary> /// Delegate which logs the reason for not resolving a reference /// </summary> internal ReferenceTable.LogExclusionReason ExclusionReasonLogDelegate { get; set; } } } }
// 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 Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.errorverifier.errorverifier { public enum ErrorElementId { None, SK_METHOD, // method SK_CLASS, // type SK_NAMESPACE, // namespace SK_FIELD, // field SK_PROPERTY, // property SK_UNKNOWN, // element SK_VARIABLE, // variable SK_EVENT, // event SK_TYVAR, // type parameter SK_ALIAS, // using alias ERRORSYM, // <error> NULL, // <null> GlobalNamespace, // <global namespace> MethodGroup, // method group AnonMethod, // anonymous method Lambda, // lambda expression AnonymousType, // anonymous type } public enum ErrorMessageId { None, BadBinaryOps, // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}' IntDivByZero, // Division by constant zero BadIndexLHS, // Cannot apply indexing with [] to an expression of type '{0}' BadIndexCount, // Wrong number of indices inside []; expected '{0}' BadUnaryOp, // Operator '{0}' cannot be applied to operand of type '{1}' NoImplicitConv, // Cannot implicitly convert type '{0}' to '{1}' NoExplicitConv, // Cannot convert type '{0}' to '{1}' ConstOutOfRange, // Constant value '{0}' cannot be converted to a '{1}' AmbigBinaryOps, // Operator '{0}' is ambiguous on operands of type '{1}' and '{2}' AmbigUnaryOp, // Operator '{0}' is ambiguous on an operand of type '{1}' ValueCantBeNull, // Cannot convert null to '{0}' because it is a non-nullable value type WrongNestedThis, // Cannot access a non-static member of outer type '{0}' via nested type '{1}' NoSuchMember, // '{0}' does not contain a definition for '{1}' ObjectRequired, // An object reference is required for the non-static field, method, or property '{0}' AmbigCall, // The call is ambiguous between the following methods or properties: '{0}' and '{1}' BadAccess, // '{0}' is inaccessible due to its protection level MethDelegateMismatch, // No overload for '{0}' matches delegate '{1}' AssgLvalueExpected, // The left-hand side of an assignment must be a variable, property or indexer NoConstructors, // The type '{0}' has no constructors defined BadDelegateConstructor, // The delegate '{0}' does not have a valid constructor PropertyLacksGet, // The property or indexer '{0}' cannot be used in this context because it lacks the get accessor ObjectProhibited, // Member '{0}' cannot be accessed with an instance reference; qualify it with a type name instead AssgReadonly, // A readonly field cannot be assigned to (except in a constructor or a variable initializer) RefReadonly, // A readonly field cannot be passed ref or out (except in a constructor) AssgReadonlyStatic, // A static readonly field cannot be assigned to (except in a static constructor or a variable initializer) RefReadonlyStatic, // A static readonly field cannot be passed ref or out (except in a static constructor) AssgReadonlyProp, // Property or indexer '{0}' cannot be assigned to -- it is read only AbstractBaseCall, // Cannot call an abstract base member: '{0}' RefProperty, // A property or indexer may not be passed as an out or ref parameter ManagedAddr, // Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}') FixedNotNeeded, // You cannot use the fixed statement to take the address of an already fixed expression UnsafeNeeded, // Dynamic calls cannot be used in conjunction with pointers BadBoolOp, // In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') must have the same return type as the type of its 2 parameters MustHaveOpTF, // The type ('{0}') must contain declarations of operator true and operator false CheckedOverflow, // The operation overflows at compile time in checked mode ConstOutOfRangeChecked, // Constant value '{0}' cannot be converted to a '{1}' (use 'unchecked' syntax to override) AmbigMember, // Ambiguity between '{0}' and '{1}' SizeofUnsafe, // '{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) FieldInitRefNonstatic, // A field initializer cannot reference the non-static field, method, or property '{0}' CallingFinalizeDepracated, // Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available. CallingBaseFinalizeDeprecated, // Do not directly call your base class Finalize method. It is called automatically from your destructor. BadCastInFixed, // The right hand side of a fixed statement assignment may not be a cast expression NoImplicitConvCast, // Cannot implicitly convert type '{0}' to '{1}'. An explicit conversion exists (are you missing a cast?) InaccessibleGetter, // The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible InaccessibleSetter, // The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible BadArity, // Using the generic {1} '{0}' requires '{2}' type arguments BadTypeArgument, // The type '{0}' may not be used as a type argument TypeArgsNotAllowed, // The {1} '{0}' cannot be used with type arguments HasNoTypeVars, // The non-generic {1} '{0}' cannot be used with type arguments NewConstraintNotSatisfied, // '{2}' must be a non-abstract type with a public parameterless constructor in order to use it as parameter '{1}' in the generic type or method '{0}' GenericConstraintNotSatisfiedRefType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no implicit reference conversion from '{3}' to '{1}'. GenericConstraintNotSatisfiedNullableEnum, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. GenericConstraintNotSatisfiedNullableInterface, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. Nullable types can not satisfy any interface constraints. GenericConstraintNotSatisfiedTyVar, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion or type parameter conversion from '{3}' to '{1}'. GenericConstraintNotSatisfiedValType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion from '{3}' to '{1}'. TypeVarCantBeNull, // Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead. BadRetType, // '{1} {0}' has the wrong return type CantInferMethTypeArgs, // The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly. MethGrpToNonDel, // Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method? RefConstraintNotSatisfied, // The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}' ValConstraintNotSatisfied, // The type '{2}' must be a non-nullable value type in order to use it as parameter '{1}' in the generic type or method '{0}' CircularConstraint, // Circular constraint dependency involving '{0}' and '{1}' BaseConstraintConflict, // Type parameter '{0}' inherits conflicting constraints '{1}' and '{2}' ConWithValCon, // Type parameter '{1}' has the 'struct' constraint so '{1}' cannot be used as a constraint for '{0}' AmbigUDConv, // Ambiguous user defined conversions '{0}' and '{1}' when converting from '{2}' to '{3}' PredefinedTypeNotFound, // Predefined type '{0}' is not defined or imported PredefinedTypeBadType, // Predefined type '{0}' is declared incorrectly BindToBogus, // '{0}' is not supported by the language CantCallSpecialMethod, // '{0}': cannot explicitly call operator or accessor BogusType, // '{0}' is a type not supported by the language MissingPredefinedMember, // Missing compiler required member '{0}.{1}' LiteralDoubleCast, // Literal of type double cannot be implicitly converted to type '{1}'; use an '{0}' suffix to create a literal of this type UnifyingInterfaceInstantiations, // '{0}' cannot implement both '{1}' and '{2}' because they may unify for some type parameter substitutions ConvertToStaticClass, // Cannot convert to static type '{0}' GenericArgIsStaticClass, // '{0}': static types cannot be used as type arguments PartialMethodToDelegate, // Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration IncrementLvalueExpected, // The operand of an increment or decrement operator must be a variable, property or indexer NoSuchMemberOrExtension, // '{0}' does not contain a definition for '{1}' and no extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?) ValueTypeExtDelegate, // Extension methods '{0}' defined on value type '{1}' cannot be used to create delegates BadArgCount, // No overload for method '{0}' takes '{1}' arguments BadArgTypes, // The best overloaded method match for '{0}' has some invalid arguments BadArgType, // Argument '{0}': cannot convert from '{1}' to '{2}' RefLvalueExpected, // A ref or out argument must be an assignable variable BadProtectedAccess, // Cannot access protected member '{0}' via a qualifier of type '{1}'; the qualifier must be of type '{2}' (or derived from it) BindToBogusProp2, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor methods '{1}' or '{2}' BindToBogusProp1, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor method '{1}' BadDelArgCount, // Delegate '{0}' does not take '{1}' arguments BadDelArgTypes, // Delegate '{0}' has some invalid arguments AssgReadonlyLocal, // Cannot assign to '{0}' because it is read-only RefReadonlyLocal, // Cannot pass '{0}' as a ref or out argument because it is read-only ReturnNotLValue, // Cannot modify the return value of '{0}' because it is not a variable BadArgExtraRef, // Argument '{0}' should not be passed with the '{1}' keyword // DelegateOnConditional, // Cannot create delegate with '{0}' because it has a Conditional attribute (REMOVED) BadArgRef, // Argument '{0}' must be passed with the '{1}' keyword AssgReadonly2, // Members of readonly field '{0}' cannot be modified (except in a constructor or a variable initializer) RefReadonly2, // Members of readonly field '{0}' cannot be passed ref or out (except in a constructor) AssgReadonlyStatic2, // Fields of static readonly field '{0}' cannot be assigned to (except in a static constructor or a variable initializer) RefReadonlyStatic2, // Fields of static readonly field '{0}' cannot be passed ref or out (except in a static constructor) AssgReadonlyLocalCause, // Cannot assign to '{0}' because it is a '{1}' RefReadonlyLocalCause, // Cannot pass '{0}' as a ref or out argument because it is a '{1}' ThisStructNotInAnonMeth, // Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead. DelegateOnNullable, // Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<T>' BadCtorArgCount, // '{0}' does not contain a constructor that takes '{1}' arguments BadExtensionArgTypes, // '{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' has some invalid arguments BadInstanceArgType, // Instance argument: cannot convert from '{0}' to '{1}' BadArgTypesForCollectionAdd, // The best overloaded Add method '{0}' for the collection initializer has some invalid arguments InitializerAddHasParamModifiers, // The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters. NonInvocableMemberCalled, // Non-invocable member '{0}' cannot be used like a method. NamedArgumentSpecificationBeforeFixedArgument, // Named argument specifications must appear after all fixed arguments have been specified BadNamedArgument, // The best overload for '{0}' does not have a parameter named '{1}' BadNamedArgumentForDelegateInvoke, // The delegate '{0}' does not have a parameter named '{1}' DuplicateNamedArgument, // Named argument '{0}' cannot be specified multiple times NamedArgumentUsedInPositional, // Named argument '{0}' specifies a parameter for which a positional argument has already been given } public enum RuntimeErrorId { None, // RuntimeBinderInternalCompilerException InternalCompilerError, // An unexpected exception occurred while binding a dynamic operation // ArgumentException BindRequireArguments, // Cannot bind call with no calling object // RuntimeBinderException BindCallFailedOverloadResolution, // Overload resolution failed // ArgumentException BindBinaryOperatorRequireTwoArguments, // Binary operators must be invoked with two arguments // ArgumentException BindUnaryOperatorRequireOneArgument, // Unary operators must be invoked with one argument // RuntimeBinderException BindPropertyFailedMethodGroup, // The name '{0}' is bound to a method and cannot be used like a property // RuntimeBinderException BindPropertyFailedEvent, // The event '{0}' can only appear on the left hand side of += or -= // RuntimeBinderException BindInvokeFailedNonDelegate, // Cannot invoke a non-delegate type // ArgumentException BindImplicitConversionRequireOneArgument, // Implicit conversion takes exactly one argument // ArgumentException BindExplicitConversionRequireOneArgument, // Explicit conversion takes exactly one argument // ArgumentException BindBinaryAssignmentRequireTwoArguments, // Binary operators cannot be invoked with one argument // RuntimeBinderException BindBinaryAssignmentFailedNullReference, // Cannot perform member assignment on a null reference // RuntimeBinderException NullReferenceOnMemberException, // Cannot perform runtime binding on a null reference // RuntimeBinderException BindCallToConditionalMethod, // Cannot dynamically invoke method '{0}' because it has a Conditional attribute // RuntimeBinderException BindToVoidMethodButExpectResult, // Cannot implicitly convert type 'void' to 'object' // EE? EmptyDynamicView, // No further information on this object could be discovered // MissingMemberException GetValueonWriteOnlyProperty, // Write Only properties are not supported } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.param012.param012 { // <Title>Call methods that have different parameter modifiers with dynamic</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //<Expects Status=warning>\(23,23\).*CS0649</Expects> public struct myStruct { public int Field; } public class Foo { public int this[params int[] x] { get { return 1; } } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Foo f = new Foo(); dynamic d = "foo"; try { var rez = f[d]; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.param014.param014 { // <Title>Call methods that have different parameter modifiers with dynamic</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public struct myStruct { public int Field; } public class Foo { public int this[params int[] x] { get { return 1; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Foo f = new Foo(); dynamic d = "foo"; dynamic d2 = 3; try { var rez = f[d2, d]; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { return 0; } return 1; } } // </Code> }
// 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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AndDouble() { var test = new SimpleBinaryOpTest__AndDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AndDouble { private const int VectorSize = 32; private const int ElementCount = VectorSize / sizeof(Double); private static Double[] _data1 = new Double[ElementCount]; private static Double[] _data2 = new Double[ElementCount]; private static Vector256<Double> _clsVar1; private static Vector256<Double> _clsVar2; private Vector256<Double> _fld1; private Vector256<Double> _fld2; private SimpleBinaryOpTest__DataTable<Double> _dataTable; static SimpleBinaryOpTest__AndDouble() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__AndDouble() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Double>(_data1, _data2, new Double[ElementCount], VectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.And( Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx.And( Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx.And( Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx).GetMethod(nameof(Avx.And), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx).GetMethod(nameof(Avx.And), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx).GetMethod(nameof(Avx.And), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx.And( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr); var result = Avx.And(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.And(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.And(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__AndDouble(); var result = Avx.And(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx.And(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Double> left, Vector256<Double> right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[ElementCount]; Double[] inArray2 = new Double[ElementCount]; Double[] outArray = new Double[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[ElementCount]; Double[] inArray2 = new Double[ElementCount]; Double[] outArray = new Double[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { if ((BitConverter.DoubleToInt64Bits(left[0]) & BitConverter.DoubleToInt64Bits(right[0])) != BitConverter.DoubleToInt64Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if ((BitConverter.DoubleToInt64Bits(left[i]) & BitConverter.DoubleToInt64Bits(right[i])) != BitConverter.DoubleToInt64Bits(result[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.And)}<Double>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public enum _EffectType{DirectPositive, DirectNegative, Buff, Debuff} //~ public enum _AbilityTargetType{ //~ Self, //~ SelfTile, //~ Hostile, //~ Friendly, //~ Tile //~ } public enum _TargetArea{Default, Line, Cone} public enum _AbilityTargetType{ AllUnits, Friendly, Hostile, AllTile, EmptyTile, } public enum _EffectAttrType{ HPDamage, HPGain, APDamage, APGain, Damage, MovementRange, AttackRange, TurnPriority, HitChance, DodgeChance, CriticalChance, CriticalImmunity, ExtraAttack, ExtraCounterAttack, Stun, DisableAttack, DisableMovement, DisableAbility, //Panic, PointGain, Teleport, SpawnUnit, ChangeTargetFaction, SpawnCollectible, } public enum _AbilityShootMode{None, ShootToCenter, ShootToAll}; [System.Serializable] public class EffectAttr{ public _EffectAttrType type; public bool useDefaultDamageValue=true; public float value; public float valueAlt; public int duration; public int damageType; //public Texture icon; public int cd; public UnitTB unit; public CollectibleTB collectible; public EffectAttr Clone(){ EffectAttr effectAttr=new EffectAttr(); effectAttr.type=type; effectAttr.useDefaultDamageValue=useDefaultDamageValue; effectAttr.value=value; effectAttr.valueAlt=valueAlt; effectAttr.duration=duration; effectAttr.damageType=damageType; effectAttr.unit=unit; effectAttr.collectible=collectible; return effectAttr; } } [System.Serializable] public class Effect{ public int ID=-1; public string name=""; public string desp=""; public Texture icon; public string iconName=""; //~ public int duration=1; //public bool isBuff=true; public _EffectType effectType; public List<EffectAttr> effectAttrs=new List<EffectAttr>(); //fill up to total unit/faction count when the effect is applied, reduced at every player's turn or full unit turn cycle //when the value reach zero, effect duraction-=1; public int countTillNextTurn=1; } //~ public class CollectibleAbility : Ability{ //~ public bool enableAOE=false; //~ public int aoeRange=1; //~ } [System.Serializable] public class UnitAbility : Effect{ public Texture iconUnavailable; public string iconUnavailableName=""; public _AbilityTargetType targetType; public bool requireTargetSelection=true; public bool enableMovementAfter=true; public bool enableAttackAfter=true; public int factionID; public bool canMiss=false; public float missChance=0.15f; public bool stackMissWithDodge=true; public bool canFail=false; public float failChance=0.15f; public List<int> chainedAbilityIDList=new List<int>(); public _TargetArea targetArea; public bool enableAOE=false; public int aoeRange=1; //~ public _AOETypeHex aoe=_AOETypeHex.None; public int range=3; public int cost=2; public int totalCost; public int cdDuration=2; public int cooldown=0; public int useLimit=-1; public int useCount=0; public float delay=0; public GameObject effectUse; public GameObject effectTarget; public float effectUseDelay=0; public float effectTargetDelay=0; public AudioClip soundUse; public AudioClip soundHit; public _AbilityShootMode shootMode; public GameObject shootObject; public UnitAbility Clone(){ UnitAbility UAb=new UnitAbility(); UAb.ID=ID; UAb.name=name; UAb.desp=desp; UAb.icon=icon; UAb.iconUnavailable=iconUnavailable; UAb.iconName=iconName; UAb.iconUnavailableName=iconUnavailableName; UAb.factionID=factionID; UAb.targetArea=targetArea; UAb.targetType=targetType; UAb.requireTargetSelection=requireTargetSelection; UAb.enableMovementAfter=enableMovementAfter; UAb.enableAttackAfter=enableAttackAfter; UAb.effectType=effectType; UAb.enableAOE=enableAOE; UAb.aoeRange=aoeRange; //~ UAb.aoe=aoe; UAb.range=range; //~ UAb.duration=duration; UAb.cost=cost; UAb.totalCost=totalCost; UAb.cdDuration=cdDuration; UAb.cooldown=cooldown; UAb.useLimit=useLimit; UAb.useCount=useCount; foreach(EffectAttr effectAttr in effectAttrs){ UAb.effectAttrs.Add(effectAttr.Clone()); } UAb.delay=delay; //~ UAb.effect=effect; UAb.effectUse=effectUse; UAb.effectTarget=effectTarget; UAb.effectUseDelay=effectUseDelay; UAb.effectTargetDelay=effectTargetDelay; UAb.soundUse=soundUse; UAb.soundHit=soundHit; UAb.shootMode=shootMode; UAb.shootObject=shootObject; UAb.canMiss=canMiss; UAb.canFail=canFail; UAb.missChance=missChance; UAb.failChance=failChance; UAb.chainedAbilityIDList=chainedAbilityIDList; return UAb; } //~ public UnitAbility(int id, string n, string d, int c, int cd, int lim){ //~ ID=id; //~ name=n; //~ desp=d; //~ cost=c; //~ cooldown=cd; //~ limit=lim; //~ } } public class AbilityManagerTB : MonoBehaviour { public static List<UnitAbility> unitAbilityList=new List<UnitAbility>(); //public UnitAbility ability; public static void LoadUnitAbility(){ GameObject obj=Resources.Load("PrefabList/UnitAbilityListPrefab", typeof(GameObject)) as GameObject; if(obj==null){ Debug.Log("load unit ability fail, make sure the resource file exists"); return; } UnitAbilityListPrefab prefab=obj.GetComponent<UnitAbilityListPrefab>(); unitAbilityList=prefab.unitAbilityList; } public static UnitAbility GetUnitAbility(int ID){ foreach(UnitAbility uAB in unitAbilityList){ if(uAB.ID==ID){ return uAB.Clone(); } } return null; } public static void HealAllFriendlyUnit(int factionID){ List<UnitTB> list=UnitControl.GetAllUnitsOfFaction(factionID); foreach(UnitTB unit in list){ int val=Random.Range(2, 6); unit.ApplyHeal(val); } } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
using System; using System.Collections.Generic; using NiL.JS.Core; using NiL.JS.Statements; using NiL.JS.Core.Interop; namespace NiL.JS { [Flags] public enum Options { None = 0, SuppressUselessExpressionsElimination = 1, SuppressUselessStatementsElimination = 2, SuppressConstantPropogation = 4, } /// <summary> /// Represents and manages JavaScript module /// </summary> #if !PORTABLE [Serializable] #endif public class Module { private static readonly char[] __pathSplitChars = new[] { '\\', '/' }; private static readonly StringMap<Module> __modulesCache = new StringMap<Module>(); private static List<ResolveModuleHandler> __resolveModuleHandlers = new List<ResolveModuleHandler> { defaultModuleResolver }; /// <summary> /// Occurs when module not found in cache /// </summary> public static event ResolveModuleHandler ResolveModule { add { if (value != null) lock (__resolveModuleHandlers) __resolveModuleHandlers.Add(value); } remove { lock (__resolveModuleHandlers) __resolveModuleHandlers.Remove(value); } } public ExportTable Exports { get; } = new ExportTable(); private CodeBlock _root; /// <summary> /// Root node of AST /// </summary> public CodeBlock Root { get { return _root; } } /// <summary> /// JavaScript code, used for initialization /// </summary> public string Code { get; private set; } /// <summary> /// Root context of module /// </summary> public Context Context { get; private set; } /// <summary> /// Path to file with script /// </summary> public string FilePath { get; private set; } /// <summary> /// Initializes a new Module with specified code. /// </summary> /// <param name="code">JavaScript code.</param> public Module(string code) : this(code, null, Options.None) { } /// <summary> /// Initializes a new Module with specified code. /// </summary> /// <param name="path">Path to file with script. Used for resolving paths to other modules for importing via import directive. Can be null or empty</param> /// <param name="code">JavaScript code.</param> public Module(string path, string code) : this(path, code, null, Options.None) { } /// <summary> /// Initializes a new Module with specified code and callback for output compiler messages. /// </summary> /// <param name="code">JavaScript code.</param> /// <param name="messageCallback">Callback used to output compiler messages</param> public Module(string code, CompilerMessageCallback messageCallback) : this(code, messageCallback, Options.None) { } /// <summary> /// Initializes a new Module with specified code and callback for output compiler messages. /// </summary> /// <param name="path">Path to file with script. Used for resolving paths to other modules for importing via import directive. Can be null or empty</param> /// <param name="code">JavaScript code.</param> /// <param name="messageCallback">Callback used to output compiler messages</param> public Module(string path, string code, CompilerMessageCallback messageCallback) : this(path, code, messageCallback, Options.None) { } /// <summary> /// Initializes a new Module with specified code, callback for output compiler messages and compiler options. /// </summary> /// <param name="code">JavaScript code.</param> /// <param name="messageCallback">Callback used to output compiler messages or null</param> /// <param name="options">Compiler options</param> public Module(string code, CompilerMessageCallback messageCallback, Options options) : this(null, code, messageCallback, options) { } /// <summary> /// Initializes a new Module with specified code, callback for output compiler messages and compiler options. /// </summary> /// <param name="path">Path to file with script. Used for resolving paths to other modules for importing via import directive. Can be null or empty</param> /// <param name="code">JavaScript code.</param> /// <param name="messageCallback">Callback used to output compiler messages or null</param> /// <param name="options">Compiler options</param> public Module(string path, string code, CompilerMessageCallback messageCallback, Options options) { if (code == null) throw new ArgumentNullException(); Code = code; Context = new Context(Context.CurrentBaseContext, true, null); Context._module = this; if (!string.IsNullOrWhiteSpace(path)) { lock (__modulesCache) { if (!__modulesCache.ContainsKey(path)) __modulesCache[path] = this; } FilePath = path; } if (code == "") return; int i = 0; _root = (CodeBlock)CodeBlock.Parse(new ParseInfo(Tools.removeComments(code, 0), Code, messageCallback), ref i); CompilerMessageCallback icallback = messageCallback != null ? (level, cord, message) => { messageCallback(level, CodeCoordinates.FromTextPosition(code, cord.Column, cord.Length), message); } : null as CompilerMessageCallback; var stat = new FunctionInfo(); Parser.Build(ref _root, 0, new Dictionary<string, VariableDescriptor>(), CodeContext.None, icallback, stat, options); var body = _root as CodeBlock; body._suppressScopeIsolation = SuppressScopeIsolationMode.Suppress; Context._thisBind = new GlobalObject(Context); Context._strict = body._strict; var tv = stat.WithLexicalEnvironment ? null : new Dictionary<string, VariableDescriptor>(); body.RebuildScope(stat, tv, body._variables.Length == 0 || !stat.WithLexicalEnvironment ? 1 : 0); var bd = body as CodeNode; body.Optimize(ref bd, null, icallback, options, stat); if (tv != null) body._variables = new List<VariableDescriptor>(tv.Values).ToArray(); if (stat.NeedDecompose) body.Decompose(ref bd); } public Module() : this("") { } /// <summary> /// Run the script /// </summary> public void Run() { if (Code == "") return; try { Context.Activate(); _root.Evaluate(Context); } finally { Context.Deactivate(); } } /// <summary> /// Run the script with time limit /// </summary> /// <param name="timeLimitInMilliseconds">Time limit</param> public void Run(int timeLimitInMilliseconds) { var start = Environment.TickCount; var oldDebugValue = Context.Debugging; Context.Debugging = true; DebuggerCallback callback = (context, e) => { if (Environment.TickCount - start >= timeLimitInMilliseconds) throw new TimeoutException(); }; Context.DebuggerCallback += callback; try { Run(); } finally { Context.Debugging = oldDebugValue; Context.DebuggerCallback -= callback; } } internal Module Import(string path) { path = processPath(path); var e = new ResolveModuleEventArgs(path); for (var i = 0; i < __resolveModuleHandlers.Count && e.Module == null; i++) __resolveModuleHandlers[i](this, e); if (e.Module != null && e.AddToCache && !__modulesCache.ContainsKey(e.ModulePath)) __modulesCache[e.ModulePath] = e.Module; if (e.Module.FilePath == null) e.Module.FilePath = path; return e.Module; } private string processPath(string path) { var thisName = this.FilePath.Split(__pathSplitChars); var requestedName = path.Split(__pathSplitChars); var pathTokens = new LinkedList<string>(thisName); if (requestedName.Length > 0 && requestedName[0] == "") pathTokens.Clear(); else pathTokens.RemoveLast(); for (var i = 0; i < requestedName.Length; i++) pathTokens.AddLast(requestedName[i]); for (var node = pathTokens.First; node != null;) { if (node.Value == "." || node.Value == "") { node = node.Next; pathTokens.Remove(node.Previous); } else if (node.Value == ".." && node.Previous != null) { node = node.Next; pathTokens.Remove(node.Previous); pathTokens.Remove(node.Previous); } else node = node.Next; } if (pathTokens.Last.Value.IndexOf('.') == -1) pathTokens.Last.Value = pathTokens.Last.Value + ".js"; pathTokens.AddFirst(""); path = string.Join("/", pathTokens); return path; } private static void defaultModuleResolver(Module sender, ResolveModuleEventArgs e) { Module result; __modulesCache.TryGetValue(e.ModulePath, out result); e.Module = result; } public static void ClearModuleCache() { lock (__modulesCache) { __modulesCache.Clear(); } } public static bool RemoveFromModuleCache(string path) { lock (__modulesCache) { return __modulesCache.Remove(path); } } #if !PORTABLE /// <summary> /// Returns module, which provides access to clr-namespace /// </summary> /// <param name="namespace">Namespace</param> /// <returns></returns> public static Module ClrNamespace(string @namespace) { var result = new Module(); foreach (var type in NamespaceProvider.GetTypesByPrefix(@namespace)) { try { if (type.Namespace == @namespace) { result.Exports[type.Name] = Context.CurrentBaseContext.GetConstructor(type); } else if (type.Namespace.StartsWith(@namespace) && type.Namespace[@namespace.Length] == '.') { var nextSegment = type.Namespace.Substring(@namespace.Length).Split('.')[1]; result.Exports[nextSegment] = new NamespaceProvider($"{@namespace}.{nextSegment}"); } } catch { } } return result; } #endif } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** ** ** PURPOSE: Parse "Elementary XML", that is, XML without ** attributes or DTDs, in other words, XML with ** elements only. ** ** ===========================================================*/ namespace System.Security.Util { using System.Text; using System.Runtime.InteropServices; using System; using BinaryReader = System.IO.BinaryReader ; using ArrayList = System.Collections.ArrayList; using Stream = System.IO.Stream; using StreamReader = System.IO.StreamReader; using Encoding = System.Text.Encoding; sealed internal class Parser { private SecurityDocument _doc; private Tokenizer _t; internal SecurityElement GetTopElement() { return _doc.GetRootElement(); } private const short c_flag = 0x4000; private const short c_elementtag = (short)(SecurityDocument.c_element << 8 | c_flag); private const short c_attributetag = (short)(SecurityDocument.c_attribute << 8 | c_flag); private const short c_texttag = (short)(SecurityDocument.c_text << 8 | c_flag); private const short c_additionaltexttag = (short)(SecurityDocument.c_text << 8 | c_flag | 0x2000); private const short c_childrentag = (short)(SecurityDocument.c_children << 8 | c_flag); private const short c_wastedstringtag = (short)(0x1000 | c_flag); private void GetRequiredSizes( TokenizerStream stream, ref int index ) { // // Iteratively collect stuff up until the next end-tag. // We've already seen the open-tag. // bool needToBreak = false; bool needToPop = false; bool createdNode = false; bool intag = false; int stackDepth = 1; SecurityElementType type = SecurityElementType.Regular; String strValue = null; bool sawEquals = false; bool sawText = false; int status = 0; short i; do { for (i = stream.GetNextToken() ; i != -1 ; i = stream.GetNextToken()) { switch (i & 0x00FF) { case Tokenizer.cstr: { if (intag) { if (type == SecurityElementType.Comment) { // Ignore data in comments but still get the data // to keep the stream in the right place. stream.ThrowAwayNextString(); stream.TagLastToken( c_wastedstringtag ); } else { // We're in a regular tag, so we've found an attribute/value pair. if (strValue == null) { // Found attribute name, save it for later. strValue = stream.GetNextString(); } else { // Found attribute text, add the pair to the current element. if (!sawEquals) throw new XmlSyntaxException( _t.LineNo ); stream.TagLastToken( c_attributetag ); index += SecurityDocument.EncodedStringSize( strValue ) + SecurityDocument.EncodedStringSize( stream.GetNextString() ) + 1; strValue = null; sawEquals = false; } } } else { // We're not in a tag, so we've found text between tags. if (sawText) { stream.TagLastToken( c_additionaltexttag ); index += SecurityDocument.EncodedStringSize( stream.GetNextString() ) + SecurityDocument.EncodedStringSize( " " ); } else { stream.TagLastToken( c_texttag ); index += SecurityDocument.EncodedStringSize( stream.GetNextString() ) + 1; sawText = true; } } } break; case Tokenizer.bra: intag = true; sawText = false; i = stream.GetNextToken(); if (i == Tokenizer.slash) { stream.TagLastToken( c_childrentag ); while (true) { // spin; don't care what's in here i = stream.GetNextToken(); if (i == Tokenizer.cstr) { stream.ThrowAwayNextString(); stream.TagLastToken( c_wastedstringtag ); } else if (i == -1) throw new XmlSyntaxException (_t.LineNo, Environment.GetResourceString( "XMLSyntax_UnexpectedEndOfFile" )); else break; } if (i != Tokenizer.ket) { throw new XmlSyntaxException (_t.LineNo, Environment.GetResourceString( "XMLSyntax_ExpectedCloseBracket" )); } intag = false; // Found the end of this element index++; sawText = false; stackDepth--; needToBreak = true; } else if (i == Tokenizer.cstr) { // Found a child createdNode = true; stream.TagLastToken( c_elementtag ); index += SecurityDocument.EncodedStringSize( stream.GetNextString() ) + 1; if (type != SecurityElementType.Regular) throw new XmlSyntaxException( _t.LineNo ); needToBreak = true; stackDepth++; } else if (i == Tokenizer.bang) { // Found a child that is a comment node. Next up better be a cstr. status = 1; do { i = stream.GetNextToken(); switch (i) { case Tokenizer.bra: status++; break; case Tokenizer.ket: status--; break; case Tokenizer.cstr: stream.ThrowAwayNextString(); stream.TagLastToken( c_wastedstringtag ); break; default: break; } } while (status > 0); intag = false; sawText = false; needToBreak = true; } else if (i == Tokenizer.quest) { // Found a child that is a format node. Next up better be a cstr. i = stream.GetNextToken(); if (i != Tokenizer.cstr) throw new XmlSyntaxException( _t.LineNo ); createdNode = true; type = SecurityElementType.Format; stream.TagLastToken( c_elementtag ); index += SecurityDocument.EncodedStringSize( stream.GetNextString() ) + 1; status = 1; stackDepth++; needToBreak = true; } else { throw new XmlSyntaxException (_t.LineNo, Environment.GetResourceString( "XMLSyntax_ExpectedSlashOrString" )); } break ; case Tokenizer.equals: sawEquals = true; break; case Tokenizer.ket: if (intag) { intag = false; continue; } else { throw new XmlSyntaxException (_t.LineNo, Environment.GetResourceString( "XMLSyntax_UnexpectedCloseBracket" )); } // not reachable case Tokenizer.slash: i = stream.GetNextToken(); if (i == Tokenizer.ket) { // Found the end of this element stream.TagLastToken( c_childrentag ); index++; stackDepth--; sawText = false; needToBreak = true; } else { throw new XmlSyntaxException (_t.LineNo, Environment.GetResourceString( "XMLSyntax_ExpectedCloseBracket" )); } break; case Tokenizer.quest: if (intag && type == SecurityElementType.Format && status == 1) { i = stream.GetNextToken(); if (i == Tokenizer.ket) { stream.TagLastToken( c_childrentag ); index++; stackDepth--; sawText = false; needToBreak = true; } else { throw new XmlSyntaxException (_t.LineNo, Environment.GetResourceString( "XMLSyntax_ExpectedCloseBracket" )); } } else { throw new XmlSyntaxException (_t.LineNo); } break; case Tokenizer.dash: default: throw new XmlSyntaxException (_t.LineNo) ; } if (needToBreak) { needToBreak = false; needToPop = false; break; } else { needToPop = true; } } if (needToPop) { index++; stackDepth--; sawText = false; } else if (i == -1 && (stackDepth != 1 || !createdNode)) { // This means that we still have items on the stack, but the end of our // stream has been reached. throw new XmlSyntaxException( _t.LineNo, Environment.GetResourceString( "XMLSyntax_UnexpectedEndOfFile" )); } } while (stackDepth > 1); } private int DetermineFormat( TokenizerStream stream ) { if (stream.GetNextToken() == Tokenizer.bra) { if (stream.GetNextToken() == Tokenizer.quest) { _t.GetTokens( stream, -1, true ); stream.GoToPosition( 2 ); bool sawEquals = false; bool sawEncoding = false; short i; for (i = stream.GetNextToken(); i != -1 && i != Tokenizer.ket; i = stream.GetNextToken()) { switch (i) { case Tokenizer.cstr: if (sawEquals && sawEncoding) { _t.ChangeFormat( System.Text.Encoding.GetEncoding( stream.GetNextString() ) ); return 0; } else if (!sawEquals) { if (String.Compare( stream.GetNextString(), "encoding", StringComparison.Ordinal) == 0) sawEncoding = true; } else { sawEquals = false; sawEncoding = false; stream.ThrowAwayNextString(); } break; case Tokenizer.equals: sawEquals = true; break; default: throw new XmlSyntaxException (_t.LineNo, Environment.GetResourceString( "XMLSyntax_UnexpectedEndOfFile" )); } } return 0; } } return 2; } private void ParseContents() { short i; TokenizerStream stream = new TokenizerStream(); _t.GetTokens( stream, 2, false ); stream.Reset(); int gotoPosition = DetermineFormat( stream ); stream.GoToPosition( gotoPosition ); _t.GetTokens( stream, -1, false ); stream.Reset(); int neededIndex = 0; GetRequiredSizes( stream, ref neededIndex ); _doc = new SecurityDocument( neededIndex ); int position = 0; stream.Reset(); for (i = stream.GetNextFullToken(); i != -1; i = stream.GetNextFullToken()) { if ((i & c_flag) != c_flag) continue; else { switch((short)(i & 0xFF00)) { case c_elementtag: _doc.AddToken( SecurityDocument.c_element, ref position ); _doc.AddString( stream.GetNextString(), ref position ); break; case c_attributetag: _doc.AddToken( SecurityDocument.c_attribute, ref position ); _doc.AddString( stream.GetNextString(), ref position ); _doc.AddString( stream.GetNextString(), ref position ); break; case c_texttag: _doc.AddToken( SecurityDocument.c_text, ref position ); _doc.AddString( stream.GetNextString(), ref position ); break; case c_additionaltexttag: _doc.AppendString( " ", ref position ); _doc.AppendString( stream.GetNextString(), ref position ); break; case c_childrentag: _doc.AddToken( SecurityDocument.c_children, ref position ); break; case c_wastedstringtag: stream.ThrowAwayNextString(); break; default: throw new XmlSyntaxException(); } } } } private Parser(Tokenizer t) { _t = t; _doc = null; try { ParseContents(); } finally { _t.Recycle(); } } internal Parser (String input) : this (new Tokenizer (input)) { } internal Parser (String input, String[] searchStrings, String[] replaceStrings) : this (new Tokenizer (input, searchStrings, replaceStrings)) { } internal Parser( byte[] array, Tokenizer.ByteTokenEncoding encoding ) : this (new Tokenizer( array, encoding, 0 ) ) { } internal Parser( byte[] array, Tokenizer.ByteTokenEncoding encoding, int startIndex ) : this (new Tokenizer( array, encoding, startIndex ) ) { } internal Parser( StreamReader input ) : this (new Tokenizer( input ) ) { } internal Parser( char[] array ) : this (new Tokenizer( array ) ) { } } }
// *********************************************************************** // Copyright (c) 2014 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Reflection; using NUnit.Framework; using NUnit.Framework.Internal; using NUnitLite; namespace NUnit.Tests { namespace Assemblies { /// <summary> /// MockAssembly is intended for those few tests that can only /// be made to work by loading an entire assembly. Please don't /// add any other entries or use it for other purposes. /// /// Most tests used as data for NUnit's own tests should be /// in the testdata assembly. /// </summary> public class MockAssembly { /// <summary> /// Constant definitions used by tests that both reference the /// mock-assembly and load it in order to verify counts. /// </summary> public const string FileName = "mock.nunit.assembly.exe"; public const int Classes = 9; public const int NamespaceSuites = 6; // assembly, NUnit, Tests, Assemblies, Singletons, TestAssembly public const int Tests = MockTestFixture.Tests + Singletons.OneTestCase.Tests + TestAssembly.MockTestFixture.Tests + IgnoredFixture.Tests + ExplicitFixture.Tests + BadFixture.Tests + FixtureWithTestCases.Tests + ParameterizedFixture.Tests + GenericFixtureConstants.Tests; public const int Suites = MockTestFixture.Suites + Singletons.OneTestCase.Suites + TestAssembly.MockTestFixture.Suites + IgnoredFixture.Suites + ExplicitFixture.Suites + BadFixture.Suites + FixtureWithTestCases.Suites + ParameterizedFixture.Suites + GenericFixtureConstants.Suites + NamespaceSuites; public const int TestStartedEvents = Tests - IgnoredFixture.Tests - BadFixture.Tests - ExplicitFixture.Tests; public const int TestFinishedEvents = Tests; public const int TestOutputEvents = 1; public const int Nodes = Tests + Suites; public const int ExplicitFixtures = 1; public const int SuitesRun = Suites - ExplicitFixtures; public const int Passed = MockTestFixture.Passed + Singletons.OneTestCase.Tests + TestAssembly.MockTestFixture.Tests + FixtureWithTestCases.Tests + ParameterizedFixture.Tests + GenericFixtureConstants.Tests; public const int Skipped_Ignored = MockTestFixture.Skipped_Ignored + IgnoredFixture.Tests; public const int Skipped_Explicit = MockTestFixture.Skipped_Explicit + ExplicitFixture.Tests; public const int Skipped = Skipped_Ignored + Skipped_Explicit; public const int Warnings = MockTestFixture.Warnings; public const int Failed_Error = MockTestFixture.Failed_Error; public const int Failed_Other = MockTestFixture.Failed_Other; public const int Failed_NotRunnable = MockTestFixture.Failed_NotRunnable + BadFixture.Tests; public const int Failed = Failed_Error + Failed_Other + Failed_NotRunnable; public const int Inconclusive = MockTestFixture.Inconclusive; #if NETCOREAPP1_1 public static readonly Assembly ThisAssembly = typeof(MockAssembly).GetTypeInfo().Assembly; #else public static readonly Assembly ThisAssembly = typeof(MockAssembly).Assembly; #endif public static readonly string AssemblyPath = AssemblyHelper.GetAssemblyPath(ThisAssembly); public static void Main(string[] args) { new AutoRun(ThisAssembly).Execute(args); } } [TestFixture(Description="Fake Test Fixture")] [Category("FixtureCategory")] public class MockTestFixture { public const int Tests = 10; public const int Suites = 1; public const int Passed = 2; public const int Skipped_Ignored = 1; public const int Skipped_Explicit = 1; public const int Skipped = Skipped_Ignored + Skipped_Explicit; public const int Failed_Other = 1; public const int Failed_Error = 1; public const int Failed_NotRunnable = 2; public const int Failed = Failed_Error + Failed_Other + Failed_NotRunnable; public const int Warnings = 1; public const int Inconclusive = 1; [Test(Description="Mock Test #1")] [Category("MockCategory")] [Property("Severity", "Critical")] public void TestWithDescription() { } [Test] protected static void NonPublicTest() { } [Test] public void FailingTest() { Console.Error.WriteLine("Immediate Error Message"); Assert.Fail("Intentional failure"); } [Test] public void WarningTest() { Assert.Warn("Warning Message"); } [Test, Ignore("Ignore Message")] public void IgnoreTest() { } [Test, Explicit] public void ExplicitTest() { } [Test] public void NotRunnableTest( int a, int b) { } [Test] public void InconclusiveTest() { Assert.Inconclusive("No valid data"); } [Test] public void DisplayRunParameters() { foreach (string name in TestContext.Parameters.Names) Console.WriteLine("Parameter {0} = {1}", name, TestContext.Parameters[name]); } [Test] public void TestWithException() { MethodThrowsException(); } private void MethodThrowsException() { throw new Exception("Intentional Exception"); } } } namespace Singletons { [TestFixture] public class OneTestCase { public const int Tests = 1; public const int Suites = 1; [Test] public virtual void TestCase() {} } } namespace TestAssembly { [TestFixture] public class MockTestFixture { public const int Tests = 1; public const int Suites = 1; [Test] public void MyTest() { } } } [TestFixture, Ignore("BECAUSE")] public class IgnoredFixture { public const int Tests = 3; public const int Suites = 1; [Test] public void Test1() { } [Test] public void Test2() { } [Test] public void Test3() { } } [TestFixture,Explicit] public class ExplicitFixture { public const int Tests = 2; public const int Suites = 1; public const int Nodes = Tests + Suites; [Test] public void Test1() { } [Test] public void Test2() { } } [TestFixture] public class BadFixture { public const int Tests = 1; public const int Suites = 1; public BadFixture(int val) { } [Test] public void SomeTest() { } } [TestFixture] public class FixtureWithTestCases { public const int Tests = 4; public const int Suites = 3; [TestCase(2, 2, ExpectedResult=4)] [TestCase(9, 11, ExpectedResult=20)] public int MethodWithParameters(int x, int y) { return x+y; } [TestCase(2, 4)] [TestCase(9.2, 11.7)] public void GenericMethod<T>(T x, T y) { } } [TestFixture(5)] [TestFixture(42)] public class ParameterizedFixture { public const int Tests = 4; public const int Suites = 3; public ParameterizedFixture(int num) { } [Test] public void Test1() { } [Test] public void Test2() { } } public class GenericFixtureConstants { public const int Tests = 4; public const int Suites = 3; } [TestFixture(5)] [TestFixture(11.5)] public class GenericFixture<T> { public GenericFixture(T num){ } [Test] public void Test1() { } [Test] public void Test2() { } } }
//! \file ImagePGX.cs //! \date Tue Dec 08 02:50:45 2015 //! \brief Glib2 image format. // // Copyright (C) 2015 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using GameRes.Utility; using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Windows.Media; namespace GameRes.Formats.Glib2 { internal class PgxMetaData : ImageMetaData { public int PackedSize; } internal class StxLayerInfo { public string Path; public Rectangle? Rect; public string Effect; public int Blend; } [Export(typeof(ImageFormat))] public class PgxFormat : ImageFormat { public override string Tag { get { return "PGX"; } } public override string Description { get { return "Glib2 engine image format"; } } public override uint Signature { get { return 0x00584750; } } // 'PGX' static readonly InfoReader InfoCache = new InfoReader(); public override ImageMetaData ReadMetaData (Stream stream) { var header = new byte[0x18]; if (header.Length != stream.Read (header, 0, header.Length)) return null; return new PgxMetaData { Width = LittleEndian.ToUInt32 (header, 8), Height = LittleEndian.ToUInt32 (header, 12), BPP = LittleEndian.ToInt16 (header, 0x10) == 0 ? 24 : 32, PackedSize = LittleEndian.ToInt32 (header, 0x14), }; } public override ImageData Read (Stream stream, ImageMetaData info) { var meta = (PgxMetaData)info; PixelFormat format = 32 == meta.BPP ? PixelFormats.Bgra32 : PixelFormats.Bgr32; int stride = (int)meta.Width * 4; var pixels = new byte[stride * (int)meta.Height]; stream.Seek (-meta.PackedSize, SeekOrigin.End); LzssUnpack (stream, pixels); var layer = InfoCache.GetInfo (info.FileName); if (null != layer && null != layer.Rect) { info.OffsetX = layer.Rect.Value.X; info.OffsetY = layer.Rect.Value.Y; } return ImageData.Create (info, format, null, pixels); } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("PgxFormat.Write not implemented"); } static void LzssUnpack (Stream input, byte[] output) { var frame = new byte[0x1000]; int frame_pos = 0xFEE; using (var lz = new ArcView.Reader (input)) { int dst = 0; int bits = 1; while (dst < output.Length) { if (1 == bits) bits = lz.ReadByte() | 0x100; if (0 != (bits & 1)) { byte b = lz.ReadByte(); output[dst++] = b; frame[frame_pos++] = b; frame_pos &= 0xFFF; } else { byte lo = lz.ReadByte(); byte hi = lz.ReadByte(); int offset = (hi & 0xF0) << 4 | lo; int count = Math.Min ((~hi & 0xF) + 3, output.Length-dst); for (int i = 0; i < count; ++i) { byte b = frame[offset++ & 0xFFF]; output[dst++] = b; frame[frame_pos++] = b; frame_pos &= 0xFFF; } } bits >>= 1; } } } } internal class InfoReader { string m_last_info_dir; Dictionary<string, StxLayerInfo> m_layer_map; internal class StxEntry { public string FullName; public string Name; public int Attr; public uint InfoOffset; public uint InfoSize; } public StxLayerInfo GetInfo (string image_name) { try { var info_name = VFS.CombinePath (Path.GetDirectoryName (image_name), "info"); if (!VFS.FileExists (info_name)) return null; if (string.IsNullOrEmpty (m_last_info_dir) || string.Join (":", VFS.FullPath) != m_last_info_dir) ParseInfo (info_name); var layer_name = Path.GetFileName (image_name); return GetLayerInfo (layer_name); } catch (Exception X) { Trace.WriteLine (X.Message, "[Glib2] STX parse error"); return null; } } StxLayerInfo GetLayerInfo (string layer_name) { if (null == m_layer_map) return null; StxLayerInfo info; m_layer_map.TryGetValue (layer_name, out info); return info; } void ParseInfo (string info_name) { if (null == m_layer_map) m_layer_map = new Dictionary<string, StxLayerInfo>(); else m_layer_map.Clear(); using (var info = VFS.OpenView (info_name)) { if (!info.View.AsciiEqual (0, "CDBD")) return; int count = info.View.ReadInt32 (4); uint current_offset = 0x10; uint info_base = current_offset + info.View.ReadUInt32 (8); uint info_total_size = info.View.ReadUInt32 (12); info.View.Reserve (0, info_base+info_total_size); uint names_base = current_offset + (uint)count * 0x18; var dir = new List<StxEntry> (count); for (int i = 0; i < count; ++i) { uint name_offset = names_base + info.View.ReadUInt32 (current_offset); int parent_dir = info.View.ReadInt32 (current_offset+8); int attr = info.View.ReadInt32 (current_offset+0xC); uint info_offset = info.View.ReadUInt32 (current_offset+0x10); uint info_size = info.View.ReadUInt32 (current_offset+0x14); var name = info.View.ReadString (name_offset, info_base-name_offset); string path_name = name; if (parent_dir != -1) path_name = Path.Combine (dir[parent_dir].FullName, path_name); if (attr != -1 && info_size != 0) info_offset += info_base; var entry = new StxEntry { FullName = path_name, Name = name, Attr = attr, InfoOffset = info_offset, InfoSize = info_size, }; if (name == "filename" && parent_dir != -1 && info_size != 0) { uint filename_length = info.View.ReadUInt32 (info_offset); var filename = info.View.ReadString (info_offset+4, filename_length); m_layer_map[filename] = new StxLayerInfo { Path = dir[parent_dir].FullName + Path.DirectorySeparatorChar, }; } dir.Add (entry); current_offset += 0x18; } foreach (var layer in m_layer_map.Values) { foreach (var field in dir.Where (e => e.Attr != -1 && e.FullName.StartsWith (layer.Path))) { if ("rect" == field.Name && 0x14 == field.InfoSize) { int left = info.View.ReadInt32 (field.InfoOffset+4); int top = info.View.ReadInt32 (field.InfoOffset+8); int right = info.View.ReadInt32 (field.InfoOffset+12); int bottom = info.View.ReadInt32 (field.InfoOffset+16); layer.Rect = new Rectangle (left, top, right-left, bottom-top); } else if ("effect" == field.Name && field.InfoSize > 4) { // "norm" uint effect_length = info.View.ReadUInt32 (field.InfoOffset); layer.Effect = info.View.ReadString (field.InfoOffset+4, effect_length); if (layer.Effect != "norm") Trace.WriteLine (string.Format ("{0}: {1}effect = {2}", info_name, layer.Path, layer.Effect), "[Glib2.STX]"); } else if ("blend" == field.Name && 4 == field.InfoSize) { // 0xFF -> opaque layer.Blend = info.View.ReadInt32 (field.InfoOffset); if (layer.Blend != 0xFF) Trace.WriteLine (string.Format ("{0}: {1}blend = {2}", info_name, layer.Path, layer.Blend), "[Glib2.STX]"); } } } } m_last_info_dir = string.Join (":", VFS.FullPath); } } }
using System; using System.Linq; using Content.Client.Chat; using Content.Client.Chat.Managers; using Content.Client.EscapeMenu.UI; using Content.Client.GameTicking.Managers; using Content.Client.LateJoin; using Content.Client.Lobby.UI; using Content.Client.Preferences; using Content.Client.Preferences.UI; using Content.Client.Voting; using Content.Shared.GameTicking; using Robust.Client; using Robust.Client.Console; using Robust.Client.Input; using Robust.Client.Player; using Robust.Client.ResourceManagement; using Robust.Client.UserInterface; using Robust.Client.UserInterface.Controls; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Prototypes; using Robust.Shared.Timing; using Robust.Shared.ViewVariables; namespace Content.Client.Lobby { public sealed class LobbyState : Robust.Client.State.State { [Dependency] private readonly IBaseClient _baseClient = default!; [Dependency] private readonly IClientConsoleHost _consoleHost = default!; [Dependency] private readonly IChatManager _chatManager = default!; [Dependency] private readonly IInputManager _inputManager = default!; [Dependency] private readonly IEntityManager _entityManager = default!; [Dependency] private readonly IPlayerManager _playerManager = default!; [Dependency] private readonly IResourceCache _resourceCache = default!; [Dependency] private readonly IPrototypeManager _prototypeManager = default!; [Dependency] private readonly IUserInterfaceManager _userInterfaceManager = default!; [Dependency] private readonly IClientPreferencesManager _preferencesManager = default!; [Dependency] private readonly IGameTiming _gameTiming = default!; [Dependency] private readonly IVoteManager _voteManager = default!; [ViewVariables] private CharacterSetupGui? _characterSetup; [ViewVariables] private LobbyGui? _lobby; private ClientGameTicker _gameTicker = default!; public override void Startup() { _gameTicker = EntitySystem.Get<ClientGameTicker>(); _characterSetup = new CharacterSetupGui(_entityManager, _resourceCache, _preferencesManager, _prototypeManager); LayoutContainer.SetAnchorPreset(_characterSetup, LayoutContainer.LayoutPreset.Wide); _lobby = new LobbyGui(_entityManager, _preferencesManager); _userInterfaceManager.StateRoot.AddChild(_lobby); _characterSetup.CloseButton.OnPressed += _ => { _userInterfaceManager.StateRoot.AddChild(_lobby); _userInterfaceManager.StateRoot.RemoveChild(_characterSetup); }; _characterSetup.SaveButton.OnPressed += _ => { _characterSetup.Save(); _lobby?.CharacterPreview.UpdateUI(); }; LayoutContainer.SetAnchorPreset(_lobby, LayoutContainer.LayoutPreset.Wide); _chatManager.SetChatBox(_lobby.Chat); _voteManager.SetPopupContainer(_lobby.VoteContainer); _lobby.ServerName.Text = _baseClient.GameInfo?.ServerName; ChatInput.SetupChatInputHandlers(_inputManager, _lobby.Chat); UpdateLobbyUi(); _lobby.CharacterPreview.CharacterSetupButton.OnPressed += _ => { SetReady(false); _userInterfaceManager.StateRoot.RemoveChild(_lobby); _userInterfaceManager.StateRoot.AddChild(_characterSetup); }; _lobby.ReadyButton.OnPressed += _ => { if (!_gameTicker.IsGameStarted) { return; } new LateJoinGui().OpenCentered(); }; _lobby.ReadyButton.OnToggled += args => { SetReady(args.Pressed); }; _lobby.LeaveButton.OnPressed += _ => _consoleHost.ExecuteCommand("disconnect"); _lobby.OptionsButton.OnPressed += _ => new OptionsMenu().Open(); UpdatePlayerList(); _playerManager.PlayerListUpdated += PlayerManagerOnPlayerListUpdated; _gameTicker.InfoBlobUpdated += UpdateLobbyUi; _gameTicker.LobbyStatusUpdated += LobbyStatusUpdated; _gameTicker.LobbyReadyUpdated += LobbyReadyUpdated; _gameTicker.LobbyLateJoinStatusUpdated += LobbyLateJoinStatusUpdated; } public override void Shutdown() { _playerManager.PlayerListUpdated -= PlayerManagerOnPlayerListUpdated; _gameTicker.InfoBlobUpdated -= UpdateLobbyUi; _gameTicker.LobbyStatusUpdated -= LobbyStatusUpdated; _gameTicker.LobbyReadyUpdated -= LobbyReadyUpdated; _gameTicker.LobbyLateJoinStatusUpdated -= LobbyLateJoinStatusUpdated; _lobby?.Dispose(); _characterSetup?.Dispose(); _lobby = null; _characterSetup = null; } public override void FrameUpdate(FrameEventArgs e) { if (_lobby == null) return; var gameTicker = EntitySystem.Get<ClientGameTicker>(); if (gameTicker.IsGameStarted) { _lobby.StartTime.Text = string.Empty; return; } string text; if (gameTicker.Paused) { text = Loc.GetString("lobby-state-paused"); } else { var difference = gameTicker.StartTime - _gameTiming.CurTime; var seconds = difference.TotalSeconds; if (seconds < 0) { text = Loc.GetString(seconds < -5 ? "lobby-state-right-now-question" : "lobby-state-right-now-confirmation"); } else { text = $"{difference.Minutes}:{difference.Seconds:D2}"; } } _lobby.StartTime.Text = Loc.GetString("lobby-state-round-start-countdown-text", ("timeLeft", text)); } private void PlayerManagerOnPlayerListUpdated(object? sender, EventArgs e) { var gameTicker = EntitySystem.Get<ClientGameTicker>(); // Remove disconnected sessions from the Ready Dict foreach (var p in gameTicker.Status) { if (!_playerManager.SessionsDict.TryGetValue(p.Key, out _)) { // This is a shitty fix. Observers can rejoin because they are already in the game. // So we don't delete them, but keep them if they decide to rejoin if (p.Value != LobbyPlayerStatus.Observer) gameTicker.Status.Remove(p.Key); } } UpdatePlayerList(); } private void LobbyReadyUpdated() => UpdatePlayerList(); private void LobbyStatusUpdated() { UpdatePlayerList(); UpdateLobbyUi(); } private void LobbyLateJoinStatusUpdated() { if (_lobby == null) return; _lobby.ReadyButton.Disabled = EntitySystem.Get<ClientGameTicker>().DisallowedLateJoin; } private void UpdateLobbyUi() { if (_lobby == null) return; var gameTicker = EntitySystem.Get<ClientGameTicker>(); if (gameTicker.IsGameStarted) { _lobby.ReadyButton.Text = Loc.GetString("lobby-state-ready-button-join-state"); _lobby.ReadyButton.ToggleMode = false; _lobby.ReadyButton.Pressed = false; _lobby.ObserveButton.Disabled = false; } else { _lobby.StartTime.Text = string.Empty; _lobby.ReadyButton.Text = Loc.GetString("lobby-state-ready-button-ready-up-state"); _lobby.ReadyButton.ToggleMode = true; _lobby.ReadyButton.Disabled = false; _lobby.ReadyButton.Pressed = gameTicker.AreWeReady; _lobby.ObserveButton.Disabled = true; } if (gameTicker.ServerInfoBlob != null) { _lobby.ServerInfo.SetInfoBlob(gameTicker.ServerInfoBlob); } } private void UpdatePlayerList() { if (_lobby == null) return; _lobby.OnlinePlayerList.Clear(); var gameTicker = EntitySystem.Get<ClientGameTicker>(); foreach (var session in _playerManager.Sessions.OrderBy(s => s.Name)) { var readyState = string.Empty; // Don't show ready state if we're ingame if (!gameTicker.IsGameStarted) { LobbyPlayerStatus status; if (session.UserId == _playerManager.LocalPlayer?.UserId) status = gameTicker.AreWeReady ? LobbyPlayerStatus.Ready : LobbyPlayerStatus.NotReady; else gameTicker.Status.TryGetValue(session.UserId, out status); readyState = status switch { LobbyPlayerStatus.NotReady => Loc.GetString("lobby-state-player-status-not-ready"), LobbyPlayerStatus.Ready => Loc.GetString("lobby-state-player-status-ready"), LobbyPlayerStatus.Observer => Loc.GetString("lobby-state-player-status-observer"), _ => string.Empty, }; } _lobby.OnlinePlayerList.AddItem(session.Name, readyState); } } private void SetReady(bool newReady) { if (EntitySystem.Get<ClientGameTicker>().IsGameStarted) { return; } _consoleHost.ExecuteCommand($"toggleready {newReady}"); UpdatePlayerList(); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.HSSF.Model { using System; using NPOI.HSSF.Record; using NPOI.HSSF.Record.Aggregates; using System.Collections.Generic; using NPOI.HSSF.Record.PivotTable; /** * Finds correct insert positions for records in workbook streams<p/> * * See OOO excelfileformat.pdf sec. 4.2.5 'Record Order in a BIFF8 Workbook Stream' * * @author Josh Micich */ public class RecordOrderer { // TODO - simplify logic using a generalised record ordering private RecordOrderer() { // no instances of this class } /** * Adds the specified new record in the correct place in sheet records list * */ public static void AddNewSheetRecord(List<RecordBase> sheetRecords, RecordBase newRecord) { int index = FindSheetInsertPos(sheetRecords, newRecord.GetType()); sheetRecords.Insert(index, newRecord); } private static int FindSheetInsertPos(List<RecordBase> records, Type recClass) { if (recClass == typeof(DataValidityTable)) { return FindDataValidationTableInsertPos(records); } if (recClass == typeof(MergedCellsTable)) { return FindInsertPosForNewMergedRecordTable(records); } if (recClass == typeof(ConditionalFormattingTable)) { return FindInsertPosForNewCondFormatTable(records); } if (recClass == typeof(GutsRecord)) { return GetGutsRecordInsertPos(records); } if (recClass == typeof(PageSettingsBlock)) { return GetPageBreakRecordInsertPos(records); } if (recClass == typeof(WorksheetProtectionBlock)) { return GetWorksheetProtectionBlockInsertPos(records); } throw new InvalidOperationException("Unexpected record class (" + recClass.Name + ")"); } /// <summary> /// Finds the index where the protection block should be inserted /// </summary> /// <param name="records">the records for this sheet</param> /// <returns></returns> /// <remark> /// + BOF /// o INDEX /// o Calculation Settings Block /// o PRINTHEADERS /// o PRINTGRIDLINES /// o GRIDSET /// o GUTS /// o DEFAULTROWHEIGHT /// o SHEETPR /// o Page Settings Block /// o Worksheet Protection Block /// o DEFCOLWIDTH /// oo COLINFO /// o SORT /// + DIMENSION /// </remark> private static int GetWorksheetProtectionBlockInsertPos(List<RecordBase> records) { int i = GetDimensionsIndex(records); while (i > 0) { i--; Object rb = records[i]; if (!IsProtectionSubsequentRecord(rb)) { return i + 1; } } throw new InvalidOperationException("did not find insert pos for protection block"); } /// <summary> /// These records may occur between the 'Worksheet Protection Block' and DIMENSION: /// </summary> /// <param name="rb"></param> /// <returns></returns> /// <remarks> /// o DEFCOLWIDTH /// oo COLINFO /// o SORT /// </remarks> private static bool IsProtectionSubsequentRecord(Object rb) { if (rb is ColumnInfoRecordsAggregate) { return true; // oo COLINFO } if (rb is Record) { Record record = (Record)rb; switch (record.Sid) { case DefaultColWidthRecord.sid: case UnknownRecord.SORT_0090: return true; } } return false; } private static int GetPageBreakRecordInsertPos(List<RecordBase> records) { int dimensionsIndex = GetDimensionsIndex(records); int i = dimensionsIndex - 1; while (i > 0) { i--; RecordBase rb = records[i]; if (IsPageBreakPriorRecord(rb)) { return i + 1; } } throw new InvalidOperationException("Did not Find insert point for GUTS"); } private static bool IsPageBreakPriorRecord(RecordBase rb) { if (rb is Record) { Record record = (Record)rb; switch (record.Sid) { case BOFRecord.sid: case IndexRecord.sid: // calc settings block case UncalcedRecord.sid: case CalcCountRecord.sid: case CalcModeRecord.sid: case PrecisionRecord.sid: case RefModeRecord.sid: case DeltaRecord.sid: case IterationRecord.sid: case DateWindow1904Record.sid: case SaveRecalcRecord.sid: // end calc settings case PrintHeadersRecord.sid: case PrintGridlinesRecord.sid: case GridsetRecord.sid: case DefaultRowHeightRecord.sid: case UnknownRecord.SHEETPR_0081: return true; // next is the 'Worksheet Protection Block' } } return false; } /// <summary> /// Find correct position to add new CFHeader record /// </summary> /// <param name="records"></param> /// <returns></returns> private static int FindInsertPosForNewCondFormatTable(List<RecordBase> records) { for (int i = records.Count - 2; i >= 0; i--) { // -2 to skip EOF record Object rb = records[i]; if (rb is MergedCellsTable) { return i + 1; } if (rb is DataValidityTable) { continue; } Record rec = (Record)rb; switch (rec.Sid) { case WindowTwoRecord.sid: case SCLRecord.sid: case PaneRecord.sid: case SelectionRecord.sid: case UnknownRecord.STANDARDWIDTH_0099: // MergedCellsTable usually here case UnknownRecord.LABELRANGES_015F: case UnknownRecord.PHONETICPR_00EF: // ConditionalFormattingTable goes here return i + 1; // HyperlinkTable (not aggregated by POI yet) // DataValidityTable } } throw new InvalidOperationException("Did not Find Window2 record"); } private static int FindInsertPosForNewMergedRecordTable(List<RecordBase> records) { for (int i = records.Count - 2; i >= 0; i--) { // -2 to skip EOF record Object rb = records[i]; if (!(rb is Record)) { // DataValidityTable, ConditionalFormattingTable, // even PageSettingsBlock (which doesn't normally appear after 'View Settings') continue; } Record rec = (Record)rb; switch (rec.Sid) { // 'View Settings' (4 records) case WindowTwoRecord.sid: case SCLRecord.sid: case PaneRecord.sid: case SelectionRecord.sid: case UnknownRecord.STANDARDWIDTH_0099: return i + 1; } } throw new InvalidOperationException("Did not Find Window2 record"); } /** * Finds the index where the sheet validations header record should be inserted * @param records the records for this sheet * * + WINDOW2 * o SCL * o PANE * oo SELECTION * o STANDARDWIDTH * oo MERGEDCELLS * o LABELRANGES * o PHONETICPR * o Conditional Formatting Table * o Hyperlink Table * o Data Validity Table * o SHEETLAYOUT * o SHEETPROTECTION * o RANGEPROTECTION * + EOF */ private static int FindDataValidationTableInsertPos(List<RecordBase> records) { int i = records.Count - 1; if (!(records[i] is EOFRecord)) { throw new InvalidOperationException("Last sheet record should be EOFRecord"); } while (i > 0) { i--; RecordBase rb = records[i]; if (IsDVTPriorRecord(rb)) { Record nextRec = (Record)records[i + 1]; if (!IsDVTSubsequentRecord(nextRec.Sid)) { throw new InvalidOperationException("Unexpected (" + nextRec.GetType().Name + ") found after (" + rb.GetType().Name + ")"); } return i + 1; } Record rec = (Record)rb; if (!IsDVTSubsequentRecord(rec.Sid)) { throw new InvalidOperationException("Unexpected (" + rec.GetType().Name + ") while looking for DV Table insert pos"); } } return 0; } private static bool IsDVTPriorRecord(RecordBase rb) { if (rb is MergedCellsTable || rb is ConditionalFormattingTable) { return true; } short sid = ((Record)rb).Sid; switch (sid) { case WindowTwoRecord.sid: case SCLRecord.sid: case PaneRecord.sid: case SelectionRecord.sid: case UnknownRecord.STANDARDWIDTH_0099: // MergedCellsTable case UnknownRecord.LABELRANGES_015F: case UnknownRecord.PHONETICPR_00EF: // ConditionalFormattingTable case HyperlinkRecord.sid: case UnknownRecord.QUICKTIP_0800: return true; } return false; } private static bool IsDVTSubsequentRecord(short sid) { switch (sid) { //case UnknownRecord.SHEETEXT_0862: case SheetExtRecord.sid: case UnknownRecord.SHEETPROTECTION_0867: //case UnknownRecord.RANGEPROTECTION_0868: case FeatRecord.sid: case EOFRecord.sid: return true; } return false; } /** * DIMENSIONS record is always present */ private static int GetDimensionsIndex(List<RecordBase> records) { int nRecs = records.Count; for (int i = 0; i < nRecs; i++) { if (records[i] is DimensionsRecord) { return i; } } // worksheet stream is seriously broken throw new InvalidOperationException("DimensionsRecord not found"); } private static int GetGutsRecordInsertPos(List<RecordBase> records) { int dimensionsIndex = GetDimensionsIndex(records); int i = dimensionsIndex - 1; while (i > 0) { i--; RecordBase rb = records[i]; if (IsGutsPriorRecord(rb)) { return i + 1; } } throw new InvalidOperationException("Did not Find insert point for GUTS"); } private static bool IsGutsPriorRecord(RecordBase rb) { if (rb is Record) { Record record = (Record)rb; switch (record.Sid) { case BOFRecord.sid: case IndexRecord.sid: // calc settings block case UncalcedRecord.sid: case CalcCountRecord.sid: case CalcModeRecord.sid: case PrecisionRecord.sid: case RefModeRecord.sid: case DeltaRecord.sid: case IterationRecord.sid: case DateWindow1904Record.sid: case SaveRecalcRecord.sid: // end calc settings case PrintHeadersRecord.sid: case PrintGridlinesRecord.sid: case GridsetRecord.sid: return true; // DefaultRowHeightRecord.sid is next } } return false; } /// <summary> /// if the specified record ID terminates a sequence of Row block records /// It is assumed that at least one row or cell value record has been found prior to the current /// record /// </summary> /// <param name="sid"></param> /// <returns></returns> public static bool IsEndOfRowBlock(int sid) { switch (sid) { case ViewDefinitionRecord.sid: // should have been prefixed with DrawingRecord (0x00EC), but bug 46280 seems to allow this case DrawingRecord.sid: case DrawingSelectionRecord.sid: case ObjRecord.sid: case TextObjectRecord.sid: case GutsRecord.sid: // see Bugzilla 50426 case WindowOneRecord.sid: // should really be part of workbook stream, but some apps seem to put this before WINDOW2 case WindowTwoRecord.sid: return true; case DVALRecord.sid: return true; case EOFRecord.sid: // WINDOW2 should always be present, so shouldn't have got this far throw new InvalidOperationException("Found EOFRecord before WindowTwoRecord was encountered"); } return PageSettingsBlock.IsComponentRecord(sid); } /// <summary> /// Whether the specified record id normally appears in the row blocks section of the sheet records /// </summary> /// <param name="sid"></param> /// <returns></returns> public static bool IsRowBlockRecord(int sid) { switch (sid) { case RowRecord.sid: case BlankRecord.sid: case BoolErrRecord.sid: case FormulaRecord.sid: case LabelRecord.sid: case LabelSSTRecord.sid: case NumberRecord.sid: case RKRecord.sid: case ArrayRecord.sid: case SharedFormulaRecord.sid: case TableRecord.sid: return true; } return false; } } }
using System; using System.Collections.Generic; using MySql.Data.MySqlClient; using ProjectStableLibrary; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.IO; using Microsoft.EntityFrameworkCore; namespace ConsoleTools { public class CareerDay { public const int date = 20190315; private static bool prioritizeByGrade = true; public static void run() { bool careerDay = false; string s; char c; do { Console.Write("Save to db? (y/n/q): "); s = Console.ReadLine().ToUpper(); if(s.Length > 0) { c = s[0]; if(c == 'Y' || c == 'N') PlaceViewers(c == 'Y'); } else { c = ' '; } } while(c != 'Q'); } static void PlaceViewers(bool saveToDB) { var conStr = new MySqlConnectionStringBuilder(); using(StreamReader file = File.OpenText("config.json")) { using(JsonTextReader r = new JsonTextReader(file)) { JObject conf = (JObject)JToken.ReadFrom(r); conStr.Server = (string)conf["server"]; conStr.Port = uint.Parse((string)conf["port"]); conStr.UserID = (string)conf["user"]; conStr.Password = (string)conf["password"]; conStr.Database = (string)conf["database"]; conStr.SslMode = MySqlSslMode.Required; } } bool clean = true; using(StableContext ctx = StableContextFactory.Build(conStr.ToString())) { //3 2 4 1 var viewers = ctx.Viewers; Console.WriteLine($"Fetched {viewers.Count} viewers"); var schedule = ctx.Schedule; var capacityCheck = new Dictionary<Schedule, uint>(); foreach(Schedule s in schedule) { capacityCheck.Add(s, 0); } Console.WriteLine($"Fetched {schedule.Count} schedules"); var blocks = ctx.Blocks; Console.WriteLine($"Fetched {blocks.Count} blocks"); var preferences = ctx.preferences.ToList(); Console.WriteLine($"Fetched {preferences.Count} preferences"); var presentations = ctx.Presentations; Console.WriteLine($"Fetched {presentations.Count} presentations"); int expected_count = blocks.Count; const int retry_count = 5; uint f_count = 0; var toAddToDB = new List<Registration>(); { string s; char c; do { Console.Write("Prioritize by grade? (y/n): "); s = Console.ReadLine().ToUpper(); if(s.Length > 0) { c = s[0]; if(c == 'Y' || c == 'N') { prioritizeByGrade = c == 'Y'; break; } } else { c = ' '; } } while(true); } uint[] grade_pri = new uint[] { 0 }; if(prioritizeByGrade) { grade_pri = new uint[] { 3, 2, 4, 1 }; } uint max_viewers = 26; do { try { Console.Write($"max_viewers [{max_viewers}]: "); string s = Console.ReadLine(); if(s.Length == 0) break; max_viewers = uint.Parse(s); break; } catch { Console.WriteLine("Invalid input!"); } } while(true); var registrationsToAdd = new List<Registration>(); DateTime start = DateTime.Now; foreach(Block b in blocks.Values) { var temp_s = new Schedule() { date = date }; temp_s.block_id = b.block_id; foreach(uint g in grade_pri) { var viewers_to_proc = new List<uint>(); if(prioritizeByGrade) viewers_to_proc.AddRange(from thus in viewers where thus.Value.grade_id == g select thus.Value.viewer_id); else viewers_to_proc.AddRange(from thus in viewers select thus.Value.viewer_id); viewers_to_proc.Randomize(); foreach(uint v in viewers_to_proc) { //var currentSelectedPresentations = new List<uint>(); var v_pref = (from thus in preferences where thus.viewer_id == v orderby thus.order select thus.presentation_id).ToList(); var currentRegistrations = (from thus in registrationsToAdd where thus.viewer_id == v select thus.presentation_id).ToList(); bool randomize = v_pref.Count < presentations.Count; if(randomize) { Dictionary<uint, int> currentPCount = new Dictionary<uint, int>(); foreach(var p_id in presentations.Keys) { currentPCount.Add( p_id, registrationsToAdd.Count(thus => thus.date == temp_s.date && thus.block_id == temp_s.block_id && thus.presentation_id == p_id) ); } var popOrder = currentPCount.OrderBy(thus => thus.Value); v_pref = popOrder.Select(thus => thus.Key).ToList(); //v_pref = (from thus in presentations select thus.Value.presentation_id).ToList(); } //if(currentRegistrations.Count == 1) //Console.WriteLine(); v_pref = v_pref.Where(thus => !currentRegistrations.Contains(thus)).ToList(); var v_pref_queue = new Queue<uint>(v_pref); uint presentation_to_add; //Add capacity check int presentationViewerCount = 0; do { if(v_pref_queue.Count == 0) { f_count++; foreach(uint p_idd in presentations.Select(thus => thus.Value.presentation_id)) { var c2 = registrationsToAdd.Count(thus => thus.date == temp_s.date && thus.block_id == temp_s.block_id && thus.presentation_id == p_idd); //Console.WriteLine($"{p_idd}: {c2}"); } v_pref = v_pref.Where(thus => !currentRegistrations.Contains(thus)).ToList(); v_pref_queue = new Queue<uint>(v_pref); presentation_to_add = v_pref_queue.Dequeue(); break; } presentation_to_add = v_pref_queue.Dequeue(); presentationViewerCount = registrationsToAdd.Count(thus => thus.date == temp_s.date && thus.block_id == temp_s.block_id && thus.presentation_id == presentation_to_add); //if(presentationViewerCount >= max_viewers) //Console.WriteLine(); } while(presentationViewerCount >= max_viewers); registrationsToAdd.Add(new Registration() { date = temp_s.date, block_id = temp_s.block_id, presentation_id = presentation_to_add, viewer_id = v }); } } foreach(uint p_idd in presentations.Select(thus => thus.Value.presentation_id)) { var c2 = registrationsToAdd.Count(thus => thus.date == temp_s.date && thus.block_id == temp_s.block_id && thus.presentation_id == p_idd); Console.WriteLine($"{temp_s.block_id} {p_idd}: {c2}"); } } clean = registrationsToAdd.Count == viewers.Count * blocks.Count; toAddToDB = registrationsToAdd; /* foreach(uint g in grade_pri) { // if(g != 3) // continue; var viewers_to_proc = new List<uint>(); if(prioritizeByGrade) viewers_to_proc.AddRange(from thus in viewers where thus.Value.grade_id == g select thus.Value.viewer_id); else viewers_to_proc.AddRange(from thus in viewers select thus.Value.viewer_id); viewers_to_proc.Randomize(); foreach(uint v in viewers_to_proc) { var registrationEntries = new List<Tuple<uint, uint>>(); var currentSelectedPresentations = new List<uint>(); var v_pref = (from thus in preferences where thus.viewer_id == v orderby thus.order select thus.presentation_id).ToList(); bool randomize = v_pref.Count < presentations.Count; var temp_s = new Schedule(){ date = date }; var blocks_r = blocks.Values.ToList(); int error_count = 0; do { blocks_r.Randomize(); foreach(Block b in blocks_r) { temp_s.block_id = b.block_id; if(randomize) { var r_p = from thus in capacityCheck orderby thus.Value select thus.Key.presentation_id; foreach(uint p in r_p) { if(currentSelectedPresentations.Contains(p)) continue; temp_s.presentation_id = p; if(!capacityCheck.ContainsKey(temp_s)) continue; if(capacityCheck[temp_s] >= max_viewers) continue; capacityCheck[temp_s]++; registrationEntries.Add(new Tuple<uint, uint>(b.block_id, p)); currentSelectedPresentations.Add(p); break; } continue; } foreach(uint p in v_pref) { if(currentSelectedPresentations.Contains(p)) continue; temp_s.presentation_id = p; if(!capacityCheck.ContainsKey(temp_s)) continue; if(capacityCheck[temp_s] >= max_viewers) continue; capacityCheck[temp_s]++; registrationEntries.Add(new Tuple<uint, uint>(b.block_id, p)); currentSelectedPresentations.Add(p); break; } } if(currentSelectedPresentations.Count != expected_count) { //Console.WriteLine("ERROR " + string.Join(", ", bleh_v)); //undo foreach(var toRemove in registrationEntries) { temp_s.block_id = toRemove.Item1; temp_s.presentation_id = toRemove.Item2; capacityCheck[temp_s]--; } registrationEntries.Clear(); currentSelectedPresentations.Clear(); error_count++; if(error_count > retry_count) { clean = false; break; } } else { foreach(var toAdd in registrationEntries) { toAddToDB.Add(new Registration() { date = temp_s.date, block_id = toAdd.Item1, presentation_id = toAdd.Item2, viewer_id = v }); } } } while(currentSelectedPresentations.Count != expected_count); //var rng = randomize ? "RNG" : ""; //Console.WriteLine($"Student: {v} {rng} {string.Join(", ", bleh)}"); } } */ DateTime end = DateTime.Now; Console.WriteLine($"Took {(end - start).TotalMilliseconds} ms to sort"); Console.WriteLine($"F Count: {f_count}"); if(saveToDB) { start = DateTime.Now; if(clean) { using(var tx = ctx.Database.BeginTransaction()) { try { ctx.Database.ExecuteSqlCommand("DELETE FROM `registrations`;"); tx.Commit(); } catch(Exception e) { tx.Rollback(); Console.WriteLine(e); } } using(var tx = ctx.Database.BeginTransaction()) { try { ctx.registrations.AddRange(toAddToDB); ctx.SaveChanges(); tx.Commit(); } catch(Exception e) { tx.Rollback(); Console.WriteLine(e); } } } end = DateTime.Now; Console.WriteLine($"Took {(end - start).TotalMilliseconds} ms to add to db!"); } foreach(var e in capacityCheck) { Console.WriteLine(e.Key.block_id + " " + e.Key.presentation_id + " " + e.Value); } if(!saveToDB) Console.WriteLine("Did not save to DB!"); Console.WriteLine($"{toAddToDB.Count} entries to add to DB!"); } Console.WriteLine("Clean: " + clean.ToString()); } } }
// 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.Threading.Tasks; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.IO { // A MemoryStream represents a Stream in memory (i.e, it has no backing store). // This stream may reduce the need for temporary buffers and files in // an application. // // There are two ways to create a MemoryStream. You can initialize one // from an unsigned byte array, or you can create an empty one. Empty // memory streams are resizable, while ones created with a byte array provide // a stream "view" of the data. public class MemoryStream : Stream { private byte[] _buffer; // Either allocated internally or externally. private int _origin; // For user-provided arrays, start at this origin private int _position; // read/write head. [ContractPublicPropertyName("Length")] private int _length; // Number of bytes within the memory stream private int _capacity; // length of usable portion of buffer for stream // Note that _capacity == _buffer.Length for non-user-provided byte[]'s private bool _expandable; // User-provided buffers aren't expandable. private bool _writable; // Can user write to this stream? private bool _exposable; // Whether the array can be returned to the user. private bool _isOpen; // Is this stream open or closed? // <TODO>In V2, if we get support for arrays of more than 2 GB worth of elements, // consider removing this constraint, or setting it to Int64.MaxValue.</TODO> private const int MemStreamMaxLength = int.MaxValue; public MemoryStream() : this(0) { } public MemoryStream(int capacity) { if (capacity < 0) { throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity); } _buffer = capacity != 0 ? new byte[capacity] : Array.Empty<byte>(); _capacity = capacity; _expandable = true; _writable = true; _exposable = true; _origin = 0; // Must be 0 for byte[]'s created by MemoryStream _isOpen = true; } public MemoryStream(byte[] buffer) : this(buffer, true) { } public MemoryStream(byte[] buffer, bool writable) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } _buffer = buffer; _length = _capacity = buffer.Length; _writable = writable; _exposable = false; _origin = 0; _isOpen = true; } public MemoryStream(byte[] buffer, int index, int count) : this(buffer, index, count, true, false) { } public MemoryStream(byte[] buffer, int index, int count, bool writable) : this(buffer, index, count, writable, false) { } public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } _buffer = buffer; _origin = _position = index; _length = _capacity = index + count; _writable = writable; _exposable = publiclyVisible; // Can TryGetBuffer return the array? _expandable = false; _isOpen = true; } public override bool CanRead { [Pure] get { return _isOpen; } } public override bool CanSeek { [Pure] get { return _isOpen; } } public override bool CanWrite { [Pure] get { return _writable; } } private void EnsureWriteable() { if (!CanWrite) { throw new NotSupportedException(SR.NotSupported_UnwritableStream); } } protected override void Dispose(bool disposing) { try { if (disposing) { _isOpen = false; _writable = false; _expandable = false; // Don't set buffer to null - allow TryGetBuffer & ToArray to work. } } finally { // Call base.Close() to cleanup async IO resources base.Dispose(disposing); } } // returns a bool saying whether we allocated a new array. private bool EnsureCapacity(int value) { // Check for overflow if (value < 0) { throw new IOException(SR.IO_IO_StreamTooLong); } if (value > _capacity) { int newCapacity = value; if (newCapacity < 256) { newCapacity = 256; } if (newCapacity < _capacity * 2) { newCapacity = _capacity * 2; } Capacity = newCapacity; return true; } return false; } public override void Flush() { } #pragma warning disable 1998 //async method with no await operators public override async Task FlushAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); Flush(); } #pragma warning restore 1998 public virtual bool TryGetBuffer(out ArraySegment<byte> buffer) { if (!_exposable) { buffer = default(ArraySegment<byte>); return false; } buffer = new ArraySegment<byte>(_buffer, offset: _origin, count: (_length - _origin)); return true; } public virtual byte[] GetBuffer() { if (!_exposable) throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer); return _buffer; } // PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer()) internal byte[] InternalGetBuffer() { return _buffer; } // PERF: True cursor position, we don't need _origin for direct access internal int InternalGetPosition() { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } return _position; } // PERF: Takes out Int32 as fast as possible internal int InternalReadInt32() { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } int pos = (_position += 4); // use temp to avoid race if (pos > _length) { _position = _length; throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF); } return (int)(_buffer[pos - 4] | _buffer[pos - 3] << 8 | _buffer[pos - 2] << 16 | _buffer[pos - 1] << 24); } // PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes internal int InternalEmulateRead(int count) { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } int n = _length - _position; if (n > count) { n = count; } if (n < 0) { n = 0; } Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. _position += n; return n; } // Gets & sets the capacity (number of bytes allocated) for this stream. // The capacity cannot be set to a value less than the current length // of the stream. // public virtual int Capacity { get { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } return _capacity - _origin; } set { // Only update the capacity if the MS is expandable and the value is different than the current capacity. // Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity if (value < Length) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity); } if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } if (!_expandable && (value != Capacity)) { throw new NotSupportedException(SR.NotSupported_MemStreamNotExpandable); } // MemoryStream has this invariant: _origin > 0 => !expandable (see ctors) if (_expandable && value != _capacity) { if (value > 0) { byte[] newBuffer = new byte[value]; if (_length > 0) { Buffer.BlockCopy(_buffer, 0, newBuffer, 0, _length); } _buffer = newBuffer; } else { _buffer = null; } _capacity = value; } } } public override long Length { get { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } return _length - _origin; } } public override long Position { get { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } return _position - _origin; } set { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); } if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } if (value > MemStreamMaxLength) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); } _position = _origin + (int)value; } } public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } int n = _length - _position; if (n > count) { n = count; } if (n <= 0) { return 0; } Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. if (n <= 8) { int byteCount = n; while (--byteCount >= 0) buffer[offset + byteCount] = _buffer[_position + byteCount]; } else Buffer.BlockCopy(_buffer, _position, buffer, offset, n); _position += n; return n; } public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return ReadAsyncImpl(buffer, offset, count, cancellationToken); } #pragma warning disable 1998 //async method with no await operators private async Task<int> ReadAsyncImpl(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Read(buffer, offset, count); } #pragma warning restore 1998 public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state); public override int EndRead(IAsyncResult asyncResult) => TaskToApm.End<int>(asyncResult); public override int ReadByte() { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } if (_position >= _length) { return -1; } return _buffer[_position++]; } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { // This implementation offers better performance compared to the base class version. // The parameter checks must be in sync with the base version: if (destination == null) { throw new ArgumentNullException(nameof(destination)); } if (bufferSize <= 0) { throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); } if (!CanRead && !CanWrite) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } if (!destination.CanRead && !destination.CanWrite) { throw new ObjectDisposedException(nameof(destination), SR.ObjectDisposed_StreamClosed); } if (!CanRead) { throw new NotSupportedException(SR.NotSupported_UnreadableStream); } if (!destination.CanWrite) { throw new NotSupportedException(SR.NotSupported_UnwritableStream); } // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Read() or Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Read/Write) when we are not sure. if (GetType() != typeof(MemoryStream)) { return base.CopyToAsync(destination, bufferSize, cancellationToken); } return CopyToAsyncImpl(destination, bufferSize, cancellationToken); } private async Task CopyToAsyncImpl(Stream destination, int bufferSize, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Avoid copying data from this buffer into a temp buffer: // (require that InternalEmulateRead does not throw, // otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below) int pos = _position; int n = InternalEmulateRead(_length - _position); // If destination is not a memory stream, write there asynchronously: MemoryStream memStrDest = destination as MemoryStream; if (memStrDest == null) { await destination.WriteAsync(_buffer, pos, n, cancellationToken).ConfigureAwait(false); } else { memStrDest.Write(_buffer, pos, n); } } public override long Seek(long offset, SeekOrigin loc) { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } if (offset > MemStreamMaxLength) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_StreamLength); } switch (loc) { case SeekOrigin.Begin: { int tempPosition = unchecked(_origin + (int)offset); if (offset < 0 || tempPosition < _origin) { throw new IOException(SR.IO_IO_SeekBeforeBegin); } _position = tempPosition; break; } case SeekOrigin.Current: { int tempPosition = unchecked(_position + (int)offset); if (unchecked(_position + offset) < _origin || tempPosition < _origin) { throw new IOException(SR.IO_IO_SeekBeforeBegin); } _position = tempPosition; break; } case SeekOrigin.End: { int tempPosition = unchecked(_length + (int)offset); if (unchecked(_length + offset) < _origin || tempPosition < _origin) { throw new IOException(SR.IO_IO_SeekBeforeBegin); } _position = tempPosition; break; } default: throw new ArgumentException(SR.Argument_InvalidSeekOrigin); } Debug.Assert(_position >= 0, "_position >= 0"); return _position; } // Sets the length of the stream to a given value. The new // value must be nonnegative and less than the space remaining in // the array, Int32.MaxValue - origin // Origin is 0 in all cases other than a MemoryStream created on // top of an existing array and a specific starting offset was passed // into the MemoryStream constructor. The upper bounds prevents any // situations where a stream may be created on top of an array then // the stream is made longer than the maximum possible length of the // array (Int32.MaxValue). // public override void SetLength(long value) { if (value < 0 || value > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); } EnsureWriteable(); // Origin wasn't publicly exposed above. Debug.Assert(MemStreamMaxLength == int.MaxValue); // Check parameter validation logic in this method if this fails. if (value > (int.MaxValue - _origin)) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); } int newLength = _origin + (int)value; bool allocatedNewArray = EnsureCapacity(newLength); if (!allocatedNewArray && newLength > _length) { Array.Clear(_buffer, _length, newLength - _length); } _length = newLength; if (_position > newLength) { _position = newLength; } } public virtual byte[] ToArray() { //BCLDebug.Perf(_exposable, "MemoryStream::GetBuffer will let you avoid a copy."); int count = _length - _origin; if (count == 0) { return Array.Empty<byte>(); } byte[] copy = new byte[count]; Buffer.BlockCopy(_buffer, _origin, copy, 0, _length - _origin); return copy; } public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } EnsureWriteable(); int i = _position + count; // Check for overflow if (i < 0) { throw new IOException(SR.IO_IO_StreamTooLong); } if (i > _length) { bool mustZero = _position > _length; if (i > _capacity) { bool allocatedNewArray = EnsureCapacity(i); if (allocatedNewArray) { mustZero = false; } } if (mustZero) { Array.Clear(_buffer, _length, i - _length); } _length = i; } if ((count <= 8) && (buffer != _buffer)) { int byteCount = count; while (--byteCount >= 0) { _buffer[_position + byteCount] = buffer[offset + byteCount]; } } else { Buffer.BlockCopy(buffer, offset, _buffer, _position, count); } _position = i; } public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return WriteAsyncImpl(buffer, offset, count, cancellationToken); } #pragma warning disable 1998 //async method with no await operators private async Task WriteAsyncImpl(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); Write(buffer, offset, count); } #pragma warning restore 1998 public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), callback, state); public override void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); public override void WriteByte(byte value) { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } EnsureWriteable(); if (_position >= _length) { int newLength = _position + 1; bool mustZero = _position > _length; if (newLength >= _capacity) { bool allocatedNewArray = EnsureCapacity(newLength); if (allocatedNewArray) { mustZero = false; } } if (mustZero) { Array.Clear(_buffer, _length, _position - _length); } _length = newLength; } _buffer[_position++] = value; } // Writes this MemoryStream to another stream. public virtual void WriteTo(Stream stream) { if (stream == null) { throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream); } if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } stream.Write(_buffer, _origin, _length - _origin); } } }
// 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 Fixtures.PetstoreV2NoSync { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; using Microsoft.Rest; using Models; /// <summary> /// This is a sample server Petstore server. You can find out more about /// Swagger at &lt;a /// href="http://swagger.io"&gt;http://swagger.io&lt;/a&gt; or on /// irc.freenode.net, #swagger. For this sample, you can use the api key /// "special-key" to test the authorization filters /// </summary> public partial interface ISwaggerPetstoreV2 : IDisposable { /// <summary> /// The base URI of the service. /// </summary> Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> JsonSerializerSettings SerializationSettings { get; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> JsonSerializerSettings DeserializationSettings { get; } /// <summary> /// Add a new pet to the store /// </summary> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Pet>> AddPetWithHttpMessagesAsync(Pet body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Update an existing pet /// </summary> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> UpdatePetWithHttpMessagesAsync(Pet body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Finds Pets by status /// </summary> /// Multiple status values can be provided with comma seperated strings /// <param name='status'> /// Status values that need to be considered for filter /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<Pet>>> FindPetsByStatusWithHttpMessagesAsync(IList<string> status, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Finds Pets by tags /// </summary> /// Muliple tags can be provided with comma seperated strings. Use /// tag1, tag2, tag3 for testing. /// <param name='tags'> /// Tags to filter by /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<Pet>>> FindPetsByTagsWithHttpMessagesAsync(IList<string> tags, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Find pet by Id /// </summary> /// Returns a single pet /// <param name='petId'> /// Id of pet to return /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Pet>> GetPetByIdWithHttpMessagesAsync(long petId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='petId'> /// Id of pet that needs to be updated /// </param> /// <param name='fileContent'> /// File to upload. /// </param> /// <param name='fileName'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> UpdatePetWithFormWithHttpMessagesAsync(long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a pet /// </summary> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> DeletePetWithHttpMessagesAsync(long petId, string apiKey = "", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns pet inventories by status /// </summary> /// Returns a map of status codes to quantities /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetInventoryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Place an order for a pet /// </summary> /// <param name='body'> /// order placed for purchasing the pet /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Order>> PlaceOrderWithHttpMessagesAsync(Order body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Find purchase order by Id /// </summary> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. /// Other values will generated exceptions /// <param name='orderId'> /// Id of pet that needs to be fetched /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Order>> GetOrderByIdWithHttpMessagesAsync(string orderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete purchase order by Id /// </summary> /// For valid response try integer IDs with value &lt; 1000. Anything /// above 1000 or nonintegers will generate API errors /// <param name='orderId'> /// Id of the order that needs to be deleted /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> DeleteOrderWithHttpMessagesAsync(string orderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create user /// </summary> /// This can only be done by the logged in user. /// <param name='body'> /// Created user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> CreateUserWithHttpMessagesAsync(User body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='body'> /// List of user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> CreateUsersWithArrayInputWithHttpMessagesAsync(IList<User> body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='body'> /// List of user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> CreateUsersWithListInputWithHttpMessagesAsync(IList<User> body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Logs user into the system /// </summary> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<string,LoginUserHeaders>> LoginUserWithHttpMessagesAsync(string username, string password, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> LogoutUserWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get user by user name /// </summary> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<User>> GetUserByNameWithHttpMessagesAsync(string username, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updated user /// </summary> /// This can only be done by the logged in user. /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> UpdateUserWithHttpMessagesAsync(string username, User body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete user /// </summary> /// This can only be done by the logged in user. /// <param name='username'> /// The name that needs to be deleted /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> DeleteUserWithHttpMessagesAsync(string username, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic{ /// <summary> /// Strongly-typed collection for the ConCantidadTipoTurnosEspecialidad class. /// </summary> [Serializable] public partial class ConCantidadTipoTurnosEspecialidadCollection : ReadOnlyList<ConCantidadTipoTurnosEspecialidad, ConCantidadTipoTurnosEspecialidadCollection> { public ConCantidadTipoTurnosEspecialidadCollection() {} } /// <summary> /// This is Read-only wrapper class for the CON_CantidadTipoTurnosEspecialidad view. /// </summary> [Serializable] public partial class ConCantidadTipoTurnosEspecialidad : ReadOnlyRecord<ConCantidadTipoTurnosEspecialidad>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor public static TableSchema.Table Schema { get { if (BaseSchema == null) { SetSQLProps(); } return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("CON_CantidadTipoTurnosEspecialidad", TableType.View, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarCantidad = new TableSchema.TableColumn(schema); colvarCantidad.ColumnName = "Cantidad"; colvarCantidad.DataType = DbType.Int32; colvarCantidad.MaxLength = 0; colvarCantidad.AutoIncrement = false; colvarCantidad.IsNullable = true; colvarCantidad.IsPrimaryKey = false; colvarCantidad.IsForeignKey = false; colvarCantidad.IsReadOnly = false; schema.Columns.Add(colvarCantidad); TableSchema.TableColumn colvarIdTipoTurno = new TableSchema.TableColumn(schema); colvarIdTipoTurno.ColumnName = "idTipoTurno"; colvarIdTipoTurno.DataType = DbType.Int32; colvarIdTipoTurno.MaxLength = 0; colvarIdTipoTurno.AutoIncrement = false; colvarIdTipoTurno.IsNullable = false; colvarIdTipoTurno.IsPrimaryKey = false; colvarIdTipoTurno.IsForeignKey = false; colvarIdTipoTurno.IsReadOnly = false; schema.Columns.Add(colvarIdTipoTurno); TableSchema.TableColumn colvarIdAgenda = new TableSchema.TableColumn(schema); colvarIdAgenda.ColumnName = "idAgenda"; colvarIdAgenda.DataType = DbType.Int32; colvarIdAgenda.MaxLength = 0; colvarIdAgenda.AutoIncrement = false; colvarIdAgenda.IsNullable = false; colvarIdAgenda.IsPrimaryKey = false; colvarIdAgenda.IsForeignKey = false; colvarIdAgenda.IsReadOnly = false; schema.Columns.Add(colvarIdAgenda); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("CON_CantidadTipoTurnosEspecialidad",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public ConCantidadTipoTurnosEspecialidad() { SetSQLProps(); SetDefaults(); MarkNew(); } public ConCantidadTipoTurnosEspecialidad(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public ConCantidadTipoTurnosEspecialidad(object keyID) { SetSQLProps(); LoadByKey(keyID); } public ConCantidadTipoTurnosEspecialidad(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("Cantidad")] [Bindable(true)] public int? Cantidad { get { return GetColumnValue<int?>("Cantidad"); } set { SetColumnValue("Cantidad", value); } } [XmlAttribute("IdTipoTurno")] [Bindable(true)] public int IdTipoTurno { get { return GetColumnValue<int>("idTipoTurno"); } set { SetColumnValue("idTipoTurno", value); } } [XmlAttribute("IdAgenda")] [Bindable(true)] public int IdAgenda { get { return GetColumnValue<int>("idAgenda"); } set { SetColumnValue("idAgenda", value); } } #endregion #region Columns Struct public struct Columns { public static string Cantidad = @"Cantidad"; public static string IdTipoTurno = @"idTipoTurno"; public static string IdAgenda = @"idAgenda"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
using System; using System.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 TestWebApp.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>(); } /// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and 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)) { 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="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <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, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [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.IO; using System.Collections.Generic; using System.Linq; using CobaltAHK.Expressions; namespace CobaltAHK { public class Parser { public Expression[] Parse(TextReader code) { var lexer = new Lexer(code); var expressions = new List<Expression>(); SkipNewlinesAndComments(lexer); var token = lexer.PeekToken(); while (token != Token.EOF) { expressions.Add(ParseExpression(lexer)); SkipNewlinesAndComments(lexer); token = lexer.PeekToken(); } return expressions.ToArray(); } private Expression ParseExpression(Lexer lexer) { var token = lexer.PeekToken(); if (token is DirectiveToken) { var directive = (DirectiveToken)token; if (directive.Directive == Syntax.Directive.If) { return ParseWithState(lexer, Lexer.State.Expression, () => new IfDirectiveExpression(lexer.Position, ParseExpressionChain(lexer).ToExpression()) ); } return ParseDirective(lexer); } else if (token is IdToken) { var id = (IdToken)lexer.GetToken(); Expression expr; if (TryParseIdExpression(lexer, id, out expr) || TryParseIdTraditional(lexer, id, out expr)) { return expr; } throw new Exception(); // todo } else if (token is FunctionToken) { return ParseFunctionCallOrDefinition(lexer); } else if (token is KeywordToken) { var kw = ((KeywordToken)token).Keyword; switch (kw) { case Syntax.Keyword.Class: return ParseClassDefinition(lexer); case Syntax.Keyword.Return: return ParseReturn(lexer); case Syntax.Keyword.Throw: return ParseThrow(lexer); case Syntax.Keyword.If: return ParseIf(lexer); case Syntax.Keyword.Else: throw new InvalidOperationException(); // todo } } else if (token is HotkeyToken) { throw new NotImplementedException("hotkey"); } else if (token is HotstringToken) { throw new NotImplementedException("hotstring"); } throw new NotImplementedException(token.ToString()); } #region try modes private bool TryParseIdExpression(Lexer lexer, IdToken id, out Expression expr) { return ParseWithState(lexer, Lexer.State.Expression, out expr, token => { if (token is OperatorToken) { var chain = new ExpressionChain(); if (token == OperatorToken.GetToken(Operator.ObjectAccess)) { var acc = ParseObjectAccess(lexer, GetVariable(id.Text, id.Position)); chain.Append(acc); } else { chain.Append(GetVariable(id.Text, id.Position)); } ParseExpressionChain(lexer, chain); return chain.ToExpression(); } // todo: ParseExpressionSequence() parses a list of unrelated, comma-separated expressions // todo: put them in the expression queue return null; }); } private bool TryParseIdTraditional(Lexer lexer, IdToken id, out Expression expr) { return ParseWithState(lexer, Lexer.State.Traditional, out expr, token => { if (token == Token.Comma || token == Token.Newline || token == Token.EOF || token == Token.ForceExpression || token is TraditionalStringToken || token is VariableToken) { return ParseCommand(lexer, id); } return null; }); } #endregion private FunctionCallExpression ParseCommand(Lexer lexer, IdToken command) { lexer.PushState(Lexer.State.Traditional); if (lexer.PeekToken() == Token.Comma) { lexer.GetToken();// consume it so it isn't mistakened for an empty parameter } var parameters = ParseParameters(lexer); lexer.PopState(); return new FunctionCallExpression(command.Position, command.Text, parameters); } private BlockExpression ParseIf(Lexer lexer) { AssertToken(lexer.PeekToken(), KeywordToken.GetToken(Syntax.Keyword.If)); var before = lexer.Position; var token = lexer.PeekToken(); var branches = new List<ControlFlowExpression>(); while (token is KeywordToken && (((KeywordToken)token).Keyword == Syntax.Keyword.If || ((KeywordToken)token).Keyword == Syntax.Keyword.Else)) { branches.Add(ParseControlFlowBranch(lexer)); before = lexer.Position; SkipNewline(lexer, UInt32.MaxValue); token = lexer.PeekToken(); } lexer.Rewind(before); lexer.ResetToken(); return new BlockExpression(lexer.Position, branches.ToArray()); } private ControlFlowExpression ParseControlFlowBranch(Lexer lexer) { AssertToken(lexer.PeekToken(), typeof(KeywordToken)); var token = (KeywordToken)lexer.GetToken(); ValueExpression cond = null; bool isElse = false; if (token.Keyword == Syntax.Keyword.Else) { var before = lexer.Position; isElse = lexer.PeekToken() != KeywordToken.GetToken(Syntax.Keyword.If); if (isElse) { lexer.Rewind(before); lexer.ResetToken(); } else { lexer.GetToken(); } } else if (token.Keyword != Syntax.Keyword.If) { throw new Exception(); // todo } if (!isElse) { cond = ParseIfCondition(lexer); } var body = ParseBlock(lexer, e => ValidateExpressionInIfElse(e)); if (isElse) { return new ElseExpression(lexer.Position, body); } else { return new IfExpression(lexer.Position, cond, body); } } private void ValidateExpressionInIfElse(Expression expr) { if (expr is DirectiveExpression || expr is FunctionDefinitionExpression || expr is ClassDefinitionExpression) { throw new Exception(); // todo } } private ValueExpression ParseIfCondition(Lexer lexer) { lexer.PushState(Lexer.State.Expression); var endToken = Token.OpenBrace; // todo: what about object literals? bool inParentheses = lexer.PeekToken() == Token.OpenParenthesis; if (inParentheses) { lexer.GetToken(); endToken = Token.CloseParenthesis; } var cond = ParseExpressionChain(lexer, endToken).ToExpression(); if (inParentheses) { AssertToken(lexer.GetToken(), Token.CloseParenthesis); } lexer.PopState(); return cond; } private ReturnExpression ParseReturn(Lexer lexer) { AssertToken(lexer.GetToken(), KeywordToken.GetToken(Syntax.Keyword.Return)); lexer.PushState(Lexer.State.Expression); Token endToken = null; if (lexer.PeekToken() == Token.OpenParenthesis) { lexer.GetToken(); endToken = Token.CloseParenthesis; } var exprs = ParseExpressionSequence(lexer, endToken); if (endToken != null) { AssertToken(lexer.GetToken(), endToken); } var value = exprs.Length > 0 ? exprs.Last() : null; var others = exprs.Except(new[] { value }); lexer.PopState(); return new ReturnExpression(lexer.Position, value, others); } private ThrowExpression ParseThrow(Lexer lexer) { AssertToken(lexer.GetToken(), KeywordToken.GetToken(Syntax.Keyword.Throw)); lexer.PushState(Lexer.State.Expression); Token[] endToken = {}; if (lexer.PeekToken() == Token.OpenParenthesis) { lexer.GetToken(); endToken = new[] { Token.CloseParenthesis }; } var val = ParseExpressionChain(lexer, endToken); if (endToken.Length > 0) { AssertToken(lexer.GetToken(), endToken[0]); } lexer.PopState(); return new ThrowExpression(lexer.Position, val.ToExpression()); } private DirectiveExpression ParseDirective(Lexer lexer) { AssertToken(lexer.PeekToken(), typeof(DirectiveToken)); var directive = (DirectiveToken)lexer.GetToken(); lexer.PushState(Lexer.State.Traditional); if (lexer.PeekToken() == Token.Comma) { lexer.GetToken(); // consume so it's not considered an empty parameter } var parameters = ValidateDirectiveParams(ParseParameters(lexer), directive.Directive); lexer.PopState(); return new DirectiveExpression(lexer.Position, directive.Directive, parameters.ToArray()); } private ClassDefinitionExpression ParseClassDefinition(Lexer lexer) { AssertToken(lexer.GetToken(), KeywordToken.GetToken(Syntax.Keyword.Class)); lexer.PushState(Lexer.State.Expression); AssertToken(lexer.PeekToken(), typeof(IdToken)); var name = (IdToken)lexer.GetToken(); SkipNewline(lexer); var token = lexer.PeekToken(); AssertToken(token, Token.OpenBrace); var expressions = ParseBlock(lexer, e => ValidateExpressionInDefinition(e)); AssertToken(lexer.GetToken(), Token.Newline, Token.EOF); IEnumerable<FunctionDefinitionExpression> methods; FilterClassBodyExpressions(expressions, out methods); lexer.PopState(); return new ClassDefinitionExpression(lexer.Position, name.Text, methods); } /// <summary> /// Parses a function call. /// </summary> /// <returns> /// The FunctionCallExpression representing the function call. /// </returns> /// <param name='lexer'> /// The current Lexer instance; /// </param> /// <remarks> /// Expects a <see cref="FunctionToken"/> and <see cref="Token.OpenParenthesis"/> from the Lexer. /// </remarks> private FunctionCallExpression ParseFunctionCall(ITokenStream stream) { AssertToken(stream.PeekToken(), typeof(FunctionToken)); var func = (FunctionToken)stream.GetToken(); AssertToken(stream.PeekToken(), Token.OpenParenthesis); var parameters = ParseExpressionList(stream); return new FunctionCallExpression(func.Position, func.Text, parameters); } private Expression ParseFunctionCallOrDefinition(Lexer lexer) { AssertToken(lexer.PeekToken(), typeof(FunctionToken)); var func = (FunctionToken)lexer.GetToken(); lexer.PushState(Lexer.State.Expression); var parameters = ReadFunctionParamTokens(lexer); var beforeToken = lexer.Position; bool newline = SkipNewline(lexer); var token = lexer.PeekToken(); Expression result; if (token == Token.OpenBrace) { // function definition var body = ParseBlock(lexer, e => ValidateExpressionInDefinition(e)); AssertToken(lexer.GetToken(), Token.Newline, Token.EOF); var prms = ParseParamDefinitions(parameters); result = new FunctionDefinitionExpression(func.Position, func.Text, prms, body); } else { // function call var funcExpr = new FunctionCallExpression(func.Position, func.Text, ParseExpressionList(parameters)); bool concat = newline && token is OperatorToken; // todo if (!newline || concat) { var chain = new ExpressionChain(); if (token == OperatorToken.GetToken(Operator.ObjectAccess)) { chain.Append(ParseObjectAccess(lexer, funcExpr)); } else { chain.Append(funcExpr); } ParseExpressionChain(lexer, chain); // parse further expressions here, like `myfunc("myParam").Add(5)` result = chain.ToExpression(); } else { result = funcExpr; lexer.Rewind(beforeToken); lexer.ResetToken(); } } lexer.PopState(); return result; } private ITokenStream ReadFunctionParamTokens(Lexer lexer) { var list = new List<Token>(); var pos = lexer.Position; int level = 0; lexer.PushState(Lexer.State.Expression); AssertToken(lexer.PeekToken(), Token.OpenParenthesis); list.Add(lexer.GetToken()); var token = lexer.PeekToken(); while (token != Token.CloseParenthesis || level > 0) { if (token == Token.OpenParenthesis) { ++level; } else if (token == Token.CloseParenthesis) { --level; } else if (token == Token.EOF) { throw new Exception(); // todo } list.Add(lexer.GetToken()); token = lexer.PeekToken(); } AssertToken(lexer.PeekToken(), Token.CloseParenthesis); list.Add(lexer.GetToken()); lexer.PopState(); return new ArrayTokenStream(pos, list.ToArray()); } #region helpers #region traditional private IEnumerable<ValueExpression> ValidateDirectiveParams(IEnumerable<ValueExpression> parameters, Syntax.Directive directive) { var list = new List<ValueExpression>(); foreach (var param in parameters) { if (param is BuiltinVariableExpression) { if (directive != Syntax.Directive.Include) { throw new Exception(); // todo } var variable = (BuiltinVariableExpression)param; if (!variable.Variable.IsAllowedInInclude()) { throw new Exception(); // todo } } else if (param is BinaryExpression && ((BinaryExpression)param).Operator == Operator.Concatenate) { // (implicit, traditional) concat ValidateDirectiveParams(((BinaryExpression)param).Expressions, directive); } else { throw new Exception(); // todo } list.Add(param); } return list.ToArray(); } private ValueExpression[] ParseParameters(Lexer lexer) { lexer.PushState(Lexer.State.Traditional); var list = new List<ValueExpression>(); var token = lexer.PeekToken(); ExpressionChain currentParam = new ExpressionChain(); while (true) { bool consumed = false; if (token == Token.EOF || token is SingleCommentToken) { if (currentParam.Length == 0 && list.Count > 0) { // throw, but not if there are no params at all throw new Exception(); // todo } else if (currentParam.Length > 0) { list.Add(currentParam.ToExpression()); } currentParam = null; break; } else if (token == Token.Newline) { consumed = true; var pos = lexer.Position; bool concat = lexer.PeekToken() == Token.Comma; // todo: concat with a comment in between // possibly: expression queue if (currentParam.Length == 0 && !concat && list.Count > 0) { // throw, but not if there are no params at all throw new Exception(); // todo } if (!concat) { if (currentParam.Length > 0) { list.Add(currentParam.ToExpression()); currentParam = null; } lexer.ResetToken(); lexer.Rewind(pos); break; } } else if (token == Token.Comma) { if (currentParam.Length == 0) { list.Add(null); // append NULL for empty parameters } else { list.Add(currentParam.ToExpression()); } currentParam = new ExpressionChain(); } else if (token == Token.ForceExpression) { if (currentParam.Length > 0) { throw new Exception("ForceExpression must be first"); // todo } lexer.GetToken(); consumed = true; currentParam.Append( ParseWithState(lexer, Lexer.State.Expression, () => ParseExpressionChain(lexer, Token.Comma).ToExpression() ) ); } else if (token is TraditionalStringToken) { // todo: ensure currentParam is not forced expression var str = (TraditionalStringToken)token; if (str.Text.Trim() == String.Empty && currentParam.Length == 0) { continue; // ignore leading whitespace } var expr = new StringLiteralExpression(str.Position, str.Text); currentParam.Append(expr); } else if (token is VariableToken) { // todo: ensure currentParam is not forced expression var variable = (VariableToken)token; var expr = GetVariable(variable.Text, variable.Position); currentParam.Append(expr); } else { throw new Exception("unsupported token: " + token); // todo } if (!consumed) { lexer.GetToken(); } token = lexer.PeekToken(); } lexer.PopState(); return list.ToArray(); } #endregion #region expression mode private ExpressionChain ParseExpressionChain(ITokenStream stream, params Token[] terminators) { var chain = new ExpressionChain(); ParseExpressionChain(stream, chain, terminators); return chain; } private void ParseExpressionChain(ITokenStream stream, ExpressionChain chain, IEnumerable<Token> terminators = null) { var token = stream.PeekToken(); UnaryOperator prefixOp = null; while (token != Token.EOF) { if (token == Token.Newline) { if (prefixOp != null) { throw new Exception(); // todo } stream.GetToken(); token = stream.PeekToken(); if (!(token is OperatorToken)) { // don't concat break; } } if (terminators != null && terminators.Contains(token)) { if (prefixOp != null) { throw new Exception(); // todo } break; } if (token is OperatorToken) { if (prefixOp != null) { throw new Exception(); // todo } var op = ((OperatorToken)token).Operator; if (op == Operator.AltObjAccess) { // special handling for f[A, B] ParseAltObjAccess(stream, chain); } else if (op is UnaryOperator) { prefixOp = (UnaryOperator)op; if (prefixOp.Position != Position.prefix) { throw new Exception(); // todo } } else if (op is BinaryOperator) { chain.Append((BinaryOperator)op); } else { throw new Exception(); // todo } } else { ValueExpression expr; if (token == Token.OpenParenthesis) { stream.GetToken(); // consume parenthesis expr = ParseExpressionChain(stream, Token.CloseParenthesis).ToExpression(); stream.GetToken(); // consume closing parenthesis } else { expr = TokenToValueExpression(stream); } if (prefixOp != null) { expr = new UnaryExpression(stream.Position, prefixOp, expr); prefixOp = null; } token = stream.PeekToken(); var objAcc = OperatorToken.GetToken(Operator.ObjectAccess); var ternary = OperatorToken.GetToken(Operator.Ternary); while (token == objAcc || token == ternary || IsUnaryPostfixOperator(token)) { if (token == objAcc) { expr = ParseObjectAccess(stream, expr); } else if (token == ternary) { expr = ParseTernary(stream, expr, terminators); } else if (IsUnaryPostfixOperator(token)) { stream.GetToken(); expr = new UnaryExpression(expr.Position, ((OperatorToken)token).Operator, expr); } token = stream.PeekToken(); } chain.Append(expr); continue; } stream.GetToken(); token = stream.PeekToken(); } } private static bool IsUnaryPostfixOperator(Token token) { return token is OperatorToken && ((OperatorToken)token).Operator is UnaryOperator && ((UnaryOperator)((OperatorToken)token).Operator).Position == Position.postfix; } private ValueExpression[] ParseExpressionList(ITokenStream stream) { return ParseExpressionList(stream, Token.OpenParenthesis, Token.CloseParenthesis); } private ValueExpression[] ParseExpressionList(ITokenStream stream, Token open, Token close) { AssertToken(stream.GetToken(), open); var list = ParseExpressionSequence(stream, close); AssertToken(stream.GetToken(), close); return list; } private ValueExpression[] ParseExpressionSequence(ITokenStream stream, Token abort = null) { var list = new List<ValueExpression>(); ExpressionChain currentExpr = null; var token = stream.PeekToken(); while (true) { if (token == Token.EOF) { // todo: if currentExpr == null -> allow empty? or fail? (param to define?) (to allow empty, must add Expression.Empty parameter) list.Add(currentExpr.ToExpression()); break; } else if (token == Token.Comma) { // todo: if currentExpr == null -> allow empty? or fail? (param to define?) (to allow empty, must add Expression.Empty parameter) list.Add(currentExpr.ToExpression()); currentExpr = null; } else if (abort != null && token == abort) { // todo: if currentExpr == null -> allow empty? or fail? (to allow empty, just ignore) (if list.Count == 0 -> don't fail) if (currentExpr != null) { list.Add(currentExpr.ToExpression()); } break; } else { if (currentExpr != null) { if (token == Token.Newline) { break; } throw new Exception(token.ToString()); } currentExpr = ParseExpressionChain(stream, Token.Comma, abort); token = stream.PeekToken(); continue; } stream.GetToken(); token = stream.PeekToken(); } return list.ToArray(); } /// <summary> /// Converts a Token to a ValueExpression. /// </summary> /// <returns> /// The ValueExpression. /// </returns> /// <param name='lexer'> /// The current Lexer instance. /// </param> /// <exception cref="Exception"> /// Thrown if the token cannot be converted. /// </exception> /// <remarks> /// This function consumes the converted token(s). /// </remarks> private ValueExpression TokenToValueExpression(ITokenStream stream) { var token = stream.PeekToken(); if (token is FunctionToken) { return ParseFunctionCall(stream); } else if (token is IdToken) { var id = (IdToken)stream.GetToken(); return GetVariable(id.Text, id.Position); } else if (token is ValueKeywordToken) { var value = (ValueKeywordToken)stream.GetToken(); return new ValueKeywordExpression(stream.Position, value.Keyword); } else if (token is QuotedStringToken) { var str = (QuotedStringToken)stream.GetToken(); return new StringLiteralExpression(str.Position, str.Text); } else if (token is NumberToken) { var number = (NumberToken)stream.GetToken(); return new NumberLiteralExpression(number.Position, number.Text, number.Type); } else if (token == Token.OpenBracket) { var arr = ParseExpressionList(stream, Token.OpenBracket, Token.CloseBracket); return new ArrayLiteralExpression(stream.Position, arr); } else if (token == Token.OpenBrace) { var obj = ParseObjectLiteral(stream); return new ObjectLiteralExpression(stream.Position, obj); } throw new Exception(token.ToString()); // todo } private TernaryExpression ParseTernary(ITokenStream stream, ValueExpression cond, IEnumerable<Token> terminators) { AssertToken(stream.GetToken(), OperatorToken.GetToken(Operator.Ternary)); var ifTrue = ParseExpressionChain(stream, Token.Colon); AssertToken(stream.GetToken(), Token.Colon); var ifFalse = ParseExpressionChain(stream, terminators != null ? terminators.ToArray() : null); return new TernaryExpression(cond.Position, cond, ifTrue.ToExpression(), ifFalse.ToExpression()); } private MemberExpression ParseObjectAccess(ITokenStream stream, ValueExpression obj) { AssertToken(stream.GetToken(), OperatorToken.GetToken(Operator.ObjectAccess)); AssertToken(stream.PeekToken(), typeof(TextToken)); AssertToken(stream.PeekToken(), typeof(TextToken)); var token = (TextToken)stream.GetToken(); if (token is IdToken) { return new MemberAccessExpression(obj.Position, obj, token.Text); } else if (token is FunctionToken) { return new MemberInvokeExpression(obj.Position, obj, token.Text); } throw new Exception(); // todo } private void ParseAltObjAccess(ITokenStream stream, ExpressionChain chain) { AssertToken(stream.GetToken(), OperatorToken.GetToken(Operator.AltObjAccess)); chain.Append((BinaryOperator)Operator.AltObjAccess); var token = stream.PeekToken(); ValueExpression currentParam = null; while (token != Token.CloseBracket) { // todo if (token == Token.Comma) { stream.GetToken(); if (currentParam == null) { // todo: empty expression? fail? } chain.Append(currentParam); chain.Append((BinaryOperator)Operator.AltObjAccess); currentParam = null; } else { if (currentParam != null) { throw new Exception(); // todo } currentParam = ParseExpressionChain(stream, Token.Comma, Token.CloseBracket).ToExpression(); } token = stream.PeekToken(); } if (currentParam == null) { // todo (see above for comma) } chain.Append(currentParam); } private IDictionary<ValueExpression, ValueExpression> ParseObjectLiteral(ITokenStream stream) { AssertToken(stream.GetToken(), Token.OpenBrace); var dict = new Dictionary<ValueExpression, ValueExpression>(); var token = stream.PeekToken(); while (token != Token.CloseBrace) { var key = ParseExpressionChain(stream, Token.Colon).ToExpression(); AssertToken(stream.GetToken(), Token.Colon); var value = ParseExpressionChain(stream, Token.Comma, Token.CloseBrace).ToExpression(); dict[key] = value; if (stream.PeekToken() == Token.Comma) { stream.GetToken(); } token = stream.PeekToken(); } AssertToken(stream.GetToken(), Token.CloseBrace); return dict; } #endregion #region definitions #region function definitions private ParameterDefinitionExpression[] ParseParamDefinitions(ITokenStream stream) { var list = new List<ParameterDefinitionExpression>(); AssertToken(stream.GetToken(), Token.OpenParenthesis); while (stream.PeekToken() != Token.CloseParenthesis) { IdToken nameToken = null, modifierToken = null; ValueExpression value = null; AssertToken(stream.PeekToken(), typeof(IdToken)); nameToken = (IdToken)stream.GetToken(); if (stream.PeekToken() is IdToken) { // first was actually a modifier if (!IsValidParamModifier(nameToken)) { throw new Exception(); // todo } modifierToken = nameToken; nameToken = (IdToken)stream.GetToken(); } if (stream.PeekToken() is OperatorToken) { // default value specified stream.GetToken(); value = ParseExpressionChain(stream, Token.Comma, Token.CloseParenthesis).ToExpression(); // todo: what's actually allowed as default value? } AssertToken(stream.PeekToken(), Token.Comma, Token.CloseParenthesis); if (stream.PeekToken() == Token.Comma) { stream.GetToken(); } Syntax.ParameterModifier modifier = modifierToken != null ? Syntax.GetParameterModifier(modifierToken.Text) : Syntax.ParameterModifier.None; list.Add( new ParameterDefinitionExpression((modifierToken ?? nameToken).Position, nameToken.Text, modifier, value ) ); } AssertToken(stream.GetToken(), Token.CloseParenthesis); return list.ToArray(); } private bool IsValidParamModifier(IdToken token) { return Syntax.IsParameterModifier(token.Text); } #endregion #region class definitions private void FilterClassBodyExpressions(IEnumerable<Expression> expressions, out IEnumerable<FunctionDefinitionExpression> methods) { var methodList = new List<FunctionDefinitionExpression> (); foreach (var expr in expressions) { if (expr is FunctionDefinitionExpression) { methodList.Add((FunctionDefinitionExpression)expr); } else { // todo: fields, comments and other allowed expressions throw new Exception(); // todo } } methods = methodList.ToArray(); } #endregion private Expression[] ParseBlock(Lexer lexer, Action<Expression> validate) { AssertToken(lexer.GetToken(), Token.OpenBrace); AssertToken(lexer.GetToken(), Token.Newline); // todo: is newline enforced? var body = new List<Expression>(); lexer.PushState(Lexer.State.Root); var token = lexer.PeekToken(); while (token != Token.CloseBrace) { if (token == Token.EOF) { throw new UnexpectedEOFException(lexer.Position); } else if (token == Token.Newline) { lexer.GetToken(); // consume newline token = lexer.PeekToken(); continue; } if (token is CommentToken) { lexer.GetToken(); // consume token } else { var expr = ParseExpression(lexer); // consumes tokens validate(expr); body.Add(expr); } token = lexer.PeekToken(); } lexer.GetToken(); // swallow the closing brace lexer.PopState(); return body.ToArray(); } private void ValidateExpressionInDefinition(Expression expr) { if (expr is DirectiveExpression) { throw new Exception(); // todo } // this currently allows nested functions and classes - must be properly handled or disallowed } #endregion private bool ParseWithState(Lexer lexer, Lexer.State state, out Expression result, Func<Token, Expression> fn) { var before = lexer.Position; lexer.PushState(state); var token = lexer.PeekToken(); result = fn(token); var success = result != null; if (!success) { lexer.ResetToken(); lexer.Rewind(before); } lexer.PopState(); return success; } private TResult ParseWithState<TResult>(Lexer lexer, Lexer.State state, Func<TResult> fn) { lexer.PushState(state); var expr = fn(); lexer.PopState(); return expr; } private VariableExpression GetVariable(string name, SourcePosition pos) { if (Syntax.IsBuiltinVariable(name)) { return new BuiltinVariableExpression(pos, Syntax.GetBuiltinVariable(name)); } else { return new CustomVariableExpression(pos, name); } } private void AssertToken(Token actual, params Token[] expected) { if (!expected.Contains(actual)) { throw new UnexpectedTokenException("Expected token '" + expected.ToString() + "' but was '" + actual.ToString() + "'"); } } private void AssertToken(Token actual, Type expected) { if (!actual.GetType().TypeIs(expected)) { throw new UnexpectedTokenException("Expected token of type '" + expected.ToString() + "' but was '" + actual.ToString() + "'"); } } private bool SkipNewline(Lexer lexer, uint max = 1) { var token = lexer.PeekToken(); uint index = 0; bool skipped = false; while (token == Token.Newline && index < max) { skipped = true; lexer.GetToken(); token = lexer.PeekToken(); } return skipped; } private void SkipNewlinesAndComments(Lexer lexer) { var token = lexer.PeekToken(); while (token == Token.Newline || token is CommentToken) { lexer.GetToken(); token = lexer.PeekToken(); } } #endregion } public class UnexpectedTokenException : Exception { public UnexpectedTokenException(string msg) : base(msg) { } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Threading; using System.Timers; using System.Xml; using Timer=System.Timers.Timer; using Nini.Config; using NUnit.Framework; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.CoreModules.Avatar.Attachments; using OpenSim.Region.CoreModules.Framework; using OpenSim.Region.CoreModules.Framework.EntityTransfer; using OpenSim.Region.CoreModules.Framework.InventoryAccess; using OpenSim.Region.CoreModules.Scripting.WorldComm; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation; using OpenSim.Region.CoreModules.World.Serialiser; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.Interfaces; using OpenSim.Region.ScriptEngine.XEngine; using OpenSim.Services.Interfaces; using OpenSim.Tests.Common; namespace OpenSim.Region.CoreModules.Avatar.Attachments.Tests { /// <summary> /// Attachment tests /// </summary> [TestFixture] public class AttachmentsModuleTests : OpenSimTestCase { private AutoResetEvent m_chatEvent = new AutoResetEvent(false); // private OSChatMessage m_osChatMessageReceived; // Used to test whether the operations have fired the attach event. Must be reset after each test. private int m_numberOfAttachEventsFired; [TestFixtureSetUp] public void FixtureInit() { // Don't allow tests to be bamboozled by asynchronous events. Execute everything on the same thread. Util.FireAndForgetMethod = FireAndForgetMethod.None; } [TestFixtureTearDown] public void TearDown() { // We must set this back afterwards, otherwise later tests will fail since they're expecting multiple // threads. Possibly, later tests should be rewritten not to worry about such things. Util.FireAndForgetMethod = Util.DefaultFireAndForgetMethod; } private void OnChatFromWorld(object sender, OSChatMessage oscm) { // Console.WriteLine("Got chat [{0}]", oscm.Message); // m_osChatMessageReceived = oscm; m_chatEvent.Set(); } private Scene CreateTestScene() { IConfigSource config = new IniConfigSource(); List<object> modules = new List<object>(); AddCommonConfig(config, modules); Scene scene = new SceneHelpers().SetupScene( "attachments-test-scene", TestHelpers.ParseTail(999), 1000, 1000, config); SceneHelpers.SetupSceneModules(scene, config, modules.ToArray()); scene.EventManager.OnAttach += (localID, itemID, avatarID) => m_numberOfAttachEventsFired++; return scene; } private Scene CreateScriptingEnabledTestScene() { IConfigSource config = new IniConfigSource(); List<object> modules = new List<object>(); AddCommonConfig(config, modules); AddScriptingConfig(config, modules); Scene scene = new SceneHelpers().SetupScene( "attachments-test-scene", TestHelpers.ParseTail(999), 1000, 1000, config); SceneHelpers.SetupSceneModules(scene, config, modules.ToArray()); scene.StartScripts(); return scene; } private void AddCommonConfig(IConfigSource config, List<object> modules) { config.AddConfig("Modules"); config.Configs["Modules"].Set("InventoryAccessModule", "BasicInventoryAccessModule"); AttachmentsModule attMod = new AttachmentsModule(); attMod.DebugLevel = 1; modules.Add(attMod); modules.Add(new BasicInventoryAccessModule()); } private void AddScriptingConfig(IConfigSource config, List<object> modules) { IConfig startupConfig = config.AddConfig("Startup"); startupConfig.Set("DefaultScriptEngine", "XEngine"); IConfig xEngineConfig = config.AddConfig("XEngine"); xEngineConfig.Set("Enabled", "true"); xEngineConfig.Set("StartDelay", "0"); // These tests will not run with AppDomainLoading = true, at least on mono. For unknown reasons, the call // to AssemblyResolver.OnAssemblyResolve fails. xEngineConfig.Set("AppDomainLoading", "false"); modules.Add(new XEngine()); // Necessary to stop serialization complaining // FIXME: Stop this being necessary if at all possible // modules.Add(new WorldCommModule()); } /// <summary> /// Creates an attachment item in the given user's inventory. Does not attach. /// </summary> /// <remarks> /// A user with the given ID and an inventory must already exist. /// </remarks> /// <returns> /// The attachment item. /// </returns> /// <param name='scene'></param> /// <param name='userId'></param> /// <param name='attName'></param> /// <param name='rawItemId'></param> /// <param name='rawAssetId'></param> private InventoryItemBase CreateAttachmentItem( Scene scene, UUID userId, string attName, int rawItemId, int rawAssetId) { return UserInventoryHelpers.CreateInventoryItem( scene, attName, TestHelpers.ParseTail(rawItemId), TestHelpers.ParseTail(rawAssetId), userId, InventoryType.Object); } [Test] public void TestAddAttachmentFromGround() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); m_numberOfAttachEventsFired = 0; Scene scene = CreateTestScene(); UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1); ScenePresence sp = SceneHelpers.AddScenePresence(scene, ua1); string attName = "att"; SceneObjectGroup so = SceneHelpers.AddSceneObject(scene, attName, sp.UUID); Assert.That(so.Backup, Is.True); m_numberOfAttachEventsFired = 0; scene.AttachmentsModule.AttachObject(sp, so, (uint)AttachmentPoint.Chest, false, true, false); // Check status on scene presence Assert.That(sp.HasAttachments(), Is.True); List<SceneObjectGroup> attachments = sp.GetAttachments(); Assert.That(attachments.Count, Is.EqualTo(1)); SceneObjectGroup attSo = attachments[0]; Assert.That(attSo.Name, Is.EqualTo(attName)); Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.Chest)); Assert.That(attSo.IsAttachment); Assert.That(attSo.UsesPhysics, Is.False); Assert.That(attSo.IsTemporary, Is.False); Assert.That(attSo.Backup, Is.False); // Check item status Assert.That( sp.Appearance.GetAttachpoint(attSo.FromItemID), Is.EqualTo((int)AttachmentPoint.Chest)); InventoryItemBase attachmentItem = scene.InventoryService.GetItem(new InventoryItemBase(attSo.FromItemID)); Assert.That(attachmentItem, Is.Not.Null); Assert.That(attachmentItem.Name, Is.EqualTo(attName)); InventoryFolderBase targetFolder = scene.InventoryService.GetFolderForType(sp.UUID, FolderType.Object); Assert.That(attachmentItem.Folder, Is.EqualTo(targetFolder.ID)); Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1)); // Check events Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1)); } [Test] public void TestWearAttachmentFromGround() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); Scene scene = CreateTestScene(); UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1); ScenePresence sp = SceneHelpers.AddScenePresence(scene, ua1); SceneObjectGroup so2 = SceneHelpers.AddSceneObject(scene, "att2", sp.UUID); { SceneObjectGroup so = SceneHelpers.AddSceneObject(scene, "att1", sp.UUID); m_numberOfAttachEventsFired = 0; scene.AttachmentsModule.AttachObject(sp, so, (uint)AttachmentPoint.Default, false, true, false); // Check status on scene presence Assert.That(sp.HasAttachments(), Is.True); List<SceneObjectGroup> attachments = sp.GetAttachments(); Assert.That(attachments.Count, Is.EqualTo(1)); SceneObjectGroup attSo = attachments[0]; Assert.That(attSo.Name, Is.EqualTo(so.Name)); Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.LeftHand)); Assert.That(attSo.IsAttachment); Assert.That(attSo.UsesPhysics, Is.False); Assert.That(attSo.IsTemporary, Is.False); // Check item status Assert.That( sp.Appearance.GetAttachpoint(attSo.FromItemID), Is.EqualTo((int)AttachmentPoint.LeftHand)); InventoryItemBase attachmentItem = scene.InventoryService.GetItem(new InventoryItemBase(attSo.FromItemID)); Assert.That(attachmentItem, Is.Not.Null); Assert.That(attachmentItem.Name, Is.EqualTo(so.Name)); InventoryFolderBase targetFolder = scene.InventoryService.GetFolderForType(sp.UUID, FolderType.Object); Assert.That(attachmentItem.Folder, Is.EqualTo(targetFolder.ID)); Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(2)); // Check events Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1)); } // Test wearing a different attachment from the ground. { scene.AttachmentsModule.AttachObject(sp, so2, (uint)AttachmentPoint.Default, false, true, false); // Check status on scene presence Assert.That(sp.HasAttachments(), Is.True); List<SceneObjectGroup> attachments = sp.GetAttachments(); Assert.That(attachments.Count, Is.EqualTo(1)); SceneObjectGroup attSo = attachments[0]; Assert.That(attSo.Name, Is.EqualTo(so2.Name)); Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.LeftHand)); Assert.That(attSo.IsAttachment); Assert.That(attSo.UsesPhysics, Is.False); Assert.That(attSo.IsTemporary, Is.False); // Check item status Assert.That( sp.Appearance.GetAttachpoint(attSo.FromItemID), Is.EqualTo((int)AttachmentPoint.LeftHand)); InventoryItemBase attachmentItem = scene.InventoryService.GetItem(new InventoryItemBase(attSo.FromItemID)); Assert.That(attachmentItem, Is.Not.Null); Assert.That(attachmentItem.Name, Is.EqualTo(so2.Name)); InventoryFolderBase targetFolder = scene.InventoryService.GetFolderForType(sp.UUID, FolderType.Object); Assert.That(attachmentItem.Folder, Is.EqualTo(targetFolder.ID)); Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1)); // Check events Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(3)); } // Test rewearing an already worn attachment from ground. Nothing should happen. { scene.AttachmentsModule.AttachObject(sp, so2, (uint)AttachmentPoint.Default, false, true, false); // Check status on scene presence Assert.That(sp.HasAttachments(), Is.True); List<SceneObjectGroup> attachments = sp.GetAttachments(); Assert.That(attachments.Count, Is.EqualTo(1)); SceneObjectGroup attSo = attachments[0]; Assert.That(attSo.Name, Is.EqualTo(so2.Name)); Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.LeftHand)); Assert.That(attSo.IsAttachment); Assert.That(attSo.UsesPhysics, Is.False); Assert.That(attSo.IsTemporary, Is.False); // Check item status Assert.That( sp.Appearance.GetAttachpoint(attSo.FromItemID), Is.EqualTo((int)AttachmentPoint.LeftHand)); InventoryItemBase attachmentItem = scene.InventoryService.GetItem(new InventoryItemBase(attSo.FromItemID)); Assert.That(attachmentItem, Is.Not.Null); Assert.That(attachmentItem.Name, Is.EqualTo(so2.Name)); InventoryFolderBase targetFolder = scene.InventoryService.GetFolderForType(sp.UUID, FolderType.Object); Assert.That(attachmentItem.Folder, Is.EqualTo(targetFolder.ID)); Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1)); // Check events Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(3)); } } /// <summary> /// Test that we do not attempt to attach an in-world object that someone else is sitting on. /// </summary> [Test] public void TestAddSatOnAttachmentFromGround() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); m_numberOfAttachEventsFired = 0; Scene scene = CreateTestScene(); UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1); ScenePresence sp = SceneHelpers.AddScenePresence(scene, ua1); string attName = "att"; SceneObjectGroup so = SceneHelpers.AddSceneObject(scene, attName, sp.UUID); UserAccount ua2 = UserAccountHelpers.CreateUserWithInventory(scene, 0x2); ScenePresence sp2 = SceneHelpers.AddScenePresence(scene, ua2); // Put avatar within 10m of the prim so that sit doesn't fail. sp2.AbsolutePosition = new Vector3(0, 0, 0); sp2.HandleAgentRequestSit(sp2.ControllingClient, sp2.UUID, so.UUID, Vector3.Zero); scene.AttachmentsModule.AttachObject(sp, so, (uint)AttachmentPoint.Chest, false, true, false); Assert.That(sp.HasAttachments(), Is.False); Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1)); // Check events Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(0)); } [Test] public void TestRezAttachmentFromInventory() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); Scene scene = CreateTestScene(); UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1); ScenePresence sp = SceneHelpers.AddScenePresence(scene, ua1.PrincipalID); InventoryItemBase attItem = CreateAttachmentItem(scene, ua1.PrincipalID, "att", 0x10, 0x20); { scene.AttachmentsModule.RezSingleAttachmentFromInventory( sp, attItem.ID, (uint)AttachmentPoint.Chest); // Check scene presence status Assert.That(sp.HasAttachments(), Is.True); List<SceneObjectGroup> attachments = sp.GetAttachments(); Assert.That(attachments.Count, Is.EqualTo(1)); SceneObjectGroup attSo = attachments[0]; Assert.That(attSo.Name, Is.EqualTo(attItem.Name)); Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.Chest)); Assert.That(attSo.IsAttachment); Assert.That(attSo.UsesPhysics, Is.False); Assert.That(attSo.IsTemporary, Is.False); Assert.IsFalse(attSo.Backup); // Check appearance status Assert.That(sp.Appearance.GetAttachments().Count, Is.EqualTo(1)); Assert.That(sp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest)); Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1)); // Check events Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1)); } // Test attaching an already attached attachment { scene.AttachmentsModule.RezSingleAttachmentFromInventory( sp, attItem.ID, (uint)AttachmentPoint.Chest); // Check scene presence status Assert.That(sp.HasAttachments(), Is.True); List<SceneObjectGroup> attachments = sp.GetAttachments(); Assert.That(attachments.Count, Is.EqualTo(1)); SceneObjectGroup attSo = attachments[0]; Assert.That(attSo.Name, Is.EqualTo(attItem.Name)); Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.Chest)); Assert.That(attSo.IsAttachment); Assert.That(attSo.UsesPhysics, Is.False); Assert.That(attSo.IsTemporary, Is.False); // Check appearance status Assert.That(sp.Appearance.GetAttachments().Count, Is.EqualTo(1)); Assert.That(sp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest)); Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1)); // Check events Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1)); } } /// <summary> /// Test wearing an attachment from inventory, as opposed to explicit choosing the rez point /// </summary> [Test] public void TestWearAttachmentFromInventory() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); Scene scene = CreateTestScene(); UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1); ScenePresence sp = SceneHelpers.AddScenePresence(scene, ua1.PrincipalID); InventoryItemBase attItem1 = CreateAttachmentItem(scene, ua1.PrincipalID, "att1", 0x10, 0x20); InventoryItemBase attItem2 = CreateAttachmentItem(scene, ua1.PrincipalID, "att2", 0x11, 0x21); { m_numberOfAttachEventsFired = 0; scene.AttachmentsModule.RezSingleAttachmentFromInventory(sp, attItem1.ID, (uint)AttachmentPoint.Default); // default attachment point is currently the left hand. Assert.That(sp.HasAttachments(), Is.True); List<SceneObjectGroup> attachments = sp.GetAttachments(); Assert.That(attachments.Count, Is.EqualTo(1)); SceneObjectGroup attSo = attachments[0]; Assert.That(attSo.Name, Is.EqualTo(attItem1.Name)); Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.LeftHand)); Assert.That(attSo.IsAttachment); // Check appearance status Assert.That(sp.Appearance.GetAttachments().Count, Is.EqualTo(1)); Assert.That(sp.Appearance.GetAttachpoint(attItem1.ID), Is.EqualTo((int)AttachmentPoint.LeftHand)); Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1)); // Check events Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1)); } // Test wearing a second attachment at the same position // Until multiple attachments at one point is implemented, this will remove the first attachment // This test relies on both attachments having the same default attachment point (in this case LeftHand // since none other has been set). { scene.AttachmentsModule.RezSingleAttachmentFromInventory(sp, attItem2.ID, (uint)AttachmentPoint.Default); // default attachment point is currently the left hand. Assert.That(sp.HasAttachments(), Is.True); List<SceneObjectGroup> attachments = sp.GetAttachments(); Assert.That(attachments.Count, Is.EqualTo(1)); SceneObjectGroup attSo = attachments[0]; Assert.That(attSo.Name, Is.EqualTo(attItem2.Name)); Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.LeftHand)); Assert.That(attSo.IsAttachment); // Check appearance status Assert.That(sp.Appearance.GetAttachments().Count, Is.EqualTo(1)); Assert.That(sp.Appearance.GetAttachpoint(attItem2.ID), Is.EqualTo((int)AttachmentPoint.LeftHand)); Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1)); // Check events Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(3)); } // Test wearing an already attached attachment { scene.AttachmentsModule.RezSingleAttachmentFromInventory(sp, attItem2.ID, (uint)AttachmentPoint.Default); // default attachment point is currently the left hand. Assert.That(sp.HasAttachments(), Is.True); List<SceneObjectGroup> attachments = sp.GetAttachments(); Assert.That(attachments.Count, Is.EqualTo(1)); SceneObjectGroup attSo = attachments[0]; Assert.That(attSo.Name, Is.EqualTo(attItem2.Name)); Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.LeftHand)); Assert.That(attSo.IsAttachment); // Check appearance status Assert.That(sp.Appearance.GetAttachments().Count, Is.EqualTo(1)); Assert.That(sp.Appearance.GetAttachpoint(attItem2.ID), Is.EqualTo((int)AttachmentPoint.LeftHand)); Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1)); // Check events Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(3)); } } /// <summary> /// Test specific conditions associated with rezzing a scripted attachment from inventory. /// </summary> [Test] public void TestRezScriptedAttachmentFromInventory() { TestHelpers.InMethod(); Scene scene = CreateScriptingEnabledTestScene(); UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1); ScenePresence sp = SceneHelpers.AddScenePresence(scene, ua1); SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, sp.UUID, "att-name", 0x10); TaskInventoryItem scriptItem = TaskInventoryHelpers.AddScript( scene.AssetService, so.RootPart, "scriptItem", "default { attach(key id) { if (id != NULL_KEY) { llSay(0, \"Hello World\"); } } }"); InventoryItemBase userItem = UserInventoryHelpers.AddInventoryItem(scene, so, 0x100, 0x1000); // FIXME: Right now, we have to do a tricksy chat listen to make sure we know when the script is running. // In the future, we need to be able to do this programatically more predicably. scene.EventManager.OnChatFromWorld += OnChatFromWorld; scene.AttachmentsModule.RezSingleAttachmentFromInventory(sp, userItem.ID, (uint)AttachmentPoint.Chest); m_chatEvent.WaitOne(60000); // TODO: Need to have a test that checks the script is actually started but this involves a lot more // plumbing of the script engine and either pausing for events or more infrastructure to turn off various // script engine delays/asychronicity that isn't helpful in an automated regression testing context. SceneObjectGroup attSo = scene.GetSceneObjectGroup(so.Name); Assert.That(attSo.ContainsScripts(), Is.True); TaskInventoryItem reRezzedScriptItem = attSo.RootPart.Inventory.GetInventoryItem(scriptItem.Name); IScriptModule xengine = scene.RequestModuleInterface<IScriptModule>(); Assert.That(xengine.GetScriptState(reRezzedScriptItem.ItemID), Is.True); } [Test] public void TestDetachAttachmentToGround() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); Scene scene = CreateTestScene(); UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1); ScenePresence sp = SceneHelpers.AddScenePresence(scene, ua1.PrincipalID); InventoryItemBase attItem = CreateAttachmentItem(scene, ua1.PrincipalID, "att", 0x10, 0x20); ISceneEntity so = scene.AttachmentsModule.RezSingleAttachmentFromInventory( sp, attItem.ID, (uint)AttachmentPoint.Chest); m_numberOfAttachEventsFired = 0; scene.AttachmentsModule.DetachSingleAttachmentToGround(sp, so.LocalId); // Check scene presence status Assert.That(sp.HasAttachments(), Is.False); List<SceneObjectGroup> attachments = sp.GetAttachments(); Assert.That(attachments.Count, Is.EqualTo(0)); // Check appearance status Assert.That(sp.Appearance.GetAttachments().Count, Is.EqualTo(0)); // Check item status Assert.That(scene.InventoryService.GetItem(new InventoryItemBase(attItem.ID)), Is.Null); // Check object in scene SceneObjectGroup soInScene = scene.GetSceneObjectGroup("att"); Assert.That(soInScene, Is.Not.Null); Assert.IsTrue(soInScene.Backup); // Check events Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1)); } [Test] public void TestDetachAttachmentToInventory() { TestHelpers.InMethod(); Scene scene = CreateTestScene(); UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1); ScenePresence sp = SceneHelpers.AddScenePresence(scene, ua1.PrincipalID); InventoryItemBase attItem = CreateAttachmentItem(scene, ua1.PrincipalID, "att", 0x10, 0x20); SceneObjectGroup so = (SceneObjectGroup)scene.AttachmentsModule.RezSingleAttachmentFromInventory( sp, attItem.ID, (uint)AttachmentPoint.Chest); m_numberOfAttachEventsFired = 0; scene.AttachmentsModule.DetachSingleAttachmentToInv(sp, so); // Check status on scene presence Assert.That(sp.HasAttachments(), Is.False); List<SceneObjectGroup> attachments = sp.GetAttachments(); Assert.That(attachments.Count, Is.EqualTo(0)); // Check item status Assert.That(sp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo(0)); Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(0)); // Check events Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1)); } /// <summary> /// Test specific conditions associated with detaching a scripted attachment from inventory. /// </summary> [Test] public void TestDetachScriptedAttachmentToInventory() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); Scene scene = CreateScriptingEnabledTestScene(); UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1); ScenePresence sp = SceneHelpers.AddScenePresence(scene, ua1); SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, sp.UUID, "att-name", 0x10); TaskInventoryItem scriptTaskItem = TaskInventoryHelpers.AddScript( scene.AssetService, so.RootPart, "scriptItem", "default { attach(key id) { if (id != NULL_KEY) { llSay(0, \"Hello World\"); } } }"); InventoryItemBase userItem = UserInventoryHelpers.AddInventoryItem(scene, so, 0x100, 0x1000); // FIXME: Right now, we have to do a tricksy chat listen to make sure we know when the script is running. // In the future, we need to be able to do this programatically more predicably. scene.EventManager.OnChatFromWorld += OnChatFromWorld; SceneObjectGroup rezzedSo = scene.AttachmentsModule.RezSingleAttachmentFromInventory(sp, userItem.ID, (uint)AttachmentPoint.Chest); // Wait for chat to signal rezzed script has been started. m_chatEvent.WaitOne(60000); scene.AttachmentsModule.DetachSingleAttachmentToInv(sp, rezzedSo); InventoryItemBase userItemUpdated = scene.InventoryService.GetItem(userItem); AssetBase asset = scene.AssetService.Get(userItemUpdated.AssetID.ToString()); // TODO: It would probably be better here to check script state via the saving and retrieval of state // information at a higher level, rather than having to inspect the serialization. XmlDocument soXml = new XmlDocument(); soXml.LoadXml(Encoding.UTF8.GetString(asset.Data)); XmlNodeList scriptStateNodes = soXml.GetElementsByTagName("ScriptState"); Assert.That(scriptStateNodes.Count, Is.EqualTo(1)); // Re-rez the attachment to check script running state SceneObjectGroup reRezzedSo = scene.AttachmentsModule.RezSingleAttachmentFromInventory(sp, userItem.ID, (uint)AttachmentPoint.Chest); // Wait for chat to signal rezzed script has been started. m_chatEvent.WaitOne(60000); TaskInventoryItem reRezzedScriptItem = reRezzedSo.RootPart.Inventory.GetInventoryItem(scriptTaskItem.Name); IScriptModule xengine = scene.RequestModuleInterface<IScriptModule>(); Assert.That(xengine.GetScriptState(reRezzedScriptItem.ItemID), Is.True); // Console.WriteLine(soXml.OuterXml); } /// <summary> /// Test that attachments don't hang about in the scene when the agent is closed /// </summary> [Test] public void TestRemoveAttachmentsOnAvatarExit() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); Scene scene = CreateTestScene(); UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1); InventoryItemBase attItem = CreateAttachmentItem(scene, ua1.PrincipalID, "att", 0x10, 0x20); AgentCircuitData acd = SceneHelpers.GenerateAgentData(ua1.PrincipalID); acd.Appearance = new AvatarAppearance(); acd.Appearance.SetAttachment((int)AttachmentPoint.Chest, attItem.ID, attItem.AssetID); ScenePresence presence = SceneHelpers.AddScenePresence(scene, acd); SceneObjectGroup rezzedAtt = presence.GetAttachments()[0]; m_numberOfAttachEventsFired = 0; scene.CloseAgent(presence.UUID, false); // Check that we can't retrieve this attachment from the scene. Assert.That(scene.GetSceneObjectGroup(rezzedAtt.UUID), Is.Null); // Check events Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(0)); } [Test] public void TestRezAttachmentsOnAvatarEntrance() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); Scene scene = CreateTestScene(); UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1); InventoryItemBase attItem = CreateAttachmentItem(scene, ua1.PrincipalID, "att", 0x10, 0x20); AgentCircuitData acd = SceneHelpers.GenerateAgentData(ua1.PrincipalID); acd.Appearance = new AvatarAppearance(); acd.Appearance.SetAttachment((int)AttachmentPoint.Chest, attItem.ID, attItem.AssetID); m_numberOfAttachEventsFired = 0; ScenePresence presence = SceneHelpers.AddScenePresence(scene, acd); Assert.That(presence.HasAttachments(), Is.True); List<SceneObjectGroup> attachments = presence.GetAttachments(); Assert.That(attachments.Count, Is.EqualTo(1)); SceneObjectGroup attSo = attachments[0]; Assert.That(attSo.Name, Is.EqualTo(attItem.Name)); Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.Chest)); Assert.That(attSo.IsAttachment); Assert.That(attSo.UsesPhysics, Is.False); Assert.That(attSo.IsTemporary, Is.False); Assert.IsFalse(attSo.Backup); // Check appearance status List<AvatarAttachment> retreivedAttachments = presence.Appearance.GetAttachments(); Assert.That(retreivedAttachments.Count, Is.EqualTo(1)); Assert.That(retreivedAttachments[0].AttachPoint, Is.EqualTo((int)AttachmentPoint.Chest)); Assert.That(retreivedAttachments[0].ItemID, Is.EqualTo(attItem.ID)); Assert.That(retreivedAttachments[0].AssetID, Is.EqualTo(attItem.AssetID)); Assert.That(presence.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest)); Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1)); // Check events. We expect OnAttach to fire on login. Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1)); } [Test] public void TestUpdateAttachmentPosition() { TestHelpers.InMethod(); Scene scene = CreateTestScene(); UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1); InventoryItemBase attItem = CreateAttachmentItem(scene, ua1.PrincipalID, "att", 0x10, 0x20); AgentCircuitData acd = SceneHelpers.GenerateAgentData(ua1.PrincipalID); acd.Appearance = new AvatarAppearance(); acd.Appearance.SetAttachment((int)AttachmentPoint.Chest, attItem.ID, attItem.AssetID); ScenePresence sp = SceneHelpers.AddScenePresence(scene, acd); SceneObjectGroup attSo = sp.GetAttachments()[0]; Vector3 newPosition = new Vector3(1, 2, 4); m_numberOfAttachEventsFired = 0; scene.SceneGraph.UpdatePrimGroupPosition(attSo.LocalId, newPosition, sp.ControllingClient); Assert.That(attSo.AbsolutePosition, Is.EqualTo(sp.AbsolutePosition)); Assert.That(attSo.RootPart.AttachedPos, Is.EqualTo(newPosition)); // Check events Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(0)); } [Test] public void TestSameSimulatorNeighbouringRegionsTeleportV1() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); BaseHttpServer httpServer = new BaseHttpServer(99999); MainServer.AddHttpServer(httpServer); MainServer.Instance = httpServer; AttachmentsModule attModA = new AttachmentsModule(); AttachmentsModule attModB = new AttachmentsModule(); EntityTransferModule etmA = new EntityTransferModule(); EntityTransferModule etmB = new EntityTransferModule(); LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule(); IConfigSource config = new IniConfigSource(); IConfig modulesConfig = config.AddConfig("Modules"); modulesConfig.Set("EntityTransferModule", etmA.Name); modulesConfig.Set("SimulationServices", lscm.Name); IConfig entityTransferConfig = config.AddConfig("EntityTransfer"); // In order to run a single threaded regression test we do not want the entity transfer module waiting // for a callback from the destination scene before removing its avatar data. entityTransferConfig.Set("wait_for_callback", false); modulesConfig.Set("InventoryAccessModule", "BasicInventoryAccessModule"); SceneHelpers sh = new SceneHelpers(); TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000); TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1001, 1000); SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm); SceneHelpers.SetupSceneModules( sceneA, config, new CapabilitiesModule(), etmA, attModA, new BasicInventoryAccessModule()); SceneHelpers.SetupSceneModules( sceneB, config, new CapabilitiesModule(), etmB, attModB, new BasicInventoryAccessModule()); // FIXME: Hack - this is here temporarily to revert back to older entity transfer behaviour lscm.ServiceVersion = "SIMULATION/0.1"; UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(sceneA, 0x1); AgentCircuitData acd = SceneHelpers.GenerateAgentData(ua1.PrincipalID); TestClient tc = new TestClient(acd, sceneA); List<TestClient> destinationTestClients = new List<TestClient>(); EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients); ScenePresence beforeTeleportSp = SceneHelpers.AddScenePresence(sceneA, tc, acd); beforeTeleportSp.AbsolutePosition = new Vector3(30, 31, 32); InventoryItemBase attItem = CreateAttachmentItem(sceneA, ua1.PrincipalID, "att", 0x10, 0x20); sceneA.AttachmentsModule.RezSingleAttachmentFromInventory( beforeTeleportSp, attItem.ID, (uint)AttachmentPoint.Chest); Vector3 teleportPosition = new Vector3(10, 11, 12); Vector3 teleportLookAt = new Vector3(20, 21, 22); m_numberOfAttachEventsFired = 0; sceneA.RequestTeleportLocation( beforeTeleportSp.ControllingClient, sceneB.RegionInfo.RegionHandle, teleportPosition, teleportLookAt, (uint)TeleportFlags.ViaLocation); destinationTestClients[0].CompleteMovement(); // Check attachments have made it into sceneB ScenePresence afterTeleportSceneBSp = sceneB.GetScenePresence(ua1.PrincipalID); // This is appearance data, as opposed to actually rezzed attachments List<AvatarAttachment> sceneBAttachments = afterTeleportSceneBSp.Appearance.GetAttachments(); Assert.That(sceneBAttachments.Count, Is.EqualTo(1)); Assert.That(sceneBAttachments[0].AttachPoint, Is.EqualTo((int)AttachmentPoint.Chest)); Assert.That(sceneBAttachments[0].ItemID, Is.EqualTo(attItem.ID)); Assert.That(sceneBAttachments[0].AssetID, Is.EqualTo(attItem.AssetID)); Assert.That(afterTeleportSceneBSp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest)); // This is the actual attachment List<SceneObjectGroup> actualSceneBAttachments = afterTeleportSceneBSp.GetAttachments(); Assert.That(actualSceneBAttachments.Count, Is.EqualTo(1)); SceneObjectGroup actualSceneBAtt = actualSceneBAttachments[0]; Assert.That(actualSceneBAtt.Name, Is.EqualTo(attItem.Name)); Assert.That(actualSceneBAtt.AttachmentPoint, Is.EqualTo((uint)AttachmentPoint.Chest)); Assert.IsFalse(actualSceneBAtt.Backup); Assert.That(sceneB.GetSceneObjectGroups().Count, Is.EqualTo(1)); // Check attachments have been removed from sceneA ScenePresence afterTeleportSceneASp = sceneA.GetScenePresence(ua1.PrincipalID); // Since this is appearance data, it is still present on the child avatar! List<AvatarAttachment> sceneAAttachments = afterTeleportSceneASp.Appearance.GetAttachments(); Assert.That(sceneAAttachments.Count, Is.EqualTo(1)); Assert.That(afterTeleportSceneASp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest)); // This is the actual attachment, which should no longer exist List<SceneObjectGroup> actualSceneAAttachments = afterTeleportSceneASp.GetAttachments(); Assert.That(actualSceneAAttachments.Count, Is.EqualTo(0)); Assert.That(sceneA.GetSceneObjectGroups().Count, Is.EqualTo(0)); // Check events Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(0)); } [Test] public void TestSameSimulatorNeighbouringRegionsTeleportV2() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); BaseHttpServer httpServer = new BaseHttpServer(99999); MainServer.AddHttpServer(httpServer); MainServer.Instance = httpServer; AttachmentsModule attModA = new AttachmentsModule(); AttachmentsModule attModB = new AttachmentsModule(); EntityTransferModule etmA = new EntityTransferModule(); EntityTransferModule etmB = new EntityTransferModule(); LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule(); IConfigSource config = new IniConfigSource(); IConfig modulesConfig = config.AddConfig("Modules"); modulesConfig.Set("EntityTransferModule", etmA.Name); modulesConfig.Set("SimulationServices", lscm.Name); modulesConfig.Set("InventoryAccessModule", "BasicInventoryAccessModule"); SceneHelpers sh = new SceneHelpers(); TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000); TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1001, 1000); SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm); SceneHelpers.SetupSceneModules( sceneA, config, new CapabilitiesModule(), etmA, attModA, new BasicInventoryAccessModule()); SceneHelpers.SetupSceneModules( sceneB, config, new CapabilitiesModule(), etmB, attModB, new BasicInventoryAccessModule()); UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(sceneA, 0x1); AgentCircuitData acd = SceneHelpers.GenerateAgentData(ua1.PrincipalID); TestClient tc = new TestClient(acd, sceneA); List<TestClient> destinationTestClients = new List<TestClient>(); EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients); ScenePresence beforeTeleportSp = SceneHelpers.AddScenePresence(sceneA, tc, acd); beforeTeleportSp.AbsolutePosition = new Vector3(30, 31, 32); Assert.That(destinationTestClients.Count, Is.EqualTo(1)); Assert.That(destinationTestClients[0], Is.Not.Null); InventoryItemBase attItem = CreateAttachmentItem(sceneA, ua1.PrincipalID, "att", 0x10, 0x20); sceneA.AttachmentsModule.RezSingleAttachmentFromInventory( beforeTeleportSp, attItem.ID, (uint)AttachmentPoint.Chest); Vector3 teleportPosition = new Vector3(10, 11, 12); Vector3 teleportLookAt = new Vector3(20, 21, 22); // Here, we need to make clientA's receipt of SendRegionTeleport trigger clientB's CompleteMovement(). This // is to operate the teleport V2 mechanism where the EntityTransferModule will first request the client to // CompleteMovement to the region and then call UpdateAgent to the destination region to confirm the receipt // Both these operations will occur on different threads and will wait for each other. // We have to do this via ThreadPool directly since FireAndForget has been switched to sync for the V1 // test protocol, where we are trying to avoid unpredictable async operations in regression tests. tc.OnTestClientSendRegionTeleport += (regionHandle, simAccess, regionExternalEndPoint, locationID, flags, capsURL) => ThreadPool.UnsafeQueueUserWorkItem(o => destinationTestClients[0].CompleteMovement(), null); m_numberOfAttachEventsFired = 0; sceneA.RequestTeleportLocation( beforeTeleportSp.ControllingClient, sceneB.RegionInfo.RegionHandle, teleportPosition, teleportLookAt, (uint)TeleportFlags.ViaLocation); // Check attachments have made it into sceneB ScenePresence afterTeleportSceneBSp = sceneB.GetScenePresence(ua1.PrincipalID); // This is appearance data, as opposed to actually rezzed attachments List<AvatarAttachment> sceneBAttachments = afterTeleportSceneBSp.Appearance.GetAttachments(); Assert.That(sceneBAttachments.Count, Is.EqualTo(1)); Assert.That(sceneBAttachments[0].AttachPoint, Is.EqualTo((int)AttachmentPoint.Chest)); Assert.That(sceneBAttachments[0].ItemID, Is.EqualTo(attItem.ID)); Assert.That(sceneBAttachments[0].AssetID, Is.EqualTo(attItem.AssetID)); Assert.That(afterTeleportSceneBSp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest)); // This is the actual attachment List<SceneObjectGroup> actualSceneBAttachments = afterTeleportSceneBSp.GetAttachments(); Assert.That(actualSceneBAttachments.Count, Is.EqualTo(1)); SceneObjectGroup actualSceneBAtt = actualSceneBAttachments[0]; Assert.That(actualSceneBAtt.Name, Is.EqualTo(attItem.Name)); Assert.That(actualSceneBAtt.AttachmentPoint, Is.EqualTo((uint)AttachmentPoint.Chest)); Assert.IsFalse(actualSceneBAtt.Backup); Assert.That(sceneB.GetSceneObjectGroups().Count, Is.EqualTo(1)); // Check attachments have been removed from sceneA ScenePresence afterTeleportSceneASp = sceneA.GetScenePresence(ua1.PrincipalID); // Since this is appearance data, it is still present on the child avatar! List<AvatarAttachment> sceneAAttachments = afterTeleportSceneASp.Appearance.GetAttachments(); Assert.That(sceneAAttachments.Count, Is.EqualTo(1)); Assert.That(afterTeleportSceneASp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest)); // This is the actual attachment, which should no longer exist List<SceneObjectGroup> actualSceneAAttachments = afterTeleportSceneASp.GetAttachments(); Assert.That(actualSceneAAttachments.Count, Is.EqualTo(0)); Assert.That(sceneA.GetSceneObjectGroups().Count, Is.EqualTo(0)); // Check events Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(0)); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using TransformFunc = System.Func<string, string>; #if BUILD_PEANUTBUTTER_INTERNAL namespace Imported.PeanutButter.Utils.Dictionaries #else namespace PeanutButter.Utils.Dictionaries #endif { /// <summary> /// Provides a wrapping read-write layer around another dictionary effectively /// allowing transparent rename of the keys /// </summary> /// <typeparam name="TValue">Type of values stored</typeparam> #if BUILD_PEANUTBUTTER_INTERNAL internal #else public #endif class RedirectingDictionary<TValue> : IDictionary<string, TValue> { private readonly IDictionary<string, TValue> _data; private readonly TransformFunc _toNativeTransform; private readonly TransformFunc _fromNativeTransform; /// <summary> /// Constructs a new RedirectingDictionary /// </summary> /// <param name="data">Data to wrap</param> /// <param name="toNativeTransform">Function to transform keys from those used against this object to native ones in the data parameter</param> /// <param name="fromNativeTransform">Function to transform keys from those in the data object (native) to those presented by this object</param> /// <exception cref="ArgumentNullException">Thrown if null data or key transform are supplied </exception> public RedirectingDictionary( IDictionary<string, TValue> data, TransformFunc toNativeTransform, TransformFunc fromNativeTransform ) { _data = data ?? throw new ArgumentNullException(nameof(data)); _toNativeTransform = toNativeTransform ?? throw new ArgumentNullException(nameof(toNativeTransform)); _fromNativeTransform = fromNativeTransform ?? throw new ArgumentNullException(nameof(fromNativeTransform)); } /// <inheritdoc /> public IEnumerator<KeyValuePair<string, TValue>> GetEnumerator() { return new RedirectingDictionaryEnumerator<TValue>(_data, _fromNativeTransform); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <inheritdoc /> public void Add(KeyValuePair<string, TValue> item) { // TODO: find a way to make it such that the given item is also updated // when the dictionary is updated -- currently it won't be _data.Add(new KeyValuePair<string, TValue>(_toNativeTransform(item.Key), item.Value)); } /// <inheritdoc /> public void Clear() { _data.Clear(); } /// <inheritdoc /> public bool Contains(KeyValuePair<string, TValue> item) { var nativeKey = _toNativeTransform(item.Key); return _data.ContainsKey(nativeKey) && _data[nativeKey] as object == item.Value as object; } /// <inheritdoc /> public void CopyTo(KeyValuePair<string, TValue>[] array, int arrayIndex) { foreach (var k in Keys) { array[arrayIndex++] = new KeyValuePair<string, TValue>(k, this[k]); } } /// <inheritdoc /> public bool Remove(KeyValuePair<string, TValue> item) { var nativeKey = _toNativeTransform(item.Key); if (!_data.ContainsKey(nativeKey)) return false; var dataItem = _data[nativeKey]; if (dataItem as object != item.Value as object) return false; return RemoveNative(nativeKey); } /// <inheritdoc /> public int Count => _data.Count; /// <inheritdoc /> public bool IsReadOnly => _data.IsReadOnly; /// <inheritdoc /> public bool ContainsKey(string key) { return _data.ContainsKey(_toNativeTransform(key)); } /// <inheritdoc /> public void Add(string key, TValue value) { _data.Add(_toNativeTransform(key), value); } /// <inheritdoc /> public bool Remove(string key) { var nativeKey = _toNativeTransform(key); return RemoveNative(nativeKey); } private bool RemoveNative(string nativeKey) { return _data.Remove(nativeKey); } /// <inheritdoc /> public bool TryGetValue(string key, out TValue value) { var nativeKey = _toNativeTransform(key); return _data.TryGetValue(nativeKey, out value); } /// <inheritdoc /> public TValue this[string key] { get { var nativeKey = _toNativeTransform(key); return _data[nativeKey]; } set { if (IsReadOnly) throw new InvalidOperationException("Collection is read-only"); var nativeKey = _toNativeTransform(key); _data[nativeKey] = value; } } /// <inheritdoc /> public ICollection<string> Keys => _data.Keys.Select(k => _fromNativeTransform(k)).ToArray(); /// <inheritdoc /> public ICollection<TValue> Values => _data.Values.ToArray(); } internal class RedirectingDictionaryEnumerator<T> : IEnumerator<KeyValuePair<string, T>> { private readonly IDictionary<string, T> _data; private readonly Func<string, string> _keyTransform; private string[] _nativeKeys; private int _currentIndex; internal RedirectingDictionaryEnumerator( IDictionary<string, T> data, Func<string, string> keyTransform ) { _data = data; _keyTransform = keyTransform; Reset(); } public void Dispose() { /* does nothing */ } public bool MoveNext() { _currentIndex++; return _currentIndex < _nativeKeys.Length; } public void Reset() { _currentIndex = -1; _nativeKeys = _data.Keys.ToArray(); } public KeyValuePair<string, T> Current { get { var nativeKey = _nativeKeys[_currentIndex]; var key = _keyTransform(nativeKey); return new KeyValuePair<string, T>(key, _data[nativeKey]); } } object IEnumerator.Current => Current; } }
/* ==================================================================== 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 TestCases.SS.Formula.Functions { using NPOI.SS.Formula.Eval; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System; using NUnit.Framework; using NPOI.SS.Formula.Functions; /** * Tests for the INDIRECT() function.</p> * * @author Josh Micich */ [TestFixture] public class TestIndirect { // convenient access to namespace //private static ErrorEval EE = null; private static void CreateDataRow(ISheet sheet, int rowIndex, params double[] vals) { IRow row = sheet.CreateRow(rowIndex); for (int i = 0; i < vals.Length; i++) { row.CreateCell(i).SetCellValue(vals[i]); } } private static HSSFWorkbook CreateWBA() { HSSFWorkbook wb = new HSSFWorkbook(); ISheet sheet1 = wb.CreateSheet("Sheet1"); ISheet sheet2 = wb.CreateSheet("Sheet2"); ISheet sheet3 = wb.CreateSheet("John's sales"); CreateDataRow(sheet1, 0, 11, 12, 13, 14); CreateDataRow(sheet1, 1, 21, 22, 23, 24); CreateDataRow(sheet1, 2, 31, 32, 33, 34); CreateDataRow(sheet2, 0, 50, 55, 60, 65); CreateDataRow(sheet2, 1, 51, 56, 61, 66); CreateDataRow(sheet2, 2, 52, 57, 62, 67); CreateDataRow(sheet3, 0, 30, 31, 32); CreateDataRow(sheet3, 1, 33, 34, 35); IName name1 = wb.CreateName(); name1.NameName = ("sales1"); name1.RefersToFormula = ("Sheet1!A1:D1"); IName name2 = wb.CreateName(); name2.NameName = ("sales2"); name2.RefersToFormula = ("Sheet2!B1:C3"); IRow row = sheet1.CreateRow(3); row.CreateCell(0).SetCellValue("sales1"); //A4 row.CreateCell(1).SetCellValue("sales2"); //B4 return wb; } private static HSSFWorkbook CreateWBB() { HSSFWorkbook wb = new HSSFWorkbook(); ISheet sheet1 = wb.CreateSheet("Sheet1"); ISheet sheet2 = wb.CreateSheet("Sheet2"); ISheet sheet3 = wb.CreateSheet("## Look here!"); CreateDataRow(sheet1, 0, 400, 440, 480, 520); CreateDataRow(sheet1, 1, 420, 460, 500, 540); CreateDataRow(sheet2, 0, 50, 55, 60, 65); CreateDataRow(sheet2, 1, 51, 56, 61, 66); CreateDataRow(sheet3, 0, 42); return wb; } [Test] public void TestBasic() { HSSFWorkbook wbA = CreateWBA(); ICell c = wbA.GetSheetAt(0).CreateRow(5).CreateCell(2); HSSFFormulaEvaluator feA = new HSSFFormulaEvaluator(wbA); // non-error cases Confirm(feA, c, "INDIRECT(\"C2\")", 23); Confirm(feA, c, "INDIRECT(\"C2\", TRUE)", 23); Confirm(feA, c, "INDIRECT(\"$C2\")", 23); Confirm(feA, c, "INDIRECT(\"C$2\")", 23); Confirm(feA, c, "SUM(INDIRECT(\"Sheet2!B1:C3\"))", 351); // area ref Confirm(feA, c, "SUM(INDIRECT(\"Sheet2! B1 : C3 \"))", 351); // spaces in area ref Confirm(feA, c, "SUM(INDIRECT(\"'John''s sales'!A1:C1\"))", 93); // special chars in sheet name Confirm(feA, c, "INDIRECT(\"'Sheet1'!B3\")", 32); // redundant sheet name quotes Confirm(feA, c, "INDIRECT(\"sHeet1!B3\")", 32); // case-insensitive sheet name Confirm(feA, c, "INDIRECT(\" D3 \")", 34); // spaces around cell ref Confirm(feA, c, "INDIRECT(\"Sheet1! D3 \")", 34); // spaces around cell ref Confirm(feA, c, "INDIRECT(\"A1\", TRUE)", 11); // explicit arg1. only TRUE supported so far Confirm(feA, c, "INDIRECT(\"A1:G1\")", 13); // de-reference area ref (note formula is in C4) Confirm(feA, c, "SUM(INDIRECT(A4))", 50); // indirect defined name Confirm(feA, c, "SUM(INDIRECT(B4))", 351); // indirect defined name pointinh to other sheet // simple error propagation: // arg0 is Evaluated to text first Confirm(feA, c, "INDIRECT(#DIV/0!)", ErrorEval.DIV_ZERO); Confirm(feA, c, "INDIRECT(#DIV/0!)", ErrorEval.DIV_ZERO); Confirm(feA, c, "INDIRECT(#NAME?, \"x\")", ErrorEval.NAME_INVALID); Confirm(feA, c, "INDIRECT(#NUM!, #N/A)", ErrorEval.NUM_ERROR); // arg1 is Evaluated to bool before arg0 is decoded Confirm(feA, c, "INDIRECT(\"garbage\", #N/A)", ErrorEval.NA); Confirm(feA, c, "INDIRECT(\"garbage\", \"\")", ErrorEval.VALUE_INVALID); // empty string is not valid bool Confirm(feA, c, "INDIRECT(\"garbage\", \"flase\")", ErrorEval.VALUE_INVALID); // must be "TRUE" or "FALSE" // spaces around sheet name (with or without quotes Makes no difference) Confirm(feA, c, "INDIRECT(\"'Sheet1 '!D3\")", ErrorEval.REF_INVALID); Confirm(feA, c, "INDIRECT(\" Sheet1!D3\")", ErrorEval.REF_INVALID); Confirm(feA, c, "INDIRECT(\"'Sheet1' !D3\")", ErrorEval.REF_INVALID); Confirm(feA, c, "SUM(INDIRECT(\"'John's sales'!A1:C1\"))", ErrorEval.REF_INVALID); // bad quote escaping Confirm(feA, c, "INDIRECT(\"[Book1]Sheet1!A1\")", ErrorEval.REF_INVALID); // unknown external workbook Confirm(feA, c, "INDIRECT(\"Sheet3!A1\")", ErrorEval.REF_INVALID); // unknown sheet #if !HIDE_UNREACHABLE_CODE if (false) { // TODO - support Evaluation of defined names Confirm(feA, c, "INDIRECT(\"Sheet1!IW1\")", ErrorEval.REF_INVALID); // bad column Confirm(feA, c, "INDIRECT(\"Sheet1!A65537\")", ErrorEval.REF_INVALID); // bad row } #endif Confirm(feA, c, "INDIRECT(\"Sheet1!A 1\")", ErrorEval.REF_INVALID); // space in cell ref } [Test] public void TestMultipleWorkbooks() { HSSFWorkbook wbA = CreateWBA(); ICell cellA = wbA.GetSheetAt(0).CreateRow(10).CreateCell(0); HSSFFormulaEvaluator feA = new HSSFFormulaEvaluator(wbA); HSSFWorkbook wbB = CreateWBB(); ICell cellB = wbB.GetSheetAt(0).CreateRow(10).CreateCell(0); HSSFFormulaEvaluator feB = new HSSFFormulaEvaluator(wbB); String[] workbookNames = { "MyBook", "Figures for January", }; HSSFFormulaEvaluator[] Evaluators = { feA, feB, }; HSSFFormulaEvaluator.SetupEnvironment(workbookNames, Evaluators); Confirm(feB, cellB, "INDIRECT(\"'[Figures for January]## Look here!'!A1\")", 42); // same wb Confirm(feA, cellA, "INDIRECT(\"'[Figures for January]## Look here!'!A1\")", 42); // across workbooks // 2 level recursion Confirm(feB, cellB, "INDIRECT(\"[MyBook]Sheet2!A1\")", 50); // Set up (and Check) first level Confirm(feA, cellA, "INDIRECT(\"'[Figures for January]Sheet1'!A11\")", 50); // points to cellB } private static void Confirm(IFormulaEvaluator fe, ICell cell, String formula, double expectedResult) { fe.ClearAllCachedResultValues(); cell.CellFormula = (formula); CellValue cv = fe.Evaluate(cell); if (cv.CellType != CellType.Numeric) { throw new AssertionException("expected numeric cell type but got " + cv.FormatAsString()); } Assert.AreEqual(expectedResult, cv.NumberValue, 0.0); } private static void Confirm(IFormulaEvaluator fe, ICell cell, String formula, ErrorEval expectedResult) { fe.ClearAllCachedResultValues(); cell.CellFormula=(formula); CellValue cv = fe.Evaluate(cell); if (cv.CellType != CellType.Error) { throw new AssertionException("expected error cell type but got " + cv.FormatAsString()); } int expCode = expectedResult.ErrorCode; if (cv.ErrorValue != expCode) { throw new AssertionException("Expected error '" + ErrorEval.GetText(expCode) + "' but got '" + cv.FormatAsString() + "'."); } } [Test] public void TestInvalidInput() { Assert.AreEqual(ErrorEval.VALUE_INVALID, Indirect.instance.Evaluate(new ValueEval[] { }, null)); } } }
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira ([email protected]) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira 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. #endregion // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public partial class SlicingExpression : Expression { protected Expression _target; protected SliceCollection _indices; [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public SlicingExpression CloneNode() { return (SlicingExpression)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public SlicingExpression CleanClone() { return (SlicingExpression)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public NodeType NodeType { get { return NodeType.SlicingExpression; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public void Accept(IAstVisitor visitor) { visitor.OnSlicingExpression(this); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( SlicingExpression)node; if (!Node.Matches(_target, other._target)) return NoMatch("SlicingExpression._target"); if (!Node.AllMatch(_indices, other._indices)) return NoMatch("SlicingExpression._indices"); return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } if (_target == existing) { this.Target = (Expression)newNode; return true; } if (_indices != null) { Slice item = existing as Slice; if (null != item) { Slice newItem = (Slice)newNode; if (_indices.Replace(item, newItem)) { return true; } } } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { SlicingExpression clone = new SlicingExpression(); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._isSynthetic = _isSynthetic; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); clone._expressionType = _expressionType; if (null != _target) { clone._target = _target.Clone() as Expression; clone._target.InitializeParent(clone); } if (null != _indices) { clone._indices = _indices.Clone() as SliceCollection; clone._indices.InitializeParent(clone); } return clone; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; _expressionType = null; if (null != _target) { _target.ClearTypeSystemBindings(); } if (null != _indices) { _indices.ClearTypeSystemBindings(); } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Expression Target { get { return _target; } set { if (_target != value) { _target = value; if (null != _target) { _target.InitializeParent(this); } } } } [System.Xml.Serialization.XmlArray] [System.Xml.Serialization.XmlArrayItem(typeof(Slice))] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public SliceCollection Indices { get { return _indices ?? (_indices = new SliceCollection(this)); } set { if (_indices != value) { _indices = value; if (null != _indices) { _indices.InitializeParent(this); } } } } } }
// 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 gagvr = Google.Ads.GoogleAds.V10.Resources; using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>KeywordPlan</c> resource.</summary> public sealed partial class KeywordPlanName : gax::IResourceName, sys::IEquatable<KeywordPlanName> { /// <summary>The possible contents of <see cref="KeywordPlanName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>. /// </summary> CustomerKeywordPlan = 1, } private static gax::PathTemplate s_customerKeywordPlan = new gax::PathTemplate("customers/{customer_id}/keywordPlans/{keyword_plan_id}"); /// <summary>Creates a <see cref="KeywordPlanName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="KeywordPlanName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static KeywordPlanName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new KeywordPlanName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="KeywordPlanName"/> with the pattern /// <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="keywordPlanId">The <c>KeywordPlan</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="KeywordPlanName"/> constructed from the provided ids.</returns> public static KeywordPlanName FromCustomerKeywordPlan(string customerId, string keywordPlanId) => new KeywordPlanName(ResourceNameType.CustomerKeywordPlan, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), keywordPlanId: gax::GaxPreconditions.CheckNotNullOrEmpty(keywordPlanId, nameof(keywordPlanId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="KeywordPlanName"/> with pattern /// <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="keywordPlanId">The <c>KeywordPlan</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="KeywordPlanName"/> with pattern /// <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>. /// </returns> public static string Format(string customerId, string keywordPlanId) => FormatCustomerKeywordPlan(customerId, keywordPlanId); /// <summary> /// Formats the IDs into the string representation of this <see cref="KeywordPlanName"/> with pattern /// <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="keywordPlanId">The <c>KeywordPlan</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="KeywordPlanName"/> with pattern /// <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c>. /// </returns> public static string FormatCustomerKeywordPlan(string customerId, string keywordPlanId) => s_customerKeywordPlan.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(keywordPlanId, nameof(keywordPlanId))); /// <summary>Parses the given resource name string into a new <see cref="KeywordPlanName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c></description></item> /// </list> /// </remarks> /// <param name="keywordPlanName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="KeywordPlanName"/> if successful.</returns> public static KeywordPlanName Parse(string keywordPlanName) => Parse(keywordPlanName, false); /// <summary> /// Parses the given resource name string into a new <see cref="KeywordPlanName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="keywordPlanName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="KeywordPlanName"/> if successful.</returns> public static KeywordPlanName Parse(string keywordPlanName, bool allowUnparsed) => TryParse(keywordPlanName, allowUnparsed, out KeywordPlanName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="KeywordPlanName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c></description></item> /// </list> /// </remarks> /// <param name="keywordPlanName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="KeywordPlanName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string keywordPlanName, out KeywordPlanName result) => TryParse(keywordPlanName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="KeywordPlanName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="keywordPlanName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="KeywordPlanName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string keywordPlanName, bool allowUnparsed, out KeywordPlanName result) { gax::GaxPreconditions.CheckNotNull(keywordPlanName, nameof(keywordPlanName)); gax::TemplatedResourceName resourceName; if (s_customerKeywordPlan.TryParseName(keywordPlanName, out resourceName)) { result = FromCustomerKeywordPlan(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(keywordPlanName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private KeywordPlanName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string keywordPlanId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; KeywordPlanId = keywordPlanId; } /// <summary> /// Constructs a new instance of a <see cref="KeywordPlanName"/> class from the component parts of pattern /// <c>customers/{customer_id}/keywordPlans/{keyword_plan_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="keywordPlanId">The <c>KeywordPlan</c> ID. Must not be <c>null</c> or empty.</param> public KeywordPlanName(string customerId, string keywordPlanId) : this(ResourceNameType.CustomerKeywordPlan, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), keywordPlanId: gax::GaxPreconditions.CheckNotNullOrEmpty(keywordPlanId, nameof(keywordPlanId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>KeywordPlan</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string KeywordPlanId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerKeywordPlan: return s_customerKeywordPlan.Expand(CustomerId, KeywordPlanId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as KeywordPlanName); /// <inheritdoc/> public bool Equals(KeywordPlanName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(KeywordPlanName a, KeywordPlanName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(KeywordPlanName a, KeywordPlanName b) => !(a == b); } public partial class KeywordPlan { /// <summary> /// <see cref="gagvr::KeywordPlanName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal KeywordPlanName ResourceNameAsKeywordPlanName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::KeywordPlanName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagvr::KeywordPlanName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> internal KeywordPlanName KeywordPlanName { get => string.IsNullOrEmpty(Name) ? null : gagvr::KeywordPlanName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using System; using System.Collections.Generic; using System.Linq; using System.IO; using Orchard.Abstractions.Localization; using Orchard.Hosting.Extensions.Models; using Orchard.Utility; using Orchard.FileSystem.Client; using Microsoft.Framework.Logging; namespace Orchard.Hosting.Extensions.Folders { public class ExtensionHarvester : IExtensionHarvester { private const string NameSection = "name"; private const string PathSection = "path"; private const string DescriptionSection = "description"; private const string VersionSection = "version"; private const string OrchardVersionSection = "orchardversion"; private const string AuthorSection = "author"; private const string WebsiteSection = "website"; private const string TagsSection = "tags"; private const string AntiForgerySection = "antiforgery"; private const string ZonesSection = "zones"; private const string BaseThemeSection = "basetheme"; private const string DependenciesSection = "dependencies"; private const string CategorySection = "category"; private const string FeatureDescriptionSection = "featuredescription"; private const string FeatureNameSection = "featurename"; private const string PrioritySection = "priority"; private const string FeaturesSection = "features"; private const string SessionStateSection = "sessionstate"; private readonly IClientFolder _clientFolder; private readonly ILogger _logger; public ExtensionHarvester(IClientFolder clientFolder, ILoggerFactory loggerFactory) { _clientFolder = clientFolder; _logger = loggerFactory.CreateLogger<ExtensionHarvester>(); T = NullLocalizer.Instance; } public Localizer T { get; set; } public bool DisableMonitoring { get; set; } public IEnumerable<ExtensionDescriptor> HarvestExtensions(IEnumerable<string> paths, string extensionType, string manifestName, bool manifestIsOptional) { return paths .SelectMany(path => HarvestExtensions(path, extensionType, manifestName, manifestIsOptional)) .ToList(); } private IEnumerable<ExtensionDescriptor> HarvestExtensions(string path, string extensionType, string manifestName, bool manifestIsOptional) { return AvailableExtensionsInFolder(path, extensionType, manifestName, manifestIsOptional).ToReadOnlyCollection(); } private List<ExtensionDescriptor> AvailableExtensionsInFolder(string path, string extensionType, string manifestName, bool manifestIsOptional) { _logger.LogInformation("Start looking for extensions in '{0}'...", path); var subfolderPaths = _clientFolder.ListDirectories(path); var localList = new List<ExtensionDescriptor>(); foreach (var subfolderPath in subfolderPaths) { var extensionId = Path.GetFileName(subfolderPath.TrimEnd('/', '\\')); var manifestPath = Path.Combine(subfolderPath, manifestName); try { var descriptor = GetExtensionDescriptor(path, extensionId, extensionType, manifestPath, manifestIsOptional); if (descriptor == null) continue; if (descriptor.Path != null && !descriptor.Path.IsValidUrlSegment()) { _logger.LogError("The module '{0}' could not be loaded because it has an invalid Path ({1}). It was ignored. The Path if specified must be a valid URL segment. The best bet is to stick with letters and numbers with no spaces.", extensionId, descriptor.Path); continue; } if (descriptor.Path == null) { descriptor.Path = descriptor.Name.IsValidUrlSegment() ? descriptor.Name : descriptor.Id; } localList.Add(descriptor); } catch (Exception ex) { // Ignore invalid module manifests _logger.LogError(string.Format("The module '{0}' could not be loaded. It was ignored.", extensionId), ex); } } _logger.LogInformation("Done looking for extensions in '{0}': {1}", path, string.Join(", ", localList.Select(d => d.Id))); return localList; } public static ExtensionDescriptor GetDescriptorForExtension(string locationPath, string extensionId, string extensionType, string manifestText) { Dictionary<string, string> manifest = ParseManifest(manifestText); var extensionDescriptor = new ExtensionDescriptor { Location = locationPath, Id = extensionId, ExtensionType = extensionType, Name = GetValue(manifest, NameSection) ?? extensionId, Path = GetValue(manifest, PathSection), Description = GetValue(manifest, DescriptionSection), Version = GetValue(manifest, VersionSection), OrchardVersion = GetValue(manifest, OrchardVersionSection), Author = GetValue(manifest, AuthorSection), WebSite = GetValue(manifest, WebsiteSection), Tags = GetValue(manifest, TagsSection), AntiForgery = GetValue(manifest, AntiForgerySection), Zones = GetValue(manifest, ZonesSection), BaseTheme = GetValue(manifest, BaseThemeSection), SessionState = GetValue(manifest, SessionStateSection) }; extensionDescriptor.Features = GetFeaturesForExtension(manifest, extensionDescriptor); return extensionDescriptor; } private ExtensionDescriptor GetExtensionDescriptor(string locationPath, string extensionId, string extensionType, string manifestPath, bool manifestIsOptional) { var manifestText = _clientFolder.ReadFile(manifestPath); if (manifestText == null) { if (manifestIsOptional) { manifestText = string.Format("Id: {0}", extensionId); } else { return null; } } return GetDescriptorForExtension(locationPath, extensionId, extensionType, manifestText); } private static Dictionary<string, string> ParseManifest(string manifestText) { var manifest = new Dictionary<string, string>(); using (StringReader reader = new StringReader(manifestText)) { string line; while ((line = reader.ReadLine()) != null) { string[] field = line.Split(new[] { ":" }, 2, StringSplitOptions.None); int fieldLength = field.Length; if (fieldLength != 2) continue; for (int i = 0; i < fieldLength; i++) { field[i] = field[i].Trim(); } switch (field[0].ToLowerInvariant()) { case NameSection: manifest.Add(NameSection, field[1]); break; case PathSection: manifest.Add(PathSection, field[1]); break; case DescriptionSection: manifest.Add(DescriptionSection, field[1]); break; case VersionSection: manifest.Add(VersionSection, field[1]); break; case OrchardVersionSection: manifest.Add(OrchardVersionSection, field[1]); break; case AuthorSection: manifest.Add(AuthorSection, field[1]); break; case WebsiteSection: manifest.Add(WebsiteSection, field[1]); break; case TagsSection: manifest.Add(TagsSection, field[1]); break; case AntiForgerySection: manifest.Add(AntiForgerySection, field[1]); break; case ZonesSection: manifest.Add(ZonesSection, field[1]); break; case BaseThemeSection: manifest.Add(BaseThemeSection, field[1]); break; case DependenciesSection: manifest.Add(DependenciesSection, field[1]); break; case CategorySection: manifest.Add(CategorySection, field[1]); break; case FeatureDescriptionSection: manifest.Add(FeatureDescriptionSection, field[1]); break; case FeatureNameSection: manifest.Add(FeatureNameSection, field[1]); break; case PrioritySection: manifest.Add(PrioritySection, field[1]); break; case SessionStateSection: manifest.Add(SessionStateSection, field[1]); break; case FeaturesSection: manifest.Add(FeaturesSection, reader.ReadToEnd()); break; } } } return manifest; } private static IEnumerable<FeatureDescriptor> GetFeaturesForExtension(IDictionary<string, string> manifest, ExtensionDescriptor extensionDescriptor) { var featureDescriptors = new List<FeatureDescriptor>(); // Default feature FeatureDescriptor defaultFeature = new FeatureDescriptor { Id = extensionDescriptor.Id, Name = GetValue(manifest, FeatureNameSection) ?? extensionDescriptor.Name, Priority = GetValue(manifest, PrioritySection) != null ? int.Parse(GetValue(manifest, PrioritySection)) : 0, Description = GetValue(manifest, FeatureDescriptionSection) ?? GetValue(manifest, DescriptionSection) ?? string.Empty, Dependencies = ParseFeatureDependenciesEntry(GetValue(manifest, DependenciesSection)), Extension = extensionDescriptor, Category = GetValue(manifest, CategorySection) }; featureDescriptors.Add(defaultFeature); // Remaining features string featuresText = GetValue(manifest, FeaturesSection); if (featuresText != null) { FeatureDescriptor featureDescriptor = null; using (StringReader reader = new StringReader(featuresText)) { string line; while ((line = reader.ReadLine()) != null) { if (IsFeatureDeclaration(line)) { if (featureDescriptor != null) { if (!featureDescriptor.Equals(defaultFeature)) { featureDescriptors.Add(featureDescriptor); } featureDescriptor = null; } string[] featureDeclaration = line.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries); string featureDescriptorId = featureDeclaration[0].Trim(); if (String.Equals(featureDescriptorId, extensionDescriptor.Id, StringComparison.OrdinalIgnoreCase)) { featureDescriptor = defaultFeature; featureDescriptor.Name = extensionDescriptor.Name; } else { featureDescriptor = new FeatureDescriptor { Id = featureDescriptorId, Extension = extensionDescriptor }; } } else if (IsFeatureFieldDeclaration(line)) { if (featureDescriptor != null) { string[] featureField = line.Split(new[] { ":" }, 2, StringSplitOptions.None); int featureFieldLength = featureField.Length; if (featureFieldLength != 2) continue; for (int i = 0; i < featureFieldLength; i++) { featureField[i] = featureField[i].Trim(); } switch (featureField[0].ToLowerInvariant()) { case NameSection: featureDescriptor.Name = featureField[1]; break; case DescriptionSection: featureDescriptor.Description = featureField[1]; break; case CategorySection: featureDescriptor.Category = featureField[1]; break; case PrioritySection: featureDescriptor.Priority = int.Parse(featureField[1]); break; case DependenciesSection: featureDescriptor.Dependencies = ParseFeatureDependenciesEntry(featureField[1]); break; } } else { string message = string.Format("The line {0} in manifest for extension {1} was ignored", line, extensionDescriptor.Id); throw new ArgumentException(message); } } else { string message = string.Format("The line {0} in manifest for extension {1} was ignored", line, extensionDescriptor.Id); throw new ArgumentException(message); } } if (featureDescriptor != null && !featureDescriptor.Equals(defaultFeature)) featureDescriptors.Add(featureDescriptor); } } return featureDescriptors; } private static bool IsFeatureFieldDeclaration(string line) { if (line.StartsWith("\t\t") || line.StartsWith("\t ") || line.StartsWith(" ") || line.StartsWith(" \t")) return true; return false; } private static bool IsFeatureDeclaration(string line) { int lineLength = line.Length; if (line.StartsWith("\t") && lineLength >= 2) { return !Char.IsWhiteSpace(line[1]); } if (line.StartsWith(" ") && lineLength >= 5) return !Char.IsWhiteSpace(line[4]); return false; } private static IEnumerable<string> ParseFeatureDependenciesEntry(string dependenciesEntry) { if (string.IsNullOrEmpty(dependenciesEntry)) return Enumerable.Empty<string>(); var dependencies = new List<string>(); foreach (var s in dependenciesEntry.Split(',')) { dependencies.Add(s.Trim()); } return dependencies; } private static string GetValue(IDictionary<string, string> fields, string key) { string value; return fields.TryGetValue(key, out value) ? value : null; } } }
using System; using System.Web; using System.Collections.Specialized; using System.Collections.Generic; using System.Collections; using gov.va.medora.mdo; using gov.va.medora.utils; using gov.va.medora.mdo.api; using gov.va.medora.mdo.dao; using gov.va.medora.mdws.dto; namespace gov.va.medora.mdws { public class NoteLib { MySession _mySession; NoteApi _api; public NoteLib(MySession mySession) { this._mySession = mySession; this._api = new NoteApi(); } public TaggedTextArray getNoteTitles(string target, string direction) { return getNoteTitles(null, target, direction); } public TaggedTextArray getNoteTitles(string sitecode, string target, string direction) { TaggedTextArray result = new TaggedTextArray(); string msg = MdwsUtils.isAuthorizedConnection(_mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } if (sitecode == null) { sitecode = _mySession.ConnectionSet.BaseSiteId; } if (direction == "") { direction = "1"; } try { AbstractConnection cxn = _mySession.ConnectionSet.getConnection(sitecode); Dictionary<string, ArrayList> x = _api.getNoteTitles(cxn, target, direction); IndexedHashtable t = new IndexedHashtable(); t.Add(sitecode, x); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedText isSurgeryNote(string noteDefinitionIEN) { return isSurgeryNote(null, noteDefinitionIEN); } public TaggedText isSurgeryNote(string sitecode, string noteDefinitionIEN) { TaggedText result = new TaggedText(); string msg = MdwsUtils.isAuthorizedConnection(_mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (noteDefinitionIEN == "") { result.fault = new FaultTO("Missing noteDefinitionIEN"); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = _mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = _mySession.ConnectionSet.getConnection(sitecode); bool f = _api.isSurgeryNote(cxn, noteDefinitionIEN); result.tag = (f ? "Y" : "N"); result.text = (f ? "Cannot create new surgery note at this time" : ""); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedText isOneVisitNote(string noteDefinitionIEN, string noteTitle, string visitStr) { return isOneVisitNote(null, noteDefinitionIEN, noteTitle, visitStr); } public TaggedText isOneVisitNote(string sitecode, string noteDefinitionIEN, string noteTitle, string visitStr) { TaggedText result = new TaggedText(); string msg = MdwsUtils.isAuthorizedConnection(_mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (String.IsNullOrEmpty(noteDefinitionIEN)) { result.fault = new FaultTO("Missing noteDefinitionIEN"); } // TODO - this arg is superfluous - remove from future versions or rename to dfn (patient IEN) to remove need to select patient //else if (String.IsNullOrEmpty(noteTitle)) //{ // result.fault = new FaultTO("Missing noteTitle"); //} else if (String.IsNullOrEmpty(visitStr)) { result.fault = new FaultTO("Missing visitStr"); } else if (String.IsNullOrEmpty(_mySession.ConnectionSet.BaseConnection.Pid)) { result.fault = new FaultTO("No patient selected", "Need to select patient"); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = _mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = _mySession.ConnectionSet.getConnection(sitecode); bool f = _api.isOneVisitNote(cxn, noteDefinitionIEN, _mySession.ConnectionSet.BaseConnection.Pid, visitStr); if (f) { result.tag = "Y"; result.text = "There is already a " + noteTitle + " note for this visit.\r\n" + "Only ONE record of this type per Visit is allowed...\r\n\r\n" + "You can addend the existing record."; } else { result.tag = "N"; result.text = ""; } } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TextTO isConsultNote(string noteDefinitionIEN) { return isConsultNote(null, noteDefinitionIEN); } public TextTO isConsultNote(string sitecode, string noteDefinitionIEN) { TextTO result = new TextTO(); string msg = MdwsUtils.isAuthorizedConnection(_mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (noteDefinitionIEN == "") { result.fault = new FaultTO("Missing noteDefinitionIEN"); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = _mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = _mySession.ConnectionSet.getConnection(sitecode); bool f = _api.isConsultNote(cxn, noteDefinitionIEN); result.text = (f ? "Y" : "N"); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TextTO isPrfNote(string noteDefinitionIEN) { return isPrfNote(null, noteDefinitionIEN); } public TextTO isPrfNote(string sitecode, string noteDefinitionIEN) { TextTO result = new TextTO(); string msg = MdwsUtils.isAuthorizedConnection(_mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (noteDefinitionIEN == "") { result.fault = new FaultTO("Missing noteDefinitionIEN"); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = _mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = _mySession.ConnectionSet.getConnection(sitecode); bool f = _api.isPrfNote(cxn, noteDefinitionIEN); result.text = (f ? "Y" : "N"); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TextTO isCosignerRequired(string noteDefinitionIEN, string authorDUZ) { return isCosignerRequired(null, noteDefinitionIEN, authorDUZ); } public TextTO isCosignerRequired(string sitecode, string noteDefinitionIEN, string authorDUZ) { TextTO result = new TextTO(); string msg = MdwsUtils.isAuthorizedConnection(_mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (noteDefinitionIEN == "") { result.fault = new FaultTO("Missing noteDefinitionIEN"); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = _mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = _mySession.ConnectionSet.getConnection(sitecode); bool f = false; if (authorDUZ == "") { f = _api.isCosignerRequired(cxn, _mySession.User.Uid, noteDefinitionIEN); } else { f = _api.isCosignerRequired(cxn, _mySession.User.Uid, noteDefinitionIEN, authorDUZ); } result.text = (f ? "Y" : "N"); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TextTO getNoteText(string noteIEN) { return getNoteText(null, noteIEN); } public TextTO getNoteText(string sitecode, string noteIEN) { TextTO result = new TextTO(); string msg = MdwsUtils.isAuthorizedConnection(_mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (noteIEN == "") { result.fault = new FaultTO("Missing noteIEN"); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = _mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = _mySession.ConnectionSet.getConnection(sitecode); result.text = _api.getNoteText(cxn, noteIEN); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public PatientRecordFlagArray getPrfNoteActions(string noteDefinitionIEN) { return getPrfNoteActions(null, noteDefinitionIEN); } public PatientRecordFlagArray getPrfNoteActions(string sitecode, string noteDefinitionIEN) { PatientRecordFlagArray result = new PatientRecordFlagArray(); string msg = MdwsUtils.isAuthorizedConnection(_mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (noteDefinitionIEN == "") { result.fault = new FaultTO("Missing noteDefinitionIEN"); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = _mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = _mySession.ConnectionSet.getConnection(sitecode); PatientRecordFlag[] flags = _api.getPrfNoteActions(cxn, noteDefinitionIEN); result = new PatientRecordFlagArray(flags); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public NoteResultTO writeNote( string titleIEN, string encounterString, string text, string authorDUZ, string cosignerDUZ, string consultIEN, string prfIEN) { return writeNote(null, titleIEN, encounterString, text, authorDUZ, cosignerDUZ, consultIEN, prfIEN); } public NoteResultTO writeNote( string sitecode, string titleIEN, string encounterString, string text, string authorDUZ, string cosignerDUZ, string consultIEN, string prfIEN) { NoteResultTO result = new NoteResultTO(); string msg = MdwsUtils.isAuthorizedConnection(_mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (titleIEN == "") { result.fault = new FaultTO("Missing titleIEN"); } else if (encounterString == "") { result.fault = new FaultTO("Missing encounterString"); } else if (text == "") { result.fault = new FaultTO("No text!"); } Encounter encounter = null; try { encounter = getFromEncounterString(encounterString); } catch (Exception e) { result.fault = new FaultTO(e.Message); } if (result.fault != null) { return result; } // If no author DUZ we assume author is user if (authorDUZ == "") { authorDUZ = _mySession.User.Uid; } if (sitecode == null) { sitecode = _mySession.ConnectionSet.BaseSiteId; } // Externalizing note writing business rules... //Note note = new Note(); //note.DocumentDefinitionId = titleIEN; //note.Author = new Author(authorDUZ, "", ""); //note.Timestamp = DateTime.Now.ToString("yyyyMMdd"); //note.ConsultId = consultIEN; //note.IsAddendum = false; //note.PrfId = prfIEN; //if (cosignerDUZ != "") //{ // note.Cosigner = new Author(cosignerDUZ, "", ""); //} //note.Text = text; try { AbstractConnection cxn = _mySession.ConnectionSet.getConnection(sitecode); NoteResult noteResult = _api.writeNote( cxn, titleIEN, encounter, text, authorDUZ, cosignerDUZ, consultIEN, prfIEN ); return new NoteResultTO(noteResult); } catch (Exception e) { result.fault = new FaultTO(e.Message); result.fault.stackTrace = e.StackTrace; } return result; } public TextTO signNote(string noteId, string userId, string esig) { return signNote(null, noteId, userId, esig); } public TextTO signNote(string sitecode, string noteId, string userId, string esig) { TextTO result = new TextTO(); string msg = MdwsUtils.isAuthorizedConnection(_mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (noteId == "") { result.fault = new FaultTO("Missing noteId"); } else if (esig == "") { result.fault = new FaultTO("Missing esig"); } if (userId == "") { if (_mySession.User.Uid == "") { result.fault = new FaultTO("Missing userId"); } else { userId = _mySession.User.Uid; } } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = _mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = _mySession.ConnectionSet.getConnection(sitecode); NoteApi api = new NoteApi(); string s = api.signNote(cxn, noteId, userId, esig); if (s != "OK") { result.fault = new FaultTO(s); } else { result = new TextTO(s); } } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TextTO closeNote(string noteId, string consultId) { return closeNote(null, noteId, consultId); } public TextTO closeNote(string sitecode, string noteId, string consultId) { TextTO result = new TextTO(); string msg = MdwsUtils.isAuthorizedConnection(_mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (noteId == "") { result.fault = new FaultTO("Missing noteId"); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = _mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = _mySession.ConnectionSet.getConnection(sitecode); NoteApi api = new NoteApi(); string s = api.closeNote(cxn, noteId, consultId); result = new TextTO(s); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } internal Encounter getFromEncounterString(string encounterString) { string[] flds = StringUtils.split(encounterString, StringUtils.SEMICOLON); if (flds.Length != 3) { throw new Exception("Invalid encounter string: does not contain 3 parts"); } if (!StringUtils.isNumeric(flds[0])) { throw new Exception("Invalid encounter string: non-numeric location IEN"); } //TBD: how to test for valid VistA timestamp (fld[1]) if (flds[2] != "A" && flds[2] != "H" && flds[2] != "E") { throw new Exception("Invalid encounter string: type must be A, H or E"); } Encounter result = new Encounter(); result.LocationId = flds[0]; result.Timestamp = flds[1]; result.Type = flds[2]; return result; } public TaggedNoteArrays getSignedNotes(string fromDate, string toDate, int nNotes) { TaggedNoteArrays result = new TaggedNoteArrays(); string msg = MdwsUtils.isAuthorizedConnection(_mySession); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { NoteApi api = new NoteApi(); IndexedHashtable t = api.getSignedNotes(_mySession.ConnectionSet, fromDate, toDate, nNotes); result = new TaggedNoteArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedNoteArrays getUnsignedNotes(string fromDate, string toDate, int nNotes) { TaggedNoteArrays result = new TaggedNoteArrays(); string msg = MdwsUtils.isAuthorizedConnection(_mySession); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { NoteApi api = new NoteApi(); IndexedHashtable t = api.getUnsignedNotes(_mySession.ConnectionSet, fromDate, toDate, nNotes); result = new TaggedNoteArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedNoteArrays getUncosignedNotes(string fromDate, string toDate, int nNotes) { TaggedNoteArrays result = new TaggedNoteArrays(); string msg = MdwsUtils.isAuthorizedConnection(_mySession); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { NoteApi api = new NoteApi(); IndexedHashtable t = api.getUncosignedNotes(_mySession.ConnectionSet, fromDate, toDate, nNotes); result = new TaggedNoteArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TextTO getNote(string siteId, string noteId) { TextTO result = new TextTO(); string msg = MdwsUtils.isAuthorizedConnection(_mySession, siteId); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (siteId == "") { result.fault = new FaultTO("Missing siteId"); } else if (noteId == "") { result.fault = new FaultTO("Missing noteId"); } if (result.fault != null) { return result; } try { NoteApi api = new NoteApi(); string s = api.getNoteText(_mySession.ConnectionSet.getConnection(siteId), noteId); result = new TextTO(s); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedNoteArrays getNotesWithText(string fromDate, string toDate, int nNotes) { TaggedNoteArrays result = new TaggedNoteArrays(); if (!_mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { NoteApi api = new NoteApi(); IndexedHashtable t = api.getNotes(_mySession.ConnectionSet, fromDate, toDate, nNotes); result = new TaggedNoteArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedNoteArrays getDischargeSummaries(String fromDate, String toDate, int nNotes) { TaggedNoteArrays result = new TaggedNoteArrays(); string msg = MdwsUtils.isAuthorizedConnection(_mySession); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { NoteApi api = new NoteApi(); IndexedHashtable t = api.getDischargeSummaries(_mySession.ConnectionSet, fromDate, toDate, nNotes); result = new TaggedNoteArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedTextArray getAdvanceDirectives(string fromDate, string toDate, int nrpts) { TaggedTextArray result = new TaggedTextArray(); string msg = MdwsUtils.isAuthorizedConnection(_mySession); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { NoteApi api = new NoteApi(); IndexedHashtable t = api.getAdvanceDirectives(_mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedTextArray getClinicalWarnings(string fromDate, string toDate, int nrpts) { TaggedTextArray result = new TaggedTextArray(); string msg = MdwsUtils.isAuthorizedConnection(_mySession); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { NoteApi api = new NoteApi(); IndexedHashtable t = api.getClinicalWarnings(_mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedTextArray getCrisisNotes(string fromDate, string toDate, int nrpts) { TaggedTextArray result = new TaggedTextArray(); string msg = MdwsUtils.isAuthorizedConnection(_mySession); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { NoteApi api = new NoteApi(); IndexedHashtable t = api.getCrisisNotes(_mySession.ConnectionSet, fromDate, toDate, nrpts); return new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e); return result; } } public TaggedNoteArrays getNotesForBhie(string pwd, string mpiPid, string fromDate, string toDate, string nNotes) { TaggedNoteArrays result = new TaggedNoteArrays(); if (pwd != "iBnOfs55iEZ,d") { result.fault = new FaultTO("Invalid application password"); } else if (String.IsNullOrEmpty(mpiPid)) { result.fault = new FaultTO("Missing mpiPid"); } else if (String.IsNullOrEmpty(fromDate)) { result.fault = new FaultTO("Missing fromDate"); } else if (String.IsNullOrEmpty(toDate)) { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } if (nNotes == "") { nNotes = "50"; } try { int maxNotes = Convert.ToInt16(nNotes); PatientLib patLib = new PatientLib(_mySession); TaggedTextArray sites = patLib.getPatientSitesByMpiPid(mpiPid); if (sites == null) { return null; } if (sites.fault != null) { result.fault = sites.fault; return result; } string sitelist = ""; for (int i = 0; i < sites.count; i++) { if ((string)sites.results[i].tag == "200") { continue; } if (sites.results[i].fault != null) { } else { sitelist += (string)sites.results[i].tag + ','; } } sitelist = sitelist.Substring(0, sitelist.Length - 1); AccountLib acctLib = new AccountLib(_mySession); sites = acctLib.visitSites("BHIE", sitelist, MdwsConstants.CPRS_CONTEXT); if (sites.fault != null) { result.fault = sites.fault; return result; } PatientApi patApi = new PatientApi(); IndexedHashtable t = patApi.setLocalPids(_mySession.ConnectionSet, mpiPid); NoteApi api = new NoteApi(); IndexedHashtable tNotes = api.getNotes(_mySession.ConnectionSet, fromDate, toDate, maxNotes); IndexedHashtable tSumms = api.getDischargeSummaries(_mySession.ConnectionSet, fromDate, toDate, 50); result = new TaggedNoteArrays(mergeNotesAndDischargeSummaries(tNotes, tSumms)); } catch (Exception ex) { result.fault = new FaultTO(ex); } finally { if (_mySession.ConnectionSet != null) { _mySession.ConnectionSet.disconnectAll(); } } return result; } private IndexedHashtable mergeNotesAndDischargeSummaries(IndexedHashtable tNotes, IndexedHashtable tSummaries) { if (tNotes == null) { return tSummaries; } if (tSummaries == null) { return tNotes; } IndexedHashtable result = new IndexedHashtable(tNotes.Count + tSummaries.Count); for (int i = 0; i < tNotes.Count; i++) { Note[] notes = (Note[])tNotes.GetValue(i); int notesLength = (notes == null ? 0 : notes.Length); string key = (string)tNotes.GetKey(i); Note[] summaries = (Note[])tSummaries.GetValue(key); int summariesLength = (summaries == null ? 0 : summaries.Length); ArrayList lst = new ArrayList(notesLength + summariesLength); for (int j = 0; j < notesLength; j++) { lst.Add(notes[j]); } for (int j = 0; j < summariesLength; j++) { lst.Add(summaries[j]); } result.Add(key, (Note[])lst.ToArray(typeof(Note))); } return result; } } }
// Copyright (C) 2015 Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #if UNITY_IOS using System; using System.Collections.Generic; using System.Runtime.InteropServices; using GoogleMobileAds.Api; using GoogleMobileAds.Common; namespace GoogleMobileAds.iOS { public class BannerClient : IBannerClient, IDisposable { private IntPtr bannerViewPtr; private IntPtr bannerClientPtr; #region Banner callback types internal delegate void GADUAdViewDidReceiveAdCallback(IntPtr bannerClient); internal delegate void GADUAdViewDidFailToReceiveAdWithErrorCallback( IntPtr bannerClient, string error); internal delegate void GADUAdViewWillPresentScreenCallback(IntPtr bannerClient); internal delegate void GADUAdViewDidDismissScreenCallback(IntPtr bannerClient); internal delegate void GADUAdViewWillLeaveApplicationCallback(IntPtr bannerClient); #endregion public event EventHandler<EventArgs> OnAdLoaded; public event EventHandler<AdFailedToLoadEventArgs> OnAdFailedToLoad; public event EventHandler<EventArgs> OnAdOpening; public event EventHandler<EventArgs> OnAdClosed; public event EventHandler<EventArgs> OnAdLeavingApplication; // This property should be used when setting the bannerViewPtr. private IntPtr BannerViewPtr { get { return this.bannerViewPtr; } set { Externs.GADURelease(this.bannerViewPtr); this.bannerViewPtr = value; } } #region IBannerClient implementation // Creates a banner view. public void CreateBannerView(string adUnitId, AdSize adSize, AdPosition position) { this.bannerClientPtr = (IntPtr)GCHandle.Alloc(this); if (adSize.IsSmartBanner) { this.BannerViewPtr = Externs.GADUCreateSmartBannerView( this.bannerClientPtr, adUnitId, (int)position); } else { this.BannerViewPtr = Externs.GADUCreateBannerView( this.bannerClientPtr, adUnitId, adSize.Width, adSize.Height, (int)position); } Externs.GADUSetBannerCallbacks( this.BannerViewPtr, AdViewDidReceiveAdCallback, AdViewDidFailToReceiveAdWithErrorCallback, AdViewWillPresentScreenCallback, AdViewDidDismissScreenCallback, AdViewWillLeaveApplicationCallback); } public void CreateBannerView(string adUnitId, AdSize adSize, int x, int y) { this.bannerClientPtr = (IntPtr)GCHandle.Alloc(this); if (adSize.IsSmartBanner) { this.BannerViewPtr = Externs.GADUCreateSmartBannerViewWithCustomPosition( this.bannerClientPtr, adUnitId, x, y); } else { this.BannerViewPtr = Externs.GADUCreateBannerViewWithCustomPosition( this.bannerClientPtr, adUnitId, adSize.Width, adSize.Height, x, y); } Externs.GADUSetBannerCallbacks( this.BannerViewPtr, AdViewDidReceiveAdCallback, AdViewDidFailToReceiveAdWithErrorCallback, AdViewWillPresentScreenCallback, AdViewDidDismissScreenCallback, AdViewWillLeaveApplicationCallback); } // Loads an ad. public void LoadAd(AdRequest request) { IntPtr requestPtr = Utils.BuildAdRequest(request); Externs.GADURequestBannerAd(this.BannerViewPtr, requestPtr); Externs.GADURelease(requestPtr); } // Displays the banner view on the screen. public void ShowBannerView() { Externs.GADUShowBannerView(this.BannerViewPtr); } // Hides the banner view from the screen. public void HideBannerView() { Externs.GADUHideBannerView(this.BannerViewPtr); } // Destroys the banner view. public void DestroyBannerView() { Externs.GADURemoveBannerView(this.BannerViewPtr); this.BannerViewPtr = IntPtr.Zero; } // Returns the mediation adapter class name. public string MediationAdapterClassName() { return Externs.GADUMediationAdapterClassNameForBannerView(this.BannerViewPtr); } public void Dispose() { this.DestroyBannerView(); ((GCHandle)this.bannerClientPtr).Free(); } ~BannerClient() { this.Dispose(); } #endregion #region Banner callback methods [MonoPInvokeCallback(typeof(GADUAdViewDidReceiveAdCallback))] private static void AdViewDidReceiveAdCallback(IntPtr bannerClient) { BannerClient client = IntPtrToBannerClient(bannerClient); if (client.OnAdLoaded != null) { client.OnAdLoaded(client, EventArgs.Empty); } } [MonoPInvokeCallback(typeof(GADUAdViewDidFailToReceiveAdWithErrorCallback))] private static void AdViewDidFailToReceiveAdWithErrorCallback( IntPtr bannerClient, string error) { BannerClient client = IntPtrToBannerClient(bannerClient); if (client.OnAdFailedToLoad != null) { AdFailedToLoadEventArgs args = new AdFailedToLoadEventArgs() { Message = error }; client.OnAdFailedToLoad(client, args); } } [MonoPInvokeCallback(typeof(GADUAdViewWillPresentScreenCallback))] private static void AdViewWillPresentScreenCallback(IntPtr bannerClient) { BannerClient client = IntPtrToBannerClient(bannerClient); if (client.OnAdOpening != null) { client.OnAdOpening(client, EventArgs.Empty); } } [MonoPInvokeCallback(typeof(GADUAdViewDidDismissScreenCallback))] private static void AdViewDidDismissScreenCallback(IntPtr bannerClient) { BannerClient client = IntPtrToBannerClient(bannerClient); if (client.OnAdClosed != null) { client.OnAdClosed(client, EventArgs.Empty); } } [MonoPInvokeCallback(typeof(GADUAdViewWillLeaveApplicationCallback))] private static void AdViewWillLeaveApplicationCallback(IntPtr bannerClient) { BannerClient client = IntPtrToBannerClient(bannerClient); if (client.OnAdLeavingApplication != null) { client.OnAdLeavingApplication(client, EventArgs.Empty); } } private static BannerClient IntPtrToBannerClient(IntPtr bannerClient) { GCHandle handle = (GCHandle)bannerClient; return handle.Target as BannerClient; } #endregion } } #endif
namespace PhoneSystem.Data.Migrations { using System; using System.Collections.Generic; using System.Data.Entity.Migrations; using System.Linq; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using PhoneSystem.Common; using PhoneSystem.Data.DbContext; using PhoneSystem.Data.UnitOfWork; using PhoneSystem.Models; public sealed class Configuration : DbMigrationsConfiguration<PhoneSystemDbContext> { private Random random = new Random(0); public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = true; } protected override void Seed(PhoneSystemDbContext context) { if (context.Users.Any()) { return; } var jobTitles = this.SeedJobTitles(context); var departments = this.SeedDepartment(context); var phones = this.SeedPhones(context); var users = this.SeedUsers(context, jobTitles, departments); this.SeedPhonesUsersOrders(context, phones, users); } private void SeedPhonesUsersOrders(PhoneSystemDbContext context, IList<Phone> phones, ICollection<User> users) { foreach (var user in users) { var phone = phones[this.random.Next(0, phones.Count)]; phones.Remove(phone); var order = new PhoneNumberOrder() { PhoneNumber = phone.PhoneNumber, UserId = user.Id, ActionDate = DateTime.Now, PhoneAction = PhoneAction.TakePhone, AdminId = context.Users.Where(x => x.UserName == "admin").Select(x => x.Id).FirstOrDefault() }; var newPhone = context.Phones.Where(x => x.PhoneNumber == phone.PhoneNumber).FirstOrDefault(); newPhone.PhoneStatus = PhoneStatus.Taken; newPhone.User = user; context.PhoneNumberOrders.Add(order); } context.SaveChanges(); } private IList<Department> SeedDepartment(PhoneSystemDbContext context) { var departments = new List<Department>(); var departmentNames = new List<string> { "Gastroenterology", "Pulmology", "Dermatology", "<script>alert('asd')</script>" }; foreach (var departmentName in departmentNames) { var department = new Department { Name = departmentName }; context.Departments.Add(department); departments.Add(department); } context.SaveChanges(); return departments; } private IList<JobTitle> SeedJobTitles(PhoneSystemDbContext context) { var jobTitleNames = new string[] { "admin", "expert", "<script>alert('asd')</script>" }; var jobTiles = new List<JobTitle>(); foreach (var jobTitleName in jobTitleNames) { var jobTitle = new JobTitle { Name = jobTitleName }; context.JobTitles.Add(jobTitle); jobTiles.Add(jobTitle); } context.SaveChanges(); return jobTiles; } private IList<Phone> SeedPhones(PhoneSystemDbContext context) { var phones = new List<Phone>(); for (int i = 0; i < 20; i++) { var phone = new Phone { PhoneNumber = RandomPhoneNumber(), PhoneStatus = PhoneStatus.Free, CardType = CardType.Unknown, CreditLimit = 50, HasRouming = true }; if (phones.Any(x => x.PhoneNumber == phone.PhoneNumber)) { i--; continue; } phones.Add(phone); context.Phones.Add(phone); } context.SaveChanges(); return phones; } private ICollection<User> SeedUsers(PhoneSystemDbContext context, IList<JobTitle> jobTitles, IList<Department> departments) { var usernames = new string[] { "admin", "maria", "peter", "kiro", "didi" }; var users = new List<User>(); var userStore = new UserStore<User>(context); var userManager = new UserManager<User>(userStore); userManager.PasswordValidator = new PasswordValidator { RequiredLength = 2, RequireNonLetterOrDigit = false, RequireDigit = false, RequireLowercase = false, RequireUppercase = false, }; foreach (var username in usernames) { var name = username[0].ToString().ToUpper() + username.Substring(1); int i = 0; var user = new User { UserName = username, FullName = name, Email = username + "@gmail.com", EmployeeNumber = ++i, IsActive = true, Department = departments[this.random.Next(0, departments.Count())], JobTitle = jobTitles[this.random.Next(0, jobTitles.Count())], CreatedOn = DateTime.Now }; var password = username; var userCreateResult = userManager.Create(user, password); if (userCreateResult.Succeeded) { users.Add(user); } else { throw new Exception(string.Join("; ", userCreateResult.Errors)); } } // Create "Administrator" role var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var roleCreateResult = roleManager.Create(new IdentityRole(GlobalConstants.AdminRole)); if (!roleCreateResult.Succeeded) { throw new Exception(string.Join("; ", roleCreateResult.Errors)); } // Add "admin" user to "Administrator" role var adminUser = users.First(user => user.UserName == "admin"); adminUser.JobTitle = context.JobTitles.Where(jt => jt.Name == "admin").First(); var addAdminRoleResult = userManager.AddToRole(adminUser.Id, GlobalConstants.AdminRole); if (!addAdminRoleResult.Succeeded) { throw new Exception(string.Join("; ", addAdminRoleResult.Errors)); } context.SaveChanges(); return users; } private string RandomPhoneNumber() { var middleNumber = new int[] { 993, 933 }; return "0884" + middleNumber[random.Next(0, middleNumber.Length)] + random.Next(0, 1000).ToString().PadLeft(3, '0'); } } }
// --------------------------------------------------------------------------------- // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // // The MIT License (MIT) // // 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. // --------------------------------------------------------------------------------- //#define DEBUG_LOG namespace Microsoft.OpenIoT { using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Threading; using Amqp; using Amqp.Framing; using Microsoft.OpenIoT.Common; //--// public class AMQPSender<T> : IMessageSender<T> { //--// internal class ReliableSender { private readonly object _syncRoot = new object( ); //--// private readonly string _eventHubName; private Address _address; private SenderLink _sender; private bool _alive; private ILogger _Logger; //--// internal ReliableSender( string amqpsAddress, string eventHubName ) { _eventHubName = eventHubName; //_Logger = SafeLogger.FromLogger( logger ); try { _address = new Address( amqpsAddress ); } catch( Exception ex ) { throw new ArgumentException( "Please use a correct amqp address: " + ex.Message ); } EstablishSender( ); } internal SenderLink Sender { get { EstablishSender( ); return _sender; } } internal void SetDead( ) { if( _alive ) { lock( _syncRoot ) { if( _alive ) { _alive = false; if( _sender != null ) { _sender.Closed -= OnSenderClosedCallback; _sender.Close( ); } } } } } internal void Close( ) { _sender.Close( STOP_TIMEOUT_MS ); } protected void EstablishSender( ) { try { if( _alive == false ) { lock( _syncRoot ) { if( _alive == false ) { try { Connection connection = new Connection( _address ); Session session = new Session( connection ); _sender = new SenderLink( session, "send-link:" + _eventHubName, _eventHubName ); _sender.Closed += OnSenderClosedCallback; _alive = true; } catch( Exception ex ) { _Logger.LogError( "Error on lock: " + ex.ToString() ); } } } } } catch( Exception ex ) { //we don't want service to stop working when exception was thrown at connection creation //TODO: add reraise for some cases _Logger.LogError("Error on establishing sender: " + ex.ToString()); } } protected void OnSenderClosedCallback( AmqpObject sender, Error error ) { //_Logger.LogError( "OnSenderClosedCallback: " + error.Info + error.Description ); // signal the connection will fail SetDead( ); // re-create the connection pro-actively EstablishSender( ); } } //--// internal class SendersPool { public static readonly int MAX_POOL_SIZE = 64; //--// private readonly object _sync = new object( ); //--// //private readonly ILogger _logger; private readonly ReliableSender[] _pool; private int _current; //--// public SendersPool( string amqpAddress, string eventHubName, int size) { //_logger = logger; if( size > MAX_POOL_SIZE ) { size = MAX_POOL_SIZE; } _pool = new ReliableSender[ size ]; for( int i = 0; i < size; ++i ) { _pool[ i ] = new ReliableSender( amqpAddress, eventHubName); } _current = 0; } public ReliableSender PickSender( ) { ReliableSender rs; lock( _sync ) { rs = _pool[ _current ]; _current = ( _current + 1 ) % _pool.Length; } return rs; } public void Close( ) { lock( _sync ) { foreach( ReliableSender rs in _pool ) { rs.Close( ); } } } } //--// private const int STOP_TIMEOUT_MS = 5000; // ms //--// private static readonly string _logMesagePrefix = "AMQPSender error. "; //--// private SendersPool _senders; public ILogger Logger { private get; set; } public AMQPSender( string amqpsAddress, string eventHubName ) { //Logger = SafeLogger.FromLogger( logger ); #if DEBUG_LOG Logger.LogInfo( "Connecting to Event hub" ); #endif if( eventHubName == null ) { throw new ArgumentException( "eventHubName cannot be null" ); } _senders = new SendersPool( amqpsAddress, eventHubName, Constants.ConcurrentConnections); } public TaskWrapper SendSerialized( byte[] pbData ) { TaskWrapper result = null; try { if (pbData.Length == 0) { return default( TaskWrapper ); } result = PrepareAndSend(pbData); } catch( Exception ex ) { Logger.LogError( _logMesagePrefix + ex.Message ); } return result; } public TaskWrapper SendMessage(T data) { return default(TaskWrapper); } public void Close( ) { _senders.Close( ); } private TaskWrapper PrepareAndSend( byte[] pbData ) { Message msg = PrepareMessage(pbData); // send to the cloud asynchronously, but wait for completetion // this is actually serializing access to the SenderLink type var sh = new SafeAction<Message>( m => SendAmqpMessage( m ), Logger ); return TaskWrapper.Run( ( ) => sh.SafeInvoke( msg ) ); } private void SendAmqpMessage( Message m ) { bool firstTry = true; ReliableSender rl = _senders.PickSender( ); while( true ) { try { rl.Sender.Send( m, SendOutcome, rl ); break; } catch( Exception ex ) { Logger.LogError( "Exception on send" + ex.Message ); if( firstTry ) { firstTry = false; rl.SetDead( ); } else { // re-trhrow the exception if we already re-tried throw; } } } } protected Message PrepareMessage(byte[] serializedData) { var creationTime = DateTime.UtcNow; Message message = null; if (serializedData.Length!=0) { message = new Message() { Properties = new Properties { CreationTime = creationTime, // Time of data sampling }, MessageAnnotations = new MessageAnnotations(), ApplicationProperties = new ApplicationProperties() }; message.ApplicationProperties["payload"] = System.Text.Encoding.UTF8.GetString(serializedData); message.Properties.ContentType = "text/protocol-buffer"; } return message; } int _sentMessages = 0; DateTime _start; private void SendOutcome( Message message, Outcome outcome, object state ) { int sent = Interlocked.Increment( ref _sentMessages ); string messageToLog = Encoding.UTF8.GetString( message.Encode( ).Buffer ); int jsonBracketIndex = messageToLog.IndexOf( "{", System.StringComparison.Ordinal ); if( jsonBracketIndex > 0 ) { messageToLog = messageToLog.Substring( jsonBracketIndex ); } jsonBracketIndex = messageToLog.LastIndexOf( "}", System.StringComparison.Ordinal ); if( jsonBracketIndex > 0 ) { messageToLog = messageToLog.Substring( 0, jsonBracketIndex + 1 ); } if( outcome is Accepted ) { #if DEBUG_LOG Logger.LogInfo( "Message is accepted" ); #endif if( sent == 1 ) { _start = DateTime.Now; } if( Interlocked.CompareExchange( ref _sentMessages, 0, Constants.MessagesLoggingThreshold ) == Constants.MessagesLoggingThreshold ) { DateTime now = DateTime.Now; TimeSpan elapsed = ( now - _start ); _start = now; var sh = new SafeAction<String>( s => Logger.LogInfo( s ), Logger ); TaskWrapper.Run( ( ) => sh.SafeInvoke( String.Format( "GatewayService sent {0} events to Event Hub succesfully in {1} ms ", Constants.MessagesLoggingThreshold, elapsed.TotalMilliseconds.ToString( ) ) ) ); } } else { #if DEBUG_LOG Logger.LogInfo( "Message is rejected: " + messageToLog ); #endif } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Threading; using System.Xml; using Microsoft.Win32; namespace LESs { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { const string IntendedVersion = "0.0.1.94"; private readonly BackgroundWorker worker = new BackgroundWorker(); private bool wasPatched = true; public MainWindow() { InitializeComponent(); FindButton.AddHandler(MouseDownEvent, new RoutedEventHandler(FindButton_MouseDown), true); LeagueVersionLabel.Content = IntendedVersion; if (File.Exists("debug.log")) { File.Delete("debug.log"); } File.Create("debug.log"); if (Directory.Exists("temp")) { Directory.Delete("temp", true); } if (Directory.Exists(Path.Combine(Path.GetPathRoot(Environment.SystemDirectory), "wm"))) { MessageBox.Show( "You may have malware on your system due to getting this application from an unknown source. Please delete C:/wm/ and the file inside it and then download this application from http://da.viddiaz.com/LESs"); } worker.DoWork += worker_DoWork; worker.RunWorkerCompleted += worker_RunWorkerCompleted; if (!Debugger.IsAttached) { AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException; } } void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e) { Exception ex = e.Exception; MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine); this.wasPatched = false; } private void MainGrid_Loaded(object sender, RoutedEventArgs e) { if (!Directory.Exists("mods")) { MessageBox.Show("Missing mods directory. Ensure that all files were extracted properly.", "Missing files"); } var modList = Directory.GetDirectories("mods"); foreach (string mod in modList) { var check = new CheckBox(); check.IsChecked = true; check.Content = mod.Replace("mods\\", string.Empty); if (File.Exists(Path.Combine(mod, "disabled"))) { check.IsChecked = false; } ModsListBox.Items.Add(check); } } private void ModsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { var box = (CheckBox)ModsListBox.SelectedItem; if (box == null) { return; } var selectedMod = (string)box.Content; using (XmlReader reader = XmlReader.Create(Path.Combine("mods", selectedMod, "info.xml"))) { while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "name": reader.Read(); ModNameLabel.Content = reader.Value; break; case "description": reader.Read(); ModDescriptionBox.Text = reader.Value; break; } } } } } private void FindButton_MouseDown(object sender, RoutedEventArgs e) { PatchButton.IsEnabled = false; var findLeagueDialog = new OpenFileDialog(); findLeagueDialog.InitialDirectory = !Directory.Exists(Path.Combine("C:\\", "Riot Games", "League of Legends")) ? Path.Combine("C:\\", "Program Files (x86)", "GarenaLoL", "GameData", "Apps", "LoL") : Path.Combine("C:\\", "Riot Games", "League of Legends"); findLeagueDialog.DefaultExt = ".exe"; findLeagueDialog.Filter = "League of Legends Launcher|lol.launcher*.exe|Garena Launcher|lol.exe"; bool? result = findLeagueDialog.ShowDialog(); if (result == true) { File.AppendAllText("debug.log", findLeagueDialog.FileName + Environment.NewLine); string filename = findLeagueDialog.FileName.Replace("lol.launcher.exe", string.Empty).Replace("lol.launcher.admin.exe", string.Empty); if (filename.Contains("lol.exe")) { // Ga ga ga garena PatchButton.IsEnabled = true; RemoveButton.IsEnabled = false; // Can't automatically remove on garena installations! filename = filename.Replace("lol.exe", string.Empty); LocationTextbox.Text = Path.Combine(filename, "Air"); } else { string radLocation = Path.Combine(filename, "RADS", "projects", "lol_air_client", "releases"); File.AppendAllText("debug.log", filename + Environment.NewLine + radLocation + Environment.NewLine); var versionDirectories = Directory.GetDirectories(radLocation); string finalDirectory = string.Empty; string version = string.Empty; int versionCompare = 0; foreach (string x in versionDirectories) { string compare1 = x.Substring(x.IndexOf("releases\\")).Replace("releases\\", string.Empty); int compareVersion; try { compareVersion = Convert.ToInt32(compare1.Substring(0, 8).Replace(".", string.Empty)); } catch (ArgumentOutOfRangeException) // fix for version numbers < 0.0.1.10 { // Ignore compareVersion = 0; } if (compareVersion > versionCompare) { versionCompare = compareVersion; version = x.Replace(radLocation + "\\", string.Empty); finalDirectory = x; } File.AppendAllText("debug.log", x + Environment.NewLine + compareVersion + Environment.NewLine); } if (version != IntendedVersion) { MessageBoxResult versionMismatchResult = MessageBox.Show("This version of LESs is intended for " + IntendedVersion + ". Your current version of League of Legends is " + version + ". Continue? This could harm your installation.", "Invalid Version", MessageBoxButton.YesNo); if (versionMismatchResult == MessageBoxResult.No) return; } PatchButton.IsEnabled = true; RemoveButton.IsEnabled = true; LocationTextbox.Text = Path.Combine(finalDirectory, "deploy"); } Directory.CreateDirectory(Path.Combine(LocationTextbox.Text, "LESsBackup")); Directory.CreateDirectory(Path.Combine(LocationTextbox.Text, "LESsBackup", IntendedVersion)); } } private void PatchButton_Click(object sender, RoutedEventArgs e) { PatchButton.IsEnabled = false; File.AppendAllText("debug.log", "Starting patch" + Environment.NewLine); // ToDo: Localize worker.RunWorkerAsync(); } private void RemoveButton_Click(object sender, RoutedEventArgs e) { if (File.Exists(Path.Combine(LocationTextbox.Text.Substring(0, LocationTextbox.Text.Length - 7), "S_OK"))) { File.Delete(Path.Combine(LocationTextbox.Text.Substring(0, LocationTextbox.Text.Length - 7), "S_OK")); MessageBox.Show("LESs will be removed next time League of Legends launches!"); StatusLabel.Content = "Removed LESs"; } } private void worker_DoWork(object sender, DoWorkEventArgs e) { ItemCollection modCollection = null; Dispatcher.BeginInvoke( DispatcherPriority.Input, new ThreadStart(() => { modCollection = ModsListBox.Items; })); // Wait for UI thread to respond... while (modCollection == null) { ; } foreach (var x in modCollection) { var box = (CheckBox)x; bool? isBoxChecked = null; string boxName = string.Empty; Dispatcher.BeginInvoke( DispatcherPriority.Input, new ThreadStart( () => { if (box.IsChecked != null && (bool)box.IsChecked) { isBoxChecked = true; boxName = (string)box.Content; } else { isBoxChecked = false; boxName = "blah"; } })); // Wait for UI thread to respond... while (isBoxChecked == null || String.IsNullOrEmpty(boxName)) { ; } if ((bool)isBoxChecked) { int amountOfPatches = 1; using (XmlReader reader = XmlReader.Create(Path.Combine("mods", boxName, "info.xml"))) { while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "files": reader.Read(); amountOfPatches = Convert.ToInt32(reader.Value); break; } } } } for (int i = 0; i < amountOfPatches; i++) { Directory.CreateDirectory("temp"); Patcher(boxName, i); DeletePathWithLongFileNames(Path.GetFullPath("temp")); } } } } private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { MessageBox.Show( this.wasPatched ? "LESs has been successfully patched into League of Legends!" : "LESs encountered errors during patching. However, some patches may still be applied."); PatchButton.IsEnabled = true; StatusLabel.Content = "Done patching!"; } private void Patcher(string modName, int amountOfPatches) { string patchNumber = string.Empty; if (amountOfPatches >= 1) { patchNumber = amountOfPatches.ToString(); } string[] modDetails = File.ReadAllLines(Path.Combine("mods", modName, "patch" + patchNumber + ".txt")); string fileLocation = "null"; string tryFindClass = "null"; string traitToModify = "null"; bool isNewTrait = false; foreach (string s in modDetails) { if (s.StartsWith("#")) { tryFindClass = s.Substring(1); } else if (s.StartsWith("@@@")) { traitToModify = s.Substring(3); } else if (s.StartsWith("@+@")) { // Insert the new trait above this one traitToModify = s.Substring(3); isNewTrait = true; } else if (s.StartsWith("~")) { fileLocation = s.Substring(1); } } File.AppendAllText("debug.log", "Patching " + modName + patchNumber + Environment.NewLine); // ToDo: Localize string[] filePart = fileLocation.Split('/'); string fileName = filePart[filePart.Length - 1]; string locationText = string.Empty; Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() => { locationText = LocationTextbox.Text; })); //Wait for UI thread to respond... while (String.IsNullOrEmpty(locationText)) ; string n = string.Empty; foreach (string s in filePart.Take(filePart.Length - 1)) { n = Path.Combine(n, s); if (!Directory.Exists(Path.Combine(locationText, "LESsBackup", IntendedVersion, n))) { Directory.CreateDirectory(Path.Combine(locationText, "LESsBackup", IntendedVersion, n)); } } if (!File.Exists(Path.Combine(locationText, "LESsBackup", IntendedVersion, fileLocation))) { File.Copy(Path.Combine(locationText, fileLocation), Path.Combine(locationText, "LESsBackup", IntendedVersion, fileLocation)); } File.Copy(Path.Combine(locationText, fileLocation), Path.Combine("temp", fileName)); Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() => { StatusLabel.Content = "Exporting patch " + modName; })); File.AppendAllText("debug.log", "Running abcexport" + Environment.NewLine); // ToDo: Localize var export = new ProcessStartInfo(); export.FileName = "abcexport.exe"; export.Arguments = Path.Combine("temp", fileName); var ExportProc = Process.Start(export); if (ExportProc != null) { ExportProc.WaitForExit(); } Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() => { StatusLabel.Content = "Disassembling patch (" + modName + ")"; })); string[] abcFiles = Directory.GetFiles("temp", "*.abc"); File.AppendAllText("debug.log", "Got " + abcFiles.Length + " files" + Environment.NewLine); // ToDo: Localize foreach (string s in abcFiles) { var disassemble = new ProcessStartInfo(); disassemble.FileName = "rabcdasm.exe"; disassemble.Arguments = s; disassemble.UseShellExecute = false; disassemble.CreateNoWindow = true; var disasmProc = Process.Start(disassemble); if (disasmProc != null) { disasmProc.WaitForExit(); } } if (tryFindClass.IndexOf(':') == 0) { File.AppendAllText("debug.log", "INVALID MOD!!!" + Environment.NewLine); // ToDo: Localize throw new Exception("Invalid mod " + modName); } List<string> directories = Directory.GetDirectories("temp", "*", SearchOption.AllDirectories).ToList(); //Get all directories that match the requested class to modify string searchFor = tryFindClass.Substring(0, tryFindClass.IndexOf(':')); var foundDirectories = new List<string>(); foreach (string s in directories) { if (!s.Contains("com")) continue; string tempS = s; tempS = tempS.Substring(tempS.IndexOf("com")); tempS = tempS.Replace("\\", "."); if (tempS == searchFor) { foundDirectories.Add(s); } } if (foundDirectories.Count == 0) { File.AppendAllText("debug.log", "No class matching " + searchFor + " for mod " + modName + Environment.NewLine); // ToDo: Localize throw new Exception("No class matching " + searchFor + " for mod " + modName); } string finalDirectory = string.Empty; string Class = tryFindClass.Substring(tryFindClass.IndexOf(':')).Replace(":", string.Empty); //Find the directory that has the requested class foreach (string s in foundDirectories) { string[] m = Directory.GetFiles(s); string x = Path.Combine(s, Class + ".class.asasm"); if (m.Contains(x)) { finalDirectory = s; } } string[] ClassModifier = File.ReadAllLines(Path.Combine(finalDirectory, Class + ".class.asasm")); //return if the new trait already exists if (isNewTrait) { foreach (string l in ClassModifier) { if (l == modDetails[3]) return; } } int traitStartPosition = 0; int traitEndLocation = 0; // Get location of trait for (int i = 0; i < ClassModifier.Length; i++) { if (ClassModifier[i] == traitToModify) { traitStartPosition = i; break; } } if (traitStartPosition == 0) { File.AppendAllText("debug.log", "Trait start location was not found! Corrupt mod?"); // ToDo: Localize throw new Exception("Trait start location was not found! Corrupt mod?"); } if (!isNewTrait) { // Get end location of trait for (int i = traitStartPosition; i < ClassModifier.Length; i++) { if (ClassModifier[i].Trim() == "end ; method") { if (ClassModifier[i + 1].Trim() == "end ; trait") { traitEndLocation = i + 2; } else { traitEndLocation = i + 1; } break; } } if (traitEndLocation < traitStartPosition) { File.AppendAllText("debug.log", "Trait end location was smaller than trait start location! " + traitEndLocation + ", " + traitStartPosition); // ToDo: Localize throw new Exception("Trait end location was smaller than trait start location! " + traitEndLocation + ", " + traitStartPosition); } var startTrait = new string[traitStartPosition]; Array.Copy(ClassModifier, startTrait, traitStartPosition); var afterTrait = new string[ClassModifier.Length - traitEndLocation]; Array.Copy(ClassModifier, traitEndLocation, afterTrait, 0, ClassModifier.Length - traitEndLocation); var finalClass = new string[startTrait.Length + (modDetails.Length - 3) + afterTrait.Length]; Array.Copy(startTrait, finalClass, traitStartPosition); Array.Copy(modDetails, 3, finalClass, traitStartPosition, modDetails.Length - 3); Array.Copy(afterTrait, 0, finalClass, traitStartPosition + (modDetails.Length - 3), afterTrait.Length); File.Delete(Path.Combine(finalDirectory, Class + ".class.asasm")); File.WriteAllLines(Path.Combine(finalDirectory, Class + ".class.asasm"), finalClass); } else { var finalClass = new string[ClassModifier.Length + (modDetails.Length - 3)]; Array.Copy(ClassModifier, 0, finalClass, 0, traitStartPosition); Array.Copy(modDetails, 3, finalClass, traitStartPosition, modDetails.Length - 3); Array.Copy(ClassModifier, traitStartPosition, finalClass, traitStartPosition + modDetails.Length - 3, ClassModifier.Length - traitStartPosition); File.Delete(Path.Combine(finalDirectory, Class + ".class.asasm")); File.WriteAllLines(Path.Combine(finalDirectory, Class + ".class.asasm"), finalClass); } var reAssembleLocation = finalDirectory.Substring(0, finalDirectory.IndexOf("com")).Replace("temp\\", string.Empty); string abcNumber = reAssembleLocation.Substring(reAssembleLocation.IndexOf('-')).Replace("-", string.Empty).Replace("\\", string.Empty); Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() => { StatusLabel.Content = "Repackaging " + modName; })); var reAsm = new ProcessStartInfo(); reAsm.FileName = "rabcasm.exe"; reAsm.RedirectStandardError = true; reAsm.UseShellExecute = false; reAsm.Arguments = Path.Combine("temp", reAssembleLocation, reAssembleLocation.Replace("\\", string.Empty) + ".main.asasm"); var reAsmProc = Process.Start(reAsm); while (reAsmProc != null && !reAsmProc.StandardError.EndOfStream) { string line = reAsmProc.StandardError.ReadLine(); File.AppendAllText("debug.log", line + Environment.NewLine); } if (reAsmProc != null) { reAsmProc.WaitForExit(); } Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() => { StatusLabel.Content = "Finishing touches for " + modName; })); var doPatch = new ProcessStartInfo(); doPatch.FileName = "abcreplace.exe"; doPatch.RedirectStandardError = true; doPatch.UseShellExecute = false; doPatch.Arguments = Path.Combine("temp", fileName) + " " + abcNumber + " " + Path.Combine("temp", reAssembleLocation, reAssembleLocation.Replace("\\", string.Empty) + ".main.abc"); var finalPatchProc = Process.Start(doPatch); while (finalPatchProc != null && !finalPatchProc.StandardError.EndOfStream) { string line = finalPatchProc.StandardError.ReadLine(); File.AppendAllText("debug.log", line + Environment.NewLine); } if (finalPatchProc != null) { finalPatchProc.WaitForExit(); } Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() => { StatusLabel.Content = "Done patching " + modName + "!"; })); File.Copy(Path.Combine("temp", fileName), Path.Combine(locationText, fileLocation), true); } private static void DeletePathWithLongFileNames(string path) { var tmpPath = @"\\?\" + path; var fso = new Scripting.FileSystemObject(); fso.DeleteFolder(tmpPath, true); } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using SDKTemplate; using Windows.UI.Core; using Windows.Media.SpeechRecognition; using System; using System.Collections.Generic; using System.Text; using Windows.UI.Xaml.Media; using Windows.Globalization; using Windows.UI.Xaml.Documents; using System.Threading.Tasks; namespace SDKTemplate { public sealed partial class Scenario_ContinuousDictation : Page { // Reference to the main sample page in order to post status messages. private MainPage rootPage; // The speech recognizer used throughout this sample. private SpeechRecognizer speechRecognizer; // Keep track of whether the continuous recognizer is currently running, so it can be cleaned up appropriately. private bool isListening; // Keep track of existing text that we've accepted in ContinuousRecognitionSession_ResultGenerated(), so // that we can combine it and Hypothesized results to show in-progress dictation mid-sentence. private StringBuilder dictatedTextBuilder; /// <summary> /// This HResult represents the scenario where a user is prompted to allow in-app speech, but /// declines. This should only happen on a Phone device, where speech is enabled for the entire device, /// not per-app. /// </summary> private static uint HResultPrivacyStatementDeclined = 0x80045509; public Scenario_ContinuousDictation() { this.InitializeComponent(); isListening = false; dictatedTextBuilder = new StringBuilder(); } /// <summary> /// Upon entering the scenario, ensure that we have permissions to use the Microphone. This may entail popping up /// a dialog to the user on Desktop systems. Only enable functionality once we've gained that permission in order to /// prevent errors from occurring when using the SpeechRecognizer. If speech is not a primary input mechanism, developers /// should consider disabling appropriate parts of the UI if the user does not have a recording device, or does not allow /// audio input. /// </summary> /// <param name="e">Unused navigation parameters</param> protected async override void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; // Prompt the user for permission to access the microphone. This request will only happen // once, it will not re-prompt if the user rejects the permission. bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission(); if (permissionGained) { btnContinuousRecognize.IsEnabled = true; PopulateLanguageDropdown(); await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage); } else { this.dictationTextBox.Text = "Permission to access capture resources was not given by the user, reset the application setting in Settings->Privacy->Microphone."; btnContinuousRecognize.IsEnabled = false; cbLanguageSelection.IsEnabled = false; } } /// <summary> /// Look up the supported languages for this speech recognition scenario, /// that are installed on this machine, and populate a dropdown with a list. /// </summary> private void PopulateLanguageDropdown() { Language defaultLanguage = SpeechRecognizer.SystemSpeechLanguage; IEnumerable<Language> supportedLanguages = SpeechRecognizer.SupportedTopicLanguages; foreach (Language lang in supportedLanguages) { ComboBoxItem item = new ComboBoxItem(); item.Tag = lang; item.Content = lang.DisplayName; cbLanguageSelection.Items.Add(item); if (lang.LanguageTag == defaultLanguage.LanguageTag) { item.IsSelected = true; cbLanguageSelection.SelectedItem = item; } } } /// <summary> /// When a user changes the speech recognition language, trigger re-initialization of the /// speech engine with that language, and change any speech-specific UI assets. /// </summary> /// <param name="sender">Ignored</param> /// <param name="e">Ignored</param> private async void cbLanguageSelection_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (speechRecognizer != null) { ComboBoxItem item = (ComboBoxItem)(cbLanguageSelection.SelectedItem); Language newLanguage = (Language)item.Tag; if (speechRecognizer.CurrentLanguage != newLanguage) { // trigger cleanup and re-initialization of speech. try { await InitializeRecognizer(newLanguage); } catch (Exception exception) { var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception"); await messageDialog.ShowAsync(); } } } } /// <summary> /// Initialize Speech Recognizer and compile constraints. /// </summary> /// <param name="recognizerLanguage">Language to use for the speech recognizer</param> /// <returns>Awaitable task.</returns> private async Task InitializeRecognizer(Language recognizerLanguage) { if (speechRecognizer != null) { // cleanup prior to re-initializing this scenario. speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged; speechRecognizer.ContinuousRecognitionSession.Completed -= ContinuousRecognitionSession_Completed; speechRecognizer.ContinuousRecognitionSession.ResultGenerated -= ContinuousRecognitionSession_ResultGenerated; speechRecognizer.HypothesisGenerated -= SpeechRecognizer_HypothesisGenerated; this.speechRecognizer.Dispose(); this.speechRecognizer = null; } this.speechRecognizer = new SpeechRecognizer(recognizerLanguage); // Provide feedback to the user about the state of the recognizer. This can be used to provide visual feedback in the form // of an audio indicator to help the user understand whether they're being heard. speechRecognizer.StateChanged += SpeechRecognizer_StateChanged; // Apply the dictation topic constraint to optimize for dictated freeform speech. var dictationConstraint = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.Dictation, "dictation"); speechRecognizer.Constraints.Add(dictationConstraint); SpeechRecognitionCompilationResult result = await speechRecognizer.CompileConstraintsAsync(); if (result.Status != SpeechRecognitionResultStatus.Success) { rootPage.NotifyUser("Grammar Compilation Failed: " + result.Status.ToString(), NotifyType.ErrorMessage); btnContinuousRecognize.IsEnabled = false; } // Handle continuous recognition events. Completed fires when various error states occur. ResultGenerated fires when // some recognized phrases occur, or the garbage rule is hit. HypothesisGenerated fires during recognition, and // allows us to provide incremental feedback based on what the user's currently saying. speechRecognizer.ContinuousRecognitionSession.Completed += ContinuousRecognitionSession_Completed; speechRecognizer.ContinuousRecognitionSession.ResultGenerated += ContinuousRecognitionSession_ResultGenerated; speechRecognizer.HypothesisGenerated += SpeechRecognizer_HypothesisGenerated; } /// <summary> /// Upon leaving, clean up the speech recognizer. Ensure we aren't still listening, and disable the event /// handlers to prevent leaks. /// </summary> /// <param name="e">Unused navigation parameters.</param> protected async override void OnNavigatedFrom(NavigationEventArgs e) { if (this.speechRecognizer != null) { if (isListening) { await this.speechRecognizer.ContinuousRecognitionSession.CancelAsync(); isListening = false; DictationButtonText.Text = " Dictate"; cbLanguageSelection.IsEnabled = true; } dictationTextBox.Text = ""; speechRecognizer.ContinuousRecognitionSession.Completed -= ContinuousRecognitionSession_Completed; speechRecognizer.ContinuousRecognitionSession.ResultGenerated -= ContinuousRecognitionSession_ResultGenerated; speechRecognizer.HypothesisGenerated -= SpeechRecognizer_HypothesisGenerated; speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged; this.speechRecognizer.Dispose(); this.speechRecognizer = null; } } /// <summary> /// Handle events fired when error conditions occur, such as the microphone becoming unavailable, or if /// some transient issues occur. /// </summary> /// <param name="sender">The continuous recognition session</param> /// <param name="args">The state of the recognizer</param> private async void ContinuousRecognitionSession_Completed(SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionCompletedEventArgs args) { if (args.Status != SpeechRecognitionResultStatus.Success) { // If TimeoutExceeded occurs, the user has been silent for too long. We can use this to // cancel recognition if the user in dictation mode and walks away from their device, etc. // In a global-command type scenario, this timeout won't apply automatically. // With dictation (no grammar in place) modes, the default timeout is 20 seconds. if (args.Status == SpeechRecognitionResultStatus.TimeoutExceeded) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser("Automatic Time Out of Dictation", NotifyType.StatusMessage); DictationButtonText.Text = " Dictate"; cbLanguageSelection.IsEnabled = true; dictationTextBox.Text = dictatedTextBuilder.ToString(); isListening = false; }); } else { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser("Continuous Recognition Completed: " + args.Status.ToString(), NotifyType.StatusMessage); DictationButtonText.Text = " Dictate"; cbLanguageSelection.IsEnabled = true; isListening = false; }); } } } /// <summary> /// While the user is speaking, update the textbox with the partial sentence of what's being said for user feedback. /// </summary> /// <param name="sender">The recognizer that has generated the hypothesis</param> /// <param name="args">The hypothesis formed</param> private async void SpeechRecognizer_HypothesisGenerated(SpeechRecognizer sender, SpeechRecognitionHypothesisGeneratedEventArgs args) { string hypothesis = args.Hypothesis.Text; // Update the textbox with the currently confirmed text, and the hypothesis combined. string textboxContent = dictatedTextBuilder.ToString() + " " + hypothesis + " ..."; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { dictationTextBox.Text = textboxContent; btnClearText.IsEnabled = true; }); } /// <summary> /// Handle events fired when a result is generated. Check for high to medium confidence, and then append the /// string to the end of the stringbuffer, and replace the content of the textbox with the string buffer, to /// remove any hypothesis text that may be present. /// </summary> /// <param name="sender">The Recognition session that generated this result</param> /// <param name="args">Details about the recognized speech</param> private async void ContinuousRecognitionSession_ResultGenerated(SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionResultGeneratedEventArgs args) { // We may choose to discard content that has low confidence, as that could indicate that we're picking up // noise via the microphone, or someone could be talking out of earshot. if (args.Result.Confidence == SpeechRecognitionConfidence.Medium || args.Result.Confidence == SpeechRecognitionConfidence.High) { dictatedTextBuilder.Append(args.Result.Text + " "); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { discardedTextBlock.Visibility = Windows.UI.Xaml.Visibility.Collapsed; dictationTextBox.Text = dictatedTextBuilder.ToString(); btnClearText.IsEnabled = true; }); } else { // In some scenarios, a developer may choose to ignore giving the user feedback in this case, if speech // is not the primary input mechanism for the application. // Here, just remove any hypothesis text by resetting it to the last known good. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { dictationTextBox.Text = dictatedTextBuilder.ToString(); string discardedText = args.Result.Text; if (!string.IsNullOrEmpty(discardedText)) { discardedText = discardedText.Length <= 25 ? discardedText : (discardedText.Substring(0, 25) + "..."); discardedTextBlock.Text = "Discarded due to low/rejected Confidence: " + discardedText; discardedTextBlock.Visibility = Windows.UI.Xaml.Visibility.Visible; } }); } } /// <summary> /// Provide feedback to the user based on whether the recognizer is receiving their voice input. /// </summary> /// <param name="sender">The recognizer that is currently running.</param> /// <param name="args">The current state of the recognizer.</param> private async void SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser(args.State.ToString(), NotifyType.StatusMessage); }); } /// <summary> /// Begin recognition, or finish the recognition session. /// </summary> /// <param name="sender">The button that generated this event</param> /// <param name="e">Unused event details</param> public async void ContinuousRecognize_Click(object sender, RoutedEventArgs e) { btnContinuousRecognize.IsEnabled = false; if (isListening == false) { // The recognizer can only start listening in a continuous fashion if the recognizer is currently idle. // This prevents an exception from occurring. if (speechRecognizer.State == SpeechRecognizerState.Idle) { DictationButtonText.Text = " Stop Dictation"; cbLanguageSelection.IsEnabled = false; hlOpenPrivacySettings.Visibility = Visibility.Collapsed; discardedTextBlock.Visibility = Windows.UI.Xaml.Visibility.Collapsed; try { isListening = true; await speechRecognizer.ContinuousRecognitionSession.StartAsync(); } catch (Exception ex) { if ((uint)ex.HResult == HResultPrivacyStatementDeclined) { // Show a UI link to the privacy settings. hlOpenPrivacySettings.Visibility = Visibility.Visible; } else { var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "Exception"); await messageDialog.ShowAsync(); } isListening = false; DictationButtonText.Text = " Dictate"; cbLanguageSelection.IsEnabled = true; } } } else { isListening = false; DictationButtonText.Text = " Dictate"; cbLanguageSelection.IsEnabled = true; if (speechRecognizer.State != SpeechRecognizerState.Idle) { // Cancelling recognition prevents any currently recognized speech from // generating a ResultGenerated event. StopAsync() will allow the final session to // complete. try { await speechRecognizer.ContinuousRecognitionSession.StopAsync(); // Ensure we don't leave any hypothesis text behind dictationTextBox.Text = dictatedTextBuilder.ToString(); } catch (Exception exception) { var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception"); await messageDialog.ShowAsync(); } } } btnContinuousRecognize.IsEnabled = true; } /// <summary> /// Clear the dictation textbox. /// </summary> /// <param name="sender">Ignored</param> /// <param name="e">Ignored</param> private void btnClearText_Click(object sender, RoutedEventArgs e) { btnClearText.IsEnabled = false; dictatedTextBuilder.Clear(); dictationTextBox.Text = ""; discardedTextBlock.Visibility = Windows.UI.Xaml.Visibility.Collapsed; // Avoid setting focus on the text box, since it's a non-editable control. btnContinuousRecognize.Focus(FocusState.Programmatic); } /// <summary> /// Automatically scroll the textbox down to the bottom whenever new dictated text arrives /// </summary> /// <param name="sender">The dictation textbox</param> /// <param name="e">Unused text changed arguments</param> private void dictationTextBox_TextChanged(object sender, TextChangedEventArgs e) { var grid = (Grid)VisualTreeHelper.GetChild(dictationTextBox, 0); for (var i = 0; i <= VisualTreeHelper.GetChildrenCount(grid) - 1; i++) { object obj = VisualTreeHelper.GetChild(grid, i); if (!(obj is ScrollViewer)) { continue; } ((ScrollViewer)obj).ChangeView(0.0f, ((ScrollViewer)obj).ExtentHeight, 1.0f); break; } } /// <summary> /// Open the Speech, Inking and Typing page under Settings -> Privacy, enabling a user to accept the /// Microsoft Privacy Policy, and enable personalization. /// </summary> /// <param name="sender">Ignored</param> /// <param name="args">Ignored</param> private async void openPrivacySettings_Click(Hyperlink sender, HyperlinkClickEventArgs args) { await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-speech")); } } }
// Copyright (c) Rotorz Limited. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root. using System.Collections.Generic; using ATP.ReorderableList.Internal; using UnityEditor; using UnityEngine; namespace ATP.ReorderableList { /// <summary> /// Utility class for drawing reorderable lists. /// </summary> public static class ReorderableListGUI { /// <summary> /// Default list item height is 18 pixels. /// </summary> public const float DefaultItemHeight = 18; /// <summary> /// Gets or sets zero-based index of last item which was changed. A value of -1 /// indicates that no item was changed by list. /// </summary> /// <remarks> /// <para>This property should not be set when items are added or removed.</para> /// </remarks> public static int indexOfChangedItem { get; internal set; } /// <summary> /// Gets zero-based index of list item which is currently being drawn; /// or a value of -1 if no item is currently being drawn. /// </summary> public static int currentItemIndex { get { return ReorderableListControl.currentItemIndex; } } #region Basic Item Drawers /// <summary> /// Default list item drawer implementation. /// </summary> /// <remarks> /// <para>Always presents the label "Item drawer not implemented.".</para> /// </remarks> /// <param name="position">Position to draw list item control(s).</param> /// <param name="item">Value of list item.</param> /// <returns> /// Unmodified value of list item. /// </returns> /// <typeparam name="T">Type of list item.</typeparam> public static T DefaultItemDrawer<T>(Rect position, T item) { GUI.Label(position, "Item drawer not implemented."); return item; } /// <summary> /// Draws text field allowing list items to be edited. /// </summary> /// <remarks> /// <para>Null values are automatically changed to empty strings since null /// values cannot be edited using a text field.</para> /// <para>Value of <c>GUI.changed</c> is set to <c>true</c> if value of item /// is modified.</para> /// </remarks> /// <param name="position">Position to draw list item control(s).</param> /// <param name="item">Value of list item.</param> /// <returns> /// Modified value of list item. /// </returns> public static string TextFieldItemDrawer(Rect position, string item) { if (item == null) { item = ""; GUI.changed = true; } return EditorGUI.TextField(position, item); } #endregion /// <summary> /// Gets the default list control implementation. /// </summary> private static ReorderableListControl defaultListControl { get; set; } static ReorderableListGUI() { InitStyles(); defaultListControl = new ReorderableListControl(); // Duplicate default styles to prevent user scripts from interferring with // the default list control instance. defaultListControl.containerStyle = new GUIStyle(defaultContainerStyle); defaultListControl.addButtonStyle = new GUIStyle(defaultAddButtonStyle); defaultListControl.removeButtonStyle = new GUIStyle(defaultRemoveButtonStyle); indexOfChangedItem = -1; } #region Custom Styles /// <summary> /// Gets default style for title header. /// </summary> public static GUIStyle defaultTitleStyle { get; private set; } /// <summary> /// Gets default style for background of list control. /// </summary> public static GUIStyle defaultContainerStyle { get; private set; } /// <summary> /// Gets default style for add item button. /// </summary> public static GUIStyle defaultAddButtonStyle { get; private set; } /// <summary> /// Gets default style for remove item button. /// </summary> public static GUIStyle defaultRemoveButtonStyle { get; private set; } private static void InitStyles() { defaultTitleStyle = new GUIStyle(); defaultTitleStyle.border = new RectOffset(2, 2, 2, 1); defaultTitleStyle.margin = new RectOffset(5, 5, 5, 0); defaultTitleStyle.padding = new RectOffset(5, 5, 0, 0); defaultTitleStyle.alignment = TextAnchor.MiddleLeft; defaultTitleStyle.normal.background = ReorderableListResources.texTitleBackground; defaultTitleStyle.normal.textColor = EditorGUIUtility.isProSkin ? new Color(0.8f, 0.8f, 0.8f) : new Color(0.2f, 0.2f, 0.2f); defaultContainerStyle = new GUIStyle(); defaultContainerStyle.border = new RectOffset(2, 2, 1, 2); defaultContainerStyle.margin = new RectOffset(5, 5, 5, 5); defaultContainerStyle.padding = new RectOffset(1, 1, 2, 2); defaultContainerStyle.normal.background = ReorderableListResources.texContainerBackground; defaultAddButtonStyle = new GUIStyle(); defaultAddButtonStyle.fixedWidth = 30; defaultAddButtonStyle.fixedHeight = 16; defaultAddButtonStyle.normal.background = ReorderableListResources.texAddButton; defaultAddButtonStyle.active.background = ReorderableListResources.texAddButtonActive; defaultRemoveButtonStyle = new GUIStyle(); defaultRemoveButtonStyle.fixedWidth = 27; defaultRemoveButtonStyle.active.background = ReorderableListResources.CreatePixelTexture("Dark Pixel (List GUI)", new Color32(18, 18, 18, 255)); defaultRemoveButtonStyle.imagePosition = ImagePosition.ImageOnly; defaultRemoveButtonStyle.alignment = TextAnchor.MiddleCenter; } #endregion private static GUIContent s_Temp = new GUIContent(); #region Title Control /// <summary> /// Draw title control for list field. /// </summary> /// <remarks> /// <para>When needed, should be shown immediately before list field.</para> /// </remarks> /// <example> /// <code language="csharp"><![CDATA[ /// ReorderableListGUI.Title(titleContent); /// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer); /// ]]></code> /// <code language="unityscript"><![CDATA[ /// ReorderableListGUI.Title(titleContent); /// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer); /// ]]></code> /// </example> /// <param name="title">Content for title control.</param> public static void Title(GUIContent title) { Rect position = GUILayoutUtility.GetRect(title, defaultTitleStyle); position.height += 6; Title(position, title); } /// <summary> /// Draw title control for list field. /// </summary> /// <remarks> /// <para>When needed, should be shown immediately before list field.</para> /// </remarks> /// <example> /// <code language="csharp"><![CDATA[ /// ReorderableListGUI.Title("Your Title"); /// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer); /// ]]></code> /// <code language="unityscript"><![CDATA[ /// ReorderableListGUI.Title('Your Title'); /// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer); /// ]]></code> /// </example> /// <param name="title">Text for title control.</param> public static void Title(string title) { s_Temp.text = title; Title(s_Temp); } /// <summary> /// Draw title control for list field with absolute positioning. /// </summary> /// <param name="position">Position of control.</param> /// <param name="title">Content for title control.</param> public static void Title(Rect position, GUIContent title) { if (Event.current.type == EventType.Repaint) defaultTitleStyle.Draw(position, title, false, false, false, false); } /// <summary> /// Draw title control for list field with absolute positioning. /// </summary> /// <param name="position">Position of control.</param> /// <param name="text">Text for title control.</param> public static void Title(Rect position, string text) { s_Temp.text = text; Title(position, s_Temp); } #endregion #region List<T> Control /// <summary> /// Draw list field control. /// </summary> /// <param name="list">The list which can be reordered.</param> /// <param name="drawItem">Callback to draw list item.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="itemHeight">Height of a single list item.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <typeparam name="T">Type of list item.</typeparam> private static void DoListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight, ReorderableListFlags flags) { var adaptor = new GenericListAdaptor<T>(list, drawItem, itemHeight); ReorderableListControl.DrawControlFromState(adaptor, drawEmpty, flags); } /// <summary> /// Draw list field control with absolute positioning. /// </summary> /// <param name="position">Position of control.</param> /// <param name="list">The list which can be reordered.</param> /// <param name="drawItem">Callback to draw list item.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="itemHeight">Height of a single list item.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <typeparam name="T">Type of list item.</typeparam> private static void DoListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight, ReorderableListFlags flags) { var adaptor = new GenericListAdaptor<T>(list, drawItem, itemHeight); ReorderableListControl.DrawControlFromState(position, adaptor, drawEmpty, flags); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight, ReorderableListFlags flags) { DoListField<T>(list, drawItem, drawEmpty, itemHeight, flags); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight, ReorderableListFlags flags) { DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, itemHeight, flags); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight) { DoListField<T>(list, drawItem, drawEmpty, itemHeight, 0); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight) { DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, itemHeight, 0); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) { DoListField<T>(list, drawItem, drawEmpty, DefaultItemHeight, flags); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) { DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, DefaultItemHeight, flags); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty) { DoListField<T>(list, drawItem, drawEmpty, DefaultItemHeight, 0); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty) { DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, DefaultItemHeight, 0); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight, ReorderableListFlags flags) { DoListField<T>(list, drawItem, null, itemHeight, flags); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight, ReorderableListFlags flags) { DoListFieldAbsolute<T>(position, list, drawItem, null, itemHeight, flags); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight) { DoListField<T>(list, drawItem, null, itemHeight, 0); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight) { DoListFieldAbsolute<T>(position, list, drawItem, null, itemHeight, 0); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListFlags flags) { DoListField<T>(list, drawItem, null, DefaultItemHeight, flags); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListFlags flags) { DoListFieldAbsolute<T>(position, list, drawItem, null, DefaultItemHeight, flags); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem) { DoListField<T>(list, drawItem, null, DefaultItemHeight, 0); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem) { DoListFieldAbsolute<T>(position, list, drawItem, null, DefaultItemHeight, 0); } /// <summary> /// Calculate height of list field for absolute positioning. /// </summary> /// <param name="itemCount">Count of items in list.</param> /// <param name="itemHeight">Fixed height of list item.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <returns> /// Required list height in pixels. /// </returns> public static float CalculateListFieldHeight(int itemCount, float itemHeight, ReorderableListFlags flags) { // We need to push/pop flags so that nested controls are properly calculated. var restoreFlags = defaultListControl.flags; try { defaultListControl.flags = flags; return defaultListControl.CalculateListHeight(itemCount, itemHeight); } finally { defaultListControl.flags = restoreFlags; } } /// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/> public static float CalculateListFieldHeight(int itemCount, ReorderableListFlags flags) { return CalculateListFieldHeight(itemCount, DefaultItemHeight, flags); } /// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/> public static float CalculateListFieldHeight(int itemCount, float itemHeight) { return CalculateListFieldHeight(itemCount, itemHeight, 0); } /// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/> public static float CalculateListFieldHeight(int itemCount) { return CalculateListFieldHeight(itemCount, DefaultItemHeight, 0); } #endregion #region SerializedProperty Control /// <summary> /// Draw list field control for serializable property array. /// </summary> /// <param name="arrayProperty">Serializable property.</param> /// <param name="fixedItemHeight">Use fixed height for items rather than <see cref="UnityEditor.EditorGUI.GetPropertyHeight(SerializedProperty)"/>.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="flags">Optional flags to pass into list field.</param> private static void DoListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) { var adaptor = new SerializedPropertyAdaptor(arrayProperty, fixedItemHeight); ReorderableListControl.DrawControlFromState(adaptor, drawEmpty, flags); } /// <summary> /// Draw list field control for serializable property array. /// </summary> /// <param name="position">Position of control.</param> /// <param name="arrayProperty">Serializable property.</param> /// <param name="fixedItemHeight">Use fixed height for items rather than <see cref="UnityEditor.EditorGUI.GetPropertyHeight(SerializedProperty)"/>.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="flags">Optional flags to pass into list field.</param> private static void DoListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) { var adaptor = new SerializedPropertyAdaptor(arrayProperty, fixedItemHeight); ReorderableListControl.DrawControlFromState(position, adaptor, drawEmpty, flags); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(SerializedProperty arrayProperty, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) { DoListField(arrayProperty, 0, drawEmpty, flags); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) { DoListFieldAbsolute(position, arrayProperty, 0, drawEmpty, flags); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(SerializedProperty arrayProperty, ReorderableListControl.DrawEmpty drawEmpty) { DoListField(arrayProperty, 0, drawEmpty, 0); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, ReorderableListControl.DrawEmptyAbsolute drawEmpty) { DoListFieldAbsolute(position, arrayProperty, 0, drawEmpty, 0); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(SerializedProperty arrayProperty, ReorderableListFlags flags) { DoListField(arrayProperty, 0, null, flags); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, ReorderableListFlags flags) { DoListFieldAbsolute(position, arrayProperty, 0, null, flags); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(SerializedProperty arrayProperty) { DoListField(arrayProperty, 0, null, 0); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty) { DoListFieldAbsolute(position, arrayProperty, 0, null, 0); } /// <summary> /// Calculate height of list field for absolute positioning. /// </summary> /// <param name="arrayProperty">Serializable property.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <returns> /// Required list height in pixels. /// </returns> public static float CalculateListFieldHeight(SerializedProperty arrayProperty, ReorderableListFlags flags) { // We need to push/pop flags so that nested controls are properly calculated. var restoreFlags = defaultListControl.flags; try { defaultListControl.flags = flags; return defaultListControl.CalculateListHeight(new SerializedPropertyAdaptor(arrayProperty)); } finally { defaultListControl.flags = restoreFlags; } } /// <inheritdoc cref="CalculateListFieldHeight(SerializedProperty, ReorderableListFlags)"/> public static float CalculateListFieldHeight(SerializedProperty arrayProperty) { return CalculateListFieldHeight(arrayProperty, 0); } #endregion #region SerializedProperty Control (Fixed Item Height) /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) { DoListField(arrayProperty, fixedItemHeight, drawEmpty, flags); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) { DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, drawEmpty, flags); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty) { DoListField(arrayProperty, fixedItemHeight, drawEmpty, 0); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty) { DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, drawEmpty, 0); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListFlags flags) { DoListField(arrayProperty, fixedItemHeight, null, flags); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListFlags flags) { DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, null, flags); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight) { DoListField(arrayProperty, fixedItemHeight, null, 0); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight) { DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, null, 0); } #endregion #region Adaptor Control /// <summary> /// Draw list field control for adapted collection. /// </summary> /// <param name="adaptor">Reorderable list adaptor.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="flags">Optional flags to pass into list field.</param> private static void DoListField(IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags = 0) { ReorderableListControl.DrawControlFromState(adaptor, drawEmpty, flags); } /// <summary> /// Draw list field control for adapted collection. /// </summary> /// <param name="position">Position of control.</param> /// <param name="adaptor">Reorderable list adaptor.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="flags">Optional flags to pass into list field.</param> private static void DoListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags = 0) { ReorderableListControl.DrawControlFromState(position, adaptor, drawEmpty, flags); } /// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) { DoListField(adaptor, drawEmpty, flags); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) { DoListFieldAbsolute(position, adaptor, drawEmpty, flags); } /// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty) { DoListField(adaptor, drawEmpty, 0); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty) { DoListFieldAbsolute(position, adaptor, drawEmpty, 0); } /// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(IReorderableListAdaptor adaptor, ReorderableListFlags flags) { DoListField(adaptor, null, flags); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListFlags flags) { DoListFieldAbsolute(position, adaptor, null, flags); } /// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(IReorderableListAdaptor adaptor) { DoListField(adaptor, null, 0); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor) { DoListFieldAbsolute(position, adaptor, null, 0); } /// <summary> /// Calculate height of list field for adapted collection. /// </summary> /// <param name="adaptor">Reorderable list adaptor.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <returns> /// Required list height in pixels. /// </returns> public static float CalculateListFieldHeight(IReorderableListAdaptor adaptor, ReorderableListFlags flags) { // We need to push/pop flags so that nested controls are properly calculated. var restoreFlags = defaultListControl.flags; try { defaultListControl.flags = flags; return defaultListControl.CalculateListHeight(adaptor); } finally { defaultListControl.flags = restoreFlags; } } /// <inheritdoc cref="CalculateListFieldHeight(IReorderableListAdaptor, ReorderableListFlags)"/> public static float CalculateListFieldHeight(IReorderableListAdaptor adaptor) { return CalculateListFieldHeight(adaptor, 0); } #endregion } }
using SciChart.Examples.ExternalDependencies.Common; using SciChart.Wpf.UI.Reactive; using SciChart.Wpf.UI.Reactive.Services; namespace SciChart.Examples.Demo.ViewModels { public class SmileFrownViewModel : BaseViewModel { private readonly ExampleViewModel _parent; private bool _isSmile; private bool _isFrown; private bool _firstLoad; private string _feedbackEmail = ""; private string _feedbackSubject = ""; private string _feedbackContent = ""; private bool _isFrownVisible; private bool _isSmileVisible; private bool _isVisible; public SmileFrownViewModel(ExampleViewModel parent) { _parent = parent; _firstLoad = true; ExampleChanged(); } public void ExampleChanged() { IsSmile = _parent.Usage.FeedbackType.GetValueOrDefault(ExampleFeedbackType.Frown) == ExampleFeedbackType.Smile; IsFrown = _parent.Usage.FeedbackType.GetValueOrDefault(ExampleFeedbackType.Smile) == ExampleFeedbackType.Frown; FeedbackEmail = _parent.Usage.Email; if (!string.IsNullOrEmpty(_parent.Usage.FeedbackText)) { FeedbackSubject = _parent.Usage.FeedbackText.Contains(":") ? _parent.Usage.FeedbackText.Substring(0, _parent.Usage.FeedbackText.IndexOf(":")) : ""; FeedbackContent = _parent.Usage.FeedbackText.Contains(":") ? _parent.Usage.FeedbackText.Substring(_parent.Usage.FeedbackText.IndexOf(":") + 1) : _parent.Usage.FeedbackText; } else { FeedbackSubject = null; FeedbackContent = null; } FrownVisible = false; SmileVisible = false; } public ActionCommand CloseCommand { get { return new ActionCommand(() => { SmileVisible = false; FrownVisible = false; // Revert to original values IsSmile = _parent.Usage.FeedbackType.GetValueOrDefault(ExampleFeedbackType.Frown) == ExampleFeedbackType.Smile; IsFrown = _parent.Usage.FeedbackType.GetValueOrDefault(ExampleFeedbackType.Smile) == ExampleFeedbackType.Frown; FeedbackEmail = _parent.Usage.Email; if (!string.IsNullOrEmpty(_parent.Usage.FeedbackText)) { FeedbackSubject = _parent.Usage.FeedbackText.Contains(":") ? _parent.Usage.FeedbackText.Substring(0, _parent.Usage.FeedbackText.IndexOf(":")) : ""; FeedbackContent = _parent.Usage.FeedbackText.Contains(":") ? _parent.Usage.FeedbackText.Substring(_parent.Usage.FeedbackText.IndexOf(":") + 1) : _parent.Usage.FeedbackText; } else { FeedbackSubject = null; FeedbackContent = null; } }); } } public ActionCommand SubmitCommand { get { return new ActionCommand(() => { _parent.Usage.FeedbackType = (ExampleFeedbackType?)(_isSmile ? ExampleFeedbackType.Smile : (_isFrown ? ExampleFeedbackType.Frown : (ExampleFeedbackType?)null)); _parent.Usage.FeedbackText = _feedbackSubject + ((_feedbackSubject + _feedbackContent).Length > 0 ? ": " : "") + _feedbackContent; _parent.Usage.Email = _feedbackEmail; SmileVisible = false; FrownVisible = false; }); } } public bool IsSmile { get { return _isSmile; } set { if (_isSmile != value) { _isSmile = value; if (IsSmile) { IsFrown = false; } } } } public bool IsFrown { get { return _isFrown; } set { if (_isFrown != value) { _isFrown = value; if (IsFrown) { IsSmile = false; } } } } public string FeedbackEmail { get { return _feedbackEmail; } set { if (_feedbackEmail != value) { _feedbackEmail = value; OnPropertyChanged("FeedbackEmail"); } } } public string FeedbackSubject { get { return _feedbackSubject; } set { if (_feedbackSubject != value) { _feedbackSubject = value; OnPropertyChanged("FeedbackSubject"); } } } public string FeedbackContent { get { return _feedbackContent; } set { if (_feedbackContent != value) { _feedbackContent = value; OnPropertyChanged("FeedbackContent"); } } } public bool SmileVisible { get { return _isSmileVisible; } set { if (_isSmileVisible != value) { _isSmileVisible = value; OnPropertyChanged("SmileVisible"); } if (SmileVisible) { _parent.ExportExampleViewModel.IsExportVisible = false; _parent.BreadCrumbViewModel.IsShowingBreadcrumbNavigation = false; FrownVisible = false; } else { FeedbackSubject = null; FeedbackContent = null; } _parent.InvalidateDialogProperties(); } } public bool FrownVisible { get { return _isFrownVisible; } set { if (_isFrownVisible != value) { _isFrownVisible = value; OnPropertyChanged("FrownVisible"); } if (FrownVisible) { _parent.ExportExampleViewModel.IsExportVisible = false; _parent.BreadCrumbViewModel.IsShowingBreadcrumbNavigation = false; SmileVisible = false; } else { FeedbackSubject = null; FeedbackContent = null; } _parent.InvalidateDialogProperties(); } } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using NPoco; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.Entities; using Umbraco.Cms.Core.Models.Membership; using Umbraco.Cms.Core.Persistence.Querying; using Umbraco.Cms.Core.Persistence.Repositories; using Umbraco.Cms.Core.Scoping; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Infrastructure.Persistence.Dtos; using Umbraco.Cms.Infrastructure.Persistence.Factories; using Umbraco.Cms.Infrastructure.Persistence.Querying; using Umbraco.Extensions; namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement { /// <summary> /// Represents the UserGroupRepository for doing CRUD operations for <see cref="IUserGroup"/> /// </summary> public class UserGroupRepository : EntityRepositoryBase<int, IUserGroup>, IUserGroupRepository { private readonly IShortStringHelper _shortStringHelper; private readonly UserGroupWithUsersRepository _userGroupWithUsersRepository; private readonly PermissionRepository<IContent> _permissionRepository; public UserGroupRepository(IScopeAccessor scopeAccessor, AppCaches appCaches, ILogger<UserGroupRepository> logger, ILoggerFactory loggerFactory, IShortStringHelper shortStringHelper) : base(scopeAccessor, appCaches, logger) { _shortStringHelper = shortStringHelper; _userGroupWithUsersRepository = new UserGroupWithUsersRepository(this, scopeAccessor, appCaches, loggerFactory.CreateLogger<UserGroupWithUsersRepository>()); _permissionRepository = new PermissionRepository<IContent>(scopeAccessor, appCaches, loggerFactory.CreateLogger<PermissionRepository<IContent>>()); } public static string GetByAliasCacheKey(string alias) { return CacheKeys.UserGroupGetByAliasCacheKeyPrefix + alias; } public IUserGroup Get(string alias) { try { //need to do a simple query to get the id - put this cache var id = IsolatedCache.GetCacheItem<int>(GetByAliasCacheKey(alias), () => { var groupId = Database.ExecuteScalar<int?>("SELECT id FROM umbracoUserGroup WHERE userGroupAlias=@alias", new { alias }); if (groupId.HasValue == false) throw new InvalidOperationException("No group found with alias " + alias); return groupId.Value; }); //return from the normal method which will cache return Get(id); } catch (InvalidOperationException) { //if this is caught it's because we threw this in the caching method return null; } } public IEnumerable<IUserGroup> GetGroupsAssignedToSection(string sectionAlias) { //Here we're building up a query that looks like this, a sub query is required because the resulting structure // needs to still contain all of the section rows per user group. //SELECT * //FROM [umbracoUserGroup] //LEFT JOIN [umbracoUserGroup2App] //ON [umbracoUserGroup].[id] = [umbracoUserGroup2App].[user] //WHERE umbracoUserGroup.id IN (SELECT umbracoUserGroup.id // FROM [umbracoUserGroup] // LEFT JOIN [umbracoUserGroup2App] // ON [umbracoUserGroup].[id] = [umbracoUserGroup2App].[user] // WHERE umbracoUserGroup2App.app = 'content') var sql = GetBaseQuery(QueryType.Many); var innerSql = GetBaseQuery(QueryType.Ids); innerSql.Where("umbracoUserGroup2App.app = " + SqlSyntax.GetQuotedValue(sectionAlias)); sql.Where($"umbracoUserGroup.id IN ({innerSql.SQL})"); AppendGroupBy(sql); return Database.Fetch<UserGroupDto>(sql).Select(x => UserGroupFactory.BuildEntity(_shortStringHelper, x)); } public void AddOrUpdateGroupWithUsers(IUserGroup userGroup, int[] userIds) { _userGroupWithUsersRepository.Save(new UserGroupWithUsers(userGroup, userIds)); } /// <summary> /// Gets explicitly defined permissions for the group for specified entities /// </summary> /// <param name="groupIds"></param> /// <param name="entityIds">Array of entity Ids, if empty will return permissions for the group for all entities</param> public EntityPermissionCollection GetPermissions(int[] groupIds, params int[] entityIds) { return _permissionRepository.GetPermissionsForEntities(groupIds, entityIds); } /// <summary> /// Gets explicit and default permissions (if requested) permissions for the group for specified entities /// </summary> /// <param name="groups"></param> /// <param name="fallbackToDefaultPermissions">If true will include the group's default permissions if no permissions are explicitly assigned</param> /// <param name="nodeIds">Array of entity Ids, if empty will return permissions for the group for all entities</param> public EntityPermissionCollection GetPermissions(IReadOnlyUserGroup[] groups, bool fallbackToDefaultPermissions, params int[] nodeIds) { if (groups == null) throw new ArgumentNullException(nameof(groups)); var groupIds = groups.Select(x => x.Id).ToArray(); var explicitPermissions = GetPermissions(groupIds, nodeIds); var result = new EntityPermissionCollection(explicitPermissions); // If requested, and no permissions are assigned to a particular node, then we will fill in those permissions with the group's defaults if (fallbackToDefaultPermissions) { //if no node ids are passed in, then we need to determine the node ids for the explicit permissions set nodeIds = nodeIds.Length == 0 ? explicitPermissions.Select(x => x.EntityId).Distinct().ToArray() : nodeIds; //if there are still no nodeids we can just exit if (nodeIds.Length == 0) return result; foreach (var group in groups) { foreach (var nodeId in nodeIds) { // TODO: We could/should change the EntityPermissionsCollection into a KeyedCollection and they key could be // a struct of the nodeid + groupid so then we don't actually allocate this class just to check if it's not // going to be included in the result! var defaultPermission = new EntityPermission(group.Id, nodeId, group.Permissions.ToArray(), isDefaultPermissions: true); //Since this is a hashset, this will not add anything that already exists by group/node combination result.Add(defaultPermission); } } } return result; } /// <summary> /// Replaces the same permission set for a single group to any number of entities /// </summary> /// <param name="groupId">Id of group</param> /// <param name="permissions">Permissions as enumerable list of <see cref="char"/> If nothing is specified all permissions are removed.</param> /// <param name="entityIds">Specify the nodes to replace permissions for. </param> public void ReplaceGroupPermissions(int groupId, IEnumerable<char> permissions, params int[] entityIds) { _permissionRepository.ReplacePermissions(groupId, permissions, entityIds); } /// <summary> /// Assigns the same permission set for a single group to any number of entities /// </summary> /// <param name="groupId">Id of group</param> /// <param name="permission">Permissions as enumerable list of <see cref="char"/></param> /// <param name="entityIds">Specify the nodes to replace permissions for</param> public void AssignGroupPermission(int groupId, char permission, params int[] entityIds) { _permissionRepository.AssignPermission(groupId, permission, entityIds); } #region Overrides of RepositoryBase<int,IUserGroup> protected override IUserGroup PerformGet(int id) { var sql = GetBaseQuery(QueryType.Single); sql.Where(GetBaseWhereClause(), new { id = id }); AppendGroupBy(sql); sql.OrderBy<UserGroupDto>(x => x.Id); // required for references var dto = Database.FetchOneToMany<UserGroupDto>(x => x.UserGroup2AppDtos, sql).FirstOrDefault(); if (dto == null) return null; var userGroup = UserGroupFactory.BuildEntity(_shortStringHelper, dto); return userGroup; } protected override IEnumerable<IUserGroup> PerformGetAll(params int[] ids) { var sql = GetBaseQuery(QueryType.Many); if (ids.Any()) sql.WhereIn<UserGroupDto>(x => x.Id, ids); else sql.Where<UserGroupDto>(x => x.Id >= 0); AppendGroupBy(sql); sql.OrderBy<UserGroupDto>(x => x.Id); // required for references var dtos = Database.FetchOneToMany<UserGroupDto>(x => x.UserGroup2AppDtos, sql); return dtos.Select(x=>UserGroupFactory.BuildEntity(_shortStringHelper, x)); } protected override IEnumerable<IUserGroup> PerformGetByQuery(IQuery<IUserGroup> query) { var sqlClause = GetBaseQuery(QueryType.Many); var translator = new SqlTranslator<IUserGroup>(sqlClause, query); var sql = translator.Translate(); AppendGroupBy(sql); sql.OrderBy<UserGroupDto>(x => x.Id); // required for references var dtos = Database.FetchOneToMany<UserGroupDto>(x => x.UserGroup2AppDtos, sql); return dtos.Select(x => UserGroupFactory.BuildEntity(_shortStringHelper, x)); } #endregion #region Overrides of EntityRepositoryBase<int,IUserGroup> protected Sql<ISqlContext> GetBaseQuery(QueryType type) { var sql = Sql(); var addFrom = false; switch (type) { case QueryType.Count: sql .SelectCount() .From<UserGroupDto>(); break; case QueryType.Ids: sql .Select<UserGroupDto>(x => x.Id); addFrom = true; break; case QueryType.Single: case QueryType.Many: sql .Select<UserGroupDto>(r => r.Select(x => x.UserGroup2AppDtos), s => s.Append($", COUNT({sql.Columns<User2UserGroupDto>(x => x.UserId)}) AS {SqlSyntax.GetQuotedColumnName("UserCount")}")); addFrom = true; break; default: throw new NotSupportedException(type.ToString()); } if (addFrom) sql .From<UserGroupDto>() .LeftJoin<UserGroup2AppDto>() .On<UserGroupDto, UserGroup2AppDto>(left => left.Id, right => right.UserGroupId) .LeftJoin<User2UserGroupDto>() .On<User2UserGroupDto, UserGroupDto>(left => left.UserGroupId, right => right.Id); return sql; } protected override Sql<ISqlContext> GetBaseQuery(bool isCount) { return GetBaseQuery(isCount ? QueryType.Count : QueryType.Many); } private static void AppendGroupBy(Sql<ISqlContext> sql) { sql .GroupBy<UserGroupDto>(x => x.CreateDate, x => x.Icon, x => x.Id, x => x.StartContentId, x => x.StartMediaId, x => x.UpdateDate, x => x.Alias, x => x.DefaultPermissions, x => x.Name) .AndBy<UserGroup2AppDto>(x => x.AppAlias, x => x.UserGroupId); } protected override string GetBaseWhereClause() { return $"{Constants.DatabaseSchema.Tables.UserGroup}.id = @id"; } protected override IEnumerable<string> GetDeleteClauses() { var list = new List<string> { "DELETE FROM umbracoUser2UserGroup WHERE userGroupId = @id", "DELETE FROM umbracoUserGroup2App WHERE userGroupId = @id", "DELETE FROM umbracoUserGroup2Node WHERE userGroupId = @id", "DELETE FROM umbracoUserGroup2NodePermission WHERE userGroupId = @id", "DELETE FROM umbracoUserGroup WHERE id = @id" }; return list; } protected override void PersistNewItem(IUserGroup entity) { entity.AddingEntity(); var userGroupDto = UserGroupFactory.BuildDto(entity); var id = Convert.ToInt32(Database.Insert(userGroupDto)); entity.Id = id; PersistAllowedSections(entity); entity.ResetDirtyProperties(); } protected override void PersistUpdatedItem(IUserGroup entity) { entity.UpdatingEntity(); var userGroupDto = UserGroupFactory.BuildDto(entity); Database.Update(userGroupDto); PersistAllowedSections(entity); entity.ResetDirtyProperties(); } private void PersistAllowedSections(IUserGroup entity) { var userGroup = entity; // First delete all Database.Delete<UserGroup2AppDto>("WHERE UserGroupId = @UserGroupId", new { UserGroupId = userGroup.Id }); // Then re-add any associated with the group foreach (var app in userGroup.AllowedSections) { var dto = new UserGroup2AppDto { UserGroupId = userGroup.Id, AppAlias = app }; Database.Insert(dto); } } #endregion /// <summary> /// used to persist a user group with associated users at once /// </summary> private class UserGroupWithUsers : EntityBase { public UserGroupWithUsers(IUserGroup userGroup, int[] userIds) { UserGroup = userGroup; UserIds = userIds; } public override bool HasIdentity => UserGroup.HasIdentity; public IUserGroup UserGroup { get; } public int[] UserIds { get; } } /// <summary> /// used to persist a user group with associated users at once /// </summary> private class UserGroupWithUsersRepository : EntityRepositoryBase<int, UserGroupWithUsers> { private readonly UserGroupRepository _userGroupRepo; public UserGroupWithUsersRepository(UserGroupRepository userGroupRepo, IScopeAccessor scopeAccessor, AppCaches cache, ILogger<UserGroupWithUsersRepository> logger) : base(scopeAccessor, cache, logger) { _userGroupRepo = userGroupRepo; } #region Not implemented (don't need to for the purposes of this repo) protected override UserGroupWithUsers PerformGet(int id) { throw new InvalidOperationException("This method won't be implemented."); } protected override IEnumerable<UserGroupWithUsers> PerformGetAll(params int[] ids) { throw new InvalidOperationException("This method won't be implemented."); } protected override IEnumerable<UserGroupWithUsers> PerformGetByQuery(IQuery<UserGroupWithUsers> query) { throw new InvalidOperationException("This method won't be implemented."); } protected override Sql<ISqlContext> GetBaseQuery(bool isCount) { throw new InvalidOperationException("This method won't be implemented."); } protected override string GetBaseWhereClause() { throw new InvalidOperationException("This method won't be implemented."); } protected override IEnumerable<string> GetDeleteClauses() { throw new InvalidOperationException("This method won't be implemented."); } #endregion protected override void PersistNewItem(UserGroupWithUsers entity) { //save the user group _userGroupRepo.PersistNewItem(entity.UserGroup); if (entity.UserIds == null) return; //now the user association RefreshUsersInGroup(entity.UserGroup.Id, entity.UserIds); } protected override void PersistUpdatedItem(UserGroupWithUsers entity) { //save the user group _userGroupRepo.PersistUpdatedItem(entity.UserGroup); if (entity.UserIds == null) return; //now the user association RefreshUsersInGroup(entity.UserGroup.Id, entity.UserIds); } /// <summary> /// Adds a set of users to a group, first removing any that exist /// </summary> /// <param name="groupId">Id of group</param> /// <param name="userIds">Ids of users</param> private void RefreshUsersInGroup(int groupId, int[] userIds) { RemoveAllUsersFromGroup(groupId); AddUsersToGroup(groupId, userIds); } /// <summary> /// Removes all users from a group /// </summary> /// <param name="groupId">Id of group</param> private void RemoveAllUsersFromGroup(int groupId) { Database.Delete<User2UserGroupDto>("WHERE userGroupId = @groupId", new { groupId }); } /// <summary> /// Adds a set of users to a group /// </summary> /// <param name="groupId">Id of group</param> /// <param name="userIds">Ids of users</param> private void AddUsersToGroup(int groupId, int[] userIds) { foreach (var userId in userIds) { var dto = new User2UserGroupDto { UserGroupId = groupId, UserId = userId, }; Database.Insert(dto); } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing; using System.Linq; using System.Media; using System.Windows.Forms; using L10NSharp.UI; using SIL.Code; using SIL.Windows.Forms.Widgets.BetterGrid; namespace SIL.Windows.Forms.ClearShare.WinFormsUI { /// ---------------------------------------------------------------------------------------- public partial class ContributorsListControl : UserControl { public delegate KeyValuePair<string, string> ValidatingContributorHandler( ContributorsListControl sender, Contribution contribution, CancelEventArgs e); public event ValidatingContributorHandler ValidatingContributor; public delegate void ColumnHeaderMouseClickHandler(object sender, DataGridViewCellMouseEventArgs e); public event ColumnHeaderMouseClickHandler ColumnHeaderMouseClick; private FadingMessageWindow _msgWindow; private readonly ContributorsListControlViewModel _model; /// ------------------------------------------------------------------------------------ public ContributorsListControl() { InitializeComponent(); } /// ------------------------------------------------------------------------------------ public ContributorsListControl(ContributorsListControlViewModel model) : this() { _model = model; _model.NewContributionListAvailable += HandleNewContributionListAvailable; Initialize(); } /// ------------------------------------------------------------------------------------ private void Initialize() { _grid.Font = SystemFonts.MenuFont; // TODO: Localize column headings DataGridViewColumn col = BetterGrid.CreateTextBoxColumn("name", "Name"); col.Width = 150; _grid.Columns.Add(col); col = BetterGrid.CreateDropDownListComboBoxColumn("role", _model.OlacRoles.Select(r => r.ToString())); col.HeaderText = @"Role"; col.Width = 120; _grid.Columns.Add(col); _grid.Columns.Add(BetterGrid.CreateCalendarControlColumn("date", "Date", null, CalendarCell.UserAction.CellMouseClick)); col = BetterGrid.CreateTextBoxColumn("comments", "Comments"); col.Width = 200; _grid.Columns.Add(col); _grid.AddRemoveRowColumn(null, null, null /* TODO: Enhance BetterGrid to be able to show tool tips in non-virtual mode */, rowIndex => DeleteRow(rowIndex)); _grid.AllowUserToAddRows = true; _grid.AllowUserToDeleteRows = true; _grid.EditingControlShowing += HandleEditingControlShowing; _grid.RowValidating += HandleGridRowValidating; _grid.MouseClick += HandleGridMouseClick; _grid.Leave += HandleGridLeave; _grid.Enter += delegate { _grid.SelectionMode = DataGridViewSelectionMode.CellSelect; }; _grid.RowValidated += HandleGridRowValidated; _grid.RowsRemoved += HandleGridRowsRemoved; _grid.ColumnHeaderMouseClick += _grid_ColumnHeaderMouseClick; if (_model.ContributorsGridSettings != null) _model.ContributorsGridSettings.InitializeGrid(_grid); } // SP-874: Not able to open L10NSharp with Alt-Shift-click void _grid_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (ColumnHeaderMouseClick != null) ColumnHeaderMouseClick(sender, e); } /// ------------------------------------------------------------------------------------ /// <summary> /// Gets a value indicating whether or not the extender is currently in design mode. /// I have had some problems with the base class' DesignMode property being true /// when in design mode. I'm not sure why, but adding a couple more checks fixes the /// problem. /// </summary> /// ------------------------------------------------------------------------------------ private new bool DesignMode { get { return (base.DesignMode || GetService(typeof(IDesignerHost)) != null) || (LicenseManager.UsageMode == LicenseUsageMode.Designtime); } } /// ------------------------------------------------------------------------------------ public bool InEditMode { get { return _grid.IsCurrentRowDirty; } } /// ------------------------------------------------------------------------------------ public bool InNewContributionRow { get { return (_grid.CurrentCellAddress.Y == _grid.NewRowIndex); } } /// ------------------------------------------------------------------------------------ public Contribution GetCurrentContribution() { return GetContributionFromRow(_grid.CurrentCellAddress.Y); } /// ------------------------------------------------------------------------------------ protected override void OnHandleDestroyed(EventArgs e) { if (!DesignMode) _model.ContributorsGridSettings = GridSettings.Create(_grid); base.OnHandleDestroyed(e); } /// ------------------------------------------------------------------------------------ void HandleNewContributionListAvailable(object sender, EventArgs e) { Guard.AgainstNull(_model.Contributions, "Contributions"); _grid.RowValidated -= HandleGridRowValidated; _grid.RowsRemoved -= HandleGridRowsRemoved; _grid.Rows.Clear(); foreach (var contribution in _model.Contributions) _grid.Rows.Add(contribution.ContributorName, contribution.Role.Name, contribution.Date, contribution.Comments); _grid.CurrentCell = _grid[0, 0]; _grid.IsDirty = false; _grid.RowValidated += HandleGridRowValidated; _grid.RowsRemoved += HandleGridRowsRemoved; } /// ------------------------------------------------------------------------------------ void HandleGridMouseClick(object sender, MouseEventArgs e) { var hi = _grid.HitTest(e.X, e.Y); // Did the user click on a row heading? if (e.Button != MouseButtons.Left || hi.ColumnIndex >= 0 || hi.RowIndex < 0 || hi.RowIndex >= _grid.RowCount) { return; } // At this point we know the user clicked on a row heading. Now we // need to make sure the row they're leaving is in a valid state. if (ValidatingContributor != null && _grid.CurrentCellAddress.Y >= 0 && _grid.CurrentCellAddress.Y < _grid.RowCount - 1) { if (_grid.CurrentCellAddress.Y == _model.Contributions.Count()) return; var contribution = _model.Contributions.ElementAt(_grid.CurrentCellAddress.Y); if (!GetIsValidContribution(contribution)) { SystemSounds.Beep.Play(); return; } } // Make the first cell current in the row the user clicked. _grid.CurrentCell = _grid[0, hi.RowIndex]; } /// ------------------------------------------------------------------------------------ private bool GetIsValidContribution(Contribution contribution) { if (ValidatingContributor == null) return true; var args = new CancelEventArgs(false); ValidatingContributor(this, contribution, args); return !args.Cancel; } /// ------------------------------------------------------------------------------------ void HandleGridLeave(object sender, EventArgs e) { _grid.SelectionMode = DataGridViewSelectionMode.FullRowSelect; if (_grid.CurrentRow != null) _grid.CurrentRow.Selected = true; } /// ------------------------------------------------------------------------------------ private void HandleGridRowValidating(object sender, DataGridViewCellCancelEventArgs e) { if (e.RowIndex == _grid.RowCount - 1 || !_grid.IsCurrentRowDirty) return; _grid.IsDirty = true; var contribution = GetContributionFromRow(e.RowIndex); if (ValidatingContributor == null) return; var args = new CancelEventArgs(e.Cancel); var kvp = ValidatingContributor(this, contribution, args); e.Cancel = args.Cancel; if (!string.IsNullOrEmpty(kvp.Key)) { if (_msgWindow == null) _msgWindow = new FadingMessageWindow(); var dataGridViewColumn = _grid.Columns[kvp.Key]; if (dataGridViewColumn != null) { int col = dataGridViewColumn.Index; var rc = _grid.GetCellDisplayRectangle(col, e.RowIndex, true); var pt = new Point(rc.X + (rc.Width / 2), rc.Y + 4); _msgWindow.Show(kvp.Value, _grid.PointToScreen(pt)); // Invoking here because of "reentrant call to the SetCurrentCellAddressCore" exception. // Setting the CurrentCell can trigger validation again. BeginInvoke((Action)(() =>_grid.CurrentCell = _grid[col, e.RowIndex])); } } } /// ------------------------------------------------------------------------------------ void HandleGridRowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e) { SaveContributions(); } /// ------------------------------------------------------------------------------------ void HandleGridRowValidated(object sender, DataGridViewCellEventArgs e) { SaveContributions(); } /// ------------------------------------------------------------------------------------ private void SaveContributions() { if (_grid.IsDirty) { _model.SaveContributionList(new ContributionCollection(GetContributionCollectionFromGrid())); _grid.IsDirty = false; } } /// ------------------------------------------------------------------------------------ private IEnumerable<Contribution> GetContributionCollectionFromGrid() { return _grid.GetRows().Where(r => r.Index != _grid.NewRowIndex).Select(row => GetContributionFromRow(row.Index)).Where(c => c!= null && GetIsValidContribution(c)); } /// ------------------------------------------------------------------------------------ private Contribution GetContributionFromRow(int rowIndex) { var row = _grid.Rows[rowIndex]; var contribution = new Contribution { ContributorName = row.Cells["name"].Value as string, Role = _model.OlacRoles.FirstOrDefault(o => o.Name == row.Cells["role"].Value as string), Comments = row.Cells["comments"].Value as string }; if (row.Cells["date"].Value != null) contribution.Date = (DateTime)row.Cells["date"].Value; return contribution; } /// ------------------------------------------------------------------------------------ protected void HandleEditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { if (_grid.CurrentCellAddress.X == 0) { var txtBox = e.Control as TextBox; _grid.Tag = txtBox; _grid.CellEndEdit += HandleGridCellEndEdit; if (txtBox == null) return; txtBox.KeyPress += HandleCellEditBoxKeyPress; txtBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend; txtBox.AutoCompleteSource = AutoCompleteSource.CustomSource; txtBox.AutoCompleteCustomSource = _model.GetAutoCompleteNames(); } else if (_grid.CurrentCellAddress.X == 1) { var cboBox = e.Control as ComboBox; _grid.Tag = cboBox; if (cboBox != null) cboBox.SelectedIndexChanged += HandleRoleValueChanged; _grid.CellEndEdit += HandleGridCellEndEdit; } } /// ------------------------------------------------------------------------------------ void HandleRoleValueChanged(object sender, EventArgs e) { if (_msgWindow != null) _msgWindow.Close(); } /// ------------------------------------------------------------------------------------ void HandleGridCellEndEdit(object sender, DataGridViewCellEventArgs e) { var ctrl = _grid.Tag as Control; // SP-793: Text should match case of autocomplete list if (e.ColumnIndex == 0) { var txtBox = ctrl as TextBox; if (txtBox != null) { // is the current text an exact match for the autocomplete list? var list = txtBox.AutoCompleteCustomSource.Cast<object>().ToList(); var found = list.FirstOrDefault(item => String.Equals(item.ToString(), txtBox.Text, StringComparison.CurrentCulture)); if (found == null) { // is the current text a match except for case for the autocomplete list? found = list.FirstOrDefault(item => String.Equals(item.ToString(), txtBox.Text, StringComparison.CurrentCultureIgnoreCase)); if (found != null) { txtBox.Text = found.ToString(); _grid.CurrentCell.Value = txtBox.Text; } } } } if (ctrl is TextBox) ctrl.KeyPress -= HandleCellEditBoxKeyPress; else if (ctrl is ComboBox) ((ComboBox)ctrl).SelectedIndexChanged -= HandleRoleValueChanged; _grid.CellEndEdit -= HandleGridCellEndEdit; _grid.Tag = null; } /// ------------------------------------------------------------------------------------ private void HandleCellEditBoxKeyPress(object sender, KeyPressEventArgs e) { // Prevent characters that are invalid as xml tags. There's probably more, // but this will do for now. if ("<>{}()[]/'\"\\.,;:?|!@#$%^&*=+`~".IndexOf(e.KeyChar) >= 0) { e.KeyChar = (char)0; e.Handled = true; SystemSounds.Beep.Play(); } } /// ------------------------------------------------------------------------------------ private void DeleteRow(int rowIndex) { if (_grid.IsCurrentCellInEditMode) _grid.EndEdit(DataGridViewDataErrorContexts.RowDeletion); if (_msgWindow != null) _msgWindow.Close(); _grid.Rows.RemoveAt(rowIndex); _grid.CurrentCell = _grid[0, _grid.CurrentCellAddress.Y]; } /// <remarks>SP-874: Localize column headers</remarks> public void SetColumnHeaderText(int columnIndex, string headerText) { _grid.Columns[columnIndex].HeaderText = headerText; } /// <remarks>SP-874: Localize column headers</remarks> [CLSCompliant (false)] public void SetLocalizationExtender(L10NSharpExtender extender) { extender.SetLocalizingId(_grid, "ContributorsEditorGrid"); } /// <remarks>We need to be able to adjust the visual properties to match the hosting program</remarks> public BetterGrid Grid { get { return _grid; } } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // Copyright (c) 2004 Mainsoft Co. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using Xunit; using System.ComponentModel; using System.Collections; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Tests; using System.Xml; using System.Xml.Schema; using System.IO; using System.Globalization; namespace System.Data.Tests { public class DataSetTypedDataSetTest { private string _eventStatus = string.Empty; [Fact] public void TypedDataSet() { int i = 0; //check dataset constructor myTypedDataSet ds = null; DataSet unTypedDs = new DataSet(); ds = new myTypedDataSet(); Assert.False(ds == null); Assert.Equal(typeof(myTypedDataSet), ds.GetType()); // fill dataset ds.ReadXml(new StringReader( @"<?xml version=""1.0"" standalone=""yes""?> <myTypedDataSet xmlns=""http://www.tempuri.org/myTypedDataSet.xsd""> <Order_x0020_Details> <OrderID>10250</OrderID> <ProductID>41</ProductID> <UnitPrice>7.7000</UnitPrice> <Quantity>10</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10250</OrderID> <ProductID>51</ProductID> <UnitPrice>42.4000</UnitPrice> <Quantity>35</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10250</OrderID> <ProductID>65</ProductID> <UnitPrice>16.8000</UnitPrice> <Quantity>15</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10251</OrderID> <ProductID>22</ProductID> <UnitPrice>16.8000</UnitPrice> <Quantity>6</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10251</OrderID> <ProductID>57</ProductID> <UnitPrice>15.6000</UnitPrice> <Quantity>15</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10251</OrderID> <ProductID>65</ProductID> <UnitPrice>16.8000</UnitPrice> <Quantity>20</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10252</OrderID> <ProductID>20</ProductID> <UnitPrice>64.8000</UnitPrice> <Quantity>40</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10252</OrderID> <ProductID>33</ProductID> <UnitPrice>2.0000</UnitPrice> <Quantity>25</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10252</OrderID> <ProductID>60</ProductID> <UnitPrice>27.2000</UnitPrice> <Quantity>40</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10253</OrderID> <ProductID>31</ProductID> <UnitPrice>10.0000</UnitPrice> <Quantity>20</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10253</OrderID> <ProductID>39</ProductID> <UnitPrice>14.4000</UnitPrice> <Quantity>42</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10253</OrderID> <ProductID>49</ProductID> <UnitPrice>16.0000</UnitPrice> <Quantity>40</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10254</OrderID> <ProductID>24</ProductID> <UnitPrice>3.6000</UnitPrice> <Quantity>15</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10254</OrderID> <ProductID>55</ProductID> <UnitPrice>19.2000</UnitPrice> <Quantity>21</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10254</OrderID> <ProductID>74</ProductID> <UnitPrice>8.0000</UnitPrice> <Quantity>21</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10255</OrderID> <ProductID>2</ProductID> <UnitPrice>15.2000</UnitPrice> <Quantity>20</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10255</OrderID> <ProductID>16</ProductID> <UnitPrice>13.9000</UnitPrice> <Quantity>35</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10255</OrderID> <ProductID>36</ProductID> <UnitPrice>15.2000</UnitPrice> <Quantity>25</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10255</OrderID> <ProductID>59</ProductID> <UnitPrice>44.0000</UnitPrice> <Quantity>30</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10256</OrderID> <ProductID>53</ProductID> <UnitPrice>26.2000</UnitPrice> <Quantity>15</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10256</OrderID> <ProductID>77</ProductID> <UnitPrice>10.4000</UnitPrice> <Quantity>12</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10257</OrderID> <ProductID>27</ProductID> <UnitPrice>35.1000</UnitPrice> <Quantity>25</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10257</OrderID> <ProductID>39</ProductID> <UnitPrice>14.4000</UnitPrice> <Quantity>6</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10257</OrderID> <ProductID>77</ProductID> <UnitPrice>10.4000</UnitPrice> <Quantity>15</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10258</OrderID> <ProductID>2</ProductID> <UnitPrice>15.2000</UnitPrice> <Quantity>50</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10258</OrderID> <ProductID>5</ProductID> <UnitPrice>17.0000</UnitPrice> <Quantity>65</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10258</OrderID> <ProductID>32</ProductID> <UnitPrice>25.6000</UnitPrice> <Quantity>6</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10259</OrderID> <ProductID>21</ProductID> <UnitPrice>8.0000</UnitPrice> <Quantity>10</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10259</OrderID> <ProductID>37</ProductID> <UnitPrice>20.8000</UnitPrice> <Quantity>1</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10260</OrderID> <ProductID>41</ProductID> <UnitPrice>7.7000</UnitPrice> <Quantity>16</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10260</OrderID> <ProductID>57</ProductID> <UnitPrice>15.6000</UnitPrice> <Quantity>50</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10260</OrderID> <ProductID>62</ProductID> <UnitPrice>39.4000</UnitPrice> <Quantity>15</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10260</OrderID> <ProductID>70</ProductID> <UnitPrice>12.0000</UnitPrice> <Quantity>21</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10261</OrderID> <ProductID>21</ProductID> <UnitPrice>8.0000</UnitPrice> <Quantity>20</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10261</OrderID> <ProductID>35</ProductID> <UnitPrice>14.4000</UnitPrice> <Quantity>20</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10262</OrderID> <ProductID>5</ProductID> <UnitPrice>17.0000</UnitPrice> <Quantity>12</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10262</OrderID> <ProductID>7</ProductID> <UnitPrice>24.0000</UnitPrice> <Quantity>15</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10262</OrderID> <ProductID>56</ProductID> <UnitPrice>30.4000</UnitPrice> <Quantity>2</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10263</OrderID> <ProductID>16</ProductID> <UnitPrice>13.9000</UnitPrice> <Quantity>60</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10263</OrderID> <ProductID>24</ProductID> <UnitPrice>3.6000</UnitPrice> <Quantity>28</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10263</OrderID> <ProductID>30</ProductID> <UnitPrice>20.7000</UnitPrice> <Quantity>60</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10263</OrderID> <ProductID>74</ProductID> <UnitPrice>8.0000</UnitPrice> <Quantity>36</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10264</OrderID> <ProductID>2</ProductID> <UnitPrice>15.2000</UnitPrice> <Quantity>35</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10264</OrderID> <ProductID>41</ProductID> <UnitPrice>7.7000</UnitPrice> <Quantity>25</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10265</OrderID> <ProductID>17</ProductID> <UnitPrice>31.2000</UnitPrice> <Quantity>30</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10265</OrderID> <ProductID>70</ProductID> <UnitPrice>12.0000</UnitPrice> <Quantity>20</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10266</OrderID> <ProductID>12</ProductID> <UnitPrice>30.4000</UnitPrice> <Quantity>12</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10267</OrderID> <ProductID>40</ProductID> <UnitPrice>14.7000</UnitPrice> <Quantity>50</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10267</OrderID> <ProductID>59</ProductID> <UnitPrice>44.0000</UnitPrice> <Quantity>70</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10267</OrderID> <ProductID>76</ProductID> <UnitPrice>14.4000</UnitPrice> <Quantity>15</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10268</OrderID> <ProductID>29</ProductID> <UnitPrice>99.0000</UnitPrice> <Quantity>10</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10268</OrderID> <ProductID>72</ProductID> <UnitPrice>27.8000</UnitPrice> <Quantity>4</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10269</OrderID> <ProductID>33</ProductID> <UnitPrice>2.0000</UnitPrice> <Quantity>60</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10269</OrderID> <ProductID>72</ProductID> <UnitPrice>27.8000</UnitPrice> <Quantity>20</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10270</OrderID> <ProductID>36</ProductID> <UnitPrice>15.2000</UnitPrice> <Quantity>30</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10270</OrderID> <ProductID>43</ProductID> <UnitPrice>36.8000</UnitPrice> <Quantity>25</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Orders> <OrderID>10250</OrderID> <CustomerID>HANAR</CustomerID> <EmployeeID>4</EmployeeID> <OrderDate>1996-07-08T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-05T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-12T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10251</OrderID> <CustomerID>VICTE</CustomerID> <EmployeeID>3</EmployeeID> <OrderDate>1996-07-08T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-05T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-15T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10252</OrderID> <CustomerID>SUPRD</CustomerID> <EmployeeID>4</EmployeeID> <OrderDate>1996-07-09T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-06T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-11T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10253</OrderID> <CustomerID>HANAR</CustomerID> <EmployeeID>3</EmployeeID> <OrderDate>1996-07-10T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-07-24T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-16T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10254</OrderID> <CustomerID>CHOPS</CustomerID> <EmployeeID>5</EmployeeID> <OrderDate>1996-07-11T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-08T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-23T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10255</OrderID> <CustomerID>RICSU</CustomerID> <EmployeeID>9</EmployeeID> <OrderDate>1996-07-12T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-09T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-15T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10256</OrderID> <CustomerID>WELLI</CustomerID> <EmployeeID>3</EmployeeID> <OrderDate>1996-07-15T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-12T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-17T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10257</OrderID> <CustomerID>HILAA</CustomerID> <EmployeeID>4</EmployeeID> <OrderDate>1996-07-16T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-13T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-22T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10258</OrderID> <CustomerID>ERNSH</CustomerID> <EmployeeID>1</EmployeeID> <OrderDate>1996-07-17T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-14T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-23T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10259</OrderID> <CustomerID>CENTC</CustomerID> <EmployeeID>4</EmployeeID> <OrderDate>1996-07-18T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-15T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-25T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10260</OrderID> <CustomerID>OTTIK</CustomerID> <EmployeeID>4</EmployeeID> <OrderDate>1996-07-19T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-16T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-29T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10261</OrderID> <CustomerID>QUEDE</CustomerID> <EmployeeID>4</EmployeeID> <OrderDate>1996-07-19T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-16T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-30T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10262</OrderID> <CustomerID>RATTC</CustomerID> <EmployeeID>8</EmployeeID> <OrderDate>1996-07-22T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-19T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-25T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10263</OrderID> <CustomerID>ERNSH</CustomerID> <EmployeeID>9</EmployeeID> <OrderDate>1996-07-23T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-20T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-31T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10264</OrderID> <CustomerID>FOLKO</CustomerID> <EmployeeID>6</EmployeeID> <OrderDate>1996-07-24T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-21T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-08-23T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10265</OrderID> <CustomerID>BLONP</CustomerID> <EmployeeID>2</EmployeeID> <OrderDate>1996-07-25T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-22T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-08-12T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10266</OrderID> <CustomerID>WARTH</CustomerID> <EmployeeID>3</EmployeeID> <OrderDate>1996-07-26T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-09-06T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-31T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10267</OrderID> <CustomerID>FRANK</CustomerID> <EmployeeID>4</EmployeeID> <OrderDate>1996-07-29T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-26T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-08-06T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10268</OrderID> <CustomerID>GROSR</CustomerID> <EmployeeID>8</EmployeeID> <OrderDate>1996-07-30T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-27T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-08-02T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10269</OrderID> <CustomerID>WHITC</CustomerID> <EmployeeID>5</EmployeeID> <OrderDate>1996-07-31T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-14T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-08-09T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10270</OrderID> <CustomerID>WARTH</CustomerID> <EmployeeID>1</EmployeeID> <OrderDate>1996-08-01T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-29T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-08-02T00:00:00.0000000+03:00</ShippedDate> </Orders> </myTypedDataSet>")); // check DataSet named property "Orders" myTypedDataSet.OrdersDataTable tblOrders = null; tblOrders = ds.Orders; Assert.Equal(ds.Tables["Orders"], tblOrders); //check DataSet named property Orders - by index"); tblOrders = ds.Orders; Assert.Equal(ds.Tables[1], tblOrders); //add new row AddTableNameRow, check row count"); i = tblOrders.Rows.Count; tblOrders.AddOrdersRow("SAVEA", 1, new DateTime(1998, 05, 01, 00, 00, 00, 000) , new DateTime(1998, 05, 29, 00, 00, 00, 000) , new DateTime(1998, 05, 04, 00, 00, 00, 000), 1, 30.0900m , "Save-a-lot Markets", "187 Suffolk Ln.", "Boise", "ID", "83720", "USA"); Assert.Equal(i + 1, tblOrders.Rows.Count); //check the new row AutoIncrement field - AddTableNameRow i = (int)tblOrders.Rows[tblOrders.Rows.Count - 2][0]; Assert.Equal(i + 1, (int)tblOrders.Rows[tblOrders.Rows.Count - 1][0]); //Create New Row using NewTableNameRow, check row != null myTypedDataSet.OrdersRow drOrders = null; drOrders = tblOrders.NewOrdersRow(); Assert.False(drOrders == null); //Create New Row using NewTableNameRow, check row state Assert.Equal(DataRowState.Detached, drOrders.RowState); //add new row NewTableNameRow, check row count //drOrders.OrderID = DBNull.Value; drOrders.CustomerID = "GREAL"; drOrders.EmployeeID = 4; drOrders.OrderDate = new DateTime(1998, 04, 30, 00, 00, 00, 000); drOrders.RequiredDate = new DateTime(1998, 06, 11, 00, 00, 00, 000); drOrders["ShippedDate"] = DBNull.Value; drOrders.ShipVia = 3; drOrders.Freight = 14.0100m; drOrders.ShipName = "Great Lakes"; drOrders.ShipAddress = "Food Market"; drOrders.ShipCity = "Baker Blvd."; drOrders.ShipRegion = "Eugene"; drOrders.ShipPostalCode = "OR 97403"; drOrders.ShipCountry = "USA"; i = tblOrders.Rows.Count; tblOrders.AddOrdersRow(drOrders); Assert.Equal(i + 1, tblOrders.Rows.Count); //check StrongTypingException Assert.Throws<StrongTypingException>(() => { DateTime d = drOrders.ShippedDate; //drOrders.ShippedDate = null, will raise exception }); //check the new row AutoIncrement field - NewTableNameRow i = (int)tblOrders.Rows[tblOrders.Rows.Count - 2][0]; Assert.Equal(i + 1, (int)tblOrders.Rows[tblOrders.Rows.Count - 1][0]); // convenience IsNull functions // only if it can be null Assert.False(drOrders.IsShipAddressNull()); drOrders.SetShipAddressNull(); Assert.True(drOrders.IsShipAddressNull()); // Table exposes a public property Count == table.Rows.Count Assert.Equal(tblOrders.Count, tblOrders.Rows.Count); // find function myTypedDataSet.OrdersRow dr = tblOrders[0]; Assert.Equal(tblOrders.FindByOrderID(dr.OrderID), dr); //Remove row and check row count i = tblOrders.Count; myTypedDataSet.OrdersRow drr = tblOrders[0]; tblOrders.RemoveOrdersRow(drr); Assert.Equal(i - 1, tblOrders.Count); //first column is readonly Assert.True(tblOrders.OrderIDColumn.ReadOnly); //read only exception Assert.Throws<ReadOnlyException>(() => { tblOrders[0].OrderID = 99; }); tblOrders.AcceptChanges(); //Check table events // add event handlers ds.Orders.OrdersRowChanging += new myTypedDataSet.OrdersRowChangeEventHandler(T_Changing); ds.Orders.OrdersRowChanged += new myTypedDataSet.OrdersRowChangeEventHandler(T_Changed); ds.Orders.OrdersRowDeleting += new myTypedDataSet.OrdersRowChangeEventHandler(T_Deleting); ds.Orders.OrdersRowDeleted += new myTypedDataSet.OrdersRowChangeEventHandler(T_Deleted); //RowChange event order tblOrders[0].ShipCity = "Tel Aviv"; Assert.Equal("AB", _eventStatus); _eventStatus = string.Empty; //RowDelet event order tblOrders[0].Delete(); Assert.Equal("AB", _eventStatus); //expose DataColumn as property Assert.Equal(ds.Orders.OrderIDColumn, ds.Tables["Orders"].Columns["OrderID"]); //Accept changes for all deleted and changedd rows. ds.AcceptChanges(); //check relations //ChildTableRow has property ParentTableRow myTypedDataSet.OrdersRow dr1 = ds.Order_Details[0].OrdersRow; DataRow dr2 = ds.Order_Details[0].GetParentRow(ds.Relations[0]); Assert.Equal(dr1, dr2); //ParentTableRow has property ChildTableRow myTypedDataSet.Order_DetailsRow[] drArr1 = ds.Orders[0].GetOrder_DetailsRows(); DataRow[] drArr2 = ds.Orders[0].GetChildRows(ds.Relations[0]); Assert.Equal(drArr1, drArr2); //now test serialization of a typed dataset generated by microsoft's xsd.exe DataSet1 ds1 = new DataSet1(); ds1.DataTable1.AddDataTable1Row("test"); ds1.DataTable1.AddDataTable1Row("test2"); DataSet1 ds1load = BinaryFormatterHelpers.Clone(ds1); Assert.True(ds1load.Tables.Contains("DataTable1")); Assert.Equal("DataTable1DataTable", ds1load.Tables["DataTable1"].GetType().Name); Assert.Equal(2, ds1load.DataTable1.Rows.Count); Assert.Equal("DataTable1Row", ds1load.DataTable1[0].GetType().Name); if (ds1load.DataTable1[0].Column1 == "test") { Assert.Equal("test2", ds1load.DataTable1[1].Column1); } else if (ds1load.DataTable1[0].Column1 == "test2") { Assert.Equal("test", ds1load.DataTable1[1].Column1); } else { Assert.False(true); } //now test when the mode is exclude schema ds1.SchemaSerializationMode = global::System.Data.SchemaSerializationMode.ExcludeSchema; ds1load = BinaryFormatterHelpers.Clone(ds1); Assert.True(ds1load.Tables.Contains("DataTable1")); Assert.Equal("DataTable1DataTable", ds1load.Tables["DataTable1"].GetType().Name); Assert.Equal(2, ds1load.DataTable1.Rows.Count); Assert.Equal("DataTable1Row", ds1load.DataTable1[0].GetType().Name); if (ds1load.DataTable1[0].Column1 == "test") { Assert.Equal("test2", ds1load.DataTable1[1].Column1); } else if (ds1load.DataTable1[0].Column1 == "test2") { Assert.Equal("test", ds1load.DataTable1[1].Column1); } else { Assert.False(true); } } protected void T_Changing(object sender, myTypedDataSet.OrdersRowChangeEvent e) { _eventStatus += "A"; } protected void T_Changed(object sender, myTypedDataSet.OrdersRowChangeEvent e) { _eventStatus += "B"; } protected void T_Deleting(object sender, myTypedDataSet.OrdersRowChangeEvent e) { _eventStatus += "A"; } protected void T_Deleted(object sender, myTypedDataSet.OrdersRowChangeEvent e) { _eventStatus += "B"; } [Serializable] [DesignerCategoryAttribute("code")] [ToolboxItem(true)] public class myTypedDataSet : DataSet { private Order_DetailsDataTable _tableOrder_Details; private OrdersDataTable _tableOrders; private DataRelation _relationOrdersOrder_x0020_Details; public myTypedDataSet() { InitClass(); CollectionChangeEventHandler schemaChangedHandler = new CollectionChangeEventHandler(SchemaChanged); Tables.CollectionChanged += schemaChangedHandler; Relations.CollectionChanged += schemaChangedHandler; } protected myTypedDataSet(SerializationInfo info, StreamingContext context) { string strSchema = ((string)(info.GetValue("XmlSchema", typeof(string)))); if ((strSchema != null)) { var ds = new DataSet(); ds.ReadXmlSchema(new XmlTextReader(new StringReader(strSchema))); if ((ds.Tables["Order Details"] != null)) { Tables.Add(new Order_DetailsDataTable(ds.Tables["Order Details"])); } if ((ds.Tables["Orders"] != null)) { Tables.Add(new OrdersDataTable(ds.Tables["Orders"])); } DataSetName = ds.DataSetName; Prefix = ds.Prefix; Namespace = ds.Namespace; Locale = ds.Locale; CaseSensitive = ds.CaseSensitive; EnforceConstraints = ds.EnforceConstraints; Merge(ds, false, MissingSchemaAction.Add); InitVars(); } else { InitClass(); } GetSerializationData(info, context); CollectionChangeEventHandler schemaChangedHandler = new CollectionChangeEventHandler(SchemaChanged); Tables.CollectionChanged += schemaChangedHandler; Relations.CollectionChanged += schemaChangedHandler; } [Browsable(false)] [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Content)] public Order_DetailsDataTable Order_Details { get { return _tableOrder_Details; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Content)] public OrdersDataTable Orders { get { return _tableOrders; } } public override DataSet Clone() { myTypedDataSet cln = ((myTypedDataSet)(base.Clone())); cln.InitVars(); return cln; } protected override bool ShouldSerializeTables() { return false; } protected override bool ShouldSerializeRelations() { return false; } protected override void ReadXmlSerializable(XmlReader reader) { Reset(); var ds = new DataSet(); ds.ReadXml(reader); if ((ds.Tables["Order Details"] != null)) { Tables.Add(new Order_DetailsDataTable(ds.Tables["Order Details"])); } if ((ds.Tables["Orders"] != null)) { Tables.Add(new OrdersDataTable(ds.Tables["Orders"])); } DataSetName = ds.DataSetName; Prefix = ds.Prefix; Namespace = ds.Namespace; Locale = ds.Locale; CaseSensitive = ds.CaseSensitive; EnforceConstraints = ds.EnforceConstraints; Merge(ds, false, MissingSchemaAction.Add); InitVars(); } protected override XmlSchema GetSchemaSerializable() { MemoryStream stream = new MemoryStream(); WriteXmlSchema(new XmlTextWriter(stream, null)); stream.Position = 0; return XmlSchema.Read(new XmlTextReader(stream), null); } internal void InitVars() { _tableOrder_Details = ((Order_DetailsDataTable)(Tables["Order Details"])); if ((_tableOrder_Details != null)) { _tableOrder_Details.InitVars(); } _tableOrders = ((OrdersDataTable)(Tables["Orders"])); if ((_tableOrders != null)) { _tableOrders.InitVars(); } _relationOrdersOrder_x0020_Details = Relations["OrdersOrder_x0020_Details"]; } private void InitClass() { DataSetName = "myTypedDataSet"; Prefix = ""; Namespace = "http://www.tempuri.org/myTypedDataSet.xsd"; Locale = new CultureInfo("en-US"); CaseSensitive = false; EnforceConstraints = true; _tableOrder_Details = new Order_DetailsDataTable(); Tables.Add(_tableOrder_Details); _tableOrders = new OrdersDataTable(); Tables.Add(_tableOrders); ForeignKeyConstraint fkc; fkc = new ForeignKeyConstraint("OrdersOrder_x0020_Details", new DataColumn[] { _tableOrders.OrderIDColumn}, new DataColumn[] { _tableOrder_Details.OrderIDColumn}); _tableOrder_Details.Constraints.Add(fkc); fkc.AcceptRejectRule = AcceptRejectRule.None; fkc.DeleteRule = Rule.Cascade; fkc.UpdateRule = Rule.Cascade; _relationOrdersOrder_x0020_Details = new DataRelation("OrdersOrder_x0020_Details", new DataColumn[] { _tableOrders.OrderIDColumn}, new DataColumn[] { _tableOrder_Details.OrderIDColumn}, false); Relations.Add(_relationOrdersOrder_x0020_Details); } private bool ShouldSerializeOrder_Details() { return false; } private bool ShouldSerializeOrders() { return false; } private void SchemaChanged(object sender, CollectionChangeEventArgs e) { if ((e.Action == CollectionChangeAction.Remove)) { InitVars(); } } public delegate void Order_DetailsRowChangeEventHandler(object sender, Order_DetailsRowChangeEvent e); public delegate void OrdersRowChangeEventHandler(object sender, OrdersRowChangeEvent e); public class Order_DetailsDataTable : DataTable, IEnumerable { private DataColumn _columnOrderID; private DataColumn _columnProductID; private DataColumn _columnUnitPrice; private DataColumn _columnQuantity; private DataColumn _columnDiscount; internal Order_DetailsDataTable() : base("Order Details") { InitClass(); } internal Order_DetailsDataTable(DataTable table) : base(table.TableName) { if ((table.CaseSensitive != table.DataSet.CaseSensitive)) { CaseSensitive = table.CaseSensitive; } if ((table.Locale.ToString() != table.DataSet.Locale.ToString())) { Locale = table.Locale; } if ((table.Namespace != table.DataSet.Namespace)) { Namespace = table.Namespace; } Prefix = table.Prefix; MinimumCapacity = table.MinimumCapacity; DisplayExpression = table.DisplayExpression; } [Browsable(false)] public int Count { get { return Rows.Count; } } internal DataColumn OrderIDColumn { get { return _columnOrderID; } } internal DataColumn ProductIDColumn { get { return _columnProductID; } } internal DataColumn UnitPriceColumn { get { return _columnUnitPrice; } } internal DataColumn QuantityColumn { get { return _columnQuantity; } } internal DataColumn DiscountColumn { get { return _columnDiscount; } } public Order_DetailsRow this[int index] { get { return ((Order_DetailsRow)(Rows[index])); } } public event Order_DetailsRowChangeEventHandler Order_DetailsRowChanged; public event Order_DetailsRowChangeEventHandler Order_DetailsRowChanging; public event Order_DetailsRowChangeEventHandler Order_DetailsRowDeleted; public event Order_DetailsRowChangeEventHandler Order_DetailsRowDeleting; public void AddOrder_DetailsRow(Order_DetailsRow row) { Rows.Add(row); } public Order_DetailsRow AddOrder_DetailsRow(OrdersRow parentOrdersRowByOrdersOrder_x0020_Details, int ProductID, decimal UnitPrice, short Quantity, string Discount) { Order_DetailsRow rowOrder_DetailsRow = ((Order_DetailsRow)(NewRow())); rowOrder_DetailsRow.ItemArray = new object[] { parentOrdersRowByOrdersOrder_x0020_Details[0], ProductID, UnitPrice, Quantity, Discount}; Rows.Add(rowOrder_DetailsRow); return rowOrder_DetailsRow; } public Order_DetailsRow FindByOrderIDProductID(int OrderID, int ProductID) { return ((Order_DetailsRow)(Rows.Find(new object[] { OrderID, ProductID}))); } public IEnumerator GetEnumerator() { return Rows.GetEnumerator(); } public override DataTable Clone() { Order_DetailsDataTable cln = ((Order_DetailsDataTable)(base.Clone())); cln.InitVars(); return cln; } protected override DataTable CreateInstance() { return new Order_DetailsDataTable(); } internal void InitVars() { _columnOrderID = Columns["OrderID"]; _columnProductID = Columns["ProductID"]; _columnUnitPrice = Columns["UnitPrice"]; _columnQuantity = Columns["Quantity"]; _columnDiscount = Columns["Discount"]; } private void InitClass() { _columnOrderID = new DataColumn("OrderID", typeof(int), null, MappingType.Element); Columns.Add(_columnOrderID); _columnProductID = new DataColumn("ProductID", typeof(int), null, MappingType.Element); Columns.Add(_columnProductID); _columnUnitPrice = new DataColumn("UnitPrice", typeof(decimal), null, MappingType.Element); Columns.Add(_columnUnitPrice); _columnQuantity = new DataColumn("Quantity", typeof(short), null, MappingType.Element); Columns.Add(_columnQuantity); _columnDiscount = new DataColumn("Discount", typeof(string), null, MappingType.Element); Columns.Add(_columnDiscount); Constraints.Add(new UniqueConstraint("Constraint1", new DataColumn[] { _columnOrderID, _columnProductID}, true)); _columnOrderID.AllowDBNull = false; _columnProductID.AllowDBNull = false; _columnUnitPrice.AllowDBNull = false; _columnQuantity.AllowDBNull = false; _columnDiscount.ReadOnly = true; } public Order_DetailsRow NewOrder_DetailsRow() { return ((Order_DetailsRow)(NewRow())); } protected override DataRow NewRowFromBuilder(DataRowBuilder builder) { return new Order_DetailsRow(builder); } protected override Type GetRowType() { return typeof(Order_DetailsRow); } protected override void OnRowChanged(DataRowChangeEventArgs e) { base.OnRowChanged(e); if ((Order_DetailsRowChanged != null)) { Order_DetailsRowChanged(this, new Order_DetailsRowChangeEvent(((Order_DetailsRow)(e.Row)), e.Action)); } } protected override void OnRowChanging(DataRowChangeEventArgs e) { base.OnRowChanging(e); if ((Order_DetailsRowChanging != null)) { Order_DetailsRowChanging(this, new Order_DetailsRowChangeEvent(((Order_DetailsRow)(e.Row)), e.Action)); } } protected override void OnRowDeleted(DataRowChangeEventArgs e) { base.OnRowDeleted(e); if ((Order_DetailsRowDeleted != null)) { Order_DetailsRowDeleted(this, new Order_DetailsRowChangeEvent(((Order_DetailsRow)(e.Row)), e.Action)); } } protected override void OnRowDeleting(DataRowChangeEventArgs e) { base.OnRowDeleting(e); if ((Order_DetailsRowDeleting != null)) { Order_DetailsRowDeleting(this, new Order_DetailsRowChangeEvent(((Order_DetailsRow)(e.Row)), e.Action)); } } public void RemoveOrder_DetailsRow(Order_DetailsRow row) { Rows.Remove(row); } } public class Order_DetailsRow : DataRow { private Order_DetailsDataTable _tableOrder_Details; internal Order_DetailsRow(DataRowBuilder rb) : base(rb) { _tableOrder_Details = ((Order_DetailsDataTable)(Table)); } public int OrderID { get { return ((int)(this[_tableOrder_Details.OrderIDColumn])); } set { this[_tableOrder_Details.OrderIDColumn] = value; } } public int ProductID { get { return ((int)(this[_tableOrder_Details.ProductIDColumn])); } set { this[_tableOrder_Details.ProductIDColumn] = value; } } public decimal UnitPrice { get { return ((decimal)(this[_tableOrder_Details.UnitPriceColumn])); } set { this[_tableOrder_Details.UnitPriceColumn] = value; } } public short Quantity { get { return ((short)(this[_tableOrder_Details.QuantityColumn])); } set { this[_tableOrder_Details.QuantityColumn] = value; } } public string Discount { get { try { return ((string)(this[_tableOrder_Details.DiscountColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrder_Details.DiscountColumn] = value; } } public OrdersRow OrdersRow { get { return ((OrdersRow)(GetParentRow(Table.ParentRelations["OrdersOrder_x0020_Details"]))); } set { SetParentRow(value, Table.ParentRelations["OrdersOrder_x0020_Details"]); } } public bool IsDiscountNull() { return IsNull(_tableOrder_Details.DiscountColumn); } public void SetDiscountNull() { this[_tableOrder_Details.DiscountColumn] = DBNull.Value; } } public class Order_DetailsRowChangeEvent : EventArgs { private Order_DetailsRow _eventRow; private DataRowAction _eventAction; public Order_DetailsRowChangeEvent(Order_DetailsRow row, DataRowAction action) { _eventRow = row; _eventAction = action; } public Order_DetailsRow Row { get { return _eventRow; } } public DataRowAction Action { get { return _eventAction; } } } public class OrdersDataTable : DataTable, IEnumerable { private DataColumn _columnOrderID; private DataColumn _columnCustomerID; private DataColumn _columnEmployeeID; private DataColumn _columnOrderDate; private DataColumn _columnRequiredDate; private DataColumn _columnShippedDate; private DataColumn _columnShipVia; private DataColumn _columnFreight; private DataColumn _columnShipName; private DataColumn _columnShipAddress; private DataColumn _columnShipCity; private DataColumn _columnShipRegion; private DataColumn _columnShipPostalCode; private DataColumn _columnShipCountry; internal OrdersDataTable() : base("Orders") { InitClass(); } internal OrdersDataTable(DataTable table) : base(table.TableName) { if ((table.CaseSensitive != table.DataSet.CaseSensitive)) { CaseSensitive = table.CaseSensitive; } if ((table.Locale.ToString() != table.DataSet.Locale.ToString())) { Locale = table.Locale; } if ((table.Namespace != table.DataSet.Namespace)) { Namespace = table.Namespace; } Prefix = table.Prefix; MinimumCapacity = table.MinimumCapacity; DisplayExpression = table.DisplayExpression; } [Browsable(false)] public int Count { get { return Rows.Count; } } internal DataColumn OrderIDColumn { get { return _columnOrderID; } } internal DataColumn CustomerIDColumn { get { return _columnCustomerID; } } internal DataColumn EmployeeIDColumn { get { return _columnEmployeeID; } } internal DataColumn OrderDateColumn { get { return _columnOrderDate; } } internal DataColumn RequiredDateColumn { get { return _columnRequiredDate; } } internal DataColumn ShippedDateColumn { get { return _columnShippedDate; } } internal DataColumn ShipViaColumn { get { return _columnShipVia; } } internal DataColumn FreightColumn { get { return _columnFreight; } } internal DataColumn ShipNameColumn { get { return _columnShipName; } } internal DataColumn ShipAddressColumn { get { return _columnShipAddress; } } internal DataColumn ShipCityColumn { get { return _columnShipCity; } } internal DataColumn ShipRegionColumn { get { return _columnShipRegion; } } internal DataColumn ShipPostalCodeColumn { get { return _columnShipPostalCode; } } internal DataColumn ShipCountryColumn { get { return _columnShipCountry; } } public OrdersRow this[int index] { get { return ((OrdersRow)(Rows[index])); } } public event OrdersRowChangeEventHandler OrdersRowChanged; public event OrdersRowChangeEventHandler OrdersRowChanging; public event OrdersRowChangeEventHandler OrdersRowDeleted; public event OrdersRowChangeEventHandler OrdersRowDeleting; public void AddOrdersRow(OrdersRow row) { Rows.Add(row); } public OrdersRow AddOrdersRow(string CustomerID, int EmployeeID, DateTime OrderDate, DateTime RequiredDate, DateTime ShippedDate, int ShipVia, decimal Freight, string ShipName, string ShipAddress, string ShipCity, string ShipRegion, string ShipPostalCode, string ShipCountry) { OrdersRow rowOrdersRow = ((OrdersRow)(NewRow())); rowOrdersRow.ItemArray = new object[] { null, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry}; Rows.Add(rowOrdersRow); return rowOrdersRow; } public OrdersRow FindByOrderID(int OrderID) { return ((OrdersRow)(Rows.Find(new object[] { OrderID}))); } public IEnumerator GetEnumerator() { return Rows.GetEnumerator(); } public override DataTable Clone() { OrdersDataTable cln = ((OrdersDataTable)(base.Clone())); cln.InitVars(); return cln; } protected override DataTable CreateInstance() { return new OrdersDataTable(); } internal void InitVars() { _columnOrderID = Columns["OrderID"]; _columnCustomerID = Columns["CustomerID"]; _columnEmployeeID = Columns["EmployeeID"]; _columnOrderDate = Columns["OrderDate"]; _columnRequiredDate = Columns["RequiredDate"]; _columnShippedDate = Columns["ShippedDate"]; _columnShipVia = Columns["ShipVia"]; _columnFreight = Columns["Freight"]; _columnShipName = Columns["ShipName"]; _columnShipAddress = Columns["ShipAddress"]; _columnShipCity = Columns["ShipCity"]; _columnShipRegion = Columns["ShipRegion"]; _columnShipPostalCode = Columns["ShipPostalCode"]; _columnShipCountry = Columns["ShipCountry"]; } private void InitClass() { _columnOrderID = new DataColumn("OrderID", typeof(int), null, MappingType.Element); Columns.Add(_columnOrderID); _columnCustomerID = new DataColumn("CustomerID", typeof(string), null, MappingType.Element); Columns.Add(_columnCustomerID); _columnEmployeeID = new DataColumn("EmployeeID", typeof(int), null, MappingType.Element); Columns.Add(_columnEmployeeID); _columnOrderDate = new DataColumn("OrderDate", typeof(DateTime), null, MappingType.Element); Columns.Add(_columnOrderDate); _columnRequiredDate = new DataColumn("RequiredDate", typeof(DateTime), null, MappingType.Element); Columns.Add(_columnRequiredDate); _columnShippedDate = new DataColumn("ShippedDate", typeof(DateTime), null, MappingType.Element); Columns.Add(_columnShippedDate); _columnShipVia = new DataColumn("ShipVia", typeof(int), null, MappingType.Element); Columns.Add(_columnShipVia); _columnFreight = new DataColumn("Freight", typeof(decimal), null, MappingType.Element); Columns.Add(_columnFreight); _columnShipName = new DataColumn("ShipName", typeof(string), null, MappingType.Element); Columns.Add(_columnShipName); _columnShipAddress = new DataColumn("ShipAddress", typeof(string), null, MappingType.Element); Columns.Add(_columnShipAddress); _columnShipCity = new DataColumn("ShipCity", typeof(string), null, MappingType.Element); Columns.Add(_columnShipCity); _columnShipRegion = new DataColumn("ShipRegion", typeof(string), null, MappingType.Element); Columns.Add(_columnShipRegion); _columnShipPostalCode = new DataColumn("ShipPostalCode", typeof(string), null, MappingType.Element); Columns.Add(_columnShipPostalCode); _columnShipCountry = new DataColumn("ShipCountry", typeof(string), null, MappingType.Element); Columns.Add(_columnShipCountry); Constraints.Add(new UniqueConstraint("Constraint1", new DataColumn[] { _columnOrderID}, true)); _columnOrderID.AutoIncrement = true; _columnOrderID.AllowDBNull = false; _columnOrderID.ReadOnly = true; _columnOrderID.Unique = true; } public OrdersRow NewOrdersRow() { return ((OrdersRow)(NewRow())); } protected override DataRow NewRowFromBuilder(DataRowBuilder builder) { return new OrdersRow(builder); } protected override Type GetRowType() { return typeof(OrdersRow); } protected override void OnRowChanged(DataRowChangeEventArgs e) { base.OnRowChanged(e); if ((OrdersRowChanged != null)) { OrdersRowChanged(this, new OrdersRowChangeEvent(((OrdersRow)(e.Row)), e.Action)); } } protected override void OnRowChanging(DataRowChangeEventArgs e) { base.OnRowChanging(e); if ((OrdersRowChanging != null)) { OrdersRowChanging(this, new OrdersRowChangeEvent(((OrdersRow)(e.Row)), e.Action)); } } protected override void OnRowDeleted(DataRowChangeEventArgs e) { base.OnRowDeleted(e); if ((OrdersRowDeleted != null)) { OrdersRowDeleted(this, new OrdersRowChangeEvent(((OrdersRow)(e.Row)), e.Action)); } } protected override void OnRowDeleting(DataRowChangeEventArgs e) { base.OnRowDeleting(e); if ((OrdersRowDeleting != null)) { OrdersRowDeleting(this, new OrdersRowChangeEvent(((OrdersRow)(e.Row)), e.Action)); } } public void RemoveOrdersRow(OrdersRow row) { Rows.Remove(row); } } public class OrdersRow : DataRow { private OrdersDataTable _tableOrders; internal OrdersRow(DataRowBuilder rb) : base(rb) { _tableOrders = ((OrdersDataTable)(Table)); } public int OrderID { get { return ((int)(this[_tableOrders.OrderIDColumn])); } set { this[_tableOrders.OrderIDColumn] = value; } } public string CustomerID { get { try { return ((string)(this[_tableOrders.CustomerIDColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.CustomerIDColumn] = value; } } public int EmployeeID { get { try { return ((int)(this[_tableOrders.EmployeeIDColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.EmployeeIDColumn] = value; } } public DateTime OrderDate { get { try { return ((DateTime)(this[_tableOrders.OrderDateColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.OrderDateColumn] = value; } } public DateTime RequiredDate { get { try { return ((DateTime)(this[_tableOrders.RequiredDateColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.RequiredDateColumn] = value; } } public DateTime ShippedDate { get { try { return ((DateTime)(this[_tableOrders.ShippedDateColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.ShippedDateColumn] = value; } } public int ShipVia { get { try { return ((int)(this[_tableOrders.ShipViaColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.ShipViaColumn] = value; } } public decimal Freight { get { try { return ((decimal)(this[_tableOrders.FreightColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.FreightColumn] = value; } } public string ShipName { get { try { return ((string)(this[_tableOrders.ShipNameColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.ShipNameColumn] = value; } } public string ShipAddress { get { try { return ((string)(this[_tableOrders.ShipAddressColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.ShipAddressColumn] = value; } } public string ShipCity { get { try { return ((string)(this[_tableOrders.ShipCityColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.ShipCityColumn] = value; } } public string ShipRegion { get { try { return ((string)(this[_tableOrders.ShipRegionColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.ShipRegionColumn] = value; } } public string ShipPostalCode { get { try { return ((string)(this[_tableOrders.ShipPostalCodeColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.ShipPostalCodeColumn] = value; } } public string ShipCountry { get { try { return ((string)(this[_tableOrders.ShipCountryColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.ShipCountryColumn] = value; } } public bool IsCustomerIDNull() { return IsNull(_tableOrders.CustomerIDColumn); } public void SetCustomerIDNull() { this[_tableOrders.CustomerIDColumn] = DBNull.Value; } public bool IsEmployeeIDNull() { return IsNull(_tableOrders.EmployeeIDColumn); } public void SetEmployeeIDNull() { this[_tableOrders.EmployeeIDColumn] = DBNull.Value; } public bool IsOrderDateNull() { return IsNull(_tableOrders.OrderDateColumn); } public void SetOrderDateNull() { this[_tableOrders.OrderDateColumn] = DBNull.Value; } public bool IsRequiredDateNull() { return IsNull(_tableOrders.RequiredDateColumn); } public void SetRequiredDateNull() { this[_tableOrders.RequiredDateColumn] = DBNull.Value; } public bool IsShippedDateNull() { return IsNull(_tableOrders.ShippedDateColumn); } public void SetShippedDateNull() { this[_tableOrders.ShippedDateColumn] = DBNull.Value; } public bool IsShipViaNull() { return IsNull(_tableOrders.ShipViaColumn); } public void SetShipViaNull() { this[_tableOrders.ShipViaColumn] = DBNull.Value; } public bool IsFreightNull() { return IsNull(_tableOrders.FreightColumn); } public void SetFreightNull() { this[_tableOrders.FreightColumn] = DBNull.Value; } public bool IsShipNameNull() { return IsNull(_tableOrders.ShipNameColumn); } public void SetShipNameNull() { this[_tableOrders.ShipNameColumn] = DBNull.Value; } public bool IsShipAddressNull() { return IsNull(_tableOrders.ShipAddressColumn); } public void SetShipAddressNull() { this[_tableOrders.ShipAddressColumn] = DBNull.Value; } public bool IsShipCityNull() { return IsNull(_tableOrders.ShipCityColumn); } public void SetShipCityNull() { this[_tableOrders.ShipCityColumn] = DBNull.Value; } public bool IsShipRegionNull() { return IsNull(_tableOrders.ShipRegionColumn); } public void SetShipRegionNull() { this[_tableOrders.ShipRegionColumn] = DBNull.Value; } public bool IsShipPostalCodeNull() { return IsNull(_tableOrders.ShipPostalCodeColumn); } public void SetShipPostalCodeNull() { this[_tableOrders.ShipPostalCodeColumn] = DBNull.Value; } public bool IsShipCountryNull() { return IsNull(_tableOrders.ShipCountryColumn); } public void SetShipCountryNull() { this[_tableOrders.ShipCountryColumn] = DBNull.Value; } public Order_DetailsRow[] GetOrder_DetailsRows() { return ((Order_DetailsRow[])(GetChildRows(Table.ChildRelations["OrdersOrder_x0020_Details"]))); } } public class OrdersRowChangeEvent : EventArgs { private OrdersRow _eventRow; private DataRowAction _eventAction; public OrdersRowChangeEvent(OrdersRow row, DataRowAction action) { _eventRow = row; _eventAction = action; } public OrdersRow Row { get { return _eventRow; } } public DataRowAction Action { get { return _eventAction; } } } } } }
using System; using System.Linq; using Avalonia.Automation.Peers; using System.Reactive.Disposables; using Avalonia.Controls.Generators; using Avalonia.Controls.Mixins; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Controls.Templates; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Layout; using Avalonia.Media; using Avalonia.VisualTree; namespace Avalonia.Controls { /// <summary> /// A drop-down list control. /// </summary> public class ComboBox : SelectingItemsControl { /// <summary> /// The default value for the <see cref="ItemsControl.ItemsPanel"/> property. /// </summary> private static readonly FuncTemplate<IPanel> DefaultPanel = new FuncTemplate<IPanel>(() => new VirtualizingStackPanel()); /// <summary> /// Defines the <see cref="IsDropDownOpen"/> property. /// </summary> public static readonly DirectProperty<ComboBox, bool> IsDropDownOpenProperty = AvaloniaProperty.RegisterDirect<ComboBox, bool>( nameof(IsDropDownOpen), o => o.IsDropDownOpen, (o, v) => o.IsDropDownOpen = v); /// <summary> /// Defines the <see cref="MaxDropDownHeight"/> property. /// </summary> public static readonly StyledProperty<double> MaxDropDownHeightProperty = AvaloniaProperty.Register<ComboBox, double>(nameof(MaxDropDownHeight), 200); /// <summary> /// Defines the <see cref="SelectionBoxItem"/> property. /// </summary> public static readonly DirectProperty<ComboBox, object?> SelectionBoxItemProperty = AvaloniaProperty.RegisterDirect<ComboBox, object?>(nameof(SelectionBoxItem), o => o.SelectionBoxItem); /// <summary> /// Defines the <see cref="VirtualizationMode"/> property. /// </summary> public static readonly StyledProperty<ItemVirtualizationMode> VirtualizationModeProperty = ItemsPresenter.VirtualizationModeProperty.AddOwner<ComboBox>(); /// <summary> /// Defines the <see cref="PlaceholderText"/> property. /// </summary> public static readonly StyledProperty<string?> PlaceholderTextProperty = AvaloniaProperty.Register<ComboBox, string?>(nameof(PlaceholderText)); /// <summary> /// Defines the <see cref="PlaceholderForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush?> PlaceholderForegroundProperty = AvaloniaProperty.Register<ComboBox, IBrush?>(nameof(PlaceholderForeground)); /// <summary> /// Defines the <see cref="HorizontalContentAlignment"/> property. /// </summary> public static readonly StyledProperty<HorizontalAlignment> HorizontalContentAlignmentProperty = ContentControl.HorizontalContentAlignmentProperty.AddOwner<ComboBox>(); /// <summary> /// Defines the <see cref="VerticalContentAlignment"/> property. /// </summary> public static readonly StyledProperty<VerticalAlignment> VerticalContentAlignmentProperty = ContentControl.VerticalContentAlignmentProperty.AddOwner<ComboBox>(); private bool _isDropDownOpen; private Popup? _popup; private object? _selectionBoxItem; private readonly CompositeDisposable _subscriptionsOnOpen = new CompositeDisposable(); /// <summary> /// Initializes static members of the <see cref="ComboBox"/> class. /// </summary> static ComboBox() { ItemsPanelProperty.OverrideDefaultValue<ComboBox>(DefaultPanel); FocusableProperty.OverrideDefaultValue<ComboBox>(true); SelectedItemProperty.Changed.AddClassHandler<ComboBox>((x, e) => x.SelectedItemChanged(e)); KeyDownEvent.AddClassHandler<ComboBox>((x, e) => x.OnKeyDown(e), Interactivity.RoutingStrategies.Tunnel); IsTextSearchEnabledProperty.OverrideDefaultValue<ComboBox>(true); } /// <summary> /// Gets or sets a value indicating whether the dropdown is currently open. /// </summary> public bool IsDropDownOpen { get { return _isDropDownOpen; } set { SetAndRaise(IsDropDownOpenProperty, ref _isDropDownOpen, value); } } /// <summary> /// Gets or sets the maximum height for the dropdown list. /// </summary> public double MaxDropDownHeight { get { return GetValue(MaxDropDownHeightProperty); } set { SetValue(MaxDropDownHeightProperty, value); } } /// <summary> /// Gets or sets the item to display as the control's content. /// </summary> protected object? SelectionBoxItem { get { return _selectionBoxItem; } set { SetAndRaise(SelectionBoxItemProperty, ref _selectionBoxItem, value); } } /// <summary> /// Gets or sets the PlaceHolder text. /// </summary> public string? PlaceholderText { get { return GetValue(PlaceholderTextProperty); } set { SetValue(PlaceholderTextProperty, value); } } /// <summary> /// Gets or sets the Brush that renders the placeholder text. /// </summary> public IBrush? PlaceholderForeground { get { return GetValue(PlaceholderForegroundProperty); } set { SetValue(PlaceholderForegroundProperty, value); } } /// <summary> /// Gets or sets the virtualization mode for the items. /// </summary> public ItemVirtualizationMode VirtualizationMode { get { return GetValue(VirtualizationModeProperty); } set { SetValue(VirtualizationModeProperty, value); } } /// <summary> /// Gets or sets the horizontal alignment of the content within the control. /// </summary> public HorizontalAlignment HorizontalContentAlignment { get { return GetValue(HorizontalContentAlignmentProperty); } set { SetValue(HorizontalContentAlignmentProperty, value); } } /// <summary> /// Gets or sets the vertical alignment of the content within the control. /// </summary> public VerticalAlignment VerticalContentAlignment { get { return GetValue(VerticalContentAlignmentProperty); } set { SetValue(VerticalContentAlignmentProperty, value); } } /// <inheritdoc/> protected override IItemContainerGenerator CreateItemContainerGenerator() { return new ItemContainerGenerator<ComboBoxItem>( this, ComboBoxItem.ContentProperty, ComboBoxItem.ContentTemplateProperty); } protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) { base.OnAttachedToVisualTree(e); this.UpdateSelectionBoxItem(SelectedItem); } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (e.Handled) return; if ((e.Key == Key.F4 && e.KeyModifiers.HasAllFlags(KeyModifiers.Alt) == false) || ((e.Key == Key.Down || e.Key == Key.Up) && e.KeyModifiers.HasAllFlags(KeyModifiers.Alt))) { IsDropDownOpen = !IsDropDownOpen; e.Handled = true; } else if (IsDropDownOpen && e.Key == Key.Escape) { IsDropDownOpen = false; e.Handled = true; } else if (IsDropDownOpen && e.Key == Key.Enter) { SelectFocusedItem(); IsDropDownOpen = false; e.Handled = true; } else if (!IsDropDownOpen) { if (e.Key == Key.Down) { SelectNext(); e.Handled = true; } else if (e.Key == Key.Up) { SelectPrev(); e.Handled = true; } } // This part of code is needed just to acquire initial focus, subsequent focus navigation will be done by ItemsControl. else if (IsDropDownOpen && SelectedIndex < 0 && ItemCount > 0 && (e.Key == Key.Up || e.Key == Key.Down) && IsFocused == true) { var firstChild = Presenter?.Panel?.Children.FirstOrDefault(c => CanFocus(c)); if (firstChild != null) { FocusManager.Instance?.Focus(firstChild, NavigationMethod.Directional); e.Handled = true; } } } /// <inheritdoc/> protected override void OnPointerWheelChanged(PointerWheelEventArgs e) { base.OnPointerWheelChanged(e); if (!e.Handled) { if (!IsDropDownOpen) { if (IsFocused) { if (e.Delta.Y < 0) SelectNext(); else SelectPrev(); e.Handled = true; } } else { e.Handled = true; } } } /// <inheritdoc/> protected override void OnPointerReleased(PointerReleasedEventArgs e) { if (!e.Handled && e.Source is IVisual source) { if (_popup?.IsInsidePopup(source) == true) { if (UpdateSelectionFromEventSource(e.Source)) { _popup?.Close(); e.Handled = true; } } else { IsDropDownOpen = !IsDropDownOpen; e.Handled = true; } } base.OnPointerReleased(e); } /// <inheritdoc/> protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { if (_popup != null) { _popup.Opened -= PopupOpened; _popup.Closed -= PopupClosed; } _popup = e.NameScope.Get<Popup>("PART_Popup"); _popup.Opened += PopupOpened; _popup.Closed += PopupClosed; } protected override AutomationPeer OnCreateAutomationPeer() { return new ComboBoxAutomationPeer(this); } internal void ItemFocused(ComboBoxItem dropDownItem) { if (IsDropDownOpen && dropDownItem.IsFocused && dropDownItem.IsArrangeValid) { dropDownItem.BringIntoView(); } } private void PopupClosed(object? sender, EventArgs e) { _subscriptionsOnOpen.Clear(); if (CanFocus(this)) { Focus(); } } private void PopupOpened(object? sender, EventArgs e) { TryFocusSelectedItem(); _subscriptionsOnOpen.Clear(); var toplevel = this.GetVisualRoot() as TopLevel; if (toplevel != null) { toplevel.AddDisposableHandler(PointerWheelChangedEvent, (s, ev) => { //eat wheel scroll event outside dropdown popup while it's open if (IsDropDownOpen && (ev.Source as IVisual)?.GetVisualRoot() == toplevel) { ev.Handled = true; } }, Interactivity.RoutingStrategies.Tunnel).DisposeWith(_subscriptionsOnOpen); } this.GetObservable(IsVisibleProperty).Subscribe(IsVisibleChanged).DisposeWith(_subscriptionsOnOpen); foreach (var parent in this.GetVisualAncestors().OfType<IControl>()) { parent.GetObservable(IsVisibleProperty).Subscribe(IsVisibleChanged).DisposeWith(_subscriptionsOnOpen); } } private void IsVisibleChanged(bool isVisible) { if (!isVisible && IsDropDownOpen) { IsDropDownOpen = false; } } private void SelectedItemChanged(AvaloniaPropertyChangedEventArgs e) { UpdateSelectionBoxItem(e.NewValue); TryFocusSelectedItem(); } private void TryFocusSelectedItem() { var selectedIndex = SelectedIndex; if (IsDropDownOpen && selectedIndex != -1) { var container = ItemContainerGenerator.ContainerFromIndex(selectedIndex); if (container == null && SelectedIndex != -1) { ScrollIntoView(Selection.SelectedIndex); container = ItemContainerGenerator.ContainerFromIndex(selectedIndex); } if (container != null && CanFocus(container)) { container.Focus(); } } } private bool CanFocus(IControl control) => control.Focusable && control.IsEffectivelyEnabled && control.IsVisible; private void UpdateSelectionBoxItem(object? item) { var contentControl = item as IContentControl; if (contentControl != null) { item = contentControl.Content; } var control = item as IControl; if (control != null) { if (VisualRoot is object) { control.Measure(Size.Infinity); SelectionBoxItem = new Rectangle { Width = control.DesiredSize.Width, Height = control.DesiredSize.Height, Fill = new VisualBrush { Visual = control, Stretch = Stretch.None, AlignmentX = AlignmentX.Left, } }; } } else { SelectionBoxItem = item; } } private void SelectFocusedItem() { foreach (ItemContainerInfo dropdownItem in ItemContainerGenerator.Containers) { if (dropdownItem.ContainerControl.IsFocused) { SelectedIndex = dropdownItem.Index; break; } } } private void SelectNext() { int next = SelectedIndex + 1; if (next >= ItemCount) { if (WrapSelection == true) { next = 0; } else { return; } } SelectedIndex = next; } private void SelectPrev() { int prev = SelectedIndex - 1; if (prev < 0) { if (WrapSelection == true) { prev = ItemCount - 1; } else { return; } } SelectedIndex = prev; } } }
// Copyright (c) 2015 fjz13. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; namespace Siren.Generator { public class CppGenerator : BaseGenerator { private const string mHeaderIncludeMask = "<SIREN_HEADER_INCLUDE>"; private const string mHeaderMask = "<SIREN_HEADER>"; private const string mBodyIncludeMask = "<SIREN_BODY_INCLUDE>"; private const string mBodyMask = "<SIREN_BODY>"; private const string mHeaderIncludeBegin = "//SIREN_HEADER_INCLUDE_BEGIN"; private const string mHeaderIncludeEnd = "//SIREN_HEADER_INCLUDE_END"; private const string mHeaderCopyBegin = "//SIREN_HEADER_COPY_BEGIN"; private const string mHeaderCopyEnd = "//SIREN_HEADER_COPY_END"; private const string mHeaderCompareBegin = "//SIREN_HEADER_COMPARE_BEGIN"; private const string mHeaderCompareEnd = "//SIREN_HEADER_COMPARE_END"; private const string mHeaderMethodBegin = "//SIREN_HEADER_METHOD_BEGIN"; private const string mHeaderMethodEnd = "//SIREN_HEADER_METHOD_END"; private const string mHeaderFieldBegin = "//SIREN_HEADER_FIELD_BEGIN"; private const string mHeaderFieldEnd = "//SIREN_HEADER_FIELD_END"; private const string mHeaderSchemaBegin = "//SIREN_HEADER_SCHEMA_BEGIN"; private const string mHeaderSchemaEnd = "//SIREN_HEADER_SCHEMA_END"; private const string mBodyIncludeBegin = "//SIREN_BODY_INCLUDE_BEGIN"; private const string mBodyIncludeEnd = "//SIREN_BODY_INCLUDE_END"; private const string mBodyConstructBegin = "//SIREN_BODY_CONSTRUCT_BEGIN"; private const string mBodyConstructEnd = "//SIREN_BODY_CONSTRUCT_END"; private const string mBodyDestructBegin = "//SIREN_BODY_DESTRUCT_BEGIN"; private const string mBodyDestructEnd = "//SIREN_BODY_DESTRUCT_END"; private const string mBodyMetadataBegin = "//SIREN_BODY_METADATA_BEGIN"; private const string mBodyMetadataEnd = "//SIREN_BODY_METADATA_END"; public override void GenerateClass(SirenClass sirenClass) { var hName = sirenClass.Type.Name + ".h"; var cppName = sirenClass.Type.Name + ".cpp"; var hPath = Path.Combine(WorkingDirectory.FullName, sirenClass.Template.RootDirectory, sirenClass.Attribute.Directory, hName); var cppPath = Path.Combine(WorkingDirectory.FullName, sirenClass.Template.RootDirectory, sirenClass.Attribute.Directory, cppName); //get properties if (sirenClass.Type.IsEnum) { StringBuilder header = new StringBuilder(sirenClass.Template.HeaderTemplate); var headerInclude = GenerateHeaderInclude(sirenClass); var headerStr = GenerateEnumHeader(sirenClass); header.Replace(mHeaderIncludeMask, headerInclude); header.Replace(mHeaderMask, headerStr); UpdateFile(hPath, header.ToString()); } else if (sirenClass.Attribute.Mode.HasFlag(SirenGenerateMode.Generate) || !File.Exists(hPath) || !File.Exists(cppPath)) { StringBuilder header = new StringBuilder(sirenClass.Template.HeaderTemplate); StringBuilder body = new StringBuilder(sirenClass.Template.BodyTemplate); var headerInclude = GenerateAllHeaderInclude(sirenClass); var headerStr = GenerateAllHeader(sirenClass); header.Replace(mHeaderIncludeMask, headerInclude); header.Replace(mHeaderMask, headerStr); var bodyInclude = GenerateAllBodyInclude(sirenClass); var bodyStr = GenerateAllBody(sirenClass); body.Replace(mBodyIncludeMask, bodyInclude); body.Replace(mBodyMask, bodyStr); UpdateFile(hPath, header.ToString()); UpdateFile(cppPath, body.ToString()); } else { string header = File.ReadAllText(hPath); string body = File.ReadAllText(cppPath); var headerInclude = GenerateHeaderInclude(sirenClass); headerInclude = "\r\n" + headerInclude; header = Replace(header, mHeaderIncludeBegin, mHeaderIncludeEnd, headerInclude); if (!sirenClass.Attribute.Mode.HasFlag(SirenGenerateMode.SuppressCompare)) { var hederCompare = GenerateHeaderCompare(sirenClass); hederCompare = "\r\n" + hederCompare; header = Replace(header, mHeaderCompareBegin, mHeaderCompareEnd, hederCompare); } if (!sirenClass.Attribute.Mode.HasFlag(SirenGenerateMode.SuppressCopy)) { var hederCopy = GenerateHeaderCopy(sirenClass); hederCopy = "\r\n" + hederCopy; header = Replace(header, mHeaderCopyBegin, mHeaderCopyEnd, hederCopy); } var hederMethod = GenerateHeaderMethod(sirenClass); hederMethod = "\r\n" + hederMethod; header = Replace(header, mHeaderMethodBegin, mHeaderMethodEnd, hederMethod); var hederField = GenerateHeaderField(sirenClass); hederField = "\r\n" + hederField; header = Replace(header, mHeaderFieldBegin, mHeaderFieldEnd, hederField); var hederSchema = GenerateHeaderSchema(sirenClass); hederSchema = "\r\n" + hederSchema; header = Replace(header, mHeaderSchemaBegin, mHeaderSchemaEnd, hederSchema); var bodyInclude = GenerateBodyInclude(sirenClass); bodyInclude = "\r\n" + bodyInclude; body = Replace(body, mBodyIncludeBegin, mBodyIncludeEnd, bodyInclude); var bodyConstruct = GenerateBodyConstruct(sirenClass); bodyConstruct = "\r\n" + bodyConstruct; body = Replace(body, mBodyConstructBegin, mBodyConstructEnd, bodyConstruct); var bodyDestruct = GenerateBodyDestruct(sirenClass); bodyDestruct = "\r\n" + bodyDestruct; body = Replace(body, mBodyDestructBegin, mBodyDestructEnd, bodyDestruct); var bodySchema = GenerateBodyMetadata(sirenClass); bodySchema = "\r\n" + bodySchema; body = Replace(body, mBodyMetadataBegin, mBodyMetadataEnd, bodySchema); UpdateFile(hPath, header); UpdateFile(cppPath, body); } } public string GenerateAllHeaderInclude(SirenClass sirenClass) { StringBuilder sb = new StringBuilder(); sb.AppendLine(); sb.AppendLine(mHeaderIncludeBegin); sb.Append(GenerateHeaderInclude(sirenClass)); sb.AppendLine(mHeaderIncludeEnd); return sb.ToString(); } public string GenerateHeaderInclude(SirenClass sirenClass) { StringBuilder sb = new StringBuilder(); //sb.AppendLine(); foreach (var includeType in sirenClass.IncludeTypes) { var includeSirenClass = SirenFactory.FindClass(includeType); if (includeSirenClass != null) { if (!string.IsNullOrEmpty(includeSirenClass.Attribute.NewHeader)) { sb.AppendFormat("#include \"{0}/{1}.h\"\r\n", includeSirenClass.Attribute.Directory, includeSirenClass.Attribute.NewHeader); } else { sb.AppendFormat("#include \"{0}/{1}.h\"\r\n", includeSirenClass.Attribute.Directory, SirenFactory.GetTypeName(includeType)); } } else { sb.AppendFormat("#include \"{0}.h\"\r\n", SirenFactory.GetTypeName(includeType)); } } if (sirenClass.Attribute.Mode.HasFlag(SirenGenerateMode.SirenConfig)) { sb.AppendFormat("#include \"Core/Siren/ISirenConfig.h\"\r\n"); } return sb.ToString(); } public string GenerateAllHeader(SirenClass sirenClass) { var typeName = sirenClass.Name; StringBuilder sb = new StringBuilder(); if (!sirenClass.Attribute.IsEmbeded) { if (sirenClass.IsRoot) { if (sirenClass.Attribute.Mode.HasFlag(SirenGenerateMode.SirenConfig)) { sb.AppendFormat("class {0} : public ISirenConfig<{1}>\r\n", typeName, typeName); } else { sb.AppendFormat("class {0}\r\n", typeName); } } else { if (sirenClass.Attribute.Mode.HasFlag(SirenGenerateMode.SirenConfig)) { sb.AppendFormat("class {0} : public {1},public ISirenConfig<{2}>\r\n", typeName, sirenClass.BaseSirenClass.Name, typeName); } else { sb.AppendFormat("class {0} : public {1}\r\n", typeName, sirenClass.BaseSirenClass.Name); } } sb.AppendLine("{"); } sb.Append(GenerateHeaderConstruct(sirenClass)); if (!sirenClass.Attribute.Mode.HasFlag(SirenGenerateMode.SuppressCompare)) { sb.AppendLine(mHeaderCopyBegin); sb.Append(GenerateHeaderCopy(sirenClass)); sb.AppendLine(mHeaderCopyEnd); } if (!sirenClass.Attribute.Mode.HasFlag(SirenGenerateMode.SuppressCompare)) { sb.AppendLine(mHeaderCompareBegin); sb.Append(GenerateHeaderCompare(sirenClass)); sb.AppendLine(mHeaderCompareEnd); } //add method sb.AppendLine(mHeaderMethodBegin); sb.Append(GenerateHeaderMethod(sirenClass)); sb.AppendLine(mHeaderMethodEnd); //add fields sb.AppendLine(mHeaderFieldBegin); sb.Append(GenerateHeaderField(sirenClass)); sb.AppendLine(mHeaderFieldEnd); sb.AppendLine("};"); sb.AppendLine(); sb.AppendLine(mHeaderSchemaBegin); sb.AppendLine(GenerateHeaderSchema(sirenClass)); sb.AppendLine(mHeaderSchemaEnd); return sb.ToString(); } public string GenerateHeaderConstruct(SirenClass sirenClass) { var typeName = sirenClass.Name; StringBuilder sb = new StringBuilder(); //sb.AppendLine(); sb.AppendLine("public:"); sb.AppendLine("\tstruct Schema;"); sb.AppendFormat("\t{0}();\r\n", typeName); sb.AppendFormat("\t~{0}();\r\n", typeName); return sb.ToString(); } public string GenerateHeaderCompare(SirenClass sirenClass) { var typeName = sirenClass.Name; StringBuilder sb = new StringBuilder(); //sb.AppendLine(); sb.AppendLine("public:"); //sb.AppendFormat("\tbool operator<(const {0}&)const { return true; }\r\n", typeName); //sb.AppendFormat("\tbool operator==(const {0}&)const { return true; }\r\n", typeName); sb.AppendFormat("\tSIREN_COMMON({0});\r\n", typeName); return sb.ToString(); } public string GenerateHeaderCopy(SirenClass sirenClass) { var typeName = sirenClass.Name; StringBuilder sb = new StringBuilder(); //sb.AppendLine(); sb.AppendLine("public:"); //copy construct sb.AppendFormat("\t{0}(const {1}& other)\r\n", typeName, typeName); sb.AppendFormat("\t{{\r\n"); foreach (var sirenProperty in sirenClass.Properties) { var methodType = sirenProperty.MethodType; switch (methodType) { case SirenPropertyMethodType.Pointer: sb.AppendFormat("\t\tSAFE_CONSTRUCT_PTR({0},m{1},other.m{2});\r\n", SirenFactory.GetTypeName(sirenProperty.Type), sirenProperty.Name, sirenProperty.Name); break; case SirenPropertyMethodType.Value: case SirenPropertyMethodType.List: case SirenPropertyMethodType.Dictionary: sb.AppendFormat("\t\tm{0} = other.m{1};\r\n", sirenProperty.Name, sirenProperty.Name); break; } } sb.AppendFormat("\t}}\r\n"); //assign sb.AppendFormat("\t{0}& operator=(const {1}& other)\r\n", typeName, typeName); sb.AppendFormat("\t{{\r\n"); foreach (var sirenProperty in sirenClass.Properties) { var methodType = sirenProperty.MethodType; switch (methodType) { case SirenPropertyMethodType.Pointer: sb.AppendFormat("\t\tSAFE_COPY_PTR({0},m{1},other.m{2});\r\n", SirenFactory.GetTypeName(sirenProperty.Type), sirenProperty.Name, sirenProperty.Name); break; case SirenPropertyMethodType.Value: case SirenPropertyMethodType.List: case SirenPropertyMethodType.Dictionary: sb.AppendFormat("\t\tm{0} = other.m{1};\r\n", sirenProperty.Name, sirenProperty.Name); break; } } sb.AppendFormat("\t\treturn *this;\r\n"); sb.AppendFormat("\t}}\r\n"); return sb.ToString(); } public string GenerateHeaderMethod(SirenClass sirenClass) { StringBuilder sb = new StringBuilder(); //sb.AppendLine(); //add methods sb.AppendLine("public:"); foreach (var sirenProperty in sirenClass.Properties) { if (sirenProperty.Attribute.SuppressMethod) { continue; } var methodType = sirenProperty.MethodType; switch (methodType) { case SirenPropertyMethodType.Value: sb.AppendFormat("\tSIREN_METHOD({0}, {1});\r\n", SirenFactory.GetTypeName(sirenProperty.Type), sirenProperty.Name); break; case SirenPropertyMethodType.Pointer: sb.AppendFormat("\tSIREN_METHOD_PTR({0}, {1});\r\n", SirenFactory.GetTypeName(sirenProperty.Type), sirenProperty.Name); break; case SirenPropertyMethodType.List: var itemType = sirenProperty.Type.GenericTypeArguments[0]; sb.AppendFormat("\tSIREN_METHOD_LIST({0}, {1});\r\n", SirenFactory.GetTypeName(itemType, sirenProperty.Attribute.ForceValueToPtr), sirenProperty.Name); break; case SirenPropertyMethodType.Dictionary: var keyType = sirenProperty.Type.GenericTypeArguments[0]; var valueType = sirenProperty.Type.GenericTypeArguments[1]; if (sirenProperty.Attribute.AddDictionaryMethods) { sb.AppendFormat("\tSIREN_METHOD_DICTIONARY_EX({0}, {1}, {2});\r\n", SirenFactory.GetTypeName(keyType, sirenProperty.Attribute.ForceKeyToPtr), SirenFactory.GetTypeName(valueType, sirenProperty.Attribute.ForceValueToPtr), sirenProperty.Name); } else { sb.AppendFormat("\tSIREN_METHOD_DICTIONARY({0}, {1}, {2});\r\n", SirenFactory.GetTypeName(keyType, sirenProperty.Attribute.ForceKeyToPtr), SirenFactory.GetTypeName(valueType, sirenProperty.Attribute.ForceValueToPtr), sirenProperty.Name); } break; } } return sb.ToString(); } public string GenerateHeaderField(SirenClass sirenClass) { StringBuilder sb = new StringBuilder(); //sb.AppendLine(); //add fields sb.AppendLine("protected:"); foreach (var sirenProperty in sirenClass.Properties) { var methodType = sirenProperty.MethodType; switch (methodType) { case SirenPropertyMethodType.Value: sb.AppendFormat("\t{0} m{1};\r\n", SirenFactory.GetTypeName(sirenProperty.Type), sirenProperty.Name); break; case SirenPropertyMethodType.Pointer: sb.AppendFormat("\t{0}* m{1};\r\n", SirenFactory.GetTypeName(sirenProperty.Type), sirenProperty.Name); break; case SirenPropertyMethodType.List: var itemType = sirenProperty.Type.GenericTypeArguments[0]; sb.AppendFormat("\tList<{0}> m{1};\r\n", SirenFactory.GetTypeName(itemType, sirenProperty.Attribute.ForceValueToPtr), sirenProperty.Name); break; case SirenPropertyMethodType.Dictionary: var keyType = sirenProperty.Type.GenericTypeArguments[0]; var valueType = sirenProperty.Type.GenericTypeArguments[1]; sb.AppendFormat("\tDictionary<{0}, {1}> m{2};\r\n", SirenFactory.GetTypeName(keyType, sirenProperty.Attribute.ForceKeyToPtr), SirenFactory.GetTypeName(valueType, sirenProperty.Attribute.ForceValueToPtr), sirenProperty.Name); break; } } return sb.ToString(); } public string GenerateHeaderSchema(SirenClass sirenClass) { var typeName = sirenClass.Name; StringBuilder sb = new StringBuilder(); //sb.AppendLine(); //add schema sb.AppendFormat("struct {0}::Schema\r\n", typeName); sb.AppendLine("{"); foreach (var sirenProperty in sirenClass.Properties) { var methodType = sirenProperty.MethodType; switch (methodType) { case SirenPropertyMethodType.Value: sb.AppendFormat("\tSIREN_PROPERTY({0}, {1}, {2}, {3}, {4}, m{5});\r\n", sirenProperty.Index, sirenProperty.Id, sirenProperty.Attribute.Modifier, typeName, SirenFactory.GetTypeName(sirenProperty.Type), sirenProperty.Name); break; case SirenPropertyMethodType.Pointer: sb.AppendFormat("\tSIREN_PROPERTY({0}, {1}, {2}, {3}, {4}*, m{5});\r\n", sirenProperty.Index, sirenProperty.Id, sirenProperty.Attribute.Modifier, typeName, SirenFactory.GetTypeName(sirenProperty.Type), sirenProperty.Name); break; case SirenPropertyMethodType.List: var itemType = sirenProperty.Type.GenericTypeArguments[0]; sb.AppendFormat("\tSIREN_PROPERTY_LIST({0}, {1}, {2}, {3}, {4}, m{5});\r\n", sirenProperty.Index, sirenProperty.Id, sirenProperty.Attribute.Modifier, typeName, SirenFactory.GetTypeName(itemType, sirenProperty.Attribute.ForceValueToPtr), sirenProperty.Name); break; case SirenPropertyMethodType.Dictionary: var keyType = sirenProperty.Type.GenericTypeArguments[0]; var valueType = sirenProperty.Type.GenericTypeArguments[1]; sb.AppendFormat("\tSIREN_PROPERTY_DICTIONARY({0}, {1}, {2}, {3}, {4}, {5}, m{6});\r\n", sirenProperty.Index, sirenProperty.Id, sirenProperty.Attribute.Modifier, typeName, SirenFactory.GetTypeName(keyType, sirenProperty.Attribute.ForceKeyToPtr), SirenFactory.GetTypeName(valueType, sirenProperty.Attribute.ForceValueToPtr), sirenProperty.Name); break; } } //add properties if (sirenClass.IsRoot) { sb.AppendFormat("\tSIREN_PROPERTIES_{0}(void,{1});\r\n", sirenClass.Properties.Count, typeName); } else { sb.AppendFormat("\tSIREN_PROPERTIES_{0}({1},{2});\r\n", sirenClass.Properties.Count, sirenClass.BaseSirenClass.Name, typeName); } sb.Append("};"); return sb.ToString(); } public string GenerateAllBodyInclude(SirenClass sirenClass) { StringBuilder sb = new StringBuilder(); //sb.AppendLine(); sb.AppendLine(mBodyIncludeBegin); sb.Append(GenerateBodyInclude(sirenClass)); sb.AppendLine(mBodyIncludeEnd); return sb.ToString(); } public string GenerateBodyInclude(SirenClass sirenClass) { StringBuilder sb = new StringBuilder(); //sb.AppendLine(); sb.AppendFormat("#include \"{0}.h\"\r\n", sirenClass.Type.Name); return sb.ToString(); } public string GenerateAllBody(SirenClass sirenClass) { var typeName = sirenClass.Name; StringBuilder sb = new StringBuilder(); sb.AppendFormat("{0}::{1}()\r\n", typeName, typeName); sb.AppendLine("{"); sb.AppendLine(mBodyConstructBegin); sb.Append(GenerateBodyConstruct(sirenClass)); sb.AppendLine(mBodyConstructEnd); sb.AppendLine("}"); sb.AppendLine(); sb.AppendFormat("{0}::~{1}()\r\n", typeName, typeName); sb.AppendLine("{"); sb.AppendLine(mBodyDestructBegin); sb.Append(GenerateBodyDestruct(sirenClass)); sb.AppendLine(mBodyDestructEnd); sb.AppendLine("}"); sb.AppendLine(); sb.AppendLine(mBodyMetadataBegin); sb.Append(GenerateBodyMetadata(sirenClass)); sb.AppendLine(mBodyMetadataEnd); return sb.ToString(); } public string GenerateBodyConstruct(SirenClass sirenClass) { var typeName = sirenClass.Name; StringBuilder sb = new StringBuilder(); //sb.AppendLine(); //add construct //add default assignment foreach (var sirenProperty in sirenClass.Properties) { var fieldType = sirenProperty.FieldType; switch (fieldType) { case SirenPropertyFieldType.Value: sb.AppendFormat("\tm{0} = {1};\r\n", sirenProperty.Name, sirenProperty.DefaultValueString); break; case SirenPropertyFieldType.Pointer: sb.AppendFormat("\tm{0} = NULL;\r\n", sirenProperty.Name); break; } } return sb.ToString(); } public string GenerateBodyDestruct(SirenClass sirenClass) { var typeName = sirenClass.Name; StringBuilder sb = new StringBuilder(); // sb.AppendLine(); //add destruct foreach (var sirenProperty in sirenClass.Properties) { var methodType = sirenProperty.MethodType; switch (methodType) { case SirenPropertyMethodType.Pointer: sb.AppendFormat("\tSAFE_DELETE(m{0});\r\n", sirenProperty.Name); break; case SirenPropertyMethodType.List: if (sirenProperty.Attribute.ForceValueToPtr) { sb.AppendFormat("\tSAFE_DELETE_COLLECTION(m{0});\r\n", sirenProperty.Name); } break; case SirenPropertyMethodType.Dictionary: if (sirenProperty.Attribute.ForceKeyToPtr) { if (sirenProperty.Attribute.ForceValueToPtr) { sb.AppendFormat("\tSAFE_DELETE_DICTIONARY_BOTH(m{0});\r\n", sirenProperty.Name); } else { sb.AppendFormat("\tSAFE_DELETE_DICTIONARY_KEY(m{0});\r\n", sirenProperty.Name); } } else { if (sirenProperty.Attribute.ForceValueToPtr) { sb.AppendFormat("\tSAFE_DELETE_DICTIONARY_VALUE(m{0});\r\n", sirenProperty.Name); } else { } } break; } } return sb.ToString(); } public string GenerateBodyMetadata(SirenClass sirenClass) { var typeName = sirenClass.Name; StringBuilder sb = new StringBuilder(); // sb.AppendLine(); //add class metadata sb.AppendFormat("SIREN_METADATA({0}, {1});\r\n", typeName, typeName.Length); //add property metadata int index = 0; foreach (var sirenProperty in sirenClass.Properties) { var fieldType = sirenProperty.FieldType; switch (fieldType) { case SirenPropertyFieldType.Value: { bool hasDefault = sirenProperty.Attribute.DefaultValue != null; string str2 = hasDefault.ToString().ToLower(); sb.AppendFormat("SIREN_PROPERTY_METADATA({0}, {1}, {2}, {3}, {4}, {5});\r\n", index, typeName, sirenProperty.Name, sirenProperty.Name.Length, sirenProperty.DefaultValueString, str2); } break; case SirenPropertyFieldType.Pointer: case SirenPropertyFieldType.Struct: case SirenPropertyFieldType.String: case SirenPropertyFieldType.Blob: case SirenPropertyFieldType.List: case SirenPropertyFieldType.Dictionary: sb.AppendFormat("SIREN_PROPERTY_METADATA_STRUCT({0}, {1}, {2}, {3});\r\n", index, typeName, sirenProperty.Name, sirenProperty.Name.Length); break; } ++index; } return sb.ToString(); } public string GenerateEnumHeader(SirenClass sirenClass) { var typeName = sirenClass.Name; StringBuilder sb = new StringBuilder(); var names = Enum.GetNames(sirenClass.Type); var values = Enum.GetValues(sirenClass.Type); int count = names.Length; switch (sirenClass.Attribute.Mode) { case SirenGenerateMode.CustomEnum: sb.AppendFormat("STRONG_ENUM_CUSTOM_{0}({1}", count, typeName); for (int i = 0; i < count; i++) { var name = names[i]; var val = values.GetValue(i); int v = Convert.ToInt32(val); sb.AppendFormat(",{0},{1}", name, v); } sb.AppendLine(");"); break; case SirenGenerateMode.CustomFlag: sb.AppendFormat("STRONG_FLAGS_CUSTOM_{0}({1}", count, typeName); for (int i = 0; i < count; i++) { var name = names[i]; var val = values.GetValue(i); int v = Convert.ToInt32(val); sb.AppendFormat(",{0},{1}", name, v); } sb.AppendLine(");"); break; default: { if (string.IsNullOrEmpty(sirenClass.Attribute.EnumUnderType)) { sb.AppendFormat("enum class {0}\r\n", typeName); } else { sb.AppendFormat("enum class {0}:{1}\r\n", typeName, sirenClass.Attribute.EnumUnderType); } sb.AppendLine("{"); for (int i = 0; i < count; i++) { var name = names[i]; var val = values.GetValue(i); int v = Convert.ToInt32(val); sb.AppendFormat("\t{0} = {1},\r\n", name, v); } sb.AppendLine("};"); break; } } return sb.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.Extensions.Primitives; using Xunit; namespace Microsoft.AspNetCore.Mvc.IntegrationTests { public class FormFileModelBindingIntegrationTest { private class Person { public Address Address { get; set; } } private class Address { public int Zip { get; set; } public IFormFile File { get; set; } } [Fact] public async Task BindProperty_WithData_WithEmptyPrefix_GetsBound() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "Parameter1", BindingInfo = new BindingInfo(), ParameterType = typeof(Person) }; var data = "Some Data Is Better Than No Data."; var testContext = ModelBindingTestHelper.GetTestContext( request => { request.QueryString = QueryString.Create("Address.Zip", "12345"); UpdateRequest(request, data, "Address.File"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var boundPerson = Assert.IsType<Person>(modelBindingResult.Model); Assert.NotNull(boundPerson.Address); var file = Assert.IsAssignableFrom<IFormFile>(boundPerson.Address.File); Assert.Equal("form-data; name=Address.File; filename=text.txt", file.ContentDisposition); var reader = new StreamReader(boundPerson.Address.File.OpenReadStream()); Assert.Equal(data, reader.ReadToEnd()); // ModelState Assert.True(modelState.IsValid); Assert.Equal(2, modelState.Count); Assert.Single(modelState.Keys, k => k == "Address.Zip"); var key = Assert.Single(modelState.Keys, k => k == "Address.File"); Assert.Null(modelState[key].RawValue); Assert.Empty(modelState[key].Errors); Assert.Equal(ModelValidationState.Valid, modelState[key].ValidationState); } [Fact] public async Task BindProperty_WithOnlyFormFile_WithEmptyPrefix() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "Parameter1", BindingInfo = new BindingInfo(), ParameterType = typeof(Person) }; var data = "Some Data Is Better Than No Data."; var testContext = ModelBindingTestHelper.GetTestContext( request => { UpdateRequest(request, data, "Address.File"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var boundPerson = Assert.IsType<Person>(modelBindingResult.Model); Assert.NotNull(boundPerson.Address); var file = Assert.IsAssignableFrom<IFormFile>(boundPerson.Address.File); Assert.Equal("form-data; name=Address.File; filename=text.txt", file.ContentDisposition); using var reader = new StreamReader(boundPerson.Address.File.OpenReadStream()); Assert.Equal(data, reader.ReadToEnd()); // ModelState Assert.True(modelState.IsValid); Assert.Collection( modelState.OrderBy(kvp => kvp.Key), kvp => { var (key, value) = kvp; Assert.Equal("Address.File", kvp.Key); Assert.Null(value.RawValue); Assert.Empty(value.Errors); Assert.Equal(ModelValidationState.Valid, value.ValidationState); }); } [Fact] public async Task BindProperty_WithOnlyFormFile_WithPrefix() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "Parameter1", BindingInfo = new BindingInfo(), ParameterType = typeof(Person) }; var data = "Some Data Is Better Than No Data."; var testContext = ModelBindingTestHelper.GetTestContext( request => { UpdateRequest(request, data, "Parameter1.Address.File"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var boundPerson = Assert.IsType<Person>(modelBindingResult.Model); Assert.NotNull(boundPerson.Address); var file = Assert.IsAssignableFrom<IFormFile>(boundPerson.Address.File); Assert.Equal("form-data; name=Parameter1.Address.File; filename=text.txt", file.ContentDisposition); using var reader = new StreamReader(boundPerson.Address.File.OpenReadStream()); Assert.Equal(data, reader.ReadToEnd()); // ModelState Assert.True(modelState.IsValid); Assert.Collection( modelState.OrderBy(kvp => kvp.Key), kvp => { var (key, value) = kvp; Assert.Equal("Parameter1.Address.File", kvp.Key); Assert.Null(value.RawValue); Assert.Empty(value.Errors); Assert.Equal(ModelValidationState.Valid, value.ValidationState); }); } private class Group { public string GroupName { get; set; } public Person Person { get; set; } } [Fact] public async Task BindProperty_OnFormFileInNestedSubClass_AtSecondLevel_WhenSiblingPropertyIsSpecified() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "Parameter1", BindingInfo = new BindingInfo(), ParameterType = typeof(Group) }; var data = "Some Data Is Better Than No Data."; var testContext = ModelBindingTestHelper.GetTestContext( request => { request.QueryString = QueryString.Create("Person.Address.Zip", "98056"); UpdateRequest(request, data, "Person.Address.File"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var group = Assert.IsType<Group>(modelBindingResult.Model); Assert.Null(group.GroupName); var boundPerson = group.Person; Assert.NotNull(boundPerson); Assert.NotNull(boundPerson.Address); var file = Assert.IsAssignableFrom<IFormFile>(boundPerson.Address.File); Assert.Equal("form-data; name=Person.Address.File; filename=text.txt", file.ContentDisposition); using var reader = new StreamReader(boundPerson.Address.File.OpenReadStream()); Assert.Equal(data, reader.ReadToEnd()); Assert.Equal(98056, boundPerson.Address.Zip); // ModelState Assert.True(modelState.IsValid); Assert.Collection( modelState.OrderBy(kvp => kvp.Key), kvp => { var (key, value) = kvp; Assert.Equal("Person.Address.File", kvp.Key); Assert.Null(value.RawValue); Assert.Empty(value.Errors); Assert.Equal(ModelValidationState.Valid, value.ValidationState); }, kvp => { var (key, value) = kvp; Assert.Equal("Person.Address.Zip", kvp.Key); Assert.Equal("98056", value.RawValue); Assert.Empty(value.Errors); Assert.Equal(ModelValidationState.Valid, value.ValidationState); }); } private class Fleet { public int? Id { get; set; } public FleetGarage Garage { get; set; } } public class FleetGarage { public string Name { get; set; } public FleetVehicle[] Vehicles { get; set; } } public class FleetVehicle { public string Name { get; set; } public IFormFile Spec { get; set; } public FleetVehicle BackupVehicle { get; set; } } [Fact] public async Task BindProperty_OnFormFileInNestedSubClass_AtSecondLevel_RecursiveModel() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "fleet", BindingInfo = new BindingInfo(), ParameterType = typeof(Fleet) }; var data = "Some Data Is Better Than No Data."; var testContext = ModelBindingTestHelper.GetTestContext( request => { request.QueryString = QueryString.Create("fleet.Garage.Name", "WestEnd"); UpdateRequest(request, data, "fleet.Garage.Vehicles[0].Spec"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var fleet = Assert.IsType<Fleet>(modelBindingResult.Model); Assert.Null(fleet.Id); Assert.NotNull(fleet.Garage); Assert.NotNull(fleet.Garage.Vehicles); var vehicle = Assert.Single(fleet.Garage.Vehicles); var file = Assert.IsAssignableFrom<IFormFile>(vehicle.Spec); using var reader = new StreamReader(file.OpenReadStream()); Assert.Equal(data, reader.ReadToEnd()); Assert.Null(vehicle.Name); Assert.Null(vehicle.BackupVehicle); // ModelState Assert.True(modelState.IsValid); Assert.Collection( modelState.OrderBy(kvp => kvp.Key), kvp => { var (key, value) = kvp; Assert.Equal("fleet.Garage.Name", kvp.Key); Assert.Equal("WestEnd", value.RawValue); Assert.Empty(value.Errors); Assert.Equal(ModelValidationState.Valid, value.ValidationState); }, kvp => { var (key, value) = kvp; Assert.Equal("fleet.Garage.Vehicles[0].Spec", kvp.Key); Assert.Equal(ModelValidationState.Valid, value.ValidationState); }); } [Fact] public async Task BindProperty_OnFormFileInNestedSubClass_AtThirdLevel_RecursiveModel() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "fleet", BindingInfo = new BindingInfo(), ParameterType = typeof(Fleet) }; var data = "Some Data Is Better Than No Data."; var testContext = ModelBindingTestHelper.GetTestContext( request => { request.QueryString = QueryString.Create("fleet.Garage.Name", "WestEnd"); UpdateRequest(request, data, "fleet.Garage.Vehicles[0].BackupVehicle.Spec"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var fleet = Assert.IsType<Fleet>(modelBindingResult.Model); Assert.Null(fleet.Id); Assert.NotNull(fleet.Garage); Assert.NotNull(fleet.Garage.Vehicles); var vehicle = Assert.Single(fleet.Garage.Vehicles); Assert.Null(vehicle.Spec); Assert.NotNull(vehicle.BackupVehicle); var file = Assert.IsAssignableFrom<IFormFile>(vehicle.BackupVehicle.Spec); using var reader = new StreamReader(file.OpenReadStream()); Assert.Equal(data, reader.ReadToEnd()); Assert.Null(vehicle.Name); // ModelState Assert.True(modelState.IsValid); Assert.Collection( modelState.OrderBy(kvp => kvp.Key), kvp => { var (key, value) = kvp; Assert.Equal("fleet.Garage.Name", kvp.Key); Assert.Equal("WestEnd", value.RawValue); Assert.Empty(value.Errors); Assert.Equal(ModelValidationState.Valid, value.ValidationState); }, kvp => { var (key, value) = kvp; Assert.Equal("fleet.Garage.Vehicles[0].BackupVehicle.Spec", kvp.Key); Assert.Equal(ModelValidationState.Valid, value.ValidationState); }); } [Fact] public async Task BindProperty_OnFormFileInNestedSubClass_AtSecondLevel_WhenSiblingPropertiesAreNotSpecified() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "Parameter1", BindingInfo = new BindingInfo(), ParameterType = typeof(Group) }; var data = "Some Data Is Better Than No Data."; var testContext = ModelBindingTestHelper.GetTestContext( request => { request.QueryString = QueryString.Create("GroupName", "TestGroup"); UpdateRequest(request, data, "Person.Address.File"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var group = Assert.IsType<Group>(modelBindingResult.Model); Assert.Equal("TestGroup", group.GroupName); var boundPerson = group.Person; Assert.NotNull(boundPerson); Assert.NotNull(boundPerson.Address); var file = Assert.IsAssignableFrom<IFormFile>(boundPerson.Address.File); Assert.Equal("form-data; name=Person.Address.File; filename=text.txt", file.ContentDisposition); using var reader = new StreamReader(boundPerson.Address.File.OpenReadStream()); Assert.Equal(data, reader.ReadToEnd()); Assert.Equal(0, boundPerson.Address.Zip); // ModelState Assert.True(modelState.IsValid); Assert.Collection( modelState.OrderBy(kvp => kvp.Key), kvp => { var (key, value) = kvp; Assert.Equal("GroupName", kvp.Key); Assert.Equal("TestGroup", value.RawValue); Assert.Empty(value.Errors); Assert.Equal(ModelValidationState.Valid, value.ValidationState); }, kvp => { var (key, value) = kvp; Assert.Equal("Person.Address.File", kvp.Key); Assert.Null(value.RawValue); Assert.Empty(value.Errors); Assert.Equal(ModelValidationState.Valid, value.ValidationState); }); } private class ListContainer1 { [ModelBinder(Name = "files")] public List<IFormFile> ListProperty { get; set; } } [Fact] public async Task BindCollectionProperty_WithData_IsBound() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor { Name = "Parameter1", BindingInfo = new BindingInfo(), ParameterType = typeof(ListContainer1), }; var data = "some data"; var testContext = ModelBindingTestHelper.GetTestContext( request => UpdateRequest(request, data, "files")); var modelState = testContext.ModelState; // Act var result = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(result.IsModelSet); // Model var boundContainer = Assert.IsType<ListContainer1>(result.Model); Assert.NotNull(boundContainer); Assert.NotNull(boundContainer.ListProperty); var file = Assert.Single(boundContainer.ListProperty); Assert.Equal("form-data; name=files; filename=text.txt", file.ContentDisposition); using (var reader = new StreamReader(file.OpenReadStream())) { Assert.Equal(data, reader.ReadToEnd()); } // ModelState Assert.True(modelState.IsValid); var kvp = Assert.Single(modelState); Assert.Equal("files", kvp.Key); var modelStateEntry = kvp.Value; Assert.NotNull(modelStateEntry); Assert.Empty(modelStateEntry.Errors); Assert.Equal(ModelValidationState.Valid, modelStateEntry.ValidationState); Assert.Null(modelStateEntry.AttemptedValue); Assert.Null(modelStateEntry.RawValue); } [Fact] public async Task BindCollectionProperty_NoData_IsNotBound() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor { Name = "Parameter1", BindingInfo = new BindingInfo(), ParameterType = typeof(ListContainer1), }; var testContext = ModelBindingTestHelper.GetTestContext( request => UpdateRequest(request, data: null, name: null)); var modelState = testContext.ModelState; // Act var result = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(result.IsModelSet); // Model (bound to an empty collection) var boundContainer = Assert.IsType<ListContainer1>(result.Model); Assert.NotNull(boundContainer); Assert.Null(boundContainer.ListProperty); // ModelState Assert.True(modelState.IsValid); Assert.Empty(modelState); } private class ListContainer2 { [ModelBinder(Name = "files")] public List<IFormFile> ListProperty { get; } = new List<IFormFile> { new FormFile(new MemoryStream(), baseStreamOffset: 0, length: 0, name: "file", fileName: "file1"), new FormFile(new MemoryStream(), baseStreamOffset: 0, length: 0, name: "file", fileName: "file2"), new FormFile(new MemoryStream(), baseStreamOffset: 0, length: 0, name: "file", fileName: "file3"), }; } [Fact] public async Task BindReadOnlyCollectionProperty_WithData_IsBound() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor { Name = "Parameter1", BindingInfo = new BindingInfo(), ParameterType = typeof(ListContainer2), }; var data = "some data"; var testContext = ModelBindingTestHelper.GetTestContext( request => UpdateRequest(request, data, "files")); var modelState = testContext.ModelState; // Act var result = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(result.IsModelSet); // Model var boundContainer = Assert.IsType<ListContainer2>(result.Model); Assert.NotNull(boundContainer); Assert.NotNull(boundContainer.ListProperty); var file = Assert.Single(boundContainer.ListProperty); Assert.Equal("form-data; name=files; filename=text.txt", file.ContentDisposition); using (var reader = new StreamReader(file.OpenReadStream())) { Assert.Equal(data, reader.ReadToEnd()); } // ModelState Assert.True(modelState.IsValid); var kvp = Assert.Single(modelState); Assert.Equal("files", kvp.Key); var modelStateEntry = kvp.Value; Assert.NotNull(modelStateEntry); Assert.Empty(modelStateEntry.Errors); Assert.Equal(ModelValidationState.Valid, modelStateEntry.ValidationState); Assert.Null(modelStateEntry.AttemptedValue); Assert.Null(modelStateEntry.RawValue); } [Fact] public async Task BindParameter_WithData_GetsBound() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor { Name = "Parameter1", BindingInfo = new BindingInfo { // Setting a custom parameter prevents it from falling back to an empty prefix. BinderModelName = "CustomParameter", }, ParameterType = typeof(IFormFile) }; var data = "Some Data Is Better Than No Data."; var testContext = ModelBindingTestHelper.GetTestContext( request => { UpdateRequest(request, data, "CustomParameter"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var file = Assert.IsType<FormFile>(modelBindingResult.Model); Assert.NotNull(file); Assert.Equal("form-data; name=CustomParameter; filename=text.txt", file.ContentDisposition); var reader = new StreamReader(file.OpenReadStream()); Assert.Equal(data, reader.ReadToEnd()); // ModelState Assert.True(modelState.IsValid); var entry = Assert.Single(modelState); Assert.Equal("CustomParameter", entry.Key); Assert.Empty(entry.Value.Errors); Assert.Equal(ModelValidationState.Valid, entry.Value.ValidationState); Assert.Null(entry.Value.AttemptedValue); Assert.Null(entry.Value.RawValue); } [Fact] public async Task BindParameter_NoData_DoesNotGetBound() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "Parameter1", BindingInfo = new BindingInfo() { BinderModelName = "CustomParameter", }, ParameterType = typeof(IFormFile) }; // No data is passed. var testContext = ModelBindingTestHelper.GetTestContext( request => UpdateRequest(request, data: null, name: null)); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.False(modelBindingResult.IsModelSet); // ModelState Assert.True(modelState.IsValid); Assert.Empty(modelState.Keys); } private class Car1 { public string Name { get; set; } public FormFileCollection Specs { get; set; } } [Fact] public async Task BindProperty_WithData_WithPrefix_GetsBound() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor { Name = "p", BindingInfo = new BindingInfo(), ParameterType = typeof(Car1) }; var data = "Some Data Is Better Than No Data."; var testContext = ModelBindingTestHelper.GetTestContext( request => { request.QueryString = QueryString.Create("p.Name", "Accord"); UpdateRequest(request, data, "p.Specs"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var car = Assert.IsType<Car1>(modelBindingResult.Model); Assert.NotNull(car.Specs); var file = Assert.Single(car.Specs); Assert.Equal("form-data; name=p.Specs; filename=text.txt", file.ContentDisposition); var reader = new StreamReader(file.OpenReadStream()); Assert.Equal(data, reader.ReadToEnd()); // ModelState Assert.True(modelState.IsValid); Assert.Equal(2, modelState.Count); var entry = Assert.Single(modelState, e => e.Key == "p.Name").Value; Assert.Equal("Accord", entry.AttemptedValue); Assert.Equal("Accord", entry.RawValue); Assert.Single(modelState, e => e.Key == "p.Specs"); } private class House { public Garage Garage { get; set; } } private class Garage { public List<Car1> Cars { get; set; } } [Fact] public async Task BindProperty_FormFileCollectionInCollection_WithPrefix() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor { Name = "house", BindingInfo = new BindingInfo(), ParameterType = typeof(House) }; var data = "Some Data Is Better Than No Data."; var testContext = ModelBindingTestHelper.GetTestContext( request => { request.QueryString = QueryString.Create("house.Garage.Cars[0].Name", "Accord"); UpdateRequest(request, data + 1, "house.Garage.Cars[0].Specs"); AddFormFile(request, data + 2, "house.Garage.Cars[1].Specs"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var house = Assert.IsType<House>(modelBindingResult.Model); Assert.NotNull(house.Garage); Assert.NotNull(house.Garage.Cars); Assert.Collection( house.Garage.Cars, car => { Assert.Equal("Accord", car.Name); var file = Assert.Single(car.Specs); using var reader = new StreamReader(file.OpenReadStream()); Assert.Equal(data + 1, reader.ReadToEnd()); }, car => { Assert.Null(car.Name); var file = Assert.Single(car.Specs); using var reader = new StreamReader(file.OpenReadStream()); Assert.Equal(data + 2, reader.ReadToEnd()); }); // ModelState Assert.True(modelState.IsValid); Assert.Equal(3, modelState.Count); var entry = Assert.Single(modelState, e => e.Key == "house.Garage.Cars[0].Name").Value; Assert.Equal("Accord", entry.AttemptedValue); Assert.Equal("Accord", entry.RawValue); Assert.Single(modelState, e => e.Key == "house.Garage.Cars[0].Specs"); Assert.Single(modelState, e => e.Key == "house.Garage.Cars[1].Specs"); } [Fact] public async Task BindProperty_FormFileCollectionInCollection_OnlyFiles() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor { Name = "house", BindingInfo = new BindingInfo(), ParameterType = typeof(House) }; var data = "Some Data Is Better Than No Data."; var testContext = ModelBindingTestHelper.GetTestContext( request => { UpdateRequest(request, data + 1, "house.Garage.Cars[0].Specs"); AddFormFile(request, data + 2, "house.Garage.Cars[1].Specs"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var house = Assert.IsType<House>(modelBindingResult.Model); Assert.NotNull(house.Garage); Assert.NotNull(house.Garage.Cars); Assert.Collection( house.Garage.Cars, car => { Assert.Null(car.Name); var file = Assert.Single(car.Specs); using var reader = new StreamReader(file.OpenReadStream()); Assert.Equal(data + 1, reader.ReadToEnd()); }, car => { Assert.Null(car.Name); var file = Assert.Single(car.Specs); using var reader = new StreamReader(file.OpenReadStream()); Assert.Equal(data + 2, reader.ReadToEnd()); }); // ModelState Assert.True(modelState.IsValid); Assert.Equal(2, modelState.Count); Assert.Single(modelState, e => e.Key == "house.Garage.Cars[0].Specs"); Assert.Single(modelState, e => e.Key == "house.Garage.Cars[1].Specs"); } [Fact] public async Task BindProperty_FormFileCollectionInCollection_OutOfOrderFile() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor { Name = "house", BindingInfo = new BindingInfo(), ParameterType = typeof(House) }; var data = "Some Data Is Better Than No Data."; var testContext = ModelBindingTestHelper.GetTestContext( request => { UpdateRequest(request, data + 1, "house.Garage.Cars[800].Specs"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var house = Assert.IsType<House>(modelBindingResult.Model); Assert.NotNull(house.Garage); Assert.Empty(house.Garage.Cars); // ModelState Assert.True(modelState.IsValid); Assert.Empty(modelState); } [Fact] public async Task BindProperty_FormFileCollectionInCollection_MultipleFiles() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor { Name = "house", BindingInfo = new BindingInfo(), ParameterType = typeof(House) }; var data = "Some Data Is Better Than No Data."; var testContext = ModelBindingTestHelper.GetTestContext( request => { UpdateRequest(request, data + 1, "house.Garage.Cars[0].Specs"); AddFormFile(request, data + 2, "house.Garage.Cars[0].Specs"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var house = Assert.IsType<House>(modelBindingResult.Model); Assert.NotNull(house.Garage); Assert.NotNull(house.Garage.Cars); Assert.Collection( house.Garage.Cars, car => { Assert.Null(car.Name); Assert.Collection( car.Specs, file => { using var reader = new StreamReader(file.OpenReadStream()); Assert.Equal(data + 1, reader.ReadToEnd()); }, file => { using var reader = new StreamReader(file.OpenReadStream()); Assert.Equal(data + 2, reader.ReadToEnd()); }); }); // ModelState Assert.True(modelState.IsValid); var kvp = Assert.Single(modelState); Assert.Equal("house.Garage.Cars[0].Specs", kvp.Key); } [Fact] public async Task BindProperty_FormFile_AsAPropertyOnNestedColection() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor { Name = "p", BindingInfo = new BindingInfo(), ParameterType = typeof(Car1) }; var data = "Some Data Is Better Than No Data."; var testContext = ModelBindingTestHelper.GetTestContext( request => { request.QueryString = QueryString.Create("p.Name", "Accord"); UpdateRequest(request, data, "p.Specs"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var car = Assert.IsType<Car1>(modelBindingResult.Model); Assert.NotNull(car.Specs); var file = Assert.Single(car.Specs); Assert.Equal("form-data; name=p.Specs; filename=text.txt", file.ContentDisposition); var reader = new StreamReader(file.OpenReadStream()); Assert.Equal(data, reader.ReadToEnd()); // ModelState Assert.True(modelState.IsValid); Assert.Equal(2, modelState.Count); var entry = Assert.Single(modelState, e => e.Key == "p.Name").Value; Assert.Equal("Accord", entry.AttemptedValue); Assert.Equal("Accord", entry.RawValue); Assert.Single(modelState, e => e.Key == "p.Specs"); } public class MultiDimensionalFormFileContainer { public IFormFile[][] FormFiles { get; set; } } [Fact] public async Task BindModelAsync_MultiDimensionalFormFile_Works() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor { Name = "p", BindingInfo = new BindingInfo(), ParameterType = typeof(MultiDimensionalFormFileContainer) }; var data = "Some Data Is Better Than No Data."; var testContext = ModelBindingTestHelper.GetTestContext( request => { UpdateRequest(request, data + 1, "FormFiles[0]"); AddFormFile(request, data + 2, "FormFiles[1]"); AddFormFile(request, data + 3, "FormFiles[1]"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var container = Assert.IsType<MultiDimensionalFormFileContainer>(modelBindingResult.Model); Assert.NotNull(container.FormFiles); Assert.Collection( container.FormFiles, item => { Assert.Collection( item, file => Assert.Equal(data + 1, ReadFormFile(file))); }, item => { Assert.Collection( item, file => Assert.Equal(data + 2, ReadFormFile(file)), file => Assert.Equal(data + 3, ReadFormFile(file))); }); } [Fact] public async Task BindModelAsync_MultiDimensionalFormFile_WithArrayNotation() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor { Name = "p", BindingInfo = new BindingInfo(), ParameterType = typeof(MultiDimensionalFormFileContainer) }; var data = "Some Data Is Better Than No Data."; var testContext = ModelBindingTestHelper.GetTestContext( request => { UpdateRequest(request, data + 1, "FormFiles[0][0]"); AddFormFile(request, data + 2, "FormFiles[1][0]"); AddFormFile(request, data + 3, "FormFiles[1][0]"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); var container = Assert.IsType<MultiDimensionalFormFileContainer>(modelBindingResult.Model); Assert.NotNull(container.FormFiles); Assert.Empty(container.FormFiles); } public class MultiDimensionalFormFileContainerLevel2 { public MultiDimensionalFormFileContainerLevel1 Level1 { get; set; } } public class MultiDimensionalFormFileContainerLevel1 { public MultiDimensionalFormFileContainer Container { get; set; } } [Fact] public async Task BindModelAsync_DeeplyNestedMultiDimensionalFormFile_Works() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor { Name = "p", BindingInfo = new BindingInfo(), ParameterType = typeof(MultiDimensionalFormFileContainerLevel2) }; var data = "Some Data Is Better Than No Data."; var testContext = ModelBindingTestHelper.GetTestContext( request => { UpdateRequest(request, data + 1, "p.Level1.Container.FormFiles[0]"); AddFormFile(request, data + 2, "p.Level1.Container.FormFiles[1]"); AddFormFile(request, data + 3, "p.Level1.Container.FormFiles[1]"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var level2 = Assert.IsType<MultiDimensionalFormFileContainerLevel2>(modelBindingResult.Model); Assert.NotNull(level2.Level1); var container = level2.Level1.Container; Assert.NotNull(container); Assert.NotNull(container.FormFiles); Assert.Collection( container.FormFiles, item => { Assert.Collection( item, file => Assert.Equal(data + 1, ReadFormFile(file))); }, item => { Assert.Collection( item, file => Assert.Equal(data + 2, ReadFormFile(file)), file => Assert.Equal(data + 3, ReadFormFile(file))); }); } public class DictionaryContainer { public Dictionary<string, IFormFile> Dictionary { get; set; } } [Fact] public async Task BindModelAsync_DictionaryOfFormFiles() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor { Name = "p", BindingInfo = new BindingInfo(), ParameterType = typeof(DictionaryContainer) }; var data = "Some Data Is Better Than No Data."; var testContext = ModelBindingTestHelper.GetTestContext( request => { request.QueryString = QueryString.Create(new Dictionary<string, string> { { "p.Dictionary[0].Key", "key0" }, { "p.Dictionary[1].Key", "key1" }, { "p.Dictionary[4000].Key", "key1" }, }); UpdateRequest(request, data + 1, "p.Dictionary[0].Value"); AddFormFile(request, data + 2, "p.Dictionary[1].Value"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var container = Assert.IsType<DictionaryContainer>(modelBindingResult.Model); Assert.NotNull(container.Dictionary); Assert.Collection( container.Dictionary.OrderBy(kvp => kvp.Key), kvp => { Assert.Equal("key0", kvp.Key); Assert.Equal(data + 1, ReadFormFile(kvp.Value)); }, kvp => { Assert.Equal("key1", kvp.Key); Assert.Equal(data + 2, ReadFormFile(kvp.Value)); }); } private static string ReadFormFile(IFormFile file) { using var reader = new StreamReader(file.OpenReadStream()); return reader.ReadToEnd(); } private void UpdateRequest(HttpRequest request, string data, string name) { var formCollection = new FormCollection(new Dictionary<string, StringValues>(), new FormFileCollection()); request.Form = formCollection; request.ContentType = "multipart/form-data; boundary=----WebKitFormBoundarymx2fSWqWSd0OxQqq"; AddFormFile(request, data, name); } private void AddFormFile(HttpRequest request, string data, string name) { const string fileName = "text.txt"; if (string.IsNullOrEmpty(data) || string.IsNullOrEmpty(name)) { // Leave the submission empty. return; } request.Headers["Content-Disposition"] = $"form-data; name={name}; filename={fileName}"; var fileCollection = (FormFileCollection)request.Form.Files; var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(data)); fileCollection.Add(new FormFile(memoryStream, 0, data.Length, name, fileName) { Headers = request.Headers }); } } }
/******************************************************************************* * Copyright 2009-2015 Amazon Services. 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://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. ******************************************************************************* * Get Lowest Offer Listings For SKU Request * API Version: 2011-10-01 * Library Version: 2015-09-01 * Generated: Thu Sep 10 06:52:19 PDT 2015 */ using System; using System.Xml; using System.Xml.Serialization; using MWSClientCsRuntime; namespace MarketplaceWebServiceProducts.Model { [XmlTypeAttribute(Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01")] [XmlRootAttribute(Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01", IsNullable = false)] public class GetLowestOfferListingsForSKURequest : AbstractMwsObject { private string _sellerId; private string _mwsAuthToken; private string _marketplaceId; private SellerSKUListType _sellerSKUList; private string _itemCondition; private bool? _excludeMe; /// <summary> /// Gets and sets the SellerId property. /// </summary> [XmlElementAttribute(ElementName = "SellerId")] public string SellerId { get { return this._sellerId; } set { this._sellerId = value; } } /// <summary> /// Sets the SellerId property. /// </summary> /// <param name="sellerId">SellerId property.</param> /// <returns>this instance.</returns> public GetLowestOfferListingsForSKURequest WithSellerId(string sellerId) { this._sellerId = sellerId; return this; } /// <summary> /// Checks if SellerId property is set. /// </summary> /// <returns>true if SellerId property is set.</returns> public bool IsSetSellerId() { return this._sellerId != null; } /// <summary> /// Gets and sets the MWSAuthToken property. /// </summary> [XmlElementAttribute(ElementName = "MWSAuthToken")] public string MWSAuthToken { get { return this._mwsAuthToken; } set { this._mwsAuthToken = value; } } /// <summary> /// Sets the MWSAuthToken property. /// </summary> /// <param name="mwsAuthToken">MWSAuthToken property.</param> /// <returns>this instance.</returns> public GetLowestOfferListingsForSKURequest WithMWSAuthToken(string mwsAuthToken) { this._mwsAuthToken = mwsAuthToken; return this; } /// <summary> /// Checks if MWSAuthToken property is set. /// </summary> /// <returns>true if MWSAuthToken property is set.</returns> public bool IsSetMWSAuthToken() { return this._mwsAuthToken != null; } /// <summary> /// Gets and sets the MarketplaceId property. /// </summary> [XmlElementAttribute(ElementName = "MarketplaceId")] public string MarketplaceId { get { return this._marketplaceId; } set { this._marketplaceId = value; } } /// <summary> /// Sets the MarketplaceId property. /// </summary> /// <param name="marketplaceId">MarketplaceId property.</param> /// <returns>this instance.</returns> public GetLowestOfferListingsForSKURequest WithMarketplaceId(string marketplaceId) { this._marketplaceId = marketplaceId; return this; } /// <summary> /// Checks if MarketplaceId property is set. /// </summary> /// <returns>true if MarketplaceId property is set.</returns> public bool IsSetMarketplaceId() { return this._marketplaceId != null; } /// <summary> /// Gets and sets the SellerSKUList property. /// </summary> [XmlElementAttribute(ElementName = "SellerSKUList")] public SellerSKUListType SellerSKUList { get { return this._sellerSKUList; } set { this._sellerSKUList = value; } } /// <summary> /// Sets the SellerSKUList property. /// </summary> /// <param name="sellerSKUList">SellerSKUList property.</param> /// <returns>this instance.</returns> public GetLowestOfferListingsForSKURequest WithSellerSKUList(SellerSKUListType sellerSKUList) { this._sellerSKUList = sellerSKUList; return this; } /// <summary> /// Checks if SellerSKUList property is set. /// </summary> /// <returns>true if SellerSKUList property is set.</returns> public bool IsSetSellerSKUList() { return this._sellerSKUList != null; } /// <summary> /// Gets and sets the ItemCondition property. /// </summary> [XmlElementAttribute(ElementName = "ItemCondition")] public string ItemCondition { get { return this._itemCondition; } set { this._itemCondition = value; } } /// <summary> /// Sets the ItemCondition property. /// </summary> /// <param name="itemCondition">ItemCondition property.</param> /// <returns>this instance.</returns> public GetLowestOfferListingsForSKURequest WithItemCondition(string itemCondition) { this._itemCondition = itemCondition; return this; } /// <summary> /// Checks if ItemCondition property is set. /// </summary> /// <returns>true if ItemCondition property is set.</returns> public bool IsSetItemCondition() { return this._itemCondition != null; } /// <summary> /// Gets and sets the ExcludeMe property. /// </summary> [XmlElementAttribute(ElementName = "ExcludeMe")] public bool ExcludeMe { get { return this._excludeMe.GetValueOrDefault(); } set { this._excludeMe = value; } } /// <summary> /// Sets the ExcludeMe property. /// </summary> /// <param name="excludeMe">ExcludeMe property.</param> /// <returns>this instance.</returns> public GetLowestOfferListingsForSKURequest WithExcludeMe(bool excludeMe) { this._excludeMe = excludeMe; return this; } /// <summary> /// Checks if ExcludeMe property is set. /// </summary> /// <returns>true if ExcludeMe property is set.</returns> public bool IsSetExcludeMe() { return this._excludeMe != null; } public override void ReadFragmentFrom(IMwsReader reader) { _sellerId = reader.Read<string>("SellerId"); _mwsAuthToken = reader.Read<string>("MWSAuthToken"); _marketplaceId = reader.Read<string>("MarketplaceId"); _sellerSKUList = reader.Read<SellerSKUListType>("SellerSKUList"); _itemCondition = reader.Read<string>("ItemCondition"); _excludeMe = reader.Read<bool?>("ExcludeMe"); } public override void WriteFragmentTo(IMwsWriter writer) { writer.Write("SellerId", _sellerId); writer.Write("MWSAuthToken", _mwsAuthToken); writer.Write("MarketplaceId", _marketplaceId); writer.Write("SellerSKUList", _sellerSKUList); writer.Write("ItemCondition", _itemCondition); writer.Write("ExcludeMe", _excludeMe); } public override void WriteTo(IMwsWriter writer) { writer.Write("http://mws.amazonservices.com/schema/Products/2011-10-01", "GetLowestOfferListingsForSKURequest", this); } public GetLowestOfferListingsForSKURequest() : base() { } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Codetopia.Graphics.ParticleSystem; namespace CH22___Test_Game { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; // a 2d particle emitter Emitter2D m_emitter; // handy constants to move the emitter around private static readonly Vector2 MOVE_LEFT = new Vector2(-5, 0); private static readonly Vector2 MOVE_RIGHT = new Vector2(5, 0); private static readonly Vector2 MOVE_UP = new Vector2(0, -5); private static readonly Vector2 MOVE_DOWN = new Vector2(0, 5); // remember pressed state between frames. without this, the // action for the button would be triggered on every frame. private bool m_ButtonA = false; private bool m_ButtonB = false; private bool m_ButtonX = false; private bool m_ButtonY = false; // two example particle modifiers private static readonly Modifier2D m_ModGravity = new Modifier2DGravity(200.0f); private static readonly Modifier2D m_ModWind = new Modifier2DWind(200.0f); public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } // screen constants const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // use a fixed frame rate of 30 frames per second IsFixedTimeStep = true; TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 33); IsFixedTimeStep = false; // init back buffer graphics.PreferredBackBufferHeight = SCREEN_HEIGHT; graphics.PreferredBackBufferWidth = SCREEN_WIDTH; graphics.PreferMultiSampling = false; graphics.ApplyChanges(); // init our emitter m_emitter = new Emitter2D(); m_emitter.ParticlesPerUpdate = 20; m_emitter.MaxParticles = 15000; m_emitter.EmitterRect = new Rectangle(200, 200, 0, 0); m_emitter.RangeColor = RangedVector4.FromColors(Color.Orange, Color.Yellow); // add our modifiers to the emitter m_emitter.AddModifier(m_ModGravity); m_emitter.AddModifier(m_ModWind); // disable the modifiers for now m_ModGravity.Enabled = false; m_ModWind.Enabled = false; base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // load in particle graphic and set as texture for emitter Texture2D tex = Content.Load<Texture2D>(@"media\particle"); m_emitter.Texture = tex; } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <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) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // support for game pad and keyboard GamePadState pad1 = GamePad.GetState(PlayerIndex.One); KeyboardState key1 = Keyboard.GetState(); // move emitter left or right if (pad1.ThumbSticks.Left.X < -0.10 || key1.IsKeyDown(Keys.Left)) { m_emitter.Position += MOVE_LEFT; } else if (pad1.ThumbSticks.Left.X > 0.10 || key1.IsKeyDown(Keys.Right)) { m_emitter.Position += MOVE_RIGHT; } // move emitter up or down if (pad1.ThumbSticks.Left.Y > 0.10 || key1.IsKeyDown(Keys.Up)) { m_emitter.Position += MOVE_UP; } else if (pad1.ThumbSticks.Left.Y < -0.10 || key1.IsKeyDown(Keys.Down)) { m_emitter.Position += MOVE_DOWN; } // enable / disable gravity bool buttonPressed = (pad1.Buttons.A == ButtonState.Pressed); buttonPressed |= key1.IsKeyDown(Keys.A); if (buttonPressed && !m_ButtonA) { m_ModGravity.Enabled = !m_ModGravity.Enabled; } m_ButtonA = buttonPressed; // enable / disable wind buttonPressed = (pad1.Buttons.B == ButtonState.Pressed); buttonPressed |= key1.IsKeyDown(Keys.B); if (buttonPressed && !m_ButtonB) { m_ModWind.Enabled = !m_ModWind.Enabled; } m_ButtonB = buttonPressed; // enable / disable emitter buttonPressed = (pad1.Buttons.X == ButtonState.Pressed); buttonPressed |= key1.IsKeyDown(Keys.X); if (buttonPressed && !m_ButtonX) { m_emitter.Enabled = !m_emitter.Enabled; } m_ButtonX = buttonPressed; // mark emitter as active / inactive buttonPressed = (pad1.Buttons.Y == ButtonState.Pressed); buttonPressed |= key1.IsKeyDown(Keys.Y); if (buttonPressed && !m_ButtonY) { m_emitter.Active = !m_emitter.Active; } m_ButtonY = buttonPressed; // tell the emitter to update it's state m_emitter.Update((float)gameTime.ElapsedGameTime.TotalSeconds); base.Update(gameTime); } /// <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) { graphics.GraphicsDevice.Clear(Color.CornflowerBlue); // tell the emitter to draw the particles spriteBatch.Begin(); m_emitter.Draw(spriteBatch); spriteBatch.End(); base.Draw(gameTime); } } }
// // ButtonBackend.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using AppKit; using CoreGraphics; using Foundation; using ObjCRuntime; using Xwt.Accessibility; using Xwt.Backends; using Xwt.Drawing; namespace Xwt.Mac { public class ButtonBackend: ViewBackend<NSButton,IButtonEventSink>, IButtonBackend { ButtonType currentType; ButtonStyle currentStyle; public ButtonBackend () { } #region IButtonBackend implementation public override void Initialize () { ViewObject = new MacButton (EventSink, ApplicationContext); Widget.SetButtonType (NSButtonType.MomentaryPushIn); } public void EnableEvent (Xwt.Backends.ButtonEvent ev) { ((MacButton)Widget).EnableEvent (ev); } public void DisableEvent (Xwt.Backends.ButtonEvent ev) { ((MacButton)Widget).DisableEvent (ev); } public void SetContent (string label, bool useMnemonic, ImageDescription image, ContentPosition imagePosition) { switch (((Button)Frontend).Type) { case ButtonType.Help: case ButtonType.Disclosure: return; } if (useMnemonic) label = label.RemoveMnemonic (); if (customLabelColor.HasValue) { Widget.Title = label; var ns = new NSMutableAttributedString (Widget.AttributedTitle); ns.BeginEditing (); var r = new NSRange (0, label.Length); ns.RemoveAttribute (NSStringAttributeKey.ForegroundColor, r); ns.AddAttribute (NSStringAttributeKey.ForegroundColor, customLabelColor.Value.ToNSColor (), r); ns.EndEditing (); Widget.AttributedTitle = ns; } else Widget.Title = label ?? ""; if (string.IsNullOrEmpty (label)) imagePosition = ContentPosition.Center; if (!image.IsNull) { var img = image.ToNSImage (); Widget.Image = (NSImage)img; Widget.Cell.ImageScale = NSImageScale.None; switch (imagePosition) { case ContentPosition.Bottom: Widget.ImagePosition = NSCellImagePosition.ImageBelow; break; case ContentPosition.Left: Widget.ImagePosition = NSCellImagePosition.ImageLeft; break; case ContentPosition.Right: Widget.ImagePosition = NSCellImagePosition.ImageRight; break; case ContentPosition.Top: Widget.ImagePosition = NSCellImagePosition.ImageAbove; break; case ContentPosition.Center: Widget.ImagePosition = string.IsNullOrEmpty (label) ? NSCellImagePosition.ImageOnly : NSCellImagePosition.ImageOverlaps; break; } } else { Widget.ImagePosition = NSCellImagePosition.NoImage; Widget.Image = null; } SetButtonStyle (currentStyle); ResetFittingSize (); } public virtual void SetButtonStyle (ButtonStyle style) { currentStyle = style; if (currentType == ButtonType.Normal) { switch (style) { case ButtonStyle.Normal: if (Widget.Image != null || Frontend.MinHeight > 0 || Frontend.HeightRequest > 0 || Widget.Title.Contains (Environment.NewLine)) Widget.BezelStyle = NSBezelStyle.RegularSquare; else Widget.BezelStyle = NSBezelStyle.Rounded; Widget.ShowsBorderOnlyWhileMouseInside = false; break; case ButtonStyle.Borderless: case ButtonStyle.Flat: Widget.BezelStyle = NSBezelStyle.ShadowlessSquare; Widget.ShowsBorderOnlyWhileMouseInside = true; break; } } } public void SetButtonType (ButtonType type) { currentType = type; switch (type) { case ButtonType.Disclosure: Widget.BezelStyle = NSBezelStyle.Disclosure; Widget.Title = ""; break; case ButtonType.Help: Widget.BezelStyle = NSBezelStyle.HelpButton; Widget.Title = ""; break; default: SetButtonStyle (currentStyle); break; } } bool isDefault; public bool IsDefault { get { return isDefault; } set { isDefault = value; if (Widget.Window != null && Widget.Window.DefaultButtonCell != Widget.Cell) Widget.Window.DefaultButtonCell = Widget.Cell; } } public void SetFormattedText (FormattedText text) { if (text == null || Widget is NSPopUpButton) // NSPopUpButton has no formatting support Widget.Title = text?.Text ?? string.Empty; else Widget.AttributedTitle = text.ToAttributedString(); } #endregion public override Color BackgroundColor { get { return ((MacButton)Widget).BackgroundColor; } set { ((MacButton)Widget).BackgroundColor = value; } } Color? customLabelColor; public Color LabelColor { get { return customLabelColor.HasValue ? customLabelColor.Value : NSColor.ControlText.ToXwtColor (); } set { customLabelColor = value; var ns = new NSMutableAttributedString (Widget.AttributedTitle); ns.BeginEditing (); var r = new NSRange (0, Widget.Title.Length); ns.RemoveAttribute (NSStringAttributeKey.ForegroundColor, r); ns.AddAttribute (NSStringAttributeKey.ForegroundColor, customLabelColor.Value.ToNSColor (), r); ns.EndEditing (); Widget.AttributedTitle = ns; } } } class MacButton: NSButton, IViewObject, INSAccessibleEventSource { // // This is necessary since the Activated event for NSControl in AppKit does // not take a list of handlers, instead it supports only one handler. // // This event is used by the RadioButton backend to implement radio groups // internal event Action <MacButton> ActivatedInternal; public MacButton (NativeHandle p): base (p) { } public MacButton (IButtonEventSink eventSink, ApplicationContext context) { Cell = new ColoredButtonCell (); BezelStyle = NSBezelStyle.Rounded; Activated += delegate { context.InvokeUserCode (delegate { eventSink.OnClicked (); }); OnActivatedInternal (); }; } public MacButton () { Activated += delegate { OnActivatedInternal (); }; } public MacButton (IRadioButtonEventSink eventSink, ApplicationContext context) { Activated += delegate { context.InvokeUserCode (eventSink.OnClicked); OnActivatedInternal (); }; } public ViewBackend Backend { get; set; } public NSView View { get { return this; } } public void EnableEvent (ButtonEvent ev) { } public void DisableEvent (ButtonEvent ev) { } public override void ViewDidMoveToWindow () { if ((Backend as ButtonBackend)?.IsDefault == true && Window != null) Window.DefaultButtonCell = Cell; } void OnActivatedInternal () { if (ActivatedInternal == null) return; ActivatedInternal (this); } public override void ResetCursorRects () { base.ResetCursorRects (); if (Backend.Cursor != null) AddCursorRect (Bounds, Backend.Cursor); } public Color BackgroundColor { get { return ((ColoredButtonCell)Cell).Color.GetValueOrDefault (); } set { ((ColoredButtonCell)Cell).Color = value; } } public override bool AllowsVibrancy { get { // we don't support vibrancy if (EffectiveAppearance.AllowsVibrancy) return false; return base.AllowsVibrancy; } } NSButtonType buttonType = NSButtonType.MomentaryPushIn; public override void SetButtonType (NSButtonType aType) { buttonType = aType; base.SetButtonType (aType); } public override NSAppearance EffectiveAppearance { get { // HACK: if vibrancy is enabled (inside popover) radios/checks don't handle background drawing correctly // FIXME: this fix doesn't work for the vibrant light theme, the label background is wrong if // the window background is set to a custom color if (base.EffectiveAppearance.AllowsVibrancy && (buttonType == NSButtonType.Switch || buttonType == NSButtonType.Radio)) Cell.BackgroundStyle = base.EffectiveAppearance.Name.Contains ("Dark") ? NSBackgroundStyle.Dark : NSBackgroundStyle.Light; return base.EffectiveAppearance; } } class ColoredButtonCell : NSButtonCell { public Color? Color { get; set; } public override void DrawBezelWithFrame (CGRect frame, NSView controlView) { controlView.DrawWithColorTransform(Color, delegate { base.DrawBezelWithFrame (frame, controlView); }); } } public Func<bool> PerformAccessiblePressDelegate { get; set; } public override bool AccessibilityPerformPress () { if (PerformAccessiblePressDelegate != null) { if (PerformAccessiblePressDelegate ()) return true; } return base.AccessibilityPerformPress (); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** Purpose: Abstract base class for all Streams. Provides ** default implementations of asynchronous reads & writes, in ** terms of the synchronous reads & writes (and vice versa). ** ** ===========================================================*/ using System; #if FEATURE_CORECLR using System.Buffers; #endif using System.Threading; using System.Threading.Tasks; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Security; using System.Security.Permissions; using System.Diagnostics.Contracts; using System.Reflection; namespace System.IO { [Serializable] [ComVisible(true)] public abstract class Stream : MarshalByRefObject, IDisposable { public static readonly Stream Null = new NullStream(); //We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K). // The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant // improvement in Copy performance. private const int _DefaultCopyBufferSize = 81920; // To implement Async IO operations on streams that don't support async IO [NonSerialized] private ReadWriteTask _activeReadWriteTask; [NonSerialized] private SemaphoreSlim _asyncActiveSemaphore; internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized() { // Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's // WaitHandle, we don't need to worry about Disposing it. return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1)); } public abstract bool CanRead { [Pure] get; } // If CanSeek is false, Position, Seek, Length, and SetLength should throw. public abstract bool CanSeek { [Pure] get; } [ComVisible(false)] public virtual bool CanTimeout { [Pure] get { return false; } } public abstract bool CanWrite { [Pure] get; } public abstract long Length { get; } public abstract long Position { get; set; } [ComVisible(false)] public virtual int ReadTimeout { get { Contract.Ensures(Contract.Result<int>() >= 0); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported")); } set { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported")); } } [ComVisible(false)] public virtual int WriteTimeout { get { Contract.Ensures(Contract.Result<int>() >= 0); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported")); } set { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported")); } } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public Task CopyToAsync(Stream destination) { int bufferSize = _DefaultCopyBufferSize; #if FEATURE_CORECLR if (CanSeek) { long length = Length; long position = Position; if (length <= position) // Handles negative overflows { // If we go down this branch, it means there are // no bytes left in this stream. // Ideally we would just return Task.CompletedTask here, // but CopyToAsync(Stream, int, CancellationToken) was already // virtual at the time this optimization was introduced. So // if it does things like argument validation (checking if destination // is null and throwing an exception), then await fooStream.CopyToAsync(null) // would no longer throw if there were no bytes left. On the other hand, // we also can't roll our own argument validation and return Task.CompletedTask, // because it would be a breaking change if the stream's override didn't throw before, // or in a different order. So for simplicity, we just set the bufferSize to 1 // (not 0 since the default implementation throws for 0) and forward to the virtual method. bufferSize = 1; } else { long remaining = length - position; if (remaining > 0) // In the case of a positive overflow, stick to the default size bufferSize = (int)Math.Min(bufferSize, remaining); } } #endif // FEATURE_CORECLR return CopyToAsync(destination, bufferSize); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public Task CopyToAsync(Stream destination, Int32 bufferSize) { return CopyToAsync(destination, bufferSize, CancellationToken.None); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) { StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); return CopyToAsyncInternal(destination, bufferSize, cancellationToken); } private async Task CopyToAsyncInternal(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) { Contract.Requires(destination != null); Contract.Requires(bufferSize > 0); Contract.Requires(CanRead); Contract.Requires(destination.CanWrite); #if FEATURE_CORECLR byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize); bufferSize = 0; // reuse same field for high water mark to avoid needing another field in the state machine try { while (true) { int bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); if (bytesRead == 0) break; if (bytesRead > bufferSize) bufferSize = bytesRead; await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); } } finally { Array.Clear(buffer, 0, bufferSize); // clear only the most we used ArrayPool<byte>.Shared.Return(buffer, clearArray: false); } #else byte[] buffer = new byte[bufferSize]; while (true) { int bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); if (bytesRead == 0) break; await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); } #endif } // Reads the bytes from the current stream and writes the bytes to // the destination stream until all bytes are read, starting at // the current position. public void CopyTo(Stream destination) { int bufferSize = _DefaultCopyBufferSize; #if FEATURE_CORECLR if (CanSeek) { long length = Length; long position = Position; if (length <= position) // Handles negative overflows { // No bytes left in stream // Call the other overload with a bufferSize of 1, // in case it's made virtual in the future bufferSize = 1; } else { long remaining = length - position; if (remaining > 0) // In the case of a positive overflow, stick to the default size bufferSize = (int)Math.Min(bufferSize, remaining); } } #endif // FEATURE_CORECLR CopyTo(destination, bufferSize); } public virtual void CopyTo(Stream destination, int bufferSize) { StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); #if FEATURE_CORECLR byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize); int highwaterMark = 0; try { int read; while ((read = Read(buffer, 0, buffer.Length)) != 0) { if (read > highwaterMark) highwaterMark = read; destination.Write(buffer, 0, read); } } finally { Array.Clear(buffer, 0, highwaterMark); // clear only the most we used ArrayPool<byte>.Shared.Return(buffer, clearArray: false); } #else byte[] buffer = new byte[bufferSize]; int read; while ((read = Read(buffer, 0, buffer.Length)) != 0) { destination.Write(buffer, 0, read); } #endif } // Stream used to require that all cleanup logic went into Close(), // which was thought up before we invented IDisposable. However, we // need to follow the IDisposable pattern so that users can write // sensible subclasses without needing to inspect all their base // classes, and without worrying about version brittleness, from a // base class switching to the Dispose pattern. We're moving // Stream to the Dispose(bool) pattern - that's where all subclasses // should put their cleanup starting in V2. public virtual void Close() { /* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully. Contract.Ensures(CanRead == false); Contract.Ensures(CanWrite == false); Contract.Ensures(CanSeek == false); */ Dispose(true); GC.SuppressFinalize(this); } public void Dispose() { /* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully. Contract.Ensures(CanRead == false); Contract.Ensures(CanWrite == false); Contract.Ensures(CanSeek == false); */ Close(); } protected virtual void Dispose(bool disposing) { // Note: Never change this to call other virtual methods on Stream // like Write, since the state on subclasses has already been // torn down. This is the last code to run on cleanup for a stream. } public abstract void Flush(); [HostProtection(ExternalThreading=true)] [ComVisible(false)] public Task FlushAsync() { return FlushAsync(CancellationToken.None); } [HostProtection(ExternalThreading=true)] [ComVisible(false)] public virtual Task FlushAsync(CancellationToken cancellationToken) { return Task.Factory.StartNew(state => ((Stream)state).Flush(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } [Obsolete("CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead.")] protected virtual WaitHandle CreateWaitHandle() { Contract.Ensures(Contract.Result<WaitHandle>() != null); return new ManualResetEvent(false); } [HostProtection(ExternalThreading=true)] public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true); } [HostProtection(ExternalThreading = true)] internal IAsyncResult BeginReadInternal( byte[] buffer, int offset, int count, AsyncCallback callback, Object state, bool serializeAsynchronously, bool apm) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); if (!CanRead) __Error.ReadNotSupported(); // To avoid a race with a stream's position pointer & generating race conditions // with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. var semaphore = EnsureAsyncActiveSemaphoreInitialized(); Task semaphoreTask = null; if (serializeAsynchronously) { semaphoreTask = semaphore.WaitAsync(); } else { semaphore.Wait(); } // Create the task to asynchronously do a Read. This task serves both // as the asynchronous work item and as the IAsyncResult returned to the user. var asyncResult = new ReadWriteTask(true /*isRead*/, apm, delegate { // The ReadWriteTask stores all of the parameters to pass to Read. // As we're currently inside of it, we can get the current task // and grab the parameters from it. var thisTask = Task.InternalCurrent as ReadWriteTask; Contract.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask"); try { // Do the Read and return the number of bytes read return thisTask._stream.Read(thisTask._buffer, thisTask._offset, thisTask._count); } finally { // If this implementation is part of Begin/EndXx, then the EndXx method will handle // finishing the async operation. However, if this is part of XxAsync, then there won't // be an end method, and this task is responsible for cleaning up. if (!thisTask._apm) { thisTask._stream.FinishTrackingAsyncOperation(); } thisTask.ClearBeginState(); // just to help alleviate some memory pressure } }, state, this, buffer, offset, count, callback); // Schedule it if (semaphoreTask != null) RunReadWriteTaskWhenReady(semaphoreTask, asyncResult); else RunReadWriteTask(asyncResult); return asyncResult; // return it } public virtual int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); Contract.Ensures(Contract.Result<int>() >= 0); Contract.EndContractBlock(); var readTask = _activeReadWriteTask; if (readTask == null) { throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple")); } else if (readTask != asyncResult) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple")); } else if (!readTask._isRead) { throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple")); } try { return readTask.GetAwaiter().GetResult(); // block until completion, then get result / propagate any exception } finally { FinishTrackingAsyncOperation(); } } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public Task<int> ReadAsync(Byte[] buffer, int offset, int count) { return ReadAsync(buffer, offset, count, CancellationToken.None); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // If cancellation was requested, bail early with an already completed task. // Otherwise, return a task that represents the Begin/End methods. return cancellationToken.IsCancellationRequested ? Task.FromCanceled<int>(cancellationToken) : BeginEndReadAsync(buffer, offset, count); } [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern bool HasOverriddenBeginEndRead(); private Task<Int32> BeginEndReadAsync(Byte[] buffer, Int32 offset, Int32 count) { if (!HasOverriddenBeginEndRead()) { // If the Stream does not override Begin/EndRead, then we can take an optimized path // that skips an extra layer of tasks / IAsyncResults. return (Task<Int32>)BeginReadInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false); } // Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality. return TaskFactory<Int32>.FromAsyncTrim( this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count }, (stream, args, callback, state) => stream.BeginRead(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler (stream, asyncResult) => stream.EndRead(asyncResult)); // cached by compiler } private struct ReadWriteParameters // struct for arguments to Read and Write calls { internal byte[] Buffer; internal int Offset; internal int Count; } [HostProtection(ExternalThreading=true)] public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true); } [HostProtection(ExternalThreading = true)] internal IAsyncResult BeginWriteInternal( byte[] buffer, int offset, int count, AsyncCallback callback, Object state, bool serializeAsynchronously, bool apm) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); if (!CanWrite) __Error.WriteNotSupported(); // To avoid a race condition with a stream's position pointer & generating conditions // with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. var semaphore = EnsureAsyncActiveSemaphoreInitialized(); Task semaphoreTask = null; if (serializeAsynchronously) { semaphoreTask = semaphore.WaitAsync(); // kick off the asynchronous wait, but don't block } else { semaphore.Wait(); // synchronously wait here } // Create the task to asynchronously do a Write. This task serves both // as the asynchronous work item and as the IAsyncResult returned to the user. var asyncResult = new ReadWriteTask(false /*isRead*/, apm, delegate { // The ReadWriteTask stores all of the parameters to pass to Write. // As we're currently inside of it, we can get the current task // and grab the parameters from it. var thisTask = Task.InternalCurrent as ReadWriteTask; Contract.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask"); try { // Do the Write thisTask._stream.Write(thisTask._buffer, thisTask._offset, thisTask._count); return 0; // not used, but signature requires a value be returned } finally { // If this implementation is part of Begin/EndXx, then the EndXx method will handle // finishing the async operation. However, if this is part of XxAsync, then there won't // be an end method, and this task is responsible for cleaning up. if (!thisTask._apm) { thisTask._stream.FinishTrackingAsyncOperation(); } thisTask.ClearBeginState(); // just to help alleviate some memory pressure } }, state, this, buffer, offset, count, callback); // Schedule it if (semaphoreTask != null) RunReadWriteTaskWhenReady(semaphoreTask, asyncResult); else RunReadWriteTask(asyncResult); return asyncResult; // return it } private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask) { Contract.Assert(readWriteTask != null); // Should be Contract.Requires, but CCRewrite is doing a poor job with // preconditions in async methods that await. Contract.Assert(asyncWaiter != null); // Ditto // If the wait has already completed, run the task. if (asyncWaiter.IsCompleted) { Contract.Assert(asyncWaiter.IsRanToCompletion, "The semaphore wait should always complete successfully."); RunReadWriteTask(readWriteTask); } else // Otherwise, wait for our turn, and then run the task. { asyncWaiter.ContinueWith((t, state) => { Contract.Assert(t.IsRanToCompletion, "The semaphore wait should always complete successfully."); var rwt = (ReadWriteTask)state; rwt._stream.RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask); }, readWriteTask, default(CancellationToken), TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } } private void RunReadWriteTask(ReadWriteTask readWriteTask) { Contract.Requires(readWriteTask != null); Contract.Assert(_activeReadWriteTask == null, "Expected no other readers or writers"); // Schedule the task. ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race. // Internally, we're able to directly call ScheduleAndStart rather than Start, avoiding // two interlocked operations. However, if ReadWriteTask is ever changed to use // a cancellation token, this should be changed to use Start. _activeReadWriteTask = readWriteTask; // store the task so that EndXx can validate it's given the right one readWriteTask.m_taskScheduler = TaskScheduler.Default; readWriteTask.ScheduleAndStart(needsProtection: false); } private void FinishTrackingAsyncOperation() { _activeReadWriteTask = null; Contract.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here."); _asyncActiveSemaphore.Release(); } public virtual void EndWrite(IAsyncResult asyncResult) { if (asyncResult==null) throw new ArgumentNullException(nameof(asyncResult)); Contract.EndContractBlock(); var writeTask = _activeReadWriteTask; if (writeTask == null) { throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple")); } else if (writeTask != asyncResult) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple")); } else if (writeTask._isRead) { throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple")); } try { writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions Contract.Assert(writeTask.Status == TaskStatus.RanToCompletion); } finally { FinishTrackingAsyncOperation(); } } // Task used by BeginRead / BeginWrite to do Read / Write asynchronously. // A single instance of this task serves four purposes: // 1. The work item scheduled to run the Read / Write operation // 2. The state holding the arguments to be passed to Read / Write // 3. The IAsyncResult returned from BeginRead / BeginWrite // 4. The completion action that runs to invoke the user-provided callback. // This last item is a bit tricky. Before the AsyncCallback is invoked, the // IAsyncResult must have completed, so we can't just invoke the handler // from within the task, since it is the IAsyncResult, and thus it's not // yet completed. Instead, we use AddCompletionAction to install this // task as its own completion handler. That saves the need to allocate // a separate completion handler, it guarantees that the task will // have completed by the time the handler is invoked, and it allows // the handler to be invoked synchronously upon the completion of the // task. This all enables BeginRead / BeginWrite to be implemented // with a single allocation. private sealed class ReadWriteTask : Task<int>, ITaskCompletionAction { internal readonly bool _isRead; internal readonly bool _apm; // true if this is from Begin/EndXx; false if it's from XxAsync internal Stream _stream; internal byte [] _buffer; internal readonly int _offset; internal readonly int _count; private AsyncCallback _callback; private ExecutionContext _context; internal void ClearBeginState() // Used to allow the args to Read/Write to be made available for GC { _stream = null; _buffer = null; } [SecuritySafeCritical] // necessary for EC.Capture [MethodImpl(MethodImplOptions.NoInlining)] public ReadWriteTask( bool isRead, bool apm, Func<object,int> function, object state, Stream stream, byte[] buffer, int offset, int count, AsyncCallback callback) : base(function, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach) { Contract.Requires(function != null); Contract.Requires(stream != null); Contract.Requires(buffer != null); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; // Store the arguments _isRead = isRead; _apm = apm; _stream = stream; _buffer = buffer; _offset = offset; _count = count; // If a callback was provided, we need to: // - Store the user-provided handler // - Capture an ExecutionContext under which to invoke the handler // - Add this task as its own completion handler so that the Invoke method // will run the callback when this task completes. if (callback != null) { _callback = callback; _context = ExecutionContext.Capture(ref stackMark, ExecutionContext.CaptureOptions.OptimizeDefaultCase | ExecutionContext.CaptureOptions.IgnoreSyncCtx); base.AddCompletionAction(this); } } [SecurityCritical] // necessary for CoreCLR private static void InvokeAsyncCallback(object completedTask) { var rwc = (ReadWriteTask)completedTask; var callback = rwc._callback; rwc._callback = null; callback(rwc); } [SecurityCritical] // necessary for CoreCLR private static ContextCallback s_invokeAsyncCallback; [SecuritySafeCritical] // necessary for ExecutionContext.Run void ITaskCompletionAction.Invoke(Task completingTask) { // Get the ExecutionContext. If there is none, just run the callback // directly, passing in the completed task as the IAsyncResult. // If there is one, process it with ExecutionContext.Run. var context = _context; if (context == null) { var callback = _callback; _callback = null; callback(completingTask); } else { _context = null; var invokeAsyncCallback = s_invokeAsyncCallback; if (invokeAsyncCallback == null) s_invokeAsyncCallback = invokeAsyncCallback = InvokeAsyncCallback; // benign race condition using(context) ExecutionContext.Run(context, invokeAsyncCallback, this, true); } } bool ITaskCompletionAction.InvokeMayRunArbitraryCode { get { return true; } } } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public Task WriteAsync(Byte[] buffer, int offset, int count) { return WriteAsync(buffer, offset, count, CancellationToken.None); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // If cancellation was requested, bail early with an already completed task. // Otherwise, return a task that represents the Begin/End methods. return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : BeginEndWriteAsync(buffer, offset, count); } [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern bool HasOverriddenBeginEndWrite(); private Task BeginEndWriteAsync(Byte[] buffer, Int32 offset, Int32 count) { if (!HasOverriddenBeginEndWrite()) { // If the Stream does not override Begin/EndWrite, then we can take an optimized path // that skips an extra layer of tasks / IAsyncResults. return (Task)BeginWriteInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false); } // Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality. return TaskFactory<VoidTaskResult>.FromAsyncTrim( this, new ReadWriteParameters { Buffer=buffer, Offset=offset, Count=count }, (stream, args, callback, state) => stream.BeginWrite(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler (stream, asyncResult) => // cached by compiler { stream.EndWrite(asyncResult); return default(VoidTaskResult); }); } public abstract long Seek(long offset, SeekOrigin origin); public abstract void SetLength(long value); public abstract int Read([In, Out] byte[] buffer, int offset, int count); // Reads one byte from the stream by calling Read(byte[], int, int). // Will return an unsigned byte cast to an int or -1 on end of stream. // This implementation does not perform well because it allocates a new // byte[] each time you call it, and should be overridden by any // subclass that maintains an internal buffer. Then, it can help perf // significantly for people who are reading one byte at a time. public virtual int ReadByte() { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < 256); byte[] oneByteArray = new byte[1]; int r = Read(oneByteArray, 0, 1); if (r==0) return -1; return oneByteArray[0]; } public abstract void Write(byte[] buffer, int offset, int count); // Writes one byte from the stream by calling Write(byte[], int, int). // This implementation does not perform well because it allocates a new // byte[] each time you call it, and should be overridden by any // subclass that maintains an internal buffer. Then, it can help perf // significantly for people who are writing one byte at a time. public virtual void WriteByte(byte value) { byte[] oneByteArray = new byte[1]; oneByteArray[0] = value; Write(oneByteArray, 0, 1); } [HostProtection(Synchronization=true)] public static Stream Synchronized(Stream stream) { if (stream==null) throw new ArgumentNullException(nameof(stream)); Contract.Ensures(Contract.Result<Stream>() != null); Contract.EndContractBlock(); if (stream is SyncStream) return stream; return new SyncStream(stream); } [Obsolete("Do not call or override this method.")] protected virtual void ObjectInvariant() { } internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); // To avoid a race with a stream's position pointer & generating conditions // with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread and do the IO synchronously. // This can't perform well - use a different approach. SynchronousAsyncResult asyncResult; try { int numRead = Read(buffer, offset, count); asyncResult = new SynchronousAsyncResult(numRead, state); } catch (IOException ex) { asyncResult = new SynchronousAsyncResult(ex, state, isWrite: false); } if (callback != null) { callback(asyncResult); } return asyncResult; } internal static int BlockingEndRead(IAsyncResult asyncResult) { Contract.Ensures(Contract.Result<int>() >= 0); return SynchronousAsyncResult.EndRead(asyncResult); } internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { Contract.Ensures(Contract.Result<IAsyncResult>() != null); // To avoid a race condition with a stream's position pointer & generating conditions // with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread and do the IO synchronously. // This can't perform well - use a different approach. SynchronousAsyncResult asyncResult; try { Write(buffer, offset, count); asyncResult = new SynchronousAsyncResult(state); } catch (IOException ex) { asyncResult = new SynchronousAsyncResult(ex, state, isWrite: true); } if (callback != null) { callback(asyncResult); } return asyncResult; } internal static void BlockingEndWrite(IAsyncResult asyncResult) { SynchronousAsyncResult.EndWrite(asyncResult); } [Serializable] private sealed class NullStream : Stream { internal NullStream() {} public override bool CanRead { [Pure] get { return true; } } public override bool CanWrite { [Pure] get { return true; } } public override bool CanSeek { [Pure] get { return true; } } public override long Length { get { return 0; } } public override long Position { get { return 0; } set {} } public override void CopyTo(Stream destination, int bufferSize) { StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); // After we validate arguments this is a nop. } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { // Validate arguments here for compat, since previously this method // was inherited from Stream (which did check its arguments). StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } protected override void Dispose(bool disposing) { // Do nothing - we don't want NullStream singleton (static) to be closable } public override void Flush() { } [ComVisible(false)] public override Task FlushAsync(CancellationToken cancellationToken) { return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } [HostProtection(ExternalThreading = true)] public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { if (!CanRead) __Error.ReadNotSupported(); return BlockingBeginRead(buffer, offset, count, callback, state); } public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); Contract.EndContractBlock(); return BlockingEndRead(asyncResult); } [HostProtection(ExternalThreading = true)] public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { if (!CanWrite) __Error.WriteNotSupported(); return BlockingBeginWrite(buffer, offset, count, callback, state); } public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); Contract.EndContractBlock(); BlockingEndWrite(asyncResult); } public override int Read([In, Out] byte[] buffer, int offset, int count) { return 0; } [ComVisible(false)] public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { var nullReadTask = s_nullReadTask; if (nullReadTask == null) s_nullReadTask = nullReadTask = new Task<int>(false, 0, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, CancellationToken.None); // benign race condition return nullReadTask; } private static Task<int> s_nullReadTask; public override int ReadByte() { return -1; } public override void Write(byte[] buffer, int offset, int count) { } [ComVisible(false)] public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } public override void WriteByte(byte value) { } public override long Seek(long offset, SeekOrigin origin) { return 0; } public override void SetLength(long length) { } } /// <summary>Used as the IAsyncResult object when using asynchronous IO methods on the base Stream class.</summary> internal sealed class SynchronousAsyncResult : IAsyncResult { private readonly Object _stateObject; private readonly bool _isWrite; private ManualResetEvent _waitHandle; private ExceptionDispatchInfo _exceptionInfo; private bool _endXxxCalled; private Int32 _bytesRead; internal SynchronousAsyncResult(Int32 bytesRead, Object asyncStateObject) { _bytesRead = bytesRead; _stateObject = asyncStateObject; //_isWrite = false; } internal SynchronousAsyncResult(Object asyncStateObject) { _stateObject = asyncStateObject; _isWrite = true; } internal SynchronousAsyncResult(Exception ex, Object asyncStateObject, bool isWrite) { _exceptionInfo = ExceptionDispatchInfo.Capture(ex); _stateObject = asyncStateObject; _isWrite = isWrite; } public bool IsCompleted { // We never hand out objects of this type to the user before the synchronous IO completed: get { return true; } } public WaitHandle AsyncWaitHandle { get { return LazyInitializer.EnsureInitialized(ref _waitHandle, () => new ManualResetEvent(true)); } } public Object AsyncState { get { return _stateObject; } } public bool CompletedSynchronously { get { return true; } } internal void ThrowIfError() { if (_exceptionInfo != null) _exceptionInfo.Throw(); } internal static Int32 EndRead(IAsyncResult asyncResult) { SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult; if (ar == null || ar._isWrite) __Error.WrongAsyncResult(); if (ar._endXxxCalled) __Error.EndReadCalledTwice(); ar._endXxxCalled = true; ar.ThrowIfError(); return ar._bytesRead; } internal static void EndWrite(IAsyncResult asyncResult) { SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult; if (ar == null || !ar._isWrite) __Error.WrongAsyncResult(); if (ar._endXxxCalled) __Error.EndWriteCalledTwice(); ar._endXxxCalled = true; ar.ThrowIfError(); } } // class SynchronousAsyncResult // SyncStream is a wrapper around a stream that takes // a lock for every operation making it thread safe. [Serializable] internal sealed class SyncStream : Stream, IDisposable { private Stream _stream; internal SyncStream(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); Contract.EndContractBlock(); _stream = stream; } public override bool CanRead { [Pure] get { return _stream.CanRead; } } public override bool CanWrite { [Pure] get { return _stream.CanWrite; } } public override bool CanSeek { [Pure] get { return _stream.CanSeek; } } [ComVisible(false)] public override bool CanTimeout { [Pure] get { return _stream.CanTimeout; } } public override long Length { get { lock(_stream) { return _stream.Length; } } } public override long Position { get { lock(_stream) { return _stream.Position; } } set { lock(_stream) { _stream.Position = value; } } } [ComVisible(false)] public override int ReadTimeout { get { return _stream.ReadTimeout; } set { _stream.ReadTimeout = value; } } [ComVisible(false)] public override int WriteTimeout { get { return _stream.WriteTimeout; } set { _stream.WriteTimeout = value; } } // In the off chance that some wrapped stream has different // semantics for Close vs. Dispose, let's preserve that. public override void Close() { lock(_stream) { try { _stream.Close(); } finally { base.Dispose(true); } } } protected override void Dispose(bool disposing) { lock(_stream) { try { // Explicitly pick up a potentially methodimpl'ed Dispose if (disposing) ((IDisposable)_stream).Dispose(); } finally { base.Dispose(disposing); } } } public override void Flush() { lock(_stream) _stream.Flush(); } public override int Read([In, Out]byte[] bytes, int offset, int count) { lock(_stream) return _stream.Read(bytes, offset, count); } public override int ReadByte() { lock(_stream) return _stream.ReadByte(); } [HostProtection(ExternalThreading=true)] public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { bool overridesBeginRead = _stream.HasOverriddenBeginEndRead(); lock (_stream) { // If the Stream does have its own BeginRead implementation, then we must use that override. // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic // which ensures only one asynchronous operation does so with an asynchronous wait rather // than a synchronous wait. A synchronous wait will result in a deadlock condition, because // the EndXx method for the outstanding async operation won't be able to acquire the lock on // _stream due to this call blocked while holding the lock. return overridesBeginRead ? _stream.BeginRead(buffer, offset, count, callback, state) : _stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true); } } public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); Contract.Ensures(Contract.Result<int>() >= 0); Contract.EndContractBlock(); lock(_stream) return _stream.EndRead(asyncResult); } public override long Seek(long offset, SeekOrigin origin) { lock(_stream) return _stream.Seek(offset, origin); } public override void SetLength(long length) { lock(_stream) _stream.SetLength(length); } public override void Write(byte[] bytes, int offset, int count) { lock(_stream) _stream.Write(bytes, offset, count); } public override void WriteByte(byte b) { lock(_stream) _stream.WriteByte(b); } [HostProtection(ExternalThreading=true)] public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite(); lock (_stream) { // If the Stream does have its own BeginWrite implementation, then we must use that override. // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic // which ensures only one asynchronous operation does so with an asynchronous wait rather // than a synchronous wait. A synchronous wait will result in a deadlock condition, because // the EndXx method for the outstanding async operation won't be able to acquire the lock on // _stream due to this call blocked while holding the lock. return overridesBeginWrite ? _stream.BeginWrite(buffer, offset, count, callback, state) : _stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true); } } public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); Contract.EndContractBlock(); lock(_stream) _stream.EndWrite(asyncResult); } } } }