context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Text; namespace WebsitePanel.Templates.AST { internal class IdentifierExpression : Expression { List<IdentifierPart> parts = new List<IdentifierPart>(); public IdentifierExpression(int line, int column) : base(line, column) { } public List<IdentifierPart> Parts { get { return parts; } } public override object Eval(TemplateContext context) { object val = null; for (int i = 0; i < parts.Count; i++) { // get variable from context if (i == 0 && !parts[i].IsMethod) { val = EvalContextVariable(parts[i], context); } // call built-in function else if (i == 0 && parts[i].IsMethod) { BuiltinFunctions target = new BuiltinFunctions(); target.Context = context; target.Line = parts[i].Line; target.Column = parts[i].Column; val = EvalMethod(target, parts[i], context); } // call public property else if(i > 0 && !parts[i].IsMethod) // property { val = EvalProperty(val, parts[i], context); } // call public method else if (i > 0 && parts[i].IsMethod) // property { val = EvalMethod(val, parts[i], context); } } return val; } private object EvalContextVariable(IdentifierPart variable, TemplateContext context) { object val = null; TemplateContext lookupContext = context; while (lookupContext != null) { if (lookupContext.Variables.ContainsKey(variable.Name)) { val = lookupContext.Variables[variable.Name]; break; // found local scope var - stop looking } // look into parent scope lookupContext = lookupContext.ParentContext; } // get from context if (val == null) return null; // evaluate index expression if required val = EvalIndexer(val, variable, context); return val; } private object EvalIndexer(object target, IdentifierPart indexer, TemplateContext context) { if (indexer.Index == null) return target; object index = null; index = indexer.Index.Eval(context); if (index == null) throw new ParserException("Indexer expression evaluated to NULL", Line, Column); if (target == null) throw new ParserException("Cannot call indexer on NULL object", Line, Column); // get from index if required if(target is IDictionary) { // dictionary return ((IDictionary)target)[index]; } else if (target is Array) { // array if(index is Int32) return ((Array)target).GetValue((Int32)index); else throw new ParserException("Array index expression must evaluate to integer.", Line, Column); } else if (target is IList) { // list if(index is Int32) return ((IList)target)[(Int32)index]; else throw new ParserException("IList index expression must evaluate to integer.", Line, Column); } else { // call "get_Item" method MethodInfo methodInfo = target.GetType().GetMethod("get_Item", BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public); if (methodInfo != null) return methodInfo.Invoke(target, new object[] { index }); } throw new ParserException("Cannot call indexer", Line, Column); } private object EvalProperty(object target, IdentifierPart property, TemplateContext context) { object val = target; // check for null if (val == null) throw new ParserException("Cannot read property value of NULL object", Line, Column); // get property string propName = property.Name; PropertyInfo prop = val.GetType().GetProperty(propName, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public); if (prop == null) { // build the list of available properties StringBuilder propsList = new StringBuilder(); int vi = 0; PropertyInfo[] props = val.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (PropertyInfo p in props) { if (vi++ > 0) propsList.Append(","); propsList.Append(p.Name); } throw new ParserException("Public property could not be found: " + propName + "." + " Supported properties: " + propsList.ToString(), Line, Column); } // read property try { val = prop.GetValue(val, null); } catch (Exception ex) { throw new ParserException("Cannot read property value: " + ex.Message, Line, Column); } // evaluate index expression if required val = EvalIndexer(val, property, context); return val; } private object EvalMethod(object target, IdentifierPart method, TemplateContext context) { object val = target; // check for null if (val == null) throw new ParserException("Cannot perform method of NULL object", Line, Column); // evaluate method parameters object[] prms = new object[method.MethodParameters.Count]; Type[] prmTypes = new Type[method.MethodParameters.Count]; for (int i = 0; i < prms.Length; i++) { prms[i] = method.MethodParameters[i].Eval(context); if (prms[i] != null) prmTypes[i] = prms[i].GetType(); else prmTypes[i] = typeof(object); // "null" parameter was specified } // find method string methodName = method.Name; MethodInfo methodInfo = val.GetType().GetMethod(methodName, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public, null, prmTypes, null); if (methodInfo == null) { // failed to find exact signature // try to iterate methodInfo = val.GetType().GetMethod(methodName, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public); } if (methodInfo == null) { // build the list of available methods StringBuilder methodsList = new StringBuilder(); int vi = 0; MethodInfo[] methods = val.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public); foreach (MethodInfo mi in methods) { if (vi++ > 0) methodsList.Append(","); methodsList.Append(mi.Name); } throw new ParserException("Public method could not be found: " + methodName + "." + " Available methods: " + methodsList.ToString(), Line, Column); } // call method try { val = methodInfo.Invoke(val, prms); } catch (Exception ex) { throw new ParserException("Cannot call method: " + ex.Message, Line, Column); } return val; } public override string ToString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < Parts.Count; i++) { if (i > 0) sb.Append("."); sb.Append(Parts[i]); } return sb.ToString(); } } }
// // AudioFile.cs: // // Authors: // Miguel de Icaza (miguel@novell.com) // // Copyright 2009 Novell, Inc // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Collections.Generic; using System.Runtime.InteropServices; using MonoMac.CoreFoundation; using OSStatus = System.Int32; using AudioFileStreamID = System.IntPtr; namespace MonoMac.AudioToolbox { [Flags] public enum AudioFileStreamPropertyFlag { PropertyIsCached = 1, CacheProperty = 2, } public enum AudioFileStreamStatus { Ok = 0, UnsupportedFileType=0x7479703f, UnsupportedDataFormat=0x666d743f, UnsupportedProperty=0x7074793f, BadPropertySize=0x2173697a, NotOptimized=0x6f70746d, InvalidPacketOffset=0x70636b3f, InvalidFile=0x6474613f, ValueUnknown=0x756e6b3f, DataUnavailable=0x6d6f7265, IllegalOperation=0x6e6f7065, UnspecifiedError=0x7768743f, DiscontinuityCantRecover=0x64736321, } public enum AudioFileStreamProperty { ReadyToProducePackets=0x72656479, FileFormat=0x66666d74, DataFormat=0x64666d74, FormatList=0x666c7374, MagicCookieData=0x6d676963, AudioDataByteCount=0x62636e74, AudioDataPacketCount=0x70636e74, MaximumPacketSize=0x70737a65, DataOffset=0x646f6666, ChannelLayout=0x636d6170, PacketToFrame=0x706b6672, FrameToPacket=0x6672706b, PacketToByte=0x706b6279, ByteToPacket=0x6279706b, PacketTableInfo=0x706e666f, PacketSizeUpperBound=0x706b7562, AverageBytesPerPacket=0x61627070, BitRate=0x62726174 } public class PropertyFoundEventArgs : EventArgs { public PropertyFoundEventArgs (AudioFileStreamProperty propertyID, AudioFileStreamPropertyFlag ioFlags) { Property = propertyID; Flags = ioFlags; } public AudioFileStreamProperty Property { get; private set; } public AudioFileStreamPropertyFlag Flags { get; set; } public override string ToString () { return String.Format ("AudioFileStreamProperty ({0})", Property); } } public class PacketReceivedEventArgs : EventArgs { public PacketReceivedEventArgs (int numberOfBytes, IntPtr inputData, AudioStreamPacketDescription [] packetDescriptions) { this.Bytes = numberOfBytes; this.InputData = inputData; this.PacketDescriptions = packetDescriptions; } public int Bytes { get; private set; } public IntPtr InputData { get; private set; } public AudioStreamPacketDescription [] PacketDescriptions { get; private set;} public override string ToString () { return String.Format ("Packet (Bytes={0} InputData={1} PacketDescriptions={2}", Bytes, InputData, PacketDescriptions.Length); } } public class AudioFileStream : IDisposable { IntPtr handle; GCHandle gch; ~AudioFileStream () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } public void Close () { Dispose (); } protected virtual void Dispose (bool disposing) { if (disposing){ if (gch.IsAllocated) gch.Free (); } if (handle != IntPtr.Zero){ AudioFileStreamClose (handle); handle = IntPtr.Zero; } } delegate void AudioFileStream_PropertyListenerProc(IntPtr clientData, AudioFileStreamID audioFileStream, AudioFileStreamProperty propertyID, ref AudioFileStreamPropertyFlag ioFlags); delegate void AudioFileStream_PacketsProc (IntPtr clientData, int numberBytes, int numberPackets, IntPtr inputData, IntPtr packetDescriptions); [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileStreamOpen ( IntPtr clientData, AudioFileStream_PropertyListenerProc propertyListenerProc, AudioFileStream_PacketsProc packetsProc, AudioFileType fileTypeHint, out IntPtr file_id); static AudioFileStream_PacketsProc dInPackets; static AudioFileStream_PropertyListenerProc dPropertyListener; static AudioFileStream () { dInPackets = InPackets; dPropertyListener = PropertyListener; } [MonoPInvokeCallback(typeof(AudioFileStream_PacketsProc))] static void InPackets (IntPtr clientData, int numberBytes, int numberPackets, IntPtr inputData, IntPtr packetDescriptions) { GCHandle handle = GCHandle.FromIntPtr (clientData); var afs = handle.Target as AudioFileStream; var desc = AudioFile.PacketDescriptionFrom (numberPackets, packetDescriptions); afs.OnPacketDecoded (numberBytes, inputData, desc); } public EventHandler<PacketReceivedEventArgs> PacketDecoded; protected virtual void OnPacketDecoded (int numberOfBytes, IntPtr inputData, AudioStreamPacketDescription [] packetDescriptions) { var p = PacketDecoded; if (p != null) p (this, new PacketReceivedEventArgs (numberOfBytes, inputData, packetDescriptions)); } public EventHandler<PropertyFoundEventArgs> PropertyFound; protected virtual void OnPropertyFound (AudioFileStreamProperty propertyID, ref AudioFileStreamPropertyFlag ioFlags) { var p = PropertyFound; if (p != null){ var pf = new PropertyFoundEventArgs (propertyID, ioFlags); p (this, pf); ioFlags = pf.Flags; } } [MonoPInvokeCallback(typeof(AudioFileStream_PropertyListenerProc))] static void PropertyListener (IntPtr clientData, AudioFileStreamID audioFileStream, AudioFileStreamProperty propertyID, ref AudioFileStreamPropertyFlag ioFlags) { GCHandle handle = GCHandle.FromIntPtr (clientData); var afs = handle.Target as AudioFileStream; afs.OnPropertyFound (propertyID, ref ioFlags); } public AudioFileStream (AudioFileType fileTypeHint) { IntPtr h; gch = GCHandle.Alloc (this); var code = AudioFileStreamOpen (GCHandle.ToIntPtr (gch), dPropertyListener, dInPackets, fileTypeHint, out h); if (code == 0){ handle = h; return; } throw new Exception (String.Format ("Unable to create AudioFileStream, code: 0x{0:x}", code)); } [DllImport (Constants.AudioToolboxLibrary)] extern static AudioFileStreamStatus AudioFileStreamParseBytes ( AudioFileStreamID inAudioFileStream, int inDataByteSize, IntPtr inData, UInt32 inFlags); public AudioFileStreamStatus ParseBytes (int size, IntPtr data, bool discontinuity) { return AudioFileStreamParseBytes (handle, size, data, discontinuity ? (uint) 1 : (uint) 0); } public AudioFileStreamStatus ParseBytes (byte [] bytes, bool discontinuity) { if (bytes == null) throw new ArgumentNullException ("bytes"); unsafe { fixed (byte *bp = &bytes[0]){ return AudioFileStreamParseBytes (handle, bytes.Length, (IntPtr) bp, discontinuity ? (uint) 1 : (uint) 0); } } } public AudioFileStreamStatus ParseBytes (byte [] bytes, int offset, int count, bool discontinuity) { if (bytes == null) throw new ArgumentNullException ("bytes"); if (offset < 0) throw new ArgumentException ("offset"); if (count < 0) throw new ArgumentException ("count"); if (offset+count > bytes.Length) throw new ArgumentException ("offset+count"); unsafe { fixed (byte *bp = &bytes[0]){ return AudioFileStreamParseBytes (handle, count, (IntPtr) (bp + offset) , discontinuity ? (uint) 1 : (uint) 0); } } } [DllImport (Constants.AudioToolboxLibrary)] extern static AudioFileStreamStatus AudioFileStreamSeek(AudioFileStreamID inAudioFileStream, long inPacketOffset, out long outDataByteOffset, ref int ioFlags); public AudioFileStreamStatus Seek (long packetOffset, out long dataByteOffset, out bool isEstimate) { int v = 0; var code = AudioFileStreamSeek (handle, packetOffset, out dataByteOffset, ref v); if (code != AudioFileStreamStatus.Ok){ isEstimate = false; return code; } isEstimate = (v & 1) == 1; return code; } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileStreamGetPropertyInfo( AudioFileStreamID inAudioFileStream, AudioFileStreamProperty inPropertyID, out int outPropertyDataSize, out int isWritable); [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileStreamGetProperty( AudioFileStreamID inAudioFileStream, AudioFileStreamProperty inPropertyID, ref int ioPropertyDataSize, IntPtr outPropertyData); public bool GetProperty (AudioFileStreamProperty property, ref int dataSize, IntPtr outPropertyData) { return AudioFileStreamGetProperty (handle, property, ref dataSize, outPropertyData) == 0; } public IntPtr GetProperty (AudioFileStreamProperty property, out int size) { int writable; var r = AudioFileStreamGetPropertyInfo (handle, property, out size, out writable); if (r != 0) return IntPtr.Zero; var buffer = Marshal.AllocHGlobal (size); if (buffer == IntPtr.Zero) return IntPtr.Zero; r = AudioFileStreamGetProperty (handle, property, ref size, buffer); if (r == 0) return buffer; Marshal.FreeHGlobal (buffer); return IntPtr.Zero; } int GetInt (AudioFileStreamProperty property) { unsafe { int val = 0; int size = 4; if (AudioFileStreamGetProperty (handle, property, ref size, (IntPtr) (&val)) == 0) return val; return 0; } } double GetDouble (AudioFileStreamProperty property) { unsafe { double val = 0; int size = 8; if (AudioFileStreamGetProperty (handle, property, ref size, (IntPtr) (&val)) == 0) return val; return 0; } } long GetLong (AudioFileStreamProperty property) { unsafe { long val = 0; int size = 8; if (AudioFileStreamGetProperty (handle, property, ref size, (IntPtr) (&val)) == 0) return val; return 0; } } T GetProperty<T> (AudioFileStreamProperty property) { int size, writable; if (AudioFileStreamGetPropertyInfo (handle, property, out size, out writable) != 0) return default (T); var buffer = Marshal.AllocHGlobal (size); if (buffer == IntPtr.Zero) return default(T); try { var r = AudioFileStreamGetProperty (handle, property, ref size, buffer); if (r == 0) return (T) Marshal.PtrToStructure (buffer, typeof (T)); return default(T); } finally { Marshal.FreeHGlobal (buffer); } } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileStreamSetProperty( AudioFileStreamID inAudioFileStream, AudioFileStreamProperty inPropertyID, int inPropertyDataSize, IntPtr inPropertyData); public bool SetProperty (AudioFileStreamProperty property, int dataSize, IntPtr propertyData) { return AudioFileStreamSetProperty (handle, property, dataSize, propertyData) == 0; } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileStreamClose(AudioFileStreamID inAudioFileStream); public bool ReadyToProducePackets { get { return GetInt (AudioFileStreamProperty.ReadyToProducePackets) == 1; } } public AudioFileType FileType { get { return (AudioFileType) GetInt (AudioFileStreamProperty.FileFormat); } } public AudioStreamBasicDescription StreamBasicDescription { get { return GetProperty<AudioStreamBasicDescription> (AudioFileStreamProperty.DataFormat); } } // TODO: FormatList // TODO: PacketTableInfo=0x706e666f, public byte [] MagicCookie { get { int size; var h = GetProperty (AudioFileStreamProperty.MagicCookieData, out size); if (h == IntPtr.Zero) return new byte [0]; byte [] cookie = new byte [size]; for (int i = 0; i < cookie.Length; i++) cookie [i] = Marshal.ReadByte (h, i); Marshal.FreeHGlobal (h); return cookie; } } public long DataByteCount { get { return GetLong (AudioFileStreamProperty.AudioDataByteCount); } } public long DataPacketCount { get { return GetLong (AudioFileStreamProperty.AudioDataPacketCount); } } public int MaximumPacketSize { get { return GetInt (AudioFileStreamProperty.MaximumPacketSize); } } public long DataOffset { get { return GetLong (AudioFileStreamProperty.DataOffset); } } public AudioChannelLayout ChannelLayout { get { int size; var h = GetProperty (AudioFileStreamProperty.ChannelLayout, out size); if (h == IntPtr.Zero) return null; var layout = AudioFile.AudioChannelLayoutFromHandle (h); Marshal.FreeHGlobal (h); return layout; } } public long PacketToFrame (long packet) { AudioFramePacketTranslation buffer; buffer.Packet = packet; unsafe { AudioFramePacketTranslation *p = &buffer; int size = Marshal.SizeOf (buffer); if (AudioFileStreamGetProperty (handle, AudioFileStreamProperty.PacketToFrame, ref size, (IntPtr) p) == 0) return buffer.Frame; return -1; } } public long FrameToPacket (long frame, out int frameOffsetInPacket) { AudioFramePacketTranslation buffer; buffer.Frame = frame; unsafe { AudioFramePacketTranslation *p = &buffer; int size = Marshal.SizeOf (buffer); if (AudioFileStreamGetProperty (handle, AudioFileStreamProperty.FrameToPacket, ref size, (IntPtr) p) == 0){ frameOffsetInPacket = buffer.FrameOffsetInPacket; return buffer.Packet; } frameOffsetInPacket = 0; return -1; } } public long PacketToByte (long packet, out bool isEstimate) { AudioBytePacketTranslation buffer; buffer.Packet = packet; unsafe { AudioBytePacketTranslation *p = &buffer; int size = Marshal.SizeOf (buffer); if (AudioFileStreamGetProperty (handle, AudioFileStreamProperty.PacketToByte, ref size, (IntPtr) p) == 0){ isEstimate = (buffer.Flags & 1) == 1; return buffer.Byte; } isEstimate = false; return -1; } } public long ByteToPacket (long byteval, out int byteOffsetInPacket, out bool isEstimate) { AudioBytePacketTranslation buffer; buffer.Byte = byteval; unsafe { AudioBytePacketTranslation *p = &buffer; int size = Marshal.SizeOf (buffer); if (AudioFileStreamGetProperty (handle, AudioFileStreamProperty.ByteToPacket, ref size, (IntPtr) p) == 0){ isEstimate = (buffer.Flags & 1) == 1; byteOffsetInPacket = buffer.ByteOffsetInPacket; return buffer.Packet; } byteOffsetInPacket = 0; isEstimate = false; return -1; } } public int BitRate { get { return GetInt (AudioFileStreamProperty.BitRate); } } public int PacketSizeUpperBound { get { return GetInt (AudioFileStreamProperty.PacketSizeUpperBound); } } public double AverageBytesPerPacket { get { return GetDouble (AudioFileStreamProperty.AverageBytesPerPacket); } } } }
using System; using System.Collections.Generic; using System.Linq; using Avalonia.Interactivity; using Avalonia.VisualTree; namespace Avalonia.Input { /// <summary> /// Handles access keys for a window. /// </summary> public class AccessKeyHandler : IAccessKeyHandler { /// <summary> /// Defines the AccessKeyPressed attached event. /// </summary> public static readonly RoutedEvent<RoutedEventArgs> AccessKeyPressedEvent = RoutedEvent.Register<RoutedEventArgs>( "AccessKeyPressed", RoutingStrategies.Bubble, typeof(AccessKeyHandler)); /// <summary> /// The registered access keys. /// </summary> private readonly List<Tuple<string, IInputElement>> _registered = new List<Tuple<string, IInputElement>>(); /// <summary> /// The window to which the handler belongs. /// </summary> private IInputRoot? _owner; /// <summary> /// Whether access keys are currently being shown; /// </summary> private bool _showingAccessKeys; /// <summary> /// Whether to ignore the Alt KeyUp event. /// </summary> private bool _ignoreAltUp; /// <summary> /// Whether the AltKey is down. /// </summary> private bool _altIsDown; /// <summary> /// Element to restore following AltKey taking focus. /// </summary> private IInputElement? _restoreFocusElement; /// <summary> /// The window's main menu. /// </summary> private IMainMenu? _mainMenu; /// <summary> /// Gets or sets the window's main menu. /// </summary> public IMainMenu? MainMenu { get => _mainMenu; set { if (_mainMenu != null) { _mainMenu.MenuClosed -= MainMenuClosed; } _mainMenu = value; if (_mainMenu != null) { _mainMenu.MenuClosed += MainMenuClosed; } } } /// <summary> /// Sets the owner of the access key handler. /// </summary> /// <param name="owner">The owner.</param> /// <remarks> /// This method can only be called once, typically by the owner itself on creation. /// </remarks> public void SetOwner(IInputRoot owner) { if (_owner != null) { throw new InvalidOperationException("AccessKeyHandler owner has already been set."); } _owner = owner ?? throw new ArgumentNullException(nameof(owner)); _owner.AddHandler(InputElement.KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); _owner.AddHandler(InputElement.KeyDownEvent, OnKeyDown, RoutingStrategies.Bubble); _owner.AddHandler(InputElement.KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); _owner.AddHandler(InputElement.PointerPressedEvent, OnPreviewPointerPressed, RoutingStrategies.Tunnel); } /// <summary> /// Registers an input element to be associated with an access key. /// </summary> /// <param name="accessKey">The access key.</param> /// <param name="element">The input element.</param> public void Register(char accessKey, IInputElement element) { var existing = _registered.FirstOrDefault(x => x.Item2 == element); if (existing != null) { _registered.Remove(existing); } _registered.Add(Tuple.Create(accessKey.ToString().ToUpper(), element)); } /// <summary> /// Unregisters the access keys associated with the input element. /// </summary> /// <param name="element">The input element.</param> public void Unregister(IInputElement element) { foreach (var i in _registered.Where(x => x.Item2 == element).ToList()) { _registered.Remove(i); } } /// <summary> /// Called when a key is pressed in the owner window. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> protected virtual void OnPreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.LeftAlt || e.Key == Key.RightAlt) { _altIsDown = true; if (MainMenu == null || !MainMenu.IsOpen) { // TODO: Use FocusScopes to store the current element and restore it when context menu is closed. // Save currently focused input element. _restoreFocusElement = FocusManager.Instance.Current; // When Alt is pressed without a main menu, or with a closed main menu, show // access key markers in the window (i.e. "_File"). _owner!.ShowAccessKeys = _showingAccessKeys = true; } else { // If the Alt key is pressed and the main menu is open, close the main menu. CloseMenu(); _ignoreAltUp = true; _restoreFocusElement?.Focus(); _restoreFocusElement = null; } // We always handle the Alt key. e.Handled = true; } else if (_altIsDown) { _ignoreAltUp = true; } } /// <summary> /// Called when a key is pressed in the owner window. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> protected virtual void OnKeyDown(object sender, KeyEventArgs e) { bool menuIsOpen = MainMenu?.IsOpen == true; if ((e.KeyModifiers & KeyModifiers.Alt) != 0 || menuIsOpen) { // If any other key is pressed with the Alt key held down, or the main menu is open, // find all controls who have registered that access key. var text = e.Key.ToString().ToUpper(); var matches = _registered .Where(x => x.Item1 == text && x.Item2.IsEffectivelyVisible) .Select(x => x.Item2); // If the menu is open, only match controls in the menu's visual tree. if (menuIsOpen) { matches = matches.Where(x => MainMenu.IsVisualAncestorOf(x)); } var match = matches.FirstOrDefault(); // If there was a match, raise the AccessKeyPressed event on it. if (match != null) { match.RaiseEvent(new RoutedEventArgs(AccessKeyPressedEvent)); e.Handled = true; } } } /// <summary> /// Handles the Alt/F10 keys being released in the window. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> protected virtual void OnPreviewKeyUp(object sender, KeyEventArgs e) { switch (e.Key) { case Key.LeftAlt: case Key.RightAlt: _altIsDown = false; if (_ignoreAltUp) { _ignoreAltUp = false; } else if (_showingAccessKeys && MainMenu != null) { MainMenu.Open(); e.Handled = true; } break; } } /// <summary> /// Handles pointer presses in the window. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> protected virtual void OnPreviewPointerPressed(object sender, PointerEventArgs e) { if (_showingAccessKeys) { _owner!.ShowAccessKeys = false; } } /// <summary> /// Closes the <see cref="MainMenu"/> and performs other bookeeping. /// </summary> private void CloseMenu() { MainMenu!.Close(); _owner!.ShowAccessKeys = _showingAccessKeys = false; } private void MainMenuClosed(object sender, EventArgs e) { _owner!.ShowAccessKeys = false; } } }
// 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.SpanTests { public static partial class ReadOnlySpanTests { [Fact] public static void IndexOfSequenceMatchAtStart() { ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 5, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 }); ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 5, 1, 77 }); int index = span.IndexOf(value); Assert.Equal(0, index); } [Fact] public static void IndexOfSequenceMultipleMatch() { ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 1, 2, 3, 1, 2, 3, 1, 2, 3 }); ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 2, 3 }); int index = span.IndexOf(value); Assert.Equal(1, index); } [Fact] public static void IndexOfSequenceRestart() { ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 }); ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 77, 77, 88 }); int index = span.IndexOf(value); Assert.Equal(10, index); } [Fact] public static void IndexOfSequenceNoMatch() { ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 }); ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 77, 77, 88, 99 }); int index = span.IndexOf(value); Assert.Equal(-1, index); } [Fact] public static void IndexOfSequenceNotEvenAHeadMatch() { ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 }); ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 100, 77, 88, 99 }); int index = span.IndexOf(value); Assert.Equal(-1, index); } [Fact] public static void IndexOfSequenceMatchAtVeryEnd() { ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 2, 3, 4, 5 }); ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 3, 4, 5 }); int index = span.IndexOf(value); Assert.Equal(3, index); } [Fact] public static void IndexOfSequenceJustPastVeryEnd() { ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 2, 3, 4, 5 }, 0, 5); ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 3, 4, 5 }); int index = span.IndexOf(value); Assert.Equal(-1, index); } [Fact] public static void IndexOfSequenceZeroLengthValue() { // A zero-length value is always "found" at the start of the span. ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 }); ReadOnlySpan<int> value = new ReadOnlySpan<int>(Array.Empty<int>()); int index = span.IndexOf(value); Assert.Equal(0, index); } [Fact] public static void IndexOfSequenceZeroLengthSpan() { ReadOnlySpan<int> span = new ReadOnlySpan<int>(Array.Empty<int>()); ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 1, 2, 3 }); int index = span.IndexOf(value); Assert.Equal(-1, index); } [Fact] public static void IndexOfSequenceLengthOneValue() { // A zero-length value is always "found" at the start of the span. ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 2, 3, 4, 5 }); ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 2 }); int index = span.IndexOf(value); Assert.Equal(2, index); } [Fact] public static void IndexOfSequenceLengthOneValueAtVeryEnd() { // A zero-length value is always "found" at the start of the span. ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 2, 3, 4, 5 }); ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 5 }); int index = span.IndexOf(value); Assert.Equal(5, index); } [Fact] public static void IndexOfSequenceLengthOneValueJustPasttVeryEnd() { // A zero-length value is always "found" at the start of the span. ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 2, 3, 4, 5 }, 0, 5); ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 5 }); int index = span.IndexOf(value); Assert.Equal(-1, index); } [Fact] public static void IndexOfSequenceMatchAtStart_String() { ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "5", "1", "77", "2", "3", "77", "77", "4", "5", "77", "77", "77", "88", "6", "6", "77", "77", "88", "9" }); ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "5", "1", "77" }); int index = span.IndexOf(value); Assert.Equal(0, index); } [Fact] public static void IndexOfSequenceMultipleMatch_String() { ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "1", "2", "3", "1", "2", "3", "1", "2", "3" }); ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "2", "3" }); int index = span.IndexOf(value); Assert.Equal(1, index); } [Fact] public static void IndexOfSequenceRestart_String() { ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "0", "1", "77", "2", "3", "77", "77", "4", "5", "77", "77", "77", "88", "6", "6", "77", "77", "88", "9" }); ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "77", "77", "88" }); int index = span.IndexOf(value); Assert.Equal(10, index); } [Fact] public static void IndexOfSequenceNoMatch_String() { ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "0", "1", "77", "2", "3", "77", "77", "4", "5", "77", "77", "77", "88", "6", "6", "77", "77", "88", "9" }); ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "77", "77", "88", "99" }); int index = span.IndexOf(value); Assert.Equal(-1, index); } [Fact] public static void IndexOfSequenceNotEvenAHeadMatch_String() { ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "0", "1", "77", "2", "3", "77", "77", "4", "5", "77", "77", "77", "88", "6", "6", "77", "77", "88", "9" }); ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "100", "77", "88", "99" }); int index = span.IndexOf(value); Assert.Equal(-1, index); } [Fact] public static void IndexOfSequenceMatchAtVeryEnd_String() { ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "0", "1", "2", "3", "4", "5" }); ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "3", "4", "5" }); int index = span.IndexOf(value); Assert.Equal(3, index); } [Fact] public static void IndexOfSequenceJustPastVeryEnd_String() { ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "0", "1", "2", "3", "4", "5" }, 0, 5); ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "3", "4", "5" }); int index = span.IndexOf(value); Assert.Equal(-1, index); } [Fact] public static void IndexOfSequenceZeroLengthValue_String() { // A zero-length value is always "found" at the start of the span. ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "0", "1", "77", "2", "3", "77", "77", "4", "5", "77", "77", "77", "88", "6", "6", "77", "77", "88", "9" }); ReadOnlySpan<string> value = new ReadOnlySpan<string>(Array.Empty<string>()); int index = span.IndexOf(value); Assert.Equal(0, index); } [Fact] public static void IndexOfSequenceZeroLengthSpan_String() { ReadOnlySpan<string> span = new ReadOnlySpan<string>(Array.Empty<string>()); ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "1", "2", "3" }); int index = span.IndexOf(value); Assert.Equal(-1, index); } [Fact] public static void IndexOfSequenceLengthOneValue_String() { // A zero-length value is always "found" at the start of the span. ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "0", "1", "2", "3", "4", "5" }); ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "2" }); int index = span.IndexOf(value); Assert.Equal(2, index); } [Fact] public static void IndexOfSequenceLengthOneValueAtVeryEnd_String() { // A zero-length value is always "found" at the start of the span. ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "0", "1", "2", "3", "4", "5" }); ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "5" }); int index = span.IndexOf(value); Assert.Equal(5, index); } [Fact] public static void IndexOfSequenceLengthOneValueJustPasttVeryEnd_String() { // A zero-length value is always "found" at the start of the span. ReadOnlySpan<string> span = new ReadOnlySpan<string>(new string[] { "0", "1", "2", "3", "4", "5" }, 0, 5); ReadOnlySpan<string> value = new ReadOnlySpan<string>(new string[] { "5" }); int index = span.IndexOf(value); Assert.Equal(-1, index); } [Theory] [MemberData(nameof(TestHelpers.IndexOfNullSequenceData), MemberType = typeof(TestHelpers))] public static void IndexOfNullSequence_String(string[] spanInput, string[] searchInput, int expected) { ReadOnlySpan<string> theStrings = spanInput; Assert.Equal(expected, theStrings.IndexOf(searchInput)); Assert.Equal(expected, theStrings.IndexOf((ReadOnlySpan<string>)searchInput)); } } }
namespace ALinq.SqlClient { internal static class Strings { // Methods internal static string BadProjectionInSelect { get { return SR.GetString("BadProjectionInSelect"); } } internal static string CannotCompareItemsAssociatedWithDifferentTable { get { return SR.GetString("CannotCompareItemsAssociatedWithDifferentTable"); } } internal static string CannotEnumerateResultsMoreThanOnce { get { return SR.GetString("CannotEnumerateResultsMoreThanOnce"); } } internal static string CannotTranslateExpressionToSql { get { return SR.GetString("CannotTranslateExpressionToSql"); } } internal static string CapturedValuesCannotBeSequences { get { return SR.GetString("CapturedValuesCannotBeSequences"); } } internal static string ColumnCannotReferToItself { get { return SR.GetString("ColumnCannotReferToItself"); } } internal static string ColumnClrTypeDoesNotAgreeWithExpressionsClrType { get { return SR.GetString("ColumnClrTypeDoesNotAgreeWithExpressionsClrType"); } } internal static string CompiledQueryAgainstMultipleShapesNotSupported { get { return SR.GetString("CompiledQueryAgainstMultipleShapesNotSupported"); } } internal static string ConstructedArraysNotSupported { get { return SR.GetString("ConstructedArraysNotSupported"); } } internal static string ContextNotInitialized { get { return SR.GetString("ContextNotInitialized"); } } internal static string ConvertToCharFromBoolNotSupported { get { return SR.GetString("ConvertToCharFromBoolNotSupported"); } } internal static string ConvertToDateTimeOnlyForDateTimeOrString { get { return SR.GetString("ConvertToDateTimeOnlyForDateTimeOrString"); } } internal static string CouldNotDetermineCatalogName { get { return SR.GetString("CouldNotDetermineCatalogName"); } } internal static string CouldNotGetClrType { get { return SR.GetString("CouldNotGetClrType"); } } internal static string CouldNotGetSqlType { get { return SR.GetString("CouldNotGetSqlType"); } } internal static string DatabaseDeleteThroughContext { get { return SR.GetString("DatabaseDeleteThroughContext"); } } internal static string DeferredMemberWrongType { get { return SR.GetString("DeferredMemberWrongType"); } } internal static string DidNotExpectTypeBinding { get { return SR.GetString("DidNotExpectTypeBinding"); } } internal static string DistributedTransactionsAreNotAllowed { get { return SR.GetString("DistributedTransactionsAreNotAllowed"); } } internal static string EmptyCaseNotSupported { get { return SR.GetString("EmptyCaseNotSupported"); } } internal static string ExceptNotSupportedForHierarchicalTypes { get { return SR.GetString("ExceptNotSupportedForHierarchicalTypes"); } } internal static string ExpectedBitFoundPredicate { get { return SR.GetString("ExpectedBitFoundPredicate"); } } internal static string ExpectedNoObjectType { get { return SR.GetString("ExpectedNoObjectType"); } } internal static string ExpectedPredicateFoundBit { get { return SR.GetString("ExpectedPredicateFoundBit"); } } internal static string ExpressionNotDeferredQuerySource { get { return SR.GetString("ExpressionNotDeferredQuerySource"); } } internal static string GeneralCollectionMaterializationNotSupported { get { return SR.GetString("GeneralCollectionMaterializationNotSupported"); } } internal static string GroupingNotSupportedAsOrderCriterion { get { return SR.GetString("GroupingNotSupportedAsOrderCriterion"); } } internal static string Impossible { get { return SR.GetString("Impossible"); } } internal static string IndexOfWithStringComparisonArgNotSupported { get { return SR.GetString("IndexOfWithStringComparisonArgNotSupported"); } } internal static string InfiniteDescent { get { return SR.GetString("InfiniteDescent"); } } internal static string InsertItemMustBeConstant { get { return SR.GetString("InsertItemMustBeConstant"); } } internal static string IntersectNotSupportedForHierarchicalTypes { get { return SR.GetString("IntersectNotSupportedForHierarchicalTypes"); } } internal static string InvalidGroupByExpression { get { return SR.GetString("InvalidGroupByExpression"); } } internal static string InvalidReferenceToRemovedAliasDuringDeflation { get { return SR.GetString("InvalidReferenceToRemovedAliasDuringDeflation"); } } internal static string LastIndexOfWithStringComparisonArgNotSupported { get { return SR.GetString("LastIndexOfWithStringComparisonArgNotSupported"); } } internal static string MathRoundNotSupported { get { return SR.GetString("MathRoundNotSupported"); } } internal static string NonConstantExpressionsNotSupportedForRounding { get { return SR.GetString("NonConstantExpressionsNotSupportedForRounding"); } } internal static string OwningTeam { get { return SR.GetString("OwningTeam"); } } internal static string ParametersCannotBeSequences { get { return SR.GetString("ParametersCannotBeSequences"); } } internal static string ProviderCannotBeUsedAfterDispose { get { return SR.GetString("ProviderCannotBeUsedAfterDispose"); } } internal static string QueryOnLocalCollectionNotSupported { get { return SR.GetString("QueryOnLocalCollectionNotSupported"); } } internal static string ReaderUsedAfterDispose { get { return SR.GetString("ReaderUsedAfterDispose"); } } internal static string SelectManyDoesNotSupportStrings { get { return SR.GetString("SelectManyDoesNotSupportStrings"); } } internal static string SkipIsValidOnlyOverOrderedQueries { get { return SR.GetString("SkipIsValidOnlyOverOrderedQueries"); } } internal static string SkipNotSupportedForSequenceTypes { get { return SR.GetString("SkipNotSupportedForSequenceTypes"); } } internal static string SkipRequiresSingleTableQueryWithPKs { get { return SR.GetString("SkipRequiresSingleTableQueryWithPKs"); } } internal static string SprocsCannotBeComposed { get { return SR.GetString("SprocsCannotBeComposed"); } } internal static string ToStringOnlySupportedForPrimitiveTypes { get { return SR.GetString("ToStringOnlySupportedForPrimitiveTypes"); } } internal static string TransactionDoesNotMatchConnection { get { return SR.GetString("TransactionDoesNotMatchConnection"); } } internal static string TypeBinaryOperatorNotRecognized { get { return SR.GetString("TypeBinaryOperatorNotRecognized"); } } internal static string TypeColumnWithUnhandledSource { get { return SR.GetString("TypeColumnWithUnhandledSource"); } } internal static string UnexpectedFloatingColumn { get { return SR.GetString("UnexpectedFloatingColumn"); } } internal static string UnexpectedSharedExpression { get { return SR.GetString("UnexpectedSharedExpression"); } } internal static string UnexpectedSharedExpressionReference { get { return SR.GetString("UnexpectedSharedExpressionReference"); } } internal static string UnhandledStringTypeComparison { get { return SR.GetString("UnhandledStringTypeComparison"); } } internal static string UnionDifferentMemberOrder { get { return SR.GetString("UnionDifferentMemberOrder"); } } internal static string UnionDifferentMembers { get { return SR.GetString("UnionDifferentMembers"); } } internal static string UnionIncompatibleConstruction { get { return SR.GetString("UnionIncompatibleConstruction"); } } internal static string UnionOfIncompatibleDynamicTypes { get { return SR.GetString("UnionOfIncompatibleDynamicTypes"); } } internal static string UnionWithHierarchy { get { return SR.GetString("UnionWithHierarchy"); } } internal static string UnsupportedDateTimeConstructorForm { get { return SR.GetString("UnsupportedDateTimeConstructorForm"); } } internal static string UnsupportedStringConstructorForm { get { return SR.GetString("UnsupportedStringConstructorForm"); } } internal static string UnsupportedTimeSpanConstructorForm { get { return SR.GetString("UnsupportedTimeSpanConstructorForm"); } } internal static string UpdateItemMustBeConstant { get { return SR.GetString("UpdateItemMustBeConstant"); } } internal static string VbLikeDoesNotSupportMultipleCharacterRanges { get { return SR.GetString("VbLikeDoesNotSupportMultipleCharacterRanges"); } } internal static string VbLikeUnclosedBracket { get { return SR.GetString("VbLikeUnclosedBracket"); } } internal static string WrongDataContext { get { return SR.GetString("WrongDataContext"); } } internal static string ArgumentEmpty(object p0) { return SR.GetString("ArgumentEmpty", new[] {p0}); } internal static string ArgumentTypeMismatch(object p0) { return SR.GetString("ArgumentTypeMismatch", new[] {p0}); } internal static string ArgumentWrongType(object p0, object p1, object p2) { return SR.GetString("ArgumentWrongType", new[] {p0, p1, p2}); } internal static string ArgumentWrongValue(object p0) { return SR.GetString("ArgumentWrongValue", new[] {p0}); } internal static string BadParameterType(object p0) { return SR.GetString("BadParameterType", new[] {p0}); } internal static string BinaryOperatorNotRecognized(object p0) { return SR.GetString("BinaryOperatorNotRecognized", new[] {p0}); } internal static string CannotAggregateType(object p0) { return SR.GetString("CannotAggregateType", new[] {p0}); } internal static string CannotAssignNull(object p0) { return SR.GetString("CannotAssignNull", new[] {p0}); } internal static string CannotAssignToMember(object p0) { return SR.GetString("CannotAssignToMember", new[] {p0}); } internal static string CannotConvertToEntityRef(object p0) { return SR.GetString("CannotConvertToEntityRef", new[] {p0}); } internal static string CannotDeleteTypesOf(object p0) { return SR.GetString("CannotDeleteTypesOf", new[] {p0}); } internal static string CannotMaterializeEntityType(object p0) { return SR.GetString("CannotMaterializeEntityType", new[] {p0}); } internal static string ClassLiteralsNotAllowed(object p0) { return SR.GetString("ClassLiteralsNotAllowed", new[] {p0}); } internal static string ClientCaseShouldNotHold(object p0) { return SR.GetString("ClientCaseShouldNotHold", new[] {p0}); } internal static string ClrBoolDoesNotAgreeWithSqlType(object p0) { return SR.GetString("ClrBoolDoesNotAgreeWithSqlType", new[] {p0}); } internal static string ColumnIsDefinedInMultiplePlaces(object p0) { return SR.GetString("ColumnIsDefinedInMultiplePlaces", new[] {p0}); } internal static string ColumnIsNotAccessibleThroughDistinct(object p0) { return SR.GetString("ColumnIsNotAccessibleThroughDistinct", new[] {p0}); } internal static string ColumnIsNotAccessibleThroughGroupBy(object p0) { return SR.GetString("ColumnIsNotAccessibleThroughGroupBy", new[] {p0}); } internal static string ColumnReferencedIsNotInScope(object p0) { return SR.GetString("ColumnReferencedIsNotInScope", new[] {p0}); } internal static string ComparisonNotSupportedForType(object p0) { return SR.GetString("ComparisonNotSupportedForType", new[] {p0}); } internal static string CompiledQueryCannotReturnType(object p0) { return SR.GetString("CompiledQueryCannotReturnType", new[] {p0}); } internal static string CouldNotAssignSequence(object p0, object p1) { return SR.GetString("CouldNotAssignSequence", new[] {p0, p1}); } internal static string CouldNotConvertToPropertyOrField(object p0) { return SR.GetString("CouldNotConvertToPropertyOrField", new[] {p0}); } internal static string CouldNotDetermineDbGeneratedSqlType(object p0) { return SR.GetString("CouldNotDetermineDbGeneratedSqlType", new[] {p0}); } internal static string CouldNotDetermineSqlType(object p0) { return SR.GetString("CouldNotDetermineSqlType", new[] {p0}); } internal static string CouldNotHandleAliasRef(object p0) { return SR.GetString("CouldNotHandleAliasRef", new[] {p0}); } internal static string CouldNotTranslateExpressionForReading(object p0) { return SR.GetString("CouldNotTranslateExpressionForReading", new[] {p0}); } internal static string CreateDatabaseFailedBecauseOfClassWithNoMembers(object p0) { return SR.GetString("CreateDatabaseFailedBecauseOfClassWithNoMembers", new[] {p0}); } internal static string CreateDatabaseFailedBecauseOfContextWithNoTables(object p0) { return SR.GetString("CreateDatabaseFailedBecauseOfContextWithNoTables", new[] {p0}); } internal static string CreateDatabaseFailedBecauseSqlCEDatabaseAlreadyExists(object p0) { return SR.GetString("CreateDatabaseFailedBecauseSqlCEDatabaseAlreadyExists", new[] {p0}); } internal static string DidNotExpectAs(object p0) { return SR.GetString("DidNotExpectAs", new[] {p0}); } internal static string DidNotExpectTypeChange(object p0, object p1) { return SR.GetString("DidNotExpectTypeChange", new[] {p0, p1}); } internal static string ExpectedClrTypesToAgree(object p0, object p1) { return SR.GetString("ExpectedClrTypesToAgree", new[] {p0, p1}); } internal static string ExpectedQueryableArgument(object p0, object p1, object p2) { return SR.GetString("ExpectedQueryableArgument", new[] {p0, p1, p2}); } internal static string IifReturnTypesMustBeEqual(object p0, object p1) { return SR.GetString("IifReturnTypesMustBeEqual", new[] {p0, p1}); } internal static string InvalidConnectionArgument(object p0) { return SR.GetString("InvalidConnectionArgument", new[] {p0}); } internal static string InvalidDbGeneratedType(object p0) { return SR.GetString("InvalidDbGeneratedType", new[] {p0}); } internal static string InvalidFormatNode(object p0) { return SR.GetString("InvalidFormatNode", new[] {p0}); } internal static string InvalidGroupByExpressionType(object p0) { return SR.GetString("InvalidGroupByExpressionType", new[] {p0}); } internal static string InvalidMethodExecution(object p0) { return SR.GetString("InvalidMethodExecution", new[] {p0}); } internal static string InvalidOrderByExpression(object p0) { return SR.GetString("InvalidOrderByExpression", new[] {p0}); } internal static string InvalidProviderType(object p0) { return SR.GetString("InvalidProviderType", new[] {p0}); } internal static string InvalidReturnFromSproc(object p0) { return SR.GetString("InvalidReturnFromSproc", new[] {p0}); } internal static string InvalidSequenceOperatorCall(object p0) { return SR.GetString("InvalidSequenceOperatorCall", new[] {p0}); } internal static string LenOfTextOrNTextNotSupported(object p0) { return SR.GetString("LenOfTextOrNTextNotSupported", new[] {p0}); } internal static string LogAttemptingToDeleteDatabase(object p0) { return SR.GetString("LogAttemptingToDeleteDatabase", new[] {p0}); } public static string LogGeneralInfoMessage(object p0, object p1) { return SR.GetString("LogGeneralInfoMessage", new[] {p0, p1}); } internal static string LogStoredProcedureExecution(object p0, object p1) { return SR.GetString("LogStoredProcedureExecution", new[] {p0, p1}); } internal static string MappedTypeMustHaveDefaultConstructor(object p0) { return SR.GetString("MappedTypeMustHaveDefaultConstructor", new[] {p0}); } internal static string MaxSizeNotSupported(object p0) { return SR.GetString("MaxSizeNotSupported", new[] {p0}); } internal static string MemberAccessIllegal(object p0, object p1, object p2) { return SR.GetString("MemberAccessIllegal", new[] {p0, p1, p2}); } internal static string MemberCannotBeTranslated(object p0, object p1) { return SR.GetString("MemberCannotBeTranslated", new[] {p0, p1}); } internal static string MemberCouldNotBeTranslated(object p0, object p1) { return SR.GetString("MemberCouldNotBeTranslated", new[] {p0, p1}); } internal static string MemberNotPartOfProjection(object p0, object p1) { return SR.GetString("MemberNotPartOfProjection", new[] {p0, p1}); } internal static string MethodFormHasNoSupportConversionToSql(object p0, object p1) { return SR.GetString("MethodFormHasNoSupportConversionToSql", new[] {p0, p1}); } internal static string MethodHasNoSupportConversionToSql(object p0) { return SR.GetString("MethodHasNoSupportConversionToSql", new[] {p0}); } internal static string MethodNotMappedToStoredProcedure(object p0) { return SR.GetString("MethodNotMappedToStoredProcedure", new[] {p0}); } internal static string NoMethodInTypeMatchingArguments(object p0) { return SR.GetString("NoMethodInTypeMatchingArguments", new[] {p0}); } internal static string NonConstantExpressionsNotSupportedFor(object p0) { return SR.GetString("NonConstantExpressionsNotSupportedFor", new[] {p0}); } internal static string NonCountAggregateFunctionsAreNotValidOnProjections(object p0) { return SR.GetString("NonCountAggregateFunctionsAreNotValidOnProjections", new[] {p0}); } internal static string ParameterNotInScope(object p0) { return SR.GetString("ParameterNotInScope", new[] {p0}); } internal static string ProviderNotInstalled(object p0, object p1) { return SR.GetString("ProviderNotInstalled", new[] {p0, p1}); } internal static string QueryOperatorNotSupported(object p0) { return SR.GetString("QueryOperatorNotSupported", new[] {p0}); } internal static string QueryOperatorOverloadNotSupported(object p0) { return SR.GetString("QueryOperatorOverloadNotSupported", new[] {p0}); } internal static string RequiredColumnDoesNotExist(object p0) { return SR.GetString("RequiredColumnDoesNotExist", new[] {p0}); } internal static string ResultTypeNotMappedToFunction(object p0, object p1) { return SR.GetString("ResultTypeNotMappedToFunction", new[] {p0, p1}); } internal static string SequenceOperatorsNotSupportedForType(object p0) { return SR.GetString("SequenceOperatorsNotSupportedForType", new[] {p0}); } internal static string SimpleCaseShouldNotHold(object p0) { return SR.GetString("SimpleCaseShouldNotHold", new[] {p0}); } internal static string SourceExpressionAnnotation(object p0) { return SR.GetString("SourceExpressionAnnotation", new[] {p0}); } internal static string SqlMethodOnlyForSql(object p0) { return SR.GetString("SqlMethodOnlyForSql", new[] {p0}); } internal static string TextNTextAndImageCannotOccurInDistinct(object p0) { return SR.GetString("TextNTextAndImageCannotOccurInDistinct", new[] {p0}); } internal static string TextNTextAndImageCannotOccurInUnion(object p0) { return SR.GetString("TextNTextAndImageCannotOccurInUnion", new[] {p0}); } internal static string TypeCannotBeOrdered(object p0) { return SR.GetString("TypeCannotBeOrdered", new[] {p0}); } internal static string UnableToBindUnmappedMember(object p0, object p1, object p2) { return SR.GetString("UnableToBindUnmappedMember", new[] {p0, p1, p2}); } internal static string UnexpectedNode(object p0) { return SR.GetString("UnexpectedNode", new[] {p0}); } internal static string UnexpectedTypeCode(object p0) { return SR.GetString("UnexpectedTypeCode", new[] {p0}); } internal static string UnhandledBindingType(object p0) { return SR.GetString("UnhandledBindingType", new[] {p0}); } internal static string UnhandledExpressionType(object p0) { return SR.GetString("UnhandledExpressionType", new[] {p0}); } internal static string UnhandledMemberAccess(object p0, object p1) { return SR.GetString("UnhandledMemberAccess", new[] {p0, p1}); } internal static string UnmappedDataMember(object p0, object p1, object p2) { return SR.GetString("UnmappedDataMember", new[] {p0, p1, p2}); } internal static string UnrecognizedExpressionNode(object p0) { return SR.GetString("UnrecognizedExpressionNode", new[] {p0}); } internal static string UnrecognizedProviderMode(object p0) { return SR.GetString("UnrecognizedProviderMode", new[] {p0}); } internal static string UnsafeStringConversion(object p0, object p1) { return SR.GetString("UnsafeStringConversion", new[] {p0, p1}); } internal static string UnsupportedNodeType(object p0) { return SR.GetString("UnsupportedNodeType", new[] {p0}); } internal static string UnsupportedTypeConstructorForm(object p0) { return SR.GetString("UnsupportedTypeConstructorForm", new[] {p0}); } internal static string ValueHasNoLiteralInSql(object p0) { return SR.GetString("ValueHasNoLiteralInSql", new[] {p0}); } internal static string WrongNumberOfValuesInCollectionArgument(object p0, object p1, object p2) { return SR.GetString("WrongNumberOfValuesInCollectionArgument", new[] {p0, p1, p2}); } // Properties } }
using UnityEngine; #if UNITY_EDITOR using UnityEditor; using System.IO; #endif using UMA; namespace UMA.Examples { public class UMARecipeCrowd : MonoBehaviour { public UMAContext context; public UMAGeneratorBase generator; public RuntimeAnimatorController animationController; public float atlasScale = 0.5f; public bool hideWhileGenerating; public bool stressTest; public Vector2 crowdSize; public float space = 1f; private int spawnX; private int spawnY; private bool generating = false; public bool saveCrowd = false; private string saveFolderPath; public SharedColorTable[] sharedColors; public UMARecipeMixer[] recipeMixers; public UMADataEvent CharacterCreated; public UMADataEvent CharacterDestroyed; public UMADataEvent CharacterUpdated; void Awake() { if (space <= 0) space = 1f; if (atlasScale > 1f) atlasScale = 1f; if (atlasScale < 0.0625f) atlasScale = 0.0625f; if ((crowdSize.x > 0) && (crowdSize.y > 0)) generating = true; #if UNITY_EDITOR if (saveCrowd) { saveFolderPath = "Saved Crowd " + System.DateTime.Now.ToString().Replace('/', '_'); saveFolderPath = saveFolderPath.Replace(':', '_'); string folderGUID = AssetDatabase.CreateFolder("Assets", saveFolderPath); saveFolderPath = AssetDatabase.GUIDToAssetPath(folderGUID); Debug.LogWarning("Saving all generated recipes into: " + saveFolderPath); } #endif } void Update() { if (generator.IsIdle()) { if (generating) { GenerateOneCharacter(); } else if (stressTest) { RandomizeAll(); } } } void CharacterCreatedCallback(UMAData umaData) { if (hideWhileGenerating) { if (umaData.animator != null) umaData.animator.enabled = false; Renderer[] renderers = umaData.GetRenderers(); for (int i = 0; i < renderers.Length; i++) { renderers[i].enabled = false; } } } public GameObject GenerateOneCharacter() { if ((recipeMixers == null) || (recipeMixers.Length == 0)) return null; Vector3 umaPos = new Vector3((spawnX - crowdSize.x / 2f) * space, 0f, (spawnY - crowdSize.y / 2f) * space); if (spawnY < crowdSize.y) { spawnX++; if (spawnX >= crowdSize.x) { spawnX = 0; spawnY++; } } else { if (hideWhileGenerating) { UMAData[] generatedCrowd = GetComponentsInChildren<UMAData>(); foreach (UMAData generatedData in generatedCrowd) { if (generatedData.animator != null) generatedData.animator.enabled = true; Renderer[] renderers = generatedData.GetRenderers(); for (int i = 0; i < renderers.Length; i++) { renderers[i].enabled = true; } } } spawnX = 0; spawnY = 0; generating = false; return null; } GameObject newGO = new GameObject("Generated Character"); newGO.transform.parent = transform; newGO.transform.localPosition = umaPos; newGO.transform.localRotation = Quaternion.identity; UMADynamicAvatar umaAvatar = newGO.AddComponent<UMADynamicAvatar>(); umaAvatar.context = context; umaAvatar.umaGenerator = generator; umaAvatar.Initialize(); UMAData umaData = umaAvatar.umaData; umaData.atlasResolutionScale = atlasScale; umaData.CharacterCreated = new UMADataEvent(CharacterCreated); umaData.OnCharacterCreated += CharacterCreatedCallback; umaData.CharacterDestroyed = new UMADataEvent(CharacterDestroyed); umaData.CharacterUpdated = new UMADataEvent(CharacterUpdated); RandomizeRecipe(umaData); RandomizeDNA(umaData); if (animationController != null) { umaAvatar.animationController = animationController; } umaAvatar.Show(); return newGO; } public void ReplaceAll() { if (generating) { Debug.LogWarning("Can't replace while generating."); return; } int childCount = gameObject.transform.childCount; while(--childCount >= 0) { Transform child = gameObject.transform.GetChild(childCount); UMAUtils.DestroySceneObject(child.gameObject); } generating = true; } public virtual void RandomizeRecipe(UMAData umaData) { UMARecipeMixer mixer = recipeMixers[Random.Range(0, recipeMixers.Length)]; mixer.FillUMARecipe(umaData.umaRecipe, context); OverlayColorData[] recipeColors = umaData.umaRecipe.sharedColors; if ((recipeColors != null) && (recipeColors.Length > 0)) { foreach (var sharedColor in sharedColors) { if (sharedColor == null) continue; int index = Random.Range(0, sharedColor.colors.Length); for (int i = 0; i < recipeColors.Length; i++) { if (recipeColors[i].name == sharedColor.sharedColorName) { recipeColors[i].color = sharedColor.colors[index].color; } } } } // This is a HACK - maybe there should be a clean way // of removing a conflicting slot via the recipe? int maleJeansIndex = -1; int maleLegsIndex = -1; SlotData[] slots = umaData.umaRecipe.GetAllSlots(); for (int i = 0; i < slots.Length; i++) { SlotData slot = slots[i]; if (slot == null) continue; if (slot.asset.name == null) continue; if (slot.asset.slotName == "MaleJeans01") maleJeansIndex = i; else if (slot.asset.slotName == "MaleLegs") maleLegsIndex = i; } if ((maleJeansIndex >= 0) && (maleLegsIndex >= 0)) { umaData.umaRecipe.SetSlot(maleLegsIndex, null); } #if UNITY_EDITOR if (saveCrowd) { SaveRecipe(umaData, context); } #endif } #if UNITY_EDITOR protected void SaveRecipe(UMAData umaData, UMAContext context) { string assetPath = AssetDatabase.GenerateUniqueAssetPath(Path.Combine(saveFolderPath, umaData.umaRecipe.raceData.raceName + ".asset")); var asset = ScriptableObject.CreateInstance<UMATextRecipe>(); asset.Save(umaData.umaRecipe, context); AssetDatabase.CreateAsset(asset, assetPath); AssetDatabase.SaveAssets(); } #endif public virtual void RandomizeDNA(UMAData umaData) { RaceData race = umaData.umaRecipe.GetRace(); if ((race != null) && (race.dnaRanges != null)) { foreach (DNARangeAsset dnaRange in race.dnaRanges) { dnaRange.RandomizeDNA(umaData); } } } public virtual void RandomizeDNAGaussian(UMAData umaData) { RaceData race = umaData.umaRecipe.GetRace(); if ((race != null) && (race.dnaRanges != null)) { foreach (DNARangeAsset dnaRange in race.dnaRanges) { dnaRange.RandomizeDNAGaussian(umaData); } } } public void RandomizeAll() { if (generating) { Debug.LogWarning("Can't randomize while generating."); return; } int childCount = gameObject.transform.childCount; for (int i = 0; i < childCount; i++) { Transform child = gameObject.transform.GetChild(i); UMADynamicAvatar umaAvatar = child.gameObject.GetComponent<UMADynamicAvatar>(); if (umaAvatar == null) continue; UMAData umaData = umaAvatar.umaData; umaData.umaRecipe = new UMAData.UMARecipe(); RandomizeRecipe(umaData); RandomizeDNA(umaData); if (animationController != null) { umaAvatar.animationController = animationController; } umaAvatar.Show(); } } } }
/* MIT License Copyright (c) 2017 Saied Zarrinmehr Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using SpatialAnalysis.CellularEnvironment.GetCellValue; using System.Windows; using SpatialAnalysis.Geometry; namespace SpatialAnalysis.CellularEnvironment { /// <summary> /// This class includes utility functions for cells /// </summary> internal static class CellUtility { /// <summary> /// Determines if a cell is on the edges of a cell collections /// </summary> /// <param name="cellID">The ID of the cell</param> /// <param name="cellularFloor">The CellularFloorBaseGeometry to which this cell belongs</param> /// <param name="collection">Cell ID collection</param> /// <returns>true for being on the edge false for not being on the edge</returns> private static bool onEdge(int cellID, CellularFloorBaseGeometry cellularFloor, HashSet<int> collection) { var index = cellularFloor.FindIndex(cellID); if (index.I == 0 || index.I == cellularFloor.GridWidth - 1 || index.J == 0 || index.J == cellularFloor.GridHeight - 1) { return true; } int iMin = (index.I == 0) ? 0 : index.I - 1; int iMax = (index.I == cellularFloor.GridWidth - 1) ? cellularFloor.GridWidth - 1 : index.I + 1; int jMin = (index.J == 0) ? 0 : index.J - 1; int jMax = (index.J == cellularFloor.GridHeight - 1) ? cellularFloor.GridHeight - 1 : index.J + 1; for (int i = iMin; i <= iMax; i++) { for (int j = jMin; j <= jMax; j++) { if (cellularFloor.ContainsCell(i,j)) { if (!collection.Contains(cellularFloor.Cells[i, j].ID)) { return true; } } } } return false; } /// <summary> /// Determines if a cell is on the edges of a cell collections /// </summary> /// <param name="index">The index of the cell</param> /// <param name="cellularFloor">The CellularFloorBaseGeometry to which this cell belongs</param> /// <param name="collection">Cell ID collection</param> /// <returns>true for being on the edge false for not being on the edge</returns> private static bool onEdge(Index index, CellularFloorBaseGeometry cellularFloor, HashSet<Cell> collection) { foreach (Index item in Index.Neighbors) { Index neighbor = item + index; if (cellularFloor.ContainsCell(neighbor)) { if (!collection.Contains(cellularFloor.Cells[neighbor.I,neighbor.J])) { return true; } } } return false; } /// <summary> /// Determines if a cell is on the edges of a cell collections /// </summary> /// <param name="index">The index of the cell</param> /// <param name="cellularFloor">The CellularFloorBaseGeometry to which this cell belongs</param> /// <param name="collection">Cell index collection</param> /// <returns>true for being on the edge false for not being on the edge</returns> private static bool onEdge(Index index, CellularFloorBaseGeometry cellularFloor, HashSet<Index> collection) { foreach (Index item in Index.Neighbors) { Index neighbor = item + index; if (cellularFloor.ContainsCell(neighbor)) { if (!collection.Contains(neighbor)) { return true; } } } return false; } /// <summary> /// Extracts the edges of a collection of cells /// </summary> /// <param name="cellularFloor">The CellularFloorBaseGeometry to which the cells belong</param> /// <param name="collection">A collection of cells IDs to find its edges</param> /// <returns>A collection of cell IDs on the edge</returns> public static HashSet<int> GetEdgeOfField(CellularFloorBaseGeometry cellularFloor, HashSet<int> collection) { HashSet<int> edge = new HashSet<int>(); foreach (var item in collection) { if (CellUtility.onEdge(item, cellularFloor, collection)) { edge.Add(item); } } return edge; } /// <summary> /// Extracts the edges of a collection of cells /// </summary> /// <param name="cellularFloor">The CellularFloorBaseGeometry to which the cells belong</param> /// <param name="collection">A collection of cells to find its edges</param> /// <returns>A collection of cell indices on the edge</returns> public static HashSet<Index> GetIndexEdgeOfField(CellularFloorBaseGeometry cellularFloor, HashSet<Cell> collection) { HashSet<Index> edge = new HashSet<Index>(); foreach (var item in collection) { Index index = cellularFloor.FindIndex(item); if (CellUtility.onEdge(index, cellularFloor, collection)) { edge.Add(index); } } return edge; } /// <summary> /// Get a list of ordered cells on the edge of a cell collection /// </summary> /// <param name="cellularFloor">The CellularFloorBaseGeometry to which the cells belong</param> /// <param name="collection">A collection of cells to find its edges</param> /// <returns>An ordered list of cells</returns> public static List<Cell> GetOrderedEdge(CellularFloorBaseGeometry cellularFloor, HashSet<Cell> collection) { HashSet<Index> edge = CellUtility.GetIndexEdgeOfField(cellularFloor, collection); IndexGraph indexGraph = new IndexGraph(edge); int zero = 0, one = 0, two = 0, three = 0, four = 0; foreach (var item in indexGraph.IndexNodeMap.Values) { switch (item.Connections.Count) { case 0: zero++; break; case 1: one++; break; case 2: two++; break; case 3: three++; break; case 4: four++; break; default: break; } } MessageBox.Show(string.Format("Zero: {0}\nOne: {1}\nTwo: {2}\nThree: {3}\nFour: {4}", zero.ToString(), one.ToString(), two.ToString(), three.ToString(), four.ToString())); return null; } /// <summary> /// Gets the boundary polygons of a collection of cells. /// </summary> /// <param name="cellIDs">The visible cells.</param> /// <param name="cellularFloor">The cellular floor.</param> /// <returns>List&lt;BarrierPolygons&gt;.</returns> public static List<BarrierPolygon> GetBoundary(ICollection<int> cellIDs, CellularFloorBaseGeometry cellularFloor) { Dictionary<UVLine, int> guid = new Dictionary<UVLine, int>(); foreach (var item in cellIDs) { var lines = cellularFloor.CellToLines(cellularFloor.FindCell(item)); foreach (var line in lines) { if (guid.ContainsKey(line)) { guid[line]++; } else { guid.Add(line, 1); } } } List<UVLine> boundaryLines = new List<UVLine>(); foreach (KeyValuePair<UVLine,int> item in guid) { if (item.Value==1) { boundaryLines.Add(item.Key); } } guid.Clear(); guid = null; var plines = PLine.ExtractPLines(boundaryLines); List<BarrierPolygon> boundary = new List<BarrierPolygon>(); foreach (PLine item in plines) { var oneBoundary = item.Simplify(cellularFloor.CellSize / 10); if (oneBoundary != null) { boundary.Add(new BarrierPolygon(oneBoundary.ToArray())); } } boundaryLines.Clear(); boundaryLines = null; return boundary; } /// <summary> /// Gets the field boundary polygons. /// </summary> /// <param name="cellularFloor">The cellular floor.</param> /// <returns>List&lt;BarrierPolygons&gt;.</returns> public static List<BarrierPolygon> GetFieldBoundary(CellularFloor cellularFloor) { Dictionary<UVLine, int> guid = new Dictionary<UVLine, int>(); foreach (var item in cellularFloor.Cells) { if (item.FieldOverlapState == OverlapState.Inside) { var lines = cellularFloor.CellToLines(item); foreach (var line in lines) { if (guid.ContainsKey(line)) { guid[line]++; } else { guid.Add(line, 1); } } } } List<UVLine> boundaryLines = new List<UVLine>(); foreach (KeyValuePair<UVLine, int> item in guid) { if (item.Value == 1) { boundaryLines.Add(item.Key); } } guid.Clear(); guid = null; var pLines = PLine.ExtractPLines(boundaryLines); List<BarrierPolygon> boundary = new List<BarrierPolygon>(); foreach (PLine item in pLines) { var oneBoundary = item.Simplify(cellularFloor.CellSize / 10); if (oneBoundary != null) { boundary.Add(new BarrierPolygon(oneBoundary.ToArray())); } } boundaryLines.Clear(); boundaryLines = null; return boundary; } /// <summary> /// Expands a collection of indices in the walkable field. /// </summary> /// <param name="cellularFloor">The cellular floor.</param> /// <param name="indices">The indices.</param> /// <returns>HashSet&lt;Index&gt;.</returns> public static HashSet<Index> ExpandInWalkableField(CellularFloor cellularFloor, ICollection<Index> indices) { HashSet<Index> collection = new HashSet<Index>(); foreach (var item in indices) { collection.Add(item); foreach (var relativeIndex in Index.Neighbors) { Index index = item + relativeIndex; if (cellularFloor.ContainsCell(index) && !collection.Contains(index)) { if (cellularFloor.Cells[index.I,index.J].FieldOverlapState == OverlapState.Inside) { collection.Add(index); } } } } return collection; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Security; using Xunit; using Microsoft.DotNet.XUnitExtensions; namespace System.Diagnostics.Tests { public partial class ProcessTests : ProcessTestBase { [Fact] private void TestWindowApisUnix() { // This tests the hardcoded implementations of these APIs on Unix. using (Process p = Process.GetCurrentProcess()) { Assert.True(p.Responding); Assert.Equal(string.Empty, p.MainWindowTitle); Assert.False(p.CloseMainWindow()); Assert.Throws<InvalidOperationException>(()=>p.WaitForInputIdle()); } } [Fact] public void MainWindowHandle_GetUnix_ThrowsPlatformNotSupportedException() { CreateDefaultProcess(); Assert.Equal(IntPtr.Zero, _process.MainWindowHandle); } [Fact] public void TestProcessOnRemoteMachineUnix() { Process currentProcess = Process.GetCurrentProcess(); Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1")); Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessById(currentProcess.Id, "127.0.0.1")); } [Theory] [MemberData(nameof(MachineName_Remote_TestData))] public void GetProcessesByName_RemoteMachineNameUnix_ThrowsPlatformNotSupportedException(string machineName) { Process currentProcess = Process.GetCurrentProcess(); Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessesByName(currentProcess.ProcessName, machineName)); } [Fact] public void TestRootGetProcessById() { Process p = Process.GetProcessById(1); Assert.Equal(1, p.Id); } [Fact] [PlatformSpecific(TestPlatforms.Linux)] public void ProcessStart_UseShellExecute_OnLinux_ThrowsIfNoProgramInstalled() { if (!s_allowedProgramsToRun.Any(program => IsProgramInstalled(program))) { Console.WriteLine($"None of the following programs were installed on this machine: {string.Join(",", s_allowedProgramsToRun)}."); Assert.Throws<Win32Exception>(() => Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = Environment.CurrentDirectory })); } } [Fact] [OuterLoop("Opens program")] public void ProcessStart_DirectoryNameInCurDirectorySameAsFileNameInExecDirectory_Success() { string fileToOpen = "dotnet"; string curDir = Environment.CurrentDirectory; string dotnetFolder = Path.Combine(Path.GetTempPath(),"dotnet"); bool shouldDelete = !Directory.Exists(dotnetFolder); try { Directory.SetCurrentDirectory(Path.GetTempPath()); Directory.CreateDirectory(dotnetFolder); using (var px = Process.Start(fileToOpen)) { Assert.NotNull(px); } } finally { if (shouldDelete) { Directory.Delete(dotnetFolder); } Directory.SetCurrentDirectory(curDir); } } [Fact] [OuterLoop] public void ProcessStart_UseShellExecute_OnUnix_OpenMissingFile_DoesNotThrow() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && s_allowedProgramsToRun.FirstOrDefault(program => IsProgramInstalled(program)) == null) { return; } string fileToOpen = Path.Combine(Environment.CurrentDirectory, "_no_such_file.TXT"); using (var px = Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = fileToOpen })) { Assert.NotNull(px); px.Kill(); px.WaitForExit(); Assert.True(px.HasExited); } } [Theory, InlineData(true), InlineData(false)] [OuterLoop("Opens program")] public void ProcessStart_UseShellExecute_OnUnix_SuccessWhenProgramInstalled(bool isFolder) { string programToOpen = s_allowedProgramsToRun.FirstOrDefault(program => IsProgramInstalled(program)); string fileToOpen; if (isFolder) { fileToOpen = Environment.CurrentDirectory; } else { fileToOpen = GetTestFilePath() + ".txt"; File.WriteAllText(fileToOpen, $"{nameof(ProcessStart_UseShellExecute_OnUnix_SuccessWhenProgramInstalled)}"); } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || programToOpen != null) { using (var px = Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = fileToOpen })) { Assert.NotNull(px); if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) // on OSX, process name is dotnet for some reason. Refer to #23972 { Assert.Equal(programToOpen, px.ProcessName); } px.Kill(); px.WaitForExit(); Assert.True(px.HasExited); } } } [Theory, InlineData("vi")] [PlatformSpecific(TestPlatforms.Linux)] [OuterLoop("Opens program")] public void ProcessStart_OpenFileOnLinux_UsesSpecifiedProgram(string programToOpenWith) { if (IsProgramInstalled(programToOpenWith)) { string fileToOpen = GetTestFilePath() + ".txt"; File.WriteAllText(fileToOpen, $"{nameof(ProcessStart_OpenFileOnLinux_UsesSpecifiedProgram)}"); using (var px = Process.Start(programToOpenWith, fileToOpen)) { Assert.Equal(programToOpenWith, px.ProcessName); px.Kill(); px.WaitForExit(); Assert.True(px.HasExited); } } else { Console.WriteLine($"Program specified to open file with {programToOpenWith} is not installed on this machine."); } } [Theory, InlineData("vi")] [PlatformSpecific(TestPlatforms.Linux)] [OuterLoop("Opens program")] public void ProcessStart_OpenFileOnLinux_UsesSpecifiedProgramUsingArgumentList(string programToOpenWith) { if (IsProgramInstalled(programToOpenWith)) { string fileToOpen = GetTestFilePath() + ".txt"; File.WriteAllText(fileToOpen, $"{nameof(ProcessStart_OpenFileOnLinux_UsesSpecifiedProgramUsingArgumentList)}"); ProcessStartInfo psi = new ProcessStartInfo(programToOpenWith); psi.ArgumentList.Add(fileToOpen); using (var px = Process.Start(psi)) { Assert.Equal(programToOpenWith, px.ProcessName); px.Kill(); px.WaitForExit(); Assert.True(px.HasExited); } } else { Console.WriteLine($"Program specified to open file with {programToOpenWith} is not installed on this machine."); } } [Theory, InlineData("/usr/bin/open"), InlineData("/usr/bin/nano")] [PlatformSpecific(TestPlatforms.OSX)] [OuterLoop("Opens program")] public void ProcessStart_OpenFileOnOsx_UsesSpecifiedProgram(string programToOpenWith) { string fileToOpen = GetTestFilePath() + ".txt"; File.WriteAllText(fileToOpen, $"{nameof(ProcessStart_OpenFileOnOsx_UsesSpecifiedProgram)}"); using (var px = Process.Start(programToOpenWith, fileToOpen)) { // Assert.Equal(programToOpenWith, px.ProcessName); // on OSX, process name is dotnet for some reason. Refer to #23972 Console.WriteLine($"in OSX, {nameof(programToOpenWith)} is {programToOpenWith}, while {nameof(px.ProcessName)} is {px.ProcessName}."); px.Kill(); px.WaitForExit(); Assert.True(px.HasExited); } } [Theory, InlineData("Safari"), InlineData("\"Google Chrome\"")] [PlatformSpecific(TestPlatforms.OSX)] [OuterLoop("Opens browser")] public void ProcessStart_OpenUrl_UsesSpecifiedApplication(string applicationToOpenWith) { using (var px = Process.Start("/usr/bin/open", "https://github.com/dotnet/corefx -a " + applicationToOpenWith)) { Assert.NotNull(px); px.Kill(); px.WaitForExit(); Assert.True(px.HasExited); } } [Theory, InlineData("-a Safari"), InlineData("-a \"Google Chrome\"")] [PlatformSpecific(TestPlatforms.OSX)] [OuterLoop("Opens browser")] public void ProcessStart_UseShellExecuteTrue_OpenUrl_SuccessfullyReadsArgument(string arguments) { var startInfo = new ProcessStartInfo { UseShellExecute = true, FileName = "https://github.com/dotnet/corefx", Arguments = arguments }; using (var px = Process.Start(startInfo)) { Assert.NotNull(px); px.Kill(); px.WaitForExit(); Assert.True(px.HasExited); } } public static TheoryData<string[]> StartOSXProcessWithArgumentList => new TheoryData<string[]> { { new string[] { "-a", "Safari" } }, { new string[] { "-a", "\"Google Chrome\"" } } }; [Theory, MemberData(nameof(StartOSXProcessWithArgumentList))] [PlatformSpecific(TestPlatforms.OSX)] [OuterLoop("Opens browser")] public void ProcessStart_UseShellExecuteTrue_OpenUrl_SuccessfullyReadsArgument(string[] argumentList) { var startInfo = new ProcessStartInfo { UseShellExecute = true, FileName = "https://github.com/dotnet/corefx"}; foreach (string item in argumentList) { startInfo.ArgumentList.Add(item); } using (var px = Process.Start(startInfo)) { Assert.NotNull(px); px.Kill(); px.WaitForExit(); Assert.True(px.HasExited); } } [Fact] [Trait(XunitConstants.Category, XunitConstants.RequiresElevation)] public void TestPriorityClassUnix() { CreateDefaultProcess(); ProcessPriorityClass priorityClass = _process.PriorityClass; _process.PriorityClass = ProcessPriorityClass.Idle; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Idle); try { _process.PriorityClass = ProcessPriorityClass.High; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High); _process.PriorityClass = ProcessPriorityClass.Normal; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal); _process.PriorityClass = priorityClass; } catch (Win32Exception ex) { Assert.True(!PlatformDetection.IsSuperUser, $"Failed even though superuser {ex.ToString()}"); } } [Fact] [Trait(XunitConstants.Category, XunitConstants.RequiresElevation)] public void TestBasePriorityOnUnix() { CreateDefaultProcess(); ProcessPriorityClass originalPriority = _process.PriorityClass; Assert.Equal(ProcessPriorityClass.Normal, originalPriority); // https://github.com/dotnet/corefx/issues/25861 -- returns "-19" and not "19" if (!PlatformDetection.IsWindowsSubsystemForLinux) { SetAndCheckBasePriority(ProcessPriorityClass.Idle, 19); } try { SetAndCheckBasePriority(ProcessPriorityClass.Normal, 0); // https://github.com/dotnet/corefx/issues/25861 -- returns "11" and not "-11" if (!PlatformDetection.IsWindowsSubsystemForLinux) { SetAndCheckBasePriority(ProcessPriorityClass.High, -11); } _process.PriorityClass = originalPriority; } catch (Win32Exception ex) { Assert.True(!PlatformDetection.IsSuperUser, $"Failed even though superuser {ex.ToString()}"); } } [Fact] public void TestStartOnUnixWithBadPermissions() { string path = GetTestFilePath(); File.Create(path).Dispose(); int mode = Convert.ToInt32("644", 8); Assert.Equal(0, chmod(path, mode)); Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(path)); Assert.NotEqual(0, e.NativeErrorCode); } [Fact] [PlatformSpecific(~TestPlatforms.OSX)] // OSX doesn't support throwing on Process.Start public void TestStartOnUnixWithBadFormat() { string path = GetTestFilePath(); File.Create(path).Dispose(); int mode = Convert.ToInt32("744", 8); Assert.Equal(0, chmod(path, mode)); // execute permissions Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(path)); Assert.NotEqual(0, e.NativeErrorCode); } [Fact] [PlatformSpecific(TestPlatforms.OSX)] // OSX doesn't support throwing on Process.Start public void TestStartOnOSXWithBadFormat() { string path = GetTestFilePath(); File.Create(path).Dispose(); int mode = Convert.ToInt32("744", 8); Assert.Equal(0, chmod(path, mode)); // execute permissions using (Process p = Process.Start(path)) { p.WaitForExit(); Assert.NotEqual(0, p.ExitCode); } } [Fact] public void TestStartWithNonExistingUserThrows() { Process p = CreateProcessPortable(RemotelyInvokable.Dummy); p.StartInfo.UserName = "DoesNotExist"; Assert.Throws<Win32Exception>(() => p.Start()); } [Fact] public void TestExitCodeKilledChild() { using (Process p = CreateProcessLong()) { p.Start(); p.Kill(); p.WaitForExit(); // SIGKILL may change per platform const int SIGKILL = 9; // Linux, macOS, FreeBSD, ... Assert.Equal(128 + SIGKILL, p.ExitCode); } } /// <summary> /// Tests when running as a normal user and starting a new process as the same user /// works as expected. /// </summary> [Fact] public void TestStartWithNormalUser() { TestStartWithUserName(GetCurrentRealUserName()); } /// <summary> /// Tests when running as root and starting a new process as a normal user, /// the new process doesn't have elevated privileges. /// </summary> [Fact] [OuterLoop("Needs sudo access")] [Trait(XunitConstants.Category, XunitConstants.RequiresElevation)] public void TestStartWithRootUser() { RunTestAsSudo(TestStartWithUserName, GetCurrentRealUserName()); } public static int TestStartWithUserName(string realUserName) { Assert.NotNull(realUserName); Assert.NotEqual("root", realUserName); using (ProcessTests testObject = new ProcessTests()) { using (Process p = testObject.CreateProcessPortable(GetCurrentEffectiveUserId)) { p.StartInfo.UserName = realUserName; Assert.True(p.Start()); p.WaitForExit(); // since the process was started with the current real user, even if this test // was run with 'sudo', the child process will be run as the normal real user. // Assert that the effective user of the child process was never 'root' // and was the real user of this process. Assert.NotEqual(0, p.ExitCode); } return 0; } } public static int GetCurrentEffectiveUserId() { return (int)geteuid(); } private static string GetCurrentRealUserName() { string realUserName = geteuid() == 0 ? Environment.GetEnvironmentVariable("SUDO_USER") : Environment.UserName; Assert.NotNull(realUserName); Assert.NotEqual("root", realUserName); return realUserName; } /// <summary> /// Tests when running as root and starting a new process as a normal user, /// the new process can't elevate back to root. /// </summary> [Fact] [OuterLoop("Needs sudo access")] [Trait(XunitConstants.Category, XunitConstants.RequiresElevation)] public void TestStartWithRootUserCannotElevate() { RunTestAsSudo(TestStartWithUserNameCannotElevate, GetCurrentRealUserName()); } /// <summary> /// Tests whether child processes are reaped (cleaning up OS resources) /// when they terminate. /// </summary> [Fact] [PlatformSpecific(TestPlatforms.Linux)] // Test uses Linux specific '/proc' filesystem public async Task TestChildProcessCleanup() { using (Process process = CreateShortProcess()) { process.Start(); bool processReaped = await TryWaitProcessReapedAsync(process.Id, timeoutMs: 30000); Assert.True(processReaped); } } /// <summary> /// Tests whether child processes are reaped (cleaning up OS resources) /// when they terminate after the Process was Disposed. /// </summary> [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] [InlineData(true, true)] [PlatformSpecific(TestPlatforms.Linux)] // Test uses Linux specific '/proc' filesystem public async Task TestChildProcessCleanupAfterDispose(bool shortProcess, bool enableEvents) { // We test using a long and short process. The long process will terminate after Dispose, // The short process will terminate at the same time, possibly revealing race conditions. int processId = -1; using (Process process = shortProcess ? CreateShortProcess() : CreateSleepProcess(durationMs: 500)) { process.Start(); processId = process.Id; if (enableEvents) { // Dispose will disable the Exited event. // We enable it to check this doesn't cause issues for process reaping. process.EnableRaisingEvents = true; } } bool processReaped = await TryWaitProcessReapedAsync(processId, timeoutMs: 30000); Assert.True(processReaped); } private static Process CreateShortProcess() { Process process = new Process(); process.StartInfo.FileName = "uname"; return process; } private static async Task<bool> TryWaitProcessReapedAsync(int pid, int timeoutMs) { const int SleepTimeMs = 50; // When the process is reaped, the '/proc/<pid>' directory to disappears. bool procPidExists = true; for (int attempt = 0; attempt < (timeoutMs / SleepTimeMs); attempt++) { procPidExists = Directory.Exists("/proc/" + pid); if (procPidExists) { await Task.Delay(SleepTimeMs); } else { break; } } return !procPidExists; } /// <summary> /// Tests the ProcessWaitState reference count drops to zero. /// </summary> [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Test validates Unix implementation public async Task TestProcessWaitStateReferenceCount() { using (var exitedEventSemaphore = new SemaphoreSlim(0, 1)) { object waitState = null; int processId = -1; // Process takes a reference using (var process = CreateShortProcess()) { process.EnableRaisingEvents = true; // Exited event takes a reference process.Exited += (o,e) => exitedEventSemaphore.Release(); process.Start(); processId = process.Id; waitState = GetProcessWaitState(process); process.WaitForExit(); Assert.False(GetWaitStateDictionary(childDictionary: false).Contains(processId)); Assert.True(GetWaitStateDictionary(childDictionary: true).Contains(processId)); } exitedEventSemaphore.Wait(); // Child reaping holds a reference too int referenceCount = -1; const int SleepTimeMs = 50; for (int i = 0; i < (30000 / SleepTimeMs); i++) { referenceCount = GetWaitStateReferenceCount(waitState); if (referenceCount == 0) { break; } else { // Process was reaped but ProcessWaitState not unrefed yet await Task.Delay(SleepTimeMs); } } Assert.Equal(0, referenceCount); Assert.Equal(0, GetWaitStateReferenceCount(waitState)); Assert.False(GetWaitStateDictionary(childDictionary: false).Contains(processId)); Assert.False(GetWaitStateDictionary(childDictionary: true).Contains(processId)); } } /// <summary> /// Verifies a new Process instance can refer to a process with a recycled pid for which /// there is still an existing Process instance. Operations on the existing instance will /// throw since that process has exited. /// </summary> [ConditionalFact(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))] public void TestProcessRecycledPid() { const int LinuxPidMaxDefault = 32768; var processes = new Dictionary<int, Process>(LinuxPidMaxDefault); bool foundRecycled = false; for (int i = 0; i < int.MaxValue; i++) { var process = CreateProcessLong(); process.Start(); Process recycled; foundRecycled = processes.TryGetValue(process.Id, out recycled); if (foundRecycled) { Assert.Throws<InvalidOperationException>(() => recycled.Kill()); } process.Kill(); process.WaitForExit(); if (foundRecycled) { break; } else { processes.Add(process.Id, process); } } Assert.True(foundRecycled); } private static IDictionary GetWaitStateDictionary(bool childDictionary) { Assembly assembly = typeof(Process).Assembly; Type waitStateType = assembly.GetType("System.Diagnostics.ProcessWaitState"); FieldInfo dictionaryField = waitStateType.GetField(childDictionary ? "s_childProcessWaitStates" : "s_processWaitStates", BindingFlags.NonPublic | BindingFlags.Static); return (IDictionary)dictionaryField.GetValue(null); } private static object GetProcessWaitState(Process p) { MethodInfo getWaitState = typeof(Process).GetMethod("GetWaitState", BindingFlags.NonPublic | BindingFlags.Instance); return getWaitState.Invoke(p, null); } private static int GetWaitStateReferenceCount(object waitState) { FieldInfo referenCountField = waitState.GetType().GetField("_outstandingRefCount", BindingFlags.NonPublic | BindingFlags.Instance); return (int)referenCountField.GetValue(waitState); } public static int TestStartWithUserNameCannotElevate(string realUserName) { Assert.NotNull(realUserName); Assert.NotEqual("root", realUserName); using (ProcessTests testObject = new ProcessTests()) { using (Process p = testObject.CreateProcessPortable(SetEffectiveUserIdToRoot)) { p.StartInfo.UserName = realUserName; Assert.True(p.Start()); p.WaitForExit(); // seteuid(0) should not have succeeded, thus the exit code should be non-zero Assert.NotEqual(0, p.ExitCode); } return 0; } } public static int SetEffectiveUserIdToRoot() { return seteuid(0); } private void RunTestAsSudo(Func<string, int> testMethod, string arg) { RemoteInvokeOptions options = new RemoteInvokeOptions() { Start = false, RunAsSudo = true }; Process p = null; using (RemoteInvokeHandle handle = RemoteInvoke(testMethod, arg, options)) { p = handle.Process; handle.Process = null; } AddProcessForDispose(p); p.Start(); p.WaitForExit(); Assert.Equal(0, p.ExitCode); } [DllImport("libc")] private static extern int chmod(string path, int mode); [DllImport("libc")] private static extern uint geteuid(); [DllImport("libc")] private static extern int seteuid(uint euid); private static readonly string[] s_allowedProgramsToRun = new string[] { "xdg-open", "gnome-open", "kfmclient" }; } }
#region MigraDoc - Creating Documents on the Fly // // Authors: // Stefan Lange (mailto:Stefan.Lange@pdfsharp.com) // Klaus Potzesny (mailto:Klaus.Potzesny@pdfsharp.com) // David Stephensen (mailto:David.Stephensen@pdfsharp.com) // // Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://www.migradoc.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Diagnostics; using System.IO; using System.Reflection; using MigraDoc.DocumentObjectModel.Internals; using MigraDoc.DocumentObjectModel.Visitors; using MigraDoc.DocumentObjectModel.Tables; using MigraDoc.DocumentObjectModel.Shapes.Charts; using MigraDoc.DocumentObjectModel.Shapes; namespace MigraDoc.DocumentObjectModel { /// <summary> /// Represents a collection of document elements. /// </summary> public class DocumentElements : DocumentObjectCollection, IVisitable { /// <summary> /// Initializes a new instance of the DocumentElements class. /// </summary> public DocumentElements() { } /// <summary> /// Initializes a new instance of the DocumentElements class with the specified parent. /// </summary> internal DocumentElements(DocumentObject parent) : base(parent) { } /// <summary> /// Gets a document object by its index. /// </summary> public new DocumentObject this[int index] { get { return base[index]; } } #region Methods /// <summary> /// Creates a deep copy of this object. /// </summary> public new DocumentElements Clone() { return (DocumentElements)DeepCopy(); } /// <summary> /// Adds a new paragraph to the collection. /// </summary> public Paragraph AddParagraph() { Paragraph paragraph = new Paragraph(); Add(paragraph); return paragraph; } /// <summary> /// Adds a new paragraph with the specified text to the collection. /// </summary> public Paragraph AddParagraph(string text) { Paragraph paragraph = new Paragraph(); paragraph.AddText(text); Add(paragraph); return paragraph; } /// <summary> /// Adds a new paragraph with the specified text and style to the collection. /// </summary> public Paragraph AddParagraph(string text, string style) { Paragraph paragraph = new Paragraph(); paragraph.AddText(text); paragraph.Style = style; Add(paragraph); return paragraph; } /// <summary> /// Adds a new table to the collection. /// </summary> public Table AddTable() { Table tbl = new Table(); Add(tbl); return tbl; } /// <summary> /// Adds a new legend to the collection. /// </summary> public Legend AddLegend() { Legend legend = new Legend(); Add(legend); return legend; } /// <summary> /// Add a manual page break. /// </summary> public void AddPageBreak() { PageBreak pageBreak = new PageBreak(); Add(pageBreak); } /// <summary> /// Adds a new barcode to the collection. /// </summary> public Barcode AddBarcode() { Barcode barcode = new Barcode(); Add(barcode); return barcode; } /// <summary> /// Adds a new chart with the specified type to the collection. /// </summary> public Chart AddChart(ChartType type) { Chart chart = AddChart(); chart.Type = type; return chart; } /// <summary> /// Adds a new chart with the specified type to the collection. /// </summary> public Chart AddChart() { Chart chart = new Chart(); chart.Type = ChartType.Line; Add(chart); return chart; } /// <summary> /// Adds a new image to the collection. /// </summary> public Image AddImage(string name) { Image image = new Image(); image.Name = name; Add(image); return image; } public Image AddImage(MemoryStream stream) { Image image = new Image(stream); Add(image); return image; } /// <summary> /// Adds a new text frame to the collection. /// </summary> public TextFrame AddTextFrame() { TextFrame textFrame = new TextFrame(); Add(textFrame); return textFrame; } #endregion #region Internal /// <summary> /// Converts DocumentElements into DDL. /// </summary> internal override void Serialize(Serializer serializer) { int count = Count; if (count == 1 && this[0] is Paragraph) { // Omit keyword if paragraph has no attributes set. Paragraph paragraph = (Paragraph)this[0]; if (paragraph.Style == "" && paragraph.IsNull("Format")) { paragraph.SerializeContentOnly = true; paragraph.Serialize(serializer); paragraph.SerializeContentOnly = false; return; } } for (int index = 0; index < count; index++) { DocumentObject documentElement = this[index]; documentElement.Serialize(serializer); } } /// <summary> /// Allows the visitor object to visit the document object and it's child objects. /// </summary> void IVisitable.AcceptVisitor(DocumentObjectVisitor visitor, bool visitChildren) { visitor.VisitDocumentElements(this); foreach (DocumentObject docObject in this) { if (docObject is IVisitable) ((IVisitable)docObject).AcceptVisitor(visitor, visitChildren); } } /// <summary> /// Returns the meta object of this instance. /// </summary> internal override Meta Meta { get { if (meta == null) meta = new Meta(typeof(DocumentElements)); return meta; } } static Meta meta; #endregion } }
using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace Reversi { class Board : Form { private const byte NUMBER_OF_COLUMS = Controller.NUMBER_OF_COLUMS, NUMBER_OF_ROWS = Controller.NUMBER_OF_ROWS; // Size of UI element in pixels private const short BOARD_HEIGHT = TILE_SIZE * NUMBER_OF_ROWS, BOARD_WIDTH = TILE_SIZE * NUMBER_OF_COLUMS; private const short BUTTON_HEIGHT = NewGameButton.HEIGHT, BUTTON_WIDTH = NewGameButton.WIDTH; private const short BUTTON_OFFSET = 2; private const short HEADER_HEIGHT = BUTTON_HEIGHT * 2 + PADDING * 3 + 2; private const short LABEL_HEIGHT = 24; private const short LABEL_ICON_SIZE = 24; private const short LABEL_OFFSET = 2 + BUTTON_WIDTH + PADDING; private const short TILE_SIZE = Tile.SIZE; private const short PADDING = 12; private readonly static Image LABEL_BLUE = Image.FromFile(@"../../img/disc_blue_small.png"), LABEL_RED = Image.FromFile(@"../../img/disc_red_small.png"); private Controller controller; private Tile[,] tiles; private HelpButton helpButton; private NewGameButton newGameButton; private Label labelBlue, labelRed, labelActive; public void Render() { List<Position> discs = controller.Discs; List<Position> placeholderDiscs = controller.PlaceholderDiscs; int numberOfBlue = 0, numberOfRed = 0; for (int x = 0; x < NUMBER_OF_COLUMS; x++) { for (int y = 0; y < NUMBER_OF_ROWS; y++) { // Get the position Position position = new Position(x, y); // Get the tile Tile tile = this.tiles[x, y]; // Check if the position has any kind of disc if (discs.Contains(position)) { // Get the colour of the disc Controller.Colors color = this.controller.GetDisc(position).Color; if (color == Controller.Colors.Blue) { tile.State = Tile.States.Blue; numberOfBlue++; } else { tile.State = Tile.States.Red; numberOfRed++; } } else if (placeholderDiscs.Contains(position) && this.helpButton.Active) { tile.State = Tile.States.Placeholder; } else { tile.State = Tile.States.Empty; } } } this.labelBlue.Text = numberOfBlue.ToString().ToLower(); this.labelRed.Text = numberOfRed.ToString().ToLower(); this.labelActive.Text = "It's " + this.controller.Active.ToString() + "s turn"; // Reset the button this.helpButton.Active = false; if (controller.GetValidMoves().Count == 0) { if (numberOfBlue > numberOfRed) { labelActive.Text = "Gameover! Blue has won!"; }else { labelActive.Text = "Gameover! Red has won!"; } } } /** * This method will act as a paint handler. * * Parameters * object sender * PaintEventArgs evt */ public void PaintHandler(object sender, PaintEventArgs evt) { Graphics graphics = evt.Graphics; graphics.DrawImage(LABEL_BLUE, LABEL_OFFSET, 2 + PADDING); graphics.DrawImage(LABEL_RED, LABEL_OFFSET, 2 + PADDING * 2 + LABEL_HEIGHT); } /** * This method will act as a click handler. * * Parameters * object sender * MouseEventArgs evt */ public void ClickHandler(object sender, MouseEventArgs evt) { Render(); } /* * This method creates a label at a given location with a given text * * Parameters * int x - The x coordinate of the label * int y - The y coordinate of the label * string text - The text of the label * * Output * Label label - A Label object with the given properties */ private Label DrawLabel(int x, int y) { Label label = new Label(); label.Location = new Point(x, y); label.Font = new Font(FontFamily.GenericMonospace, 14); label.Height = LABEL_HEIGHT; label.Width = NewGameButton.WIDTH; return label; } /** * Constructor of the board class. */ public Board() { this.ClientSize = new Size(BOARD_WIDTH, HEADER_HEIGHT + BOARD_HEIGHT); this.Text = "Reversi"; this.DoubleBuffered = true; this.BackColor = Color.FromArgb(0xFA, 0xFA, 0xFA); // Subscribe paint handler this.Paint += PaintHandler; // Get an instance of the controller this.controller = Controller.Instance; // Create the matrix with the tiles this.tiles = new Tile[NUMBER_OF_COLUMS, NUMBER_OF_ROWS]; this.newGameButton = new NewGameButton(2, PADDING + 2); this.helpButton = new HelpButton(2, BUTTON_HEIGHT + PADDING * 2 + 2); NewGameButton.controller = this.controller; NewGameButton.board = this; Controls.Add(this.newGameButton); Controls.Add(this.helpButton); this.labelBlue = DrawLabel(LABEL_OFFSET + LABEL_ICON_SIZE, PADDING + 4); this.labelRed = DrawLabel(LABEL_OFFSET + LABEL_ICON_SIZE, PADDING * 2 + LABEL_HEIGHT + 4); this.labelActive = DrawLabel(LABEL_OFFSET, PADDING + LABEL_HEIGHT * 4); Controls.Add(this.labelRed); Controls.Add(this.labelBlue); Controls.Add(this.labelActive); for (int x = 0; x < NUMBER_OF_COLUMS; x++) { for (int y = 0; y < NUMBER_OF_ROWS; y++) { // Get the position of the tile Position position = new Position(x, y); // Create a new tile Tile tile = new Tile(position, TILE_SIZE * x, HEADER_HEIGHT + TILE_SIZE * y); // Subscribe the click handler tile.MouseClick += ClickHandler; Controls.Add(tile); this.tiles[x, y] = tile; } } Render(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using Internal.Runtime.Augments; using Internal.DeveloperExperience; namespace System { // Eagerly preallocate instance of out of memory exception to avoid infinite recursion once we run out of memory [EagerOrderedStaticConstructor(EagerStaticConstructorOrder.SystemPreallocatedOutOfMemoryException)] internal class PreallocatedOutOfMemoryException { public static readonly OutOfMemoryException Instance = new OutOfMemoryException(message: null); // Cannot call the nullary constructor as that triggers non-trivial resource manager logic. } internal class RuntimeExceptionHelpers { //------------------------------------------------------------------------------------------------------------ // @TODO: this function is related to throwing exceptions out of Rtm. If we did not have to throw // out of Rtm, then we would note have to have the code below to get a classlib exception object given // an exception id, or the special functions to back up the MDIL THROW_* instructions, or the allocation // failure helper. If we could move to a world where we never throw out of Rtm, perhaps by moving parts // of Rtm that do need to throw out to Bartok- or Binder-generated functions, then we could remove all of this. //------------------------------------------------------------------------------------------------------------ // This is the classlib-provided "get exception" function that will be invoked whenever the runtime // needs to throw an exception back to a method in a non-runtime module. The classlib is expected // to convert every code in the ExceptionIDs enum to an exception object. [RuntimeExport("GetRuntimeException")] public static Exception GetRuntimeException(ExceptionIDs id) { // This method is called by the runtime's EH dispatch code and is not allowed to leak exceptions // back into the dispatcher. try { // @TODO: this function should return pre-allocated exception objects, either frozen in the image // or preallocated during DllMain(). In particular, this function will be called when out of memory, // and failure to create an exception will result in infinite recursion and therefore a stack overflow. switch (id) { case ExceptionIDs.OutOfMemory: return PreallocatedOutOfMemoryException.Instance; case ExceptionIDs.Arithmetic: return new ArithmeticException(); case ExceptionIDs.ArrayTypeMismatch: return new ArrayTypeMismatchException(); case ExceptionIDs.DivideByZero: return new DivideByZeroException(); case ExceptionIDs.IndexOutOfRange: return new IndexOutOfRangeException(); case ExceptionIDs.InvalidCast: return new InvalidCastException(); case ExceptionIDs.Overflow: return new OverflowException(); case ExceptionIDs.NullReference: return new NullReferenceException(); case ExceptionIDs.AccessViolation: FailFast("Access Violation: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. The application will be terminated since this platform does not support throwing an AccessViolationException."); return null; case ExceptionIDs.DataMisaligned: return new DataMisalignedException(); default: FailFast("The runtime requires an exception for a case that this class library does not understand."); return null; } } catch { return null; // returning null will cause the runtime to FailFast via the class library. } } public enum RhFailFastReason { Unknown = 0, InternalError = 1, // "Runtime internal error" UnhandledException_ExceptionDispatchNotAllowed = 2, // "Unhandled exception: no handler found before escaping a finally clause or other fail-fast scope." UnhandledException_CallerDidNotHandle = 3, // "Unhandled exception: no handler found in calling method." ClassLibDidNotTranslateExceptionID = 4, // "Unable to translate failure into a classlib-specific exception object." IllegalNativeCallableEntry = 5, // "Invalid Program: attempted to call a NativeCallable method from runtime-typesafe code." PN_UnhandledException = 6, // ProjectN: "Unhandled exception: a managed exception was not handled before reaching unmanaged code" PN_UnhandledExceptionFromPInvoke = 7, // ProjectN: "Unhandled exception: an unmanaged exception was thrown out of a managed-to-native transition." Max } private static string GetStringForFailFastReason(RhFailFastReason reason) { switch (reason) { case RhFailFastReason.InternalError: return "Runtime internal error"; case RhFailFastReason.UnhandledException_ExceptionDispatchNotAllowed: return "Unhandled exception: no handler found before escaping a finally clause or other fail-fast scope."; case RhFailFastReason.UnhandledException_CallerDidNotHandle: return "Unhandled exception: no handler found in calling method."; case RhFailFastReason.ClassLibDidNotTranslateExceptionID: return "Unable to translate failure into a classlib-specific exception object."; case RhFailFastReason.IllegalNativeCallableEntry: return "Invalid Program: attempted to call a NativeCallable method from runtime-typesafe code."; case RhFailFastReason.PN_UnhandledException: return "Unhandled exception: a managed exception was not handled before reaching unmanaged code"; case RhFailFastReason.PN_UnhandledExceptionFromPInvoke: return "Unhandled exception: an unmanaged exception was thrown out of a managed-to-native transition."; default: return "Unknown reason."; } } public static void FailFast(String message) { FailFast(message, null, RhFailFastReason.Unknown, IntPtr.Zero); } public static unsafe void FailFast(string message, Exception exception) { FailFast(message, exception, RhFailFastReason.Unknown, IntPtr.Zero); } // Used to report exceptions that *logically* go unhandled in the Fx code. For example, an // exception that escapes from a ThreadPool workitem, or from a void-returning async method. public static void ReportUnhandledException(Exception exception) { // ReportUnhandledError will also call this in APPX scenarios, // but WinRT can failfast before we get another chance // (in APPX scenarios, this one will get overwritten by the one with the CCW pointer) GenerateExceptionInformationForDump(exception, IntPtr.Zero); // If possible report the exception to GEH, if not fail fast. WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; if (callbacks == null || !callbacks.ReportUnhandledError(exception)) FailFast(GetStringForFailFastReason(RhFailFastReason.PN_UnhandledException), exception); } // This is the classlib-provided fail-fast function that will be invoked whenever the runtime // needs to cause the process to exit. It is the classlib's opprotunity to customize the // termination behavior in whatever way necessary. [RuntimeExport("FailFast")] public static void RuntimeFailFast(RhFailFastReason reason, Exception exception, IntPtr pExContext) { // This method is called by the runtime's EH dispatch code and is not allowed to leak exceptions // back into the dispatcher. try { if ((reason == RhFailFastReason.PN_UnhandledException) && (exception != null) && !(exception is OutOfMemoryException)) { Debug.WriteLine("Unhandled Exception: " + exception.ToString()); } FailFast(String.Format("Runtime-generated FailFast: ({0}): {1}{2}", reason.ToString(), // Explicit call to ToString() to avoid MissingMetadataException inside String.Format(). GetStringForFailFastReason(reason), exception != null ? " [exception object available]" : ""), exception, reason, pExContext); } catch { // Returning from this callback will cause the runtime to FailFast without involving the class // library. } } internal static void FailFast(string message, Exception exception, RhFailFastReason reason, IntPtr pExContext) { // If this a recursive call to FailFast, avoid all unnecessary and complex actitivy the second time around to avoid the recursion // that got us here the first time (Some judgement is required as to what activity is "unnecessary and complex".) bool minimalFailFast = s_inFailFast || (exception is OutOfMemoryException); s_inFailFast = true; if (!minimalFailFast) { String output = (exception != null) ? "Unhandled Exception: " + exception.ToString() : message; DeveloperExperience.Default.WriteLine(output); GenerateExceptionInformationForDump(exception, IntPtr.Zero); } if (Interop.mincore.IsDebuggerPresent()) Debug.DebugBreak(); uint errorCode = 0x80004005; // E_FAIL // To help enable testing to bucket the failures we choose one of the following as errorCode: // * RVA of EETypePtr if it is an unhandled managed exception // * HRESULT, if available // * RhFailFastReason, if it is one of the known reasons if (exception != null) { if (reason == RhFailFastReason.PN_UnhandledException) errorCode = (uint)(exception.EETypePtr.RawValue.ToInt64() - RuntimeImports.RhGetModuleFromEEType(exception.EETypePtr.RawValue).ToInt64()); else if (exception.HResult != 0) errorCode = (uint)exception.HResult; } else if (reason != RhFailFastReason.Unknown) { errorCode = (uint)reason + 0x1000; // Add something to avoid common low level exit codes } Interop.mincore.RaiseFailFastException(errorCode, pExContext); } // This boolean is used to stop runaway FailFast recursions. Though this is technically a concurrently set field, it only gets set during // fatal process shutdowns and it's only purpose is a reasonable-case effort to make a bad situation a little less bad. // Trying to use locks or other concurrent access apis would actually defeat the purpose of making FailFast as robust as possible. private static bool s_inFailFast; #pragma warning disable 414 // field is assigned, but never used -- This is because C# doesn't realize that we // copy the field into a buffer. /// <summary> /// This is the header that describes our 'error report' buffer to the minidump auxillary provider. /// Its format is know to that system-wide DLL, so do not change it. The remainder of the buffer is /// opaque to the minidump auxillary provider, so it'll have its own format that is more easily /// changed. /// </summary> [StructLayout(LayoutKind.Sequential)] private struct ERROR_REPORT_BUFFER_HEADER { private int _headerSignature; private int _bufferByteCount; public void WriteHeader(int cbBuffer) { _headerSignature = 0x31304244; // 'DB01' _bufferByteCount = cbBuffer; } } /// <summary> /// This header describes the contents of the serialized error report to DAC, which can deserialize it /// from a dump file or live debugging session. This format is easier to change than the /// ERROR_REPORT_BUFFER_HEADER, but it is still well-known to DAC, so any changes must update the /// version number and also have corresponding changes made to DAC. /// </summary> [StructLayout(LayoutKind.Sequential)] private struct SERIALIZED_ERROR_REPORT_HEADER { private int _errorReportSignature; // This is the version of the 'container format'. private int _exceptionSerializationVersion; // This is the version of the Exception format. It is // separate from the 'container format' version since the // implementation of the Exception serialization is owned by // the Exception class. private int _exceptionCount; // We just contain a logical array of exceptions. private int _loadedModuleCount; // Number of loaded modules. present when signature >= ER02. // {ExceptionCount} serialized Exceptions follow. // {LoadedModuleCount} module handles follow. present when signature >= ER02. public void WriteHeader(int nExceptions, int nLoadedModules) { _errorReportSignature = 0x32305245; // 'ER02' _exceptionSerializationVersion = Exception.CurrentSerializationSignature; _exceptionCount = nExceptions; _loadedModuleCount = nLoadedModules; } } /// <summary> /// Holds metadata about an exception in flight. Class because ConditionalWeakTable only accepts reference types /// </summary> private class ExceptionData { public ExceptionData() { // Set this to a non-zero value so that logic mapping entries to threads // doesn't think an uninitialized ExceptionData is on thread 0 ExceptionMetadata.ThreadId = 0xFFFFFFFF; } public struct ExceptionMetadataStruct { public UInt32 ExceptionId { get; set; } // Id assigned to the exception. May not be contiguous or start at 0. public UInt32 InnerExceptionId { get; set; } // ID of the inner exception or 0xFFFFFFFF for 'no inner exception' public UInt32 ThreadId { get; set; } // Managed thread ID the eception was thrown on public Int32 NestingLevel { get; set; } // If multiple exceptions are currently active on a thread, this gives the ordering for them. // The highest number is the most recent exception. -1 means the exception is not currently in flight // (but it may still be an InnerException). public IntPtr ExceptionCCWPtr { get; set; } // If the exception was thrown in an interop scenario, this contains the CCW pointer, otherwise, IntPtr.Zero } public ExceptionMetadataStruct ExceptionMetadata; /// <summary> /// Data created by Exception.SerializeForDump() /// </summary> public byte[] SerializedExceptionData { get; set; } /// <summary> /// Serializes the exception metadata and SerializedExceptionData /// </summary> public unsafe byte[] Serialize() { checked { byte[] serializedData = new byte[sizeof(ExceptionMetadataStruct) + SerializedExceptionData.Length]; fixed (byte* pSerializedData = serializedData) { ExceptionMetadataStruct* pMetadata = (ExceptionMetadataStruct*)pSerializedData; pMetadata->ExceptionId = ExceptionMetadata.ExceptionId; pMetadata->InnerExceptionId = ExceptionMetadata.InnerExceptionId; pMetadata->ThreadId = ExceptionMetadata.ThreadId; pMetadata->NestingLevel = ExceptionMetadata.NestingLevel; pMetadata->ExceptionCCWPtr = ExceptionMetadata.ExceptionCCWPtr; Array.CopyToNative(SerializedExceptionData, 0, (IntPtr)(pSerializedData + sizeof(ExceptionMetadataStruct)), SerializedExceptionData.Length); } return serializedData; } } } /// <summary> /// Table of exceptions that were on stacks triggering GenerateExceptionInformationForDump /// </summary> private readonly static ConditionalWeakTable<Exception, ExceptionData> s_exceptionDataTable = new ConditionalWeakTable<Exception, ExceptionData>(); /// <summary> /// Counter for exception ID assignment /// </summary> private static int s_currentExceptionId = 0; /// <summary> /// This method will call the runtime to gather the Exception objects from every exception dispatch in /// progress on the current thread. It will then serialize them into a new buffer and pass that /// buffer back to the runtime, which will publish it to a place where a global "minidump auxillary /// provider" will be able to save the buffer's contents into triage dumps. /// /// Thread safety information: The guarantee of this method is that the buffer it produces will have /// complete and correct information for all live exceptions on the current thread (as long as the same excption object /// is not thrown simultaneously on multiple threads). It will do a best-effort attempt to serialize information about exceptions /// already recorded on other threads, but that data can be lost or corrupted. The restrictions are: /// 1. Only exceptions active or recorded on the current thread have their table data modified. /// 2. After updating data in the table, we serialize a snapshot of the table (provided by ConditionalWeakTable.Values), /// regardless of what other threads might do to the table before or after. However, because of #1, this thread's /// exception data should stay stable /// 3. There is a dependency on the fact that ConditionalWeakTable's members are all threadsafe and that .Values returns a snapshot /// </summary> public static void GenerateExceptionInformationForDump(Exception currentException, IntPtr exceptionCCWPtr) { LowLevelList<byte[]> serializedExceptions = new LowLevelList<byte[]>(); // If currentException is null, there's a state corrupting exception in flight and we can't serialize it if (currentException != null) { SerializeExceptionsForDump(currentException, exceptionCCWPtr, serializedExceptions); } GenerateErrorReportForDump(serializedExceptions); } private static void SerializeExceptionsForDump(Exception currentException, IntPtr exceptionCCWPtr, LowLevelList<byte[]> serializedExceptions) { const UInt32 NoInnerExceptionValue = 0xFFFFFFFF; // Approximate upper size limit for the serialized exceptions (but we'll always serialize currentException) // If we hit the limit, because we serialize in arbitrary order, there may be missing InnerExceptions or nested exceptions. const int MaxBufferSize = 20000; int nExceptions; RuntimeImports.RhGetExceptionsForCurrentThread(null, out nExceptions); Exception[] curThreadExceptions = new Exception[nExceptions]; RuntimeImports.RhGetExceptionsForCurrentThread(curThreadExceptions, out nExceptions); LowLevelList<Exception> exceptions = new LowLevelList<Exception>(curThreadExceptions); LowLevelList<Exception> nonThrownInnerExceptions = new LowLevelList<Exception>(); uint currentThreadId = Interop.mincore.GetCurrentThreadId(); // Reset nesting levels for exceptions on this thread that might not be currently in flight foreach (ExceptionData exceptionData in s_exceptionDataTable.GetValues()) { if (exceptionData.ExceptionMetadata.ThreadId == currentThreadId) { exceptionData.ExceptionMetadata.NestingLevel = -1; } } // Find all inner exceptions, even if they're not currently being handled for (int i = 0; i < exceptions.Count; i++) { if (exceptions[i].InnerException != null && !exceptions.Contains(exceptions[i].InnerException)) { exceptions.Add(exceptions[i].InnerException); nonThrownInnerExceptions.Add(exceptions[i].InnerException); } } int currentNestingLevel = curThreadExceptions.Length - 1; // Populate exception data for all exceptions interesting to this thread. // Whether or not there was previously data for that object, it might have changed. for (int i = 0; i < exceptions.Count; i++) { ExceptionData exceptionData = s_exceptionDataTable.GetOrCreateValue(exceptions[i]); exceptionData.ExceptionMetadata.ExceptionId = (UInt32)System.Threading.Interlocked.Increment(ref s_currentExceptionId); if (exceptionData.ExceptionMetadata.ExceptionId == NoInnerExceptionValue) { exceptionData.ExceptionMetadata.ExceptionId = (UInt32)System.Threading.Interlocked.Increment(ref s_currentExceptionId); } exceptionData.ExceptionMetadata.ThreadId = currentThreadId; // Only include nesting information for exceptions that were thrown on this thread if (!nonThrownInnerExceptions.Contains(exceptions[i])) { exceptionData.ExceptionMetadata.NestingLevel = currentNestingLevel; currentNestingLevel--; } else { exceptionData.ExceptionMetadata.NestingLevel = -1; } // Only match the CCW pointer up to the current exception if (Object.ReferenceEquals(exceptions[i], currentException)) { exceptionData.ExceptionMetadata.ExceptionCCWPtr = exceptionCCWPtr; } byte[] serializedEx = exceptions[i].SerializeForDump(); exceptionData.SerializedExceptionData = serializedEx; } // Populate inner exception ids now that we have all of them in the table for (int i = 0; i < exceptions.Count; i++) { ExceptionData exceptionData; if (!s_exceptionDataTable.TryGetValue(exceptions[i], out exceptionData)) { // This shouldn't happen, but we can't meaningfully throw here continue; } if (exceptions[i].InnerException != null) { ExceptionData innerExceptionData; if (s_exceptionDataTable.TryGetValue(exceptions[i].InnerException, out innerExceptionData)) { exceptionData.ExceptionMetadata.InnerExceptionId = innerExceptionData.ExceptionMetadata.ExceptionId; } } else { exceptionData.ExceptionMetadata.InnerExceptionId = NoInnerExceptionValue; } } int totalSerializedExceptionSize = 0; // Make sure we include the current exception, regardless of buffer size ExceptionData currentExceptionData = null; if (s_exceptionDataTable.TryGetValue(currentException, out currentExceptionData)) { byte[] serializedExceptionData = currentExceptionData.Serialize(); serializedExceptions.Add(serializedExceptionData); totalSerializedExceptionSize = serializedExceptionData.Length; } checked { foreach (ExceptionData exceptionData in s_exceptionDataTable.GetValues()) { // Already serialized currentException if (currentExceptionData != null && exceptionData.ExceptionMetadata.ExceptionId == currentExceptionData.ExceptionMetadata.ExceptionId) { continue; } byte[] serializedExceptionData = exceptionData.Serialize(); if (totalSerializedExceptionSize + serializedExceptionData.Length >= MaxBufferSize) { break; } serializedExceptions.Add(serializedExceptionData); totalSerializedExceptionSize += serializedExceptionData.Length; } } } private unsafe static void GenerateErrorReportForDump(LowLevelList<byte[]> serializedExceptions) { checked { int loadedModuleCount = RuntimeAugments.GetLoadedModules(null); int cbModuleHandles = sizeof(System.IntPtr) * loadedModuleCount; int cbFinalBuffer = sizeof(ERROR_REPORT_BUFFER_HEADER) + sizeof(SERIALIZED_ERROR_REPORT_HEADER) + cbModuleHandles; for (int i = 0; i < serializedExceptions.Count; i++) { cbFinalBuffer += serializedExceptions[i].Length; } byte[] finalBuffer = new byte[cbFinalBuffer]; fixed (byte* pBuffer = finalBuffer) { byte* pCursor = pBuffer; int cbRemaining = cbFinalBuffer; ERROR_REPORT_BUFFER_HEADER* pDacHeader = (ERROR_REPORT_BUFFER_HEADER*)pCursor; pDacHeader->WriteHeader(cbFinalBuffer); pCursor += sizeof(ERROR_REPORT_BUFFER_HEADER); cbRemaining -= sizeof(ERROR_REPORT_BUFFER_HEADER); SERIALIZED_ERROR_REPORT_HEADER* pPayloadHeader = (SERIALIZED_ERROR_REPORT_HEADER*)pCursor; pPayloadHeader->WriteHeader(serializedExceptions.Count, loadedModuleCount); pCursor += sizeof(SERIALIZED_ERROR_REPORT_HEADER); cbRemaining -= sizeof(SERIALIZED_ERROR_REPORT_HEADER); // copy the serialized exceptions to report buffer for (int i = 0; i < serializedExceptions.Count; i++) { int cbChunk = serializedExceptions[i].Length; Array.CopyToNative(serializedExceptions[i], 0, (IntPtr)pCursor, cbChunk); cbRemaining -= cbChunk; pCursor += cbChunk; } // copy the module-handle array to report buffer System.IntPtr[] loadedModuleHandles = new System.IntPtr[loadedModuleCount]; RuntimeAugments.GetLoadedModules(loadedModuleHandles); Array.CopyToNative(loadedModuleHandles, 0, (IntPtr)pCursor, loadedModuleHandles.Length); cbRemaining -= cbModuleHandles; pCursor += cbModuleHandles; Debug.Assert(cbRemaining == 0); } UpdateErrorReportBuffer(finalBuffer); } } private static GCHandle s_ExceptionInfoBufferPinningHandle; private static object s_ExceptionInfoBufferLock = new object(); private unsafe static void UpdateErrorReportBuffer(byte[] finalBuffer) { fixed (byte* pBuffer = finalBuffer) { lock (s_ExceptionInfoBufferLock) { byte* pPrevBuffer = (byte*)RuntimeImports.RhSetErrorInfoBuffer(pBuffer); Debug.Assert(s_ExceptionInfoBufferPinningHandle.IsAllocated == (pPrevBuffer != null)); if (pPrevBuffer != null) { byte[] currentExceptionInfoBuffer = (byte[])s_ExceptionInfoBufferPinningHandle.Target; Debug.Assert(currentExceptionInfoBuffer != null); fixed (byte* pPrev = currentExceptionInfoBuffer) Debug.Assert(pPrev == pPrevBuffer); } if (!s_ExceptionInfoBufferPinningHandle.IsAllocated) { // We allocate a pinning GC handle because we are logically giving the runtime 'unmanaged memory'. s_ExceptionInfoBufferPinningHandle = GCHandle.Alloc(finalBuffer, GCHandleType.Pinned); } else { s_ExceptionInfoBufferPinningHandle.Target = finalBuffer; } } } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System.Runtime.InteropServices; using System.Diagnostics.Contracts; namespace System { // Summary: // Represents assembly binding information that can be added to an instance // of System.AppDomain. public sealed class AppDomainSetup { #if false public AppDomainInitializer AppDomainInitializer { get; set; } #endif // // Summary: // Gets or sets the arguments passed to the callback method represented by the // System.AppDomainInitializer delegate. The callback method is invoked when // the application domain is initialized. // // Returns: // An array of strings that is passed to the callback method represented by // the System.AppDomainInitializer delegate, when the callback method is invoked // during System.AppDomain initialization. // public string[] AppDomainInitializerArguments { get; set; } // // // Summary: // Gets or sets an object containing security and trust information. // // Returns: // An System.Security.Policy.ApplicationTrust object representing security and // trust information. // // Exceptions: // System.InvalidOperationException: // The property is set to an System.Security.Policy.ApplicationTrust object // whose application identity does not match the application identity of the // System.Runtime.Hosting.ActivationArguments object returned by the System.AppDomainSetup.ActivationArguments // property. No exception is thrown if the System.AppDomainSetup.ActivationArguments // property is null. // // System.ArgumentNullException: // The property is set to null. // extern public ApplicationTrust ApplicationTrust { get; set; } #if !SILVERLIGHT // // Summary: // Specifies whether the application base path and private binary path are probed // when searching for assemblies to load. // // Returns: // true if probing is not allowed; otherwise false. The default is false. extern public bool DisallowApplicationBaseProbing { get; set; } #endif #if !SILVERLIGHT // // Summary: // Gets or sets a value indicating if an application domain allows assembly // binding redirection. // // Returns: // true if redirection of assemblies is disallowed; otherwise it is allowed. extern public bool DisallowBindingRedirects { get; set; } #endif #if !SILVERLIGHT // // Summary: // Gets or sets a value indicating whether HTTP download of assemblies is allowed // for an application domain. // // Returns: // true if HTTP download of assemblies is to be disallowed; otherwise, it is // allowed. extern public bool DisallowCodeDownload { get; set; } #endif #if !SILVERLIGHT // // Summary: // Gets or sets a value indicating whether the publisher policy section of the // configuration file is applied to an application domain. // // Returns: // true if the publisherPolicy section of the configuration file for an application // domain is ignored; otherwise, the declared publisher policy is honored. extern public bool DisallowPublisherPolicy { get; set; } #endif // // Summary: // Specifies the optimization policy used to load an executable. // // Returns: // A System.LoaderOptimization enumerated constant used with the System.LoaderOptimizationAttribute. #if false public virtual LoaderOptimization LoaderOptimization { get; set; } #endif #if !SILVERLIGHT // // Summary: // Gets or sets a value indicating whether interface caching is disabled for // interop calls in the application domain, so that a QueryInterface is performed // on each call. // // Returns: // true if interface caching is disabled for interop calls in application domains // created with the current System.AppDomainSetup object; otherwise, false. extern public bool SandboxInterop { get; set; } #endif #if !SILVERLIGHT // Summary: // Gets the XML configuration information set by the System.AppDomainSetup.SetConfigurationBytes(System.Byte[]) // method, which overrides the application's XML configuration information. // // Returns: // A System.Byte array containing the XML configuration information that was // set by the System.AppDomainSetup.SetConfigurationBytes(System.Byte[]) method, // or null if the System.AppDomainSetup.SetConfigurationBytes(System.Byte[]) // method has not been called. extern public byte[] GetConfigurationBytes(); // // Summary: // Provides XML configuration information for the application domain, overriding // the application's XML configuration information. // // Parameters: // value: // A System.Byte array containing the XML configuration information to be used // for the application domain. extern public void SetConfigurationBytes(byte[] value); #endif } #if !SILVERLIGHT [ContractClass(typeof(IAppDomainSetupContract))] public interface IAppDomainSetup { string ApplicationBase { get; set; } string ApplicationName { get; set; } string CachePath { get; set; } string ConfigurationFile { get; set; } string DynamicBase { get; set; } string LicenseFile { get; set; } string PrivateBinPath { get; set; } string PrivateBinPathProbe { get; set; } string ShadowCopyDirectories { get; set; } string ShadowCopyFiles { get; set; } } [ContractClassFor(typeof(IAppDomainSetup))] abstract class IAppDomainSetupContract : IAppDomainSetup { #region IAppDomainSetup Members string IAppDomainSetup.ApplicationBase { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } string IAppDomainSetup.ApplicationName { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } string IAppDomainSetup.CachePath { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } string IAppDomainSetup.ConfigurationFile { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } string IAppDomainSetup.DynamicBase { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } string IAppDomainSetup.LicenseFile { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } string IAppDomainSetup.PrivateBinPath { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } string IAppDomainSetup.PrivateBinPathProbe { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } string IAppDomainSetup.ShadowCopyDirectories { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } string IAppDomainSetup.ShadowCopyFiles { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } #endregion } #endif }
using System; using System.Collections; using System.Data; using System.Data.OleDb; using PCSComUtils.Common; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; namespace PCSComUtils.Framework.ReportFrame.DS { public class sys_ReportDrillDownDS { public sys_ReportDrillDownDS() { } private const string THIS = "PCSComUtils.Framework.ReportFrame.DS.DS.sys_ReportDrillDownDS"; //************************************************************************** /// <Description> /// This method uses to add data to sys_ReportDrillDown /// </Description> /// <Inputs> /// sys_ReportDrillDownVO /// </Inputs> /// <Outputs> /// newly inserted primarkey value /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Monday, December 27, 2004 /// Modified: DungLA - 07/Jan/2005 /// 12/Oct/2005 Thachnn: fix bug injection /// </History> /// <Notes> /// Change strSql, insert data to one more field - MasterReportID /// </Notes> //************************************************************************** public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { sys_ReportDrillDownVO objObject = (sys_ReportDrillDownVO) pobjObjectVO; string strSql = String.Empty; strSql = "INSERT INTO " + sys_ReportDrillDownTable.TABLE_NAME + "(" + sys_ReportDrillDownTable.MASTERREPORTID_FLD + "," + sys_ReportDrillDownTable.DETAILREPORTID_FLD + "," + sys_ReportDrillDownTable.MASTERPARA_FLD + "," + sys_ReportDrillDownTable.DETAILPARA_FLD + "," + sys_ReportDrillDownTable.FROMCOLUMN_FLD + "," + sys_ReportDrillDownTable.PARAORDER_FLD + ")" + " VALUES (?,?,?,?,?,?)"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.MASTERREPORTID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportDrillDownTable.MASTERREPORTID_FLD].Value = objObject.MasterReportID; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.DETAILREPORTID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportDrillDownTable.DETAILREPORTID_FLD].Value = objObject.DetailReportID; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.MASTERPARA_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportDrillDownTable.MASTERPARA_FLD].Value = objObject.MasterPara; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.DETAILPARA_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportDrillDownTable.DETAILPARA_FLD].Value = objObject.DetailPara; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.FROMCOLUMN_FLD, OleDbType.Boolean)); ocmdPCS.Parameters[sys_ReportDrillDownTable.FROMCOLUMN_FLD].Value = objObject.FromColumn; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.PARAORDER_FLD, OleDbType.Integer)); ocmdPCS.Parameters[sys_ReportDrillDownTable.PARAORDER_FLD].Value = objObject.ParaOrder; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from sys_ReportDrillDown /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql = "DELETE " + sys_ReportDrillDownTable.TABLE_NAME + " WHERE " + sys_ReportDrillDownTable.MASTERREPORTID_FLD + "=" + pintID.ToString().Trim(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from sys_ReportDrillDown /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// 12/Oct/2005 Thachnn: fix bug injection /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(string pstrID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql = "DELETE " + sys_ReportDrillDownTable.TABLE_NAME + " WHERE " + sys_ReportDrillDownTable.MASTERREPORTID_FLD + " = ? ";// + pstrID + "'"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.MASTERREPORTID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportDrillDownTable.MASTERREPORTID_FLD].Value = pstrID; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from sys_ReportDrillDown /// </Description> /// <Inputs> /// MasterReportID, DetailReportID /// </Inputs> /// <Outputs> /// number of row(s) affected /// </Outputs> /// <Returns> /// int /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 07-Jan-2005 /// 12/Oct/2005 Thachnn: fix bug injection /// </History> /// <Notes> /// </Notes> //************************************************************************** public int Delete(string pstrMasterID, string pstrDetailID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql = "DELETE " + sys_ReportDrillDownTable.TABLE_NAME + " WHERE " + sys_ReportDrillDownTable.MASTERREPORTID_FLD + "= ? " // + pstrMasterID + "'" + " AND " + sys_ReportDrillDownTable.DETAILREPORTID_FLD + "= ? "; // + pstrDetailID + "'"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.MASTERREPORTID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportDrillDownTable.MASTERREPORTID_FLD].Value = pstrMasterID; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.DETAILREPORTID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportDrillDownTable.DETAILREPORTID_FLD].Value = pstrDetailID; ocmdPCS.Connection.Open(); int nReturn = ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; return nReturn; } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get data from sys_ReportDrillDown /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// sys_ReportDrillDownVO /// </Outputs> /// <Returns> /// sys_ReportDrillDownVO /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Monday, December 27, 2004 /// 12/Oct/2005 Thachnn: fix bug injection /// </History> /// <Notes> /// </Notes> //************************************************************************** public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + sys_ReportDrillDownTable.MASTERREPORTID_FLD + "," + sys_ReportDrillDownTable.DETAILREPORTID_FLD + "," + sys_ReportDrillDownTable.MASTERPARA_FLD + "," + sys_ReportDrillDownTable.DETAILPARA_FLD + "," + sys_ReportDrillDownTable.FROMCOLUMN_FLD + "," + sys_ReportDrillDownTable.PARAORDER_FLD + " FROM " + sys_ReportDrillDownTable.TABLE_NAME + " WHERE " + sys_ReportDrillDownTable.MASTERREPORTID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); sys_ReportDrillDownVO objObject = new sys_ReportDrillDownVO(); while (odrPCS.Read()) { objObject.MasterReportID = odrPCS[sys_ReportDrillDownTable.MASTERREPORTID_FLD].ToString().Trim(); objObject.DetailReportID = odrPCS[sys_ReportDrillDownTable.DETAILREPORTID_FLD].ToString().Trim(); objObject.MasterPara = odrPCS[sys_ReportDrillDownTable.MASTERPARA_FLD].ToString().Trim(); objObject.DetailPara = odrPCS[sys_ReportDrillDownTable.DETAILPARA_FLD].ToString().Trim(); objObject.FromColumn = Boolean.Parse(odrPCS[sys_ReportDrillDownTable.FROMCOLUMN_FLD].ToString().Trim()); objObject.ParaOrder = int.Parse(odrPCS[sys_ReportDrillDownTable.PARAORDER_FLD].ToString().Trim()); } return objObject; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get data from sys_ReportDrillDown /// </Description> /// <Inputs> /// Master Report ID /// </Inputs> /// <Outputs> /// List of sys_ReportDrillDownVO object /// </Outputs> /// <Returns> /// ArrayList /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 03-Jan-2005 /// 12/Oct/2005 Thachnn: fix bug injection /// </History> /// <Notes> /// </Notes> //************************************************************************** public ArrayList GetObjectVOs(string pstrMasterID) { const string METHOD_NAME = THIS + ".GetObjectVOs()"; ArrayList arrObjectVOs = new ArrayList(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + sys_ReportDrillDownTable.MASTERREPORTID_FLD + "," + sys_ReportDrillDownTable.DETAILREPORTID_FLD + "," + sys_ReportDrillDownTable.MASTERPARA_FLD + "," + sys_ReportDrillDownTable.DETAILPARA_FLD + "," + sys_ReportDrillDownTable.FROMCOLUMN_FLD + "," + sys_ReportDrillDownTable.PARAORDER_FLD + " FROM " + sys_ReportDrillDownTable.TABLE_NAME + " WHERE " + sys_ReportDrillDownTable.MASTERREPORTID_FLD + "= ? ";// + pstrMasterID + "'"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.MASTERREPORTID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportDrillDownTable.MASTERREPORTID_FLD].Value = pstrMasterID; ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); while (odrPCS.Read()) { sys_ReportDrillDownVO voDrillDown = new sys_ReportDrillDownVO(); voDrillDown.MasterReportID = odrPCS[sys_ReportDrillDownTable.MASTERREPORTID_FLD].ToString().Trim(); voDrillDown.DetailReportID = odrPCS[sys_ReportDrillDownTable.DETAILREPORTID_FLD].ToString().Trim(); voDrillDown.MasterPara = odrPCS[sys_ReportDrillDownTable.MASTERPARA_FLD].ToString().Trim(); voDrillDown.DetailPara = odrPCS[sys_ReportDrillDownTable.DETAILPARA_FLD].ToString().Trim(); voDrillDown.FromColumn = Boolean.Parse(odrPCS[sys_ReportDrillDownTable.FROMCOLUMN_FLD].ToString().Trim()); voDrillDown.ParaOrder = int.Parse(odrPCS[sys_ReportDrillDownTable.PARAORDER_FLD].ToString().Trim()); arrObjectVOs.Add(voDrillDown); } arrObjectVOs.TrimToSize(); return arrObjectVOs; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update data to sys_ReportDrillDown /// </Description> /// <Inputs> /// sys_ReportDrillDownVO /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// 12/Oct/2005 Thachnn: fix bug injection /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; sys_ReportDrillDownVO objObject = (sys_ReportDrillDownVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "UPDATE " + sys_ReportDrillDownTable.TABLE_NAME + " SET " + sys_ReportDrillDownTable.DETAILREPORTID_FLD + "= ?" + "," + sys_ReportDrillDownTable.MASTERPARA_FLD + "= ?" + "," + sys_ReportDrillDownTable.DETAILPARA_FLD + "= ?" + "," + sys_ReportDrillDownTable.FROMCOLUMN_FLD + "= ?" + "," + sys_ReportDrillDownTable.PARAORDER_FLD + "= ?" + " WHERE " + sys_ReportDrillDownTable.MASTERREPORTID_FLD + "= ?"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.DETAILREPORTID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportDrillDownTable.DETAILREPORTID_FLD].Value = objObject.DetailReportID; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.MASTERPARA_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportDrillDownTable.MASTERPARA_FLD].Value = objObject.MasterPara; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.DETAILPARA_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportDrillDownTable.DETAILPARA_FLD].Value = objObject.DetailPara; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.FROMCOLUMN_FLD, OleDbType.Boolean)); ocmdPCS.Parameters[sys_ReportDrillDownTable.FROMCOLUMN_FLD].Value = objObject.FromColumn; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.PARAORDER_FLD, OleDbType.Integer)); ocmdPCS.Parameters[sys_ReportDrillDownTable.PARAORDER_FLD].Value = objObject.ParaOrder; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.MASTERREPORTID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportDrillDownTable.MASTERREPORTID_FLD].Value = objObject.MasterReportID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get all data from sys_ReportDrillDown /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Monday, December 27, 2004 /// 12/Oct/2005 Thachnn: fix bug injection /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + sys_ReportDrillDownTable.MASTERREPORTID_FLD + "," + sys_ReportDrillDownTable.DETAILREPORTID_FLD + "," + sys_ReportDrillDownTable.MASTERPARA_FLD + "," + sys_ReportDrillDownTable.DETAILPARA_FLD + "," + sys_ReportDrillDownTable.FROMCOLUMN_FLD + "," + sys_ReportDrillDownTable.PARAORDER_FLD + " FROM " + sys_ReportDrillDownTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, sys_ReportDrillDownTable.TABLE_NAME); return dstPCS; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update a DataSet /// </Description> /// <Inputs> /// DataSet /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Monday, December 27, 2004 /// /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS = null; OleDbCommandBuilder odcbPCS; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql = "SELECT " + sys_ReportDrillDownTable.MASTERREPORTID_FLD + "," + sys_ReportDrillDownTable.DETAILREPORTID_FLD + "," + sys_ReportDrillDownTable.MASTERPARA_FLD + "," + sys_ReportDrillDownTable.DETAILPARA_FLD + "," + sys_ReportDrillDownTable.FROMCOLUMN_FLD + "," + sys_ReportDrillDownTable.PARAORDER_FLD + " FROM " + sys_ReportDrillDownTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData, sys_ReportDrillDownTable.TABLE_NAME); } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get data from sys_ReportDrillDown /// </Description> /// <Inputs> /// MasterID, DetailID /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 06-Jan-2005 /// 12/Oct/2005 Thachnn: fix bug injection /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet GetObjectVO(string pstrMasterID, string pstrDetailID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + sys_ReportDrillDownTable.MASTERREPORTID_FLD + "," + sys_ReportDrillDownTable.DETAILREPORTID_FLD + "," + sys_ReportDrillDownTable.MASTERPARA_FLD + "," + sys_ReportDrillDownTable.DETAILPARA_FLD + "," + sys_ReportDrillDownTable.FROMCOLUMN_FLD + "," + sys_ReportDrillDownTable.PARAORDER_FLD + " FROM " + sys_ReportDrillDownTable.TABLE_NAME + " WHERE " + sys_ReportDrillDownTable.MASTERREPORTID_FLD + "= ? "// + pstrMasterID + "'" + " AND " + sys_ReportDrillDownTable.DETAILREPORTID_FLD + "= ? ";// + pstrDetailID + "'"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.MASTERREPORTID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportDrillDownTable.MASTERREPORTID_FLD].Value = pstrMasterID; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.DETAILREPORTID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportDrillDownTable.DETAILREPORTID_FLD].Value = pstrDetailID; ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, sys_ReportDrillDownTable.TABLE_NAME); return dstPCS; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get data from sys_ReportDrillDown /// </Description> /// <Inputs> /// MasterID, DetailID /// </Inputs> /// <Outputs> /// ArrayList /// </Outputs> /// <Returns> /// ArrayList /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 06-Jan-2005 /// 12/Oct/2005 Thachnn: fix bug injection /// </History> /// <Notes> /// </Notes> //************************************************************************** public ArrayList GetObjectVOs(string pstrMasterID, string pstrDetailID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; ArrayList arrObjectVOs = new ArrayList(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; OleDbDataReader odrPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + sys_ReportDrillDownTable.MASTERREPORTID_FLD + "," + sys_ReportDrillDownTable.DETAILREPORTID_FLD + "," + sys_ReportDrillDownTable.MASTERPARA_FLD + "," + sys_ReportDrillDownTable.DETAILPARA_FLD + "," + sys_ReportDrillDownTable.FROMCOLUMN_FLD + "," + sys_ReportDrillDownTable.PARAORDER_FLD + " FROM " + sys_ReportDrillDownTable.TABLE_NAME + " WHERE " + sys_ReportDrillDownTable.MASTERREPORTID_FLD + "= ? " // + pstrMasterID + "'" + " AND " + sys_ReportDrillDownTable.DETAILREPORTID_FLD + "= ? " ; //+ pstrDetailID + "'"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.MASTERREPORTID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportDrillDownTable.MASTERREPORTID_FLD].Value = pstrMasterID; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.DETAILREPORTID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportDrillDownTable.DETAILREPORTID_FLD].Value = pstrDetailID; ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); while (odrPCS.Read()) { sys_ReportDrillDownVO voDrillDown = new sys_ReportDrillDownVO(); voDrillDown.MasterReportID = odrPCS[sys_ReportDrillDownTable.MASTERREPORTID_FLD].ToString().Trim(); voDrillDown.DetailReportID = odrPCS[sys_ReportDrillDownTable.DETAILREPORTID_FLD].ToString().Trim(); voDrillDown.MasterPara = odrPCS[sys_ReportDrillDownTable.MASTERPARA_FLD].ToString().Trim(); voDrillDown.DetailPara = odrPCS[sys_ReportDrillDownTable.DETAILPARA_FLD].ToString().Trim(); voDrillDown.FromColumn = Boolean.Parse(odrPCS[sys_ReportDrillDownTable.FROMCOLUMN_FLD].ToString().Trim()); voDrillDown.ParaOrder = int.Parse(odrPCS[sys_ReportDrillDownTable.PARAORDER_FLD].ToString().Trim()); arrObjectVOs.Add(voDrillDown); } arrObjectVOs.TrimToSize(); return arrObjectVOs; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get data for C1TrueDBGrid /// </Description> /// <Inputs> /// MasterID, DetailID /// </Inputs> /// <Outputs> /// DataTable /// </Outputs> /// <Returns> /// DataTable /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 06-Jan-2005 /// 12/Oct/2005 Thachnn: fix bug injection /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataTable GetDataForTrueDBGrid(string pstrMasterID, string pstrDetailID, out bool oblnIsEdit) { const string METHOD_NAME = THIS + ".GetDataForTrueDBGrid()"; string strSql = string.Empty; // create new table with 4 columns to store data and return to caller DataTable dtblSource = new DataTable(sys_ReportDrillDownTable.TABLE_NAME); dtblSource.Columns.Add(sys_ReportDrillDownTable.MASTERPARA_FLD); dtblSource.Columns.Add(sys_ReportDrillDownTable.DETAILPARA_FLD); dtblSource.Columns.Add(sys_ReportParaTable.DATATYPE_FLD); dtblSource.Columns.Add(sys_ReportDrillDownTable.FROMCOLUMN_FLD); dtblSource.Columns.Add(sys_ReportDrillDownTable.PARAORDER_FLD); // set data type for FromColumn column dtblSource.Columns[sys_ReportDrillDownTable.FROMCOLUMN_FLD].DataType = typeof (bool); // set default value for FromColumn dtblSource.Columns[sys_ReportDrillDownTable.FROMCOLUMN_FLD].DefaultValue = false; DataSet dstSource = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; #region Existed record in sys_ReportDrillDown table // first we check for existing record in sys_ReportDrillDown table strSql = "SELECT " + sys_ReportDrillDownTable.MASTERREPORTID_FLD + "," + sys_ReportDrillDownTable.DETAILREPORTID_FLD + "," + sys_ReportDrillDownTable.MASTERPARA_FLD + "," + sys_ReportDrillDownTable.DETAILPARA_FLD + "," + sys_ReportDrillDownTable.FROMCOLUMN_FLD + "," + sys_ReportDrillDownTable.PARAORDER_FLD + " FROM " + sys_ReportDrillDownTable.TABLE_NAME + " WHERE " + sys_ReportDrillDownTable.MASTERREPORTID_FLD + "= ? " //+ pstrMasterID + "'" + " AND " + sys_ReportDrillDownTable.DETAILREPORTID_FLD + "= ? " ;// + pstrDetailID + "'"; try { // if already existed, then get current data Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.MASTERREPORTID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportDrillDownTable.MASTERREPORTID_FLD].Value = pstrMasterID; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportDrillDownTable.DETAILREPORTID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportDrillDownTable.DETAILREPORTID_FLD].Value = pstrDetailID; ocmdPCS.Connection.Open(); OleDbDataReader odrdPCS = ocmdPCS.ExecuteReader(); if (odrdPCS.HasRows) { while (odrdPCS.Read()) { DataRow drow = dtblSource.NewRow(); drow[sys_ReportDrillDownTable.MASTERPARA_FLD] = odrdPCS[sys_ReportDrillDownTable.MASTERPARA_FLD]; drow[sys_ReportDrillDownTable.DETAILPARA_FLD] = odrdPCS[sys_ReportDrillDownTable.DETAILPARA_FLD]; drow[sys_ReportDrillDownTable.FROMCOLUMN_FLD] = odrdPCS[sys_ReportDrillDownTable.FROMCOLUMN_FLD]; drow[sys_ReportDrillDownTable.PARAORDER_FLD] = odrdPCS[sys_ReportDrillDownTable.PARAORDER_FLD]; dtblSource.Rows.Add(drow); } sys_ReportParaDS dsSysReportPara = new sys_ReportParaDS(); foreach (DataRow drow in dtblSource.Rows) { drow[sys_ReportParaTable.DATATYPE_FLD] = dsSysReportPara.GetDataType(pstrDetailID, drow[sys_ReportDrillDownTable.DETAILPARA_FLD].ToString().Trim()); } // return oblnIsEdit = true; return dtblSource; } } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } #endregion oblnIsEdit = false; #region Not existed, make new data and return to user /// TODO: Bro.DungLA. Thachnn says: I feel bug here, when creating strSql, but I don't know why and how to fix. /// The old code is really fusion with continuing plus and plus SQL string. /// Please comeback to this point when there are any errors. try { Utils utils = new Utils(); oconPCS.ConnectionString = Utils.Instance.OleDbConnectionString; string strSqlOrder = " ORDER BY " + sys_ReportParaTable.PARAORDER_FLD + " ASC"; string strSqlMaster = "SELECT " + sys_ReportParaTable.PARAORDER_FLD + "," + sys_ReportParaTable.PARANAME_FLD + "," + sys_ReportParaTable.DATATYPE_FLD + " FROM " + sys_ReportParaTable.TABLE_NAME + " WHERE " + sys_ReportParaTable.REPORTID_FLD + "= ? " + strSqlOrder; OleDbCommand ocmdMaster = new OleDbCommand(strSqlMaster,oconPCS); ocmdMaster.Parameters.Add(new OleDbParameter(sys_ReportParaTable.REPORTID_FLD, OleDbType.VarWChar)); ocmdMaster.Parameters[sys_ReportParaTable.REPORTID_FLD].Value = pstrMasterID; // fill master para into dataset with new table OleDbDataAdapter odadMaster = new OleDbDataAdapter(ocmdMaster); odadMaster.Fill(dstSource, sys_ReportDrillDownTable.MASTERPARA_FLD); string strSqlDetail = "SELECT " + sys_ReportParaTable.PARAORDER_FLD + "," + sys_ReportParaTable.PARANAME_FLD + "," + sys_ReportParaTable.DATATYPE_FLD + " FROM " + sys_ReportParaTable.TABLE_NAME + " WHERE " + sys_ReportParaTable.REPORTID_FLD + "= ? " + strSqlOrder; OleDbCommand ocmdDetail = new OleDbCommand(strSqlDetail,oconPCS); ocmdDetail.Parameters.Add(new OleDbParameter(sys_ReportParaTable.REPORTID_FLD, OleDbType.VarWChar)); ocmdDetail.Parameters[sys_ReportParaTable.REPORTID_FLD].Value = pstrDetailID; // fill detail para into dataset with new table OleDbDataAdapter odadDetail = new OleDbDataAdapter(ocmdDetail); odadDetail.Fill(dstSource, sys_ReportDrillDownTable.DETAILPARA_FLD); // get all rows DataRowCollection MasterRows = dstSource.Tables[sys_ReportDrillDownTable.MASTERPARA_FLD].Rows; DataRowCollection DetailRows = dstSource.Tables[sys_ReportDrillDownTable.DETAILPARA_FLD].Rows; // if number of master para is bigger than number of detail para // then the detail para is basic for filling parameter values if (MasterRows.Count > DetailRows.Count) { for (int i = 0; i < MasterRows.Count; i++) { DataRow drow = dtblSource.NewRow(); drow[sys_ReportDrillDownTable.MASTERPARA_FLD] = MasterRows[i][sys_ReportParaTable.PARANAME_FLD]; drow[sys_ReportDrillDownTable.PARAORDER_FLD] = i + 1; if (i < DetailRows.Count) { drow[sys_ReportDrillDownTable.DETAILPARA_FLD] = DetailRows[i][sys_ReportParaTable.PARANAME_FLD]; drow[sys_ReportParaTable.DATATYPE_FLD] = DetailRows[i][sys_ReportParaTable.DATATYPE_FLD]; } else { break; } dtblSource.Rows.Add(drow); } } // if number of detail para is bigger than number of master para // then the master para is basic for filling parameter values else { for (int i = 0; i < DetailRows.Count; i++) { DataRow drow = dtblSource.NewRow(); drow[sys_ReportDrillDownTable.DETAILPARA_FLD] = DetailRows[i][sys_ReportParaTable.PARANAME_FLD]; drow[sys_ReportDrillDownTable.PARAORDER_FLD] = i + 1; if (i < MasterRows.Count) { drow[sys_ReportDrillDownTable.MASTERPARA_FLD] = MasterRows[i][sys_ReportParaTable.PARANAME_FLD]; drow[sys_ReportParaTable.DATATYPE_FLD] = MasterRows[i][sys_ReportParaTable.DATATYPE_FLD]; } else { drow[sys_ReportDrillDownTable.MASTERPARA_FLD] = null; drow[sys_ReportParaTable.DATATYPE_FLD] = DetailRows[i][sys_ReportParaTable.DATATYPE_FLD]; } dtblSource.Rows.Add(drow); } } oblnIsEdit = true; return dtblSource; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } #endregion } } }
// *********************************************************************** // Copyright (c) 2008 Charlie Poole // // 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 NUnit.Framework.Internal; namespace NUnit.Framework.Constraints { /// <summary> /// ThrowsConstraint is used to test the exception thrown by /// a delegate by applying a constraint to it. /// </summary> public class ThrowsConstraint : PrefixConstraint { private Exception caughtException; /// <summary> /// Initializes a new instance of the <see cref="ThrowsConstraint"/> class, /// using a constraint to be applied to the exception. /// </summary> /// <param name="baseConstraint">A constraint to apply to the caught exception.</param> public ThrowsConstraint(IConstraint baseConstraint) : base(baseConstraint) { } /// <summary> /// Get the actual exception thrown - used by Assert.Throws. /// </summary> public Exception ActualException { get { return caughtException; } } #region Constraint Overrides /// <summary> /// Gets text describing a constraint /// </summary> public override string Description { get { return BaseConstraint.Description; } } /// <summary> /// Executes the code of the delegate and captures any exception. /// If a non-null base constraint was provided, it applies that /// constraint to the exception. /// </summary> /// <param name="actual">A delegate representing the code to be tested</param> /// <returns>True if an exception is thrown and the constraint succeeds, otherwise false</returns> public override ConstraintResult ApplyTo<TActual>(TActual actual) { //TestDelegate code = actual as TestDelegate; //if (code == null) // throw new ArgumentException( // string.Format("The actual value must be a TestDelegate but was {0}", actual.GetType().Name), "actual"); //caughtException = null; //try //{ // code(); //} //catch (Exception ex) //{ // caughtException = ex; //} caughtException = ExceptionInterceptor.Intercept(actual); return new ThrowsConstraintResult( this, caughtException, caughtException != null ? BaseConstraint.ApplyTo(caughtException) : null); } /// <summary> /// Converts an ActualValueDelegate to a TestDelegate /// before calling the primary overload. /// </summary> /// <param name="del"></param> /// <returns></returns> public override ConstraintResult ApplyTo<TActual>(ActualValueDelegate<TActual> del) { //TestDelegate testDelegate = new TestDelegate(delegate { del(); }); //return ApplyTo((object)testDelegate); return ApplyTo(new GenericInvocationDescriptor<TActual>(del)); } #endregion #region Nested Result Class private class ThrowsConstraintResult : ConstraintResult { private readonly ConstraintResult baseResult; public ThrowsConstraintResult(ThrowsConstraint constraint, Exception caughtException, ConstraintResult baseResult) : base(constraint, caughtException) { if (caughtException != null && baseResult.IsSuccess) Status = ConstraintStatus.Success; else Status = ConstraintStatus.Failure; this.baseResult = baseResult; } /// <summary> /// Write the actual value for a failing constraint test to a /// MessageWriter. This override only handles the special message /// used when an exception is expected but none is thrown. /// </summary> /// <param name="writer">The writer on which the actual value is displayed</param> public override void WriteActualValueTo(MessageWriter writer) { if (ActualValue == null) writer.Write("no exception thrown"); else baseResult.WriteActualValueTo(writer); } } #endregion #region ExceptionInterceptor internal class ExceptionInterceptor { private ExceptionInterceptor() { } internal static Exception Intercept(object invocation) { var invocationDescriptor = GetInvocationDescriptor(invocation); #if ASYNC if (AwaitUtils.IsAwaitable(invocationDescriptor.Delegate)) { try { object result = invocationDescriptor.Invoke(); AwaitUtils.Await(invocationDescriptor.Delegate, result); return null; } catch (Exception ex) { return ex; } } if (AwaitUtils.IsAsyncVoid(invocationDescriptor.Delegate)) throw new ArgumentException("'async void' methods are not supported. Please use 'async Task' instead."); #endif using (new TestExecutionContext.IsolatedContext()) { try { invocationDescriptor.Invoke(); return null; } catch (Exception ex) { return ex; } } } private static IInvocationDescriptor GetInvocationDescriptor(object actual) { var invocationDescriptor = actual as IInvocationDescriptor; if (invocationDescriptor == null) { var testDelegate = actual as TestDelegate; if (testDelegate != null) { invocationDescriptor = new VoidInvocationDescriptor(testDelegate); } #if ASYNC else { var asyncTestDelegate = actual as AsyncTestDelegate; if (asyncTestDelegate != null) { invocationDescriptor = new GenericInvocationDescriptor<System.Threading.Tasks.Task>(() => asyncTestDelegate()); } } #endif } if (invocationDescriptor == null) throw new ArgumentException( String.Format( "The actual value must be a TestDelegate or AsyncTestDelegate but was {0}", actual.GetType().Name), "actual"); return invocationDescriptor; } } #endregion #region InvocationDescriptor internal class GenericInvocationDescriptor<T> : IInvocationDescriptor { private readonly ActualValueDelegate<T> _del; public GenericInvocationDescriptor(ActualValueDelegate<T> del) { _del = del; } public object Invoke() { return _del(); } public Delegate Delegate { get { return _del; } } } private interface IInvocationDescriptor { Delegate Delegate { get; } object Invoke(); } private class VoidInvocationDescriptor : IInvocationDescriptor { private readonly TestDelegate _del; public VoidInvocationDescriptor(TestDelegate del) { _del = del; } public object Invoke() { _del(); return null; } public Delegate Delegate { get { return _del; } } } #endregion } }
//! \file ArcEncrypted.cs //! \date Thu Jan 14 03:27:52 2016 //! \brief Encrypted AZ system resource archives. // // Copyright (C) 2016 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.Compression; using GameRes.Utility; using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Linq; using System.Security.Cryptography; namespace GameRes.Formats.AZSys { [Serializable] public class EncryptionScheme { public readonly uint IndexKey; public readonly uint? ContentKey; public static readonly uint[] DefaultSeed = { 0x2F4D7DFE, 0x47345292, 0x1BA5FE82, 0x7BC04525 }; public EncryptionScheme (uint ikey, uint ckey) { IndexKey = ikey; ContentKey = ckey; } public EncryptionScheme (uint[] iseed) { IndexKey = GenerateKey (iseed); ContentKey = null; } public EncryptionScheme (uint[] iseed, byte[] cseed) { IndexKey = GenerateKey (iseed); ContentKey = GenerateContentKey (cseed); } public static uint GenerateKey (uint[] seed) { if (null == seed) throw new ArgumentNullException ("seed"); if (seed.Length < 4) throw new ArgumentException(); byte[] seed_bytes = new byte[0x10]; Buffer.BlockCopy (seed, 0, seed_bytes, 0, 0x10); uint key = Crc32.UpdateCrc (~seed[0], seed_bytes, 0, seed_bytes.Length) ^ Crc32.UpdateCrc (~(seed[1] & 0xFFFF), seed_bytes, 0, seed_bytes.Length) ^ Crc32.UpdateCrc (~(seed[1] >> 16), seed_bytes, 0, seed_bytes.Length) ^ Crc32.UpdateCrc (~seed[2], seed_bytes, 0, seed_bytes.Length) ^ Crc32.UpdateCrc (~seed[3], seed_bytes, 0, seed_bytes.Length); return seed[0] ^ ~key; } public static uint GenerateContentKey (byte[] env_bytes) { if (null == env_bytes) throw new ArgumentNullException ("env_bytes"); if (env_bytes.Length < 0x10) throw new ArgumentException(); uint crc = Crc32.Compute (env_bytes, 0, 0x10); var sfmt = new FastMersenneTwister (crc); var seed = new uint[4]; seed[0] = sfmt.GetRand32(); seed[1] = sfmt.GetRand32() & 0xFFFF; seed[1] |= sfmt.GetRand32() << 16; seed[2] = sfmt.GetRand32(); seed[3] = sfmt.GetRand32(); return GenerateKey (seed); } } [Serializable] public class AzScheme : ResourceScheme { public Dictionary<string, EncryptionScheme> KnownSchemes; } internal class AzArchive : ArcFile { public readonly uint SysenvKey; public readonly uint RegularKey; public AzArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, uint syskey, uint regkey) : base (arc, impl, dir) { SysenvKey = syskey; RegularKey = regkey; } } public abstract class ArcEncryptedBase : ArchiveFormat { internal List<Entry> ParseIndex (Stream input, int count, long base_offset, long max_offset) { using (var zstream = new ZLibStream (input, CompressionMode.Decompress)) using (var index = new BinaryReader (zstream)) { var dir = new List<Entry> (count); var name_buffer = new byte[0x20]; for (int i = 0; i < count; ++i) { uint offset = index.ReadUInt32(); uint size = index.ReadUInt32(); uint crc = index.ReadUInt32(); index.ReadInt32(); if (name_buffer.Length != index.Read (name_buffer, 0, name_buffer.Length)) return null; var name = Binary.GetCString (name_buffer, 0, 0x20); if (0 == name.Length) return null; var entry = FormatCatalog.Instance.Create<Entry> (name); entry.Offset = base_offset + offset; entry.Size = size; if (!entry.CheckPlacement (max_offset)) return null; dir.Add (entry); } return dir; } } internal bool DecryptAsb (byte[] data) { int packed_size = LittleEndian.ToInt32 (data, 4); if (packed_size <= 4 || packed_size > data.Length-0x10) return false; uint unpacked_size = LittleEndian.ToUInt32 (data, 8); uint key = unpacked_size ^ 0x9E370001; unsafe { fixed (byte* raw = &data[0x10]) { uint* data32 = (uint*)raw; for (int i = packed_size/4; i > 0; --i) *data32++ -= key; } } return true; } } [Export(typeof(ArchiveFormat))] public class ArcEncryptedOpener : ArcEncryptedBase { public override string Tag { get { return "ARC/AZ/encrypted"; } } public override string Description { get { return "AZ system encrypted resource archive"; } } public override uint Signature { get { return 0; } } public override bool IsHierarchic { get { return false; } } public override bool CanWrite { get { return false; } } public static Dictionary<string, EncryptionScheme> KnownSchemes = new Dictionary<string, EncryptionScheme> { { "Default", new EncryptionScheme (EncryptionScheme.DefaultSeed) }, }; public override ResourceScheme Scheme { get { return new AzScheme { KnownSchemes = KnownSchemes }; } set { KnownSchemes = ((AzScheme)value).KnownSchemes; } } public ArcEncryptedOpener () { Extensions = new string[] { "arc" }; Signatures = new uint[] { 0x53EA06EB, 0x74F98F2F }; } EncryptionScheme CurrentScheme; public override ArcFile TryOpen (ArcView file) { byte[] header_encrypted = file.View.ReadBytes (0, 0x30); if (header_encrypted.Length < 0x30) return null; byte[] header = new byte[header_encrypted.Length]; if (CurrentScheme != null) { try { Buffer.BlockCopy (header_encrypted, 0, header, 0, header.Length); Decrypt (header, 0, CurrentScheme.IndexKey); if (Binary.AsciiEqual (header, 0, "ARC\0")) { var arc = ReadIndex (file, header, CurrentScheme); if (null != arc) return arc; } } catch { /* ignore parse errors */ } } foreach (var scheme in KnownSchemes.Values) { Buffer.BlockCopy (header_encrypted, 0, header, 0, header.Length); Decrypt (header, 0, scheme.IndexKey); if (Binary.AsciiEqual (header, 0, "ARC\0")) { var arc = ReadIndex (file, header, scheme); if (null != arc) CurrentScheme = new EncryptionScheme (arc.SysenvKey, arc.RegularKey); return arc; } } return null; } public override Stream OpenEntry (ArcFile arc, Entry entry) { var azarc = arc as AzArchive; if (null == azarc) return base.OpenEntry (arc, entry); var data = arc.File.View.ReadBytes (entry.Offset, entry.Size); if (entry.Name.Equals ("sysenv.tbl", StringComparison.InvariantCultureIgnoreCase)) { Decrypt (data, entry.Offset, azarc.SysenvKey); return UnpackData (data); } Decrypt (data, entry.Offset, azarc.RegularKey); if (data.Length > 0x14 && Binary.AsciiEqual (data, 0, "ASB\0") && DecryptAsb (data)) { var asb = UnpackData (data, 0x10); var header = new byte[0x10]; Buffer.BlockCopy (data, 0, header, 0, 0x10); return new PrefixStream (header, asb); } return new BinMemoryStream (data, entry.Name); } uint ReadSysenvSeed (ArcView file, IEnumerable<Entry> dir, uint key) { var entry = dir.FirstOrDefault (e => e.Name.Equals ("sysenv.tbl", StringComparison.InvariantCultureIgnoreCase)); if (null == entry) return key; var data = file.View.ReadBytes (entry.Offset, entry.Size); if (data.Length <= 4) throw new InvalidFormatException ("Invalid sysenv.tbl size"); Decrypt (data, entry.Offset, key); uint adler32 = LittleEndian.ToUInt32 (data, 0); if (adler32 != Adler32.Compute (data, 4, data.Length-4)) throw new InvalidEncryptionScheme(); using (var input = new MemoryStream (data, 4, data.Length-4)) using (var sysenv_stream = new ZLibStream (input, CompressionMode.Decompress)) { var seed = new byte[0x10]; if (0x10 != sysenv_stream.Read (seed, 0, 0x10)) throw new InvalidFormatException ("Invalid sysenv.tbl size"); return EncryptionScheme.GenerateContentKey (seed); } } Stream UnpackData (byte[] data, int index = 0) { int length = data.Length - index; if (length <= 4) return new MemoryStream (data, index, length); uint adler32 = LittleEndian.ToUInt32 (data, index); if (adler32 != Adler32.Compute (data, index+4, length-4)) return new MemoryStream (data, index, length); var input = new MemoryStream (data, index+4, length-4); return new ZLibStream (input, CompressionMode.Decompress); } AzArchive ReadIndex (ArcView file, byte[] header, EncryptionScheme scheme) { int ext_count = LittleEndian.ToInt32 (header, 4); int count = LittleEndian.ToInt32 (header, 8); uint index_length = LittleEndian.ToUInt32 (header, 12); if (ext_count < 1 || ext_count > 8 || !IsSaneCount (count) || index_length >= file.MaxOffset) return null; var packed_index = file.View.ReadBytes (header.Length, index_length); if (packed_index.Length != index_length) return null; Decrypt (packed_index, header.Length, scheme.IndexKey); uint checksum = LittleEndian.ToUInt32 (packed_index, 0); if (checksum != Adler32.Compute (packed_index, 4, packed_index.Length-4)) { if (checksum != Crc32.Compute (packed_index, 4, packed_index.Length-4)) throw new InvalidFormatException ("Index checksum mismatch"); } using (var input = new MemoryStream (packed_index, 4, packed_index.Length-4)) { var dir = ParseIndex (input, count, header.Length + index_length, file.MaxOffset); if (null == dir) return null; uint content_key = GetContentKey (file, dir, scheme); return new AzArchive (file, this, dir, scheme.IndexKey, content_key); } } static void Decrypt (byte[] data, long offset, uint key) { ulong hash = key * 0x9E370001ul; if (0 != (offset & 0x3F)) { hash = Binary.RotL (hash, (int)offset); } for (uint i = 0; i < data.Length; ++i) { data[i] ^= (byte)hash; hash = Binary.RotL (hash, 1); } } uint GetContentKey (ArcView file, List<Entry> dir, EncryptionScheme scheme) { if (null != scheme.ContentKey) return scheme.ContentKey.Value; if (VFS.IsPathEqualsToFileName (file.Name, "system.arc")) { return ReadSysenvSeed (file, dir, scheme.IndexKey); } else { var system_arc = VFS.CombinePath (VFS.GetDirectoryName (file.Name), "system.arc"); using (var arc = VFS.OpenView (system_arc)) { var header = arc.View.ReadBytes (0, 0x30); Decrypt (header, 0, scheme.IndexKey); using (var arc_file = ReadIndex (arc, header, scheme)) { return ReadSysenvSeed (arc, arc_file.Dir, scheme.IndexKey); } } } } } [Export(typeof(ArchiveFormat))] public class ArcIsaacEncryptedOpener : ArcEncryptedBase { public override string Tag { get { return "ARC/AZ/ISAAC"; } } public override string Description { get { return "AZ system encrypted resource archive"; } } public override uint Signature { get { return 0; } } public override bool IsHierarchic { get { return false; } } public override bool CanWrite { get { return false; } } public ArcIsaacEncryptedOpener () { Extensions = new string[] { "arc" }; } public override ArcFile TryOpen (ArcView file) { byte[] header_encrypted = file.View.ReadBytes (0, 0x30); if (header_encrypted.Length < 0x30) return null; byte[] header = new byte[header_encrypted.Length]; Buffer.BlockCopy (header_encrypted, 0, header, 0, header.Length); var cipher = new AzIsaacEncryption ((uint)file.MaxOffset); cipher.Decrypt (header, 0, header.Length, 0); if (!Binary.AsciiEqual (header, 0, "ARC\0")) return null; int ext_count = LittleEndian.ToInt32 (header, 4); int count = LittleEndian.ToInt32 (header, 8); uint index_length = LittleEndian.ToUInt32 (header, 12); if (ext_count < 1 || ext_count > 8 || !IsSaneCount (count) || index_length >= file.MaxOffset) return null; var packed_index = file.View.ReadBytes (0x30, index_length); if (packed_index.Length != index_length) return null; cipher.Decrypt (packed_index, 0, packed_index.Length, 0x30); using (var input = new MemoryStream (packed_index)) { var dir = ParseIndex (input, count, header.Length + index_length, file.MaxOffset); if (null == dir) return null; return new ArcFile (file, this, dir); } } public override Stream OpenEntry (ArcFile arc, Entry entry) { var data = arc.File.View.ReadBytes (entry.Offset, entry.Size); var cipher = new AzIsaacEncryption (entry.Size); cipher.Decrypt (data, 0, data.Length, 0); if (data.Length > 0x14 && Binary.AsciiEqual (data, 0, "ASB\0") && DecryptAsb (data)) { var header = new byte[0x10]; Buffer.BlockCopy (data, 0, header, 0, 0x10); Stream input = new MemoryStream (data, 0x10, data.Length-0x10); input = new ZLibStream (input, CompressionMode.Decompress); return new PrefixStream (header, input); } return new MemoryStream (data); } /// <summary> /// Calculate SHA1 sum of archive file. /// </summary> public byte[] CalculateSum (Stream arc) { using (var sha1 = SHA1.Create()) return sha1.ComputeHash (arc); } } internal class AzIsaacEncryption { uint[] m_key = new uint[0x100]; public AzIsaacEncryption (uint seed) { var isaac = new Isaac64Cipher (seed); for (int i = 0; i < m_key.Length; ++i) { m_key[i] = isaac.GetRand32(); } } public void Decrypt (byte[] data, int index, int length, ushort offset) { for (int i = 0; i < length; ++i) { data[index + i] ^= (byte)Binary.RotL (m_key[offset & 0xFF] ^ 0x1000193, offset >> 8); ++offset; } } } /// <summary> /// ISAAC 64-bit pseudorandom number generator. /// </summary> internal class Isaac64Cipher { int m_count; ulong[] m_entropy = new ulong[0x100]; ulong[] m_state = new ulong[0x100]; public Isaac64Cipher (uint seed) { unsafe { fixed (ulong* e = m_entropy) { uint* e32 = (uint*)e; *e32 = seed ^ 0x9E370001u; for (uint i = 1; i < 0x200u; ++i) { e32[i] = i - 0x61C88647u * (e32[i-1] ^ (e32[i-1] >> 30)); } } } Init(); } ulong aa, bb, cc; ulong a, b, c, d, e, f, g, h; void Mix () { a -= e; f ^= h >> 9; h += a; b -= f; g ^= a << 9; a += b; c -= g; h ^= b >> 23; b += c; d -= h; a ^= c << 15; c += d; e -= a; b ^= d >> 14; d += e; f -= b; c ^= e << 20; e += f; g -= c; d ^= f >> 17; f += g; h -= d; e ^= g << 14; g += h; } void Init () { aa = bb = cc = 0; a = b = c = d = e = f = g = h = 0x9E3779B97F4A7C13ul; int i; for (i = 0; i < 4; ++i) { Mix(); } for (i = 0; i < 0x100; i += 8) { a += m_entropy[i ]; b += m_entropy[i+1]; c += m_entropy[i+2]; d += m_entropy[i+3]; e += m_entropy[i+4]; f += m_entropy[i+5]; g += m_entropy[i+6]; h += m_entropy[i+7]; Mix(); m_state[i ] = a; m_state[i+1] = b; m_state[i+2] = c; m_state[i+3] = d; m_state[i+4] = e; m_state[i+5] = f; m_state[i+6] = g; m_state[i+7] = h; } for (i = 0; i < 0x100; i += 8) { a += m_state[i ]; b += m_state[i+1]; c += m_state[i+2]; d += m_state[i+3]; e += m_state[i+4]; f += m_state[i+5]; g += m_state[i+6]; h += m_state[i+7]; Mix(); m_state[i ] = a; m_state[i+1] = b; m_state[i+2] = c; m_state[i+3] = d; m_state[i+4] = e; m_state[i+5] = f; m_state[i+6] = g; m_state[i+7] = h; } Shuffle(); m_count = 0x100; } void RngStep (ulong mix, ref int m, ref int m2, ref int r) { ulong x = m_state[m]; aa = mix + m_state[m2++]; ulong y = m_state[(x >> 3) & 0xFF] + aa + bb; m_state[m++] = y; m_entropy[r++] = bb = m_state[(y >> 11) & 0xFF] + x; } void Shuffle () { int m1 = 0; int r = 0; bb += ++cc; int mend, m2; mend = m2 = 0x80; while (m1 < mend) { RngStep(~(aa ^ (aa << 21)), ref m1, ref m2, ref r); RngStep( aa ^ (aa >> 5) , ref m1, ref m2, ref r); RngStep( aa ^ (aa << 12) , ref m1, ref m2, ref r); RngStep( aa ^ (aa >> 33) , ref m1, ref m2, ref r); } m2 = 0; while (m2 < mend) { RngStep(~(aa ^ (aa << 21)), ref m1, ref m2, ref r); RngStep( aa ^ (aa >> 5) , ref m1, ref m2, ref r); RngStep( aa ^ (aa << 12) , ref m1, ref m2, ref r); RngStep( aa ^ (aa >> 33) , ref m1, ref m2, ref r); } } public uint GetRand32 () { if (0 == m_count--) { Shuffle(); m_count = 0xFF; } ulong num = m_entropy[m_count]; return (uint)num ^ (uint)(num >> 32); } } }
/* * Copyright (C) 2005-2016 Christoph Rupp (chris@crupp.de). * All Rights Reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * See the file COPYING for License information. */ using System; using System.Runtime.InteropServices; // See http://stackoverflow.com/questions/772531 using SizeT = System.UIntPtr; namespace Upscaledb { internal static class NativeMethods { /// <summary> /// Define this once, so it can be easily updated /// </summary> private const string UpscaleNativeDll = "upscaledb-2.2.1.dll"; static NativeMethods() { // Since managed assembly targets AnyCPU, at runtime we need to check which version of the native dll to load. // This assumes that the native dlls are in subdirectories called x64 and x86, as is the case when using the NuGet package. // See http://stackoverflow.com/questions/10852634/ var subdir = (IntPtr.Size == 8) ? @"runtimes\win10-x64\native" : @"runtimes\win10-x86\native"; if (System.IO.Directory.Exists(subdir)) { try { LoadLibrary(subdir + "/" + UpscaleNativeDll); } catch (Exception e) { throw new Exception($"Cannot load library from {subdir}", e); } } else { // Legacy behaviour: assume native dll is in same directory as managed assembly } } [DllImport("kernel32.dll")] private static extern IntPtr LoadLibrary(string dllToLoad); [StructLayout(LayoutKind.Sequential)] unsafe struct RecordStruct { public Int32 size; public byte *data; public Int32 flags; } [StructLayout(LayoutKind.Sequential)] unsafe struct KeyStruct { public Int16 size; public byte *data; public Int32 flags; public Int32 _flags; } [StructLayout(LayoutKind.Sequential)] unsafe struct OperationLow { public Int32 type; public KeyStruct key; public RecordStruct record; public Int32 flags; public Int32 result; } [DllImport(UpscaleNativeDll, EntryPoint = "ups_db_bulk_operations", CallingConvention = CallingConvention.Cdecl)] static private unsafe extern int BulkOperationsLow(IntPtr handle, IntPtr txnhandle, OperationLow* operations, SizeT operations_length, int flags); static public unsafe int BulkOperations(IntPtr handle, IntPtr txnhandle, Operation[] operations, int flags) { var handles = new System.Collections.Generic.List<GCHandle>(2*operations.Length); try { // convert the operations, pinning the key/record arrays in the process... var operationsLow = new OperationLow[operations.Length]; fixed (OperationLow* ops = operationsLow) { for (int i = 0; i < operations.Length; ++i) { operationsLow[i].type = (int)operations[i].OperationType; operationsLow[i].flags = operations[i].Flags; var key = operations[i].Key; if (key != null) { var bk = GCHandle.Alloc(key, GCHandleType.Pinned); handles.Add(bk); operationsLow[i].key.data = (byte*)bk.AddrOfPinnedObject().ToPointer(); operationsLow[i].key.size = (short)key.GetLength(0); } if (operations[i].OperationType == OperationType.Insert) // Not required for Erase or Find { var record = operations[i].Record; if (record != null) { var br = GCHandle.Alloc(record, GCHandleType.Pinned); handles.Add(br); operationsLow[i].record.data = (byte*)br.AddrOfPinnedObject().ToPointer(); operationsLow[i].record.size = record.GetLength(0); } } } // do the bulk operations... int st = BulkOperationsLow(handle, txnhandle, ops, new SizeT((uint)operations.Length), flags); if (st == 0) { // populate the Result field for each operation, and possibly also copy key/record data over for Find operations for (int i = 0; i < operations.Length; ++i) { // Note: we do not throw here if sti != 0, this is left to the caller to check. int sti = operationsLow[i].result; operations[i].Result = sti; if (operations[i].OperationType == OperationType.Find && sti == 0) { // copy record data var recData = new IntPtr(operationsLow[i].record.data); operations[i].Record = new byte[operationsLow[i].record.size]; Marshal.Copy(recData, operations[i].Record, 0, operationsLow[i].record.size); // also copy the key data if approx. matching was requested if ((operations[i].Flags & (UpsConst.UPS_FIND_LT_MATCH | UpsConst.UPS_FIND_GT_MATCH)) != 0) { var keyData = new IntPtr(operationsLow[i].key.data); operations[i].Key = new byte[operationsLow[i].key.size]; Marshal.Copy(keyData, operations[i].Key, 0, operationsLow[i].key.size); } } } } return st; } } finally { foreach(var h in handles) h.Free(); } } [DllImport(UpscaleNativeDll, EntryPoint = "ups_set_error_handler", CallingConvention = CallingConvention.Cdecl)] static public extern void SetErrorHandler(ErrorHandler eh); [DllImport(UpscaleNativeDll, EntryPoint = "ups_strerror", CallingConvention=CallingConvention.Cdecl)] static public extern IntPtr StringErrorImpl(int error); static public string StringError(int error) { IntPtr s = StringErrorImpl(error); return System.Runtime.InteropServices.Marshal.PtrToStringAnsi(s); } [DllImport(UpscaleNativeDll, EntryPoint = "ups_get_version", CallingConvention = CallingConvention.Cdecl)] static public extern void GetVersion(out int major, out int minor, out int revision); [DllImport(UpscaleNativeDll, EntryPoint = "ups_env_create", CallingConvention = CallingConvention.Cdecl)] static public extern int EnvCreate(out IntPtr handle, String fileName, int flags, int mode, Parameter[] parameters); [DllImport(UpscaleNativeDll, EntryPoint = "ups_env_open", CallingConvention = CallingConvention.Cdecl)] static public extern int EnvOpen(out IntPtr handle, String fileName, int flags, Parameter[] parameters); [DllImport(UpscaleNativeDll, EntryPoint = "ups_env_create_db", CallingConvention = CallingConvention.Cdecl)] static public extern int EnvCreateDatabase(IntPtr handle, out IntPtr dbhandle, short name, int flags, Parameter[] parameters); [DllImport(UpscaleNativeDll, EntryPoint = "ups_env_open_db", CallingConvention = CallingConvention.Cdecl)] static public extern int EnvOpenDatabase(IntPtr handle, out IntPtr dbhandle, short name, int flags, Parameter[] parameters); [DllImport(UpscaleNativeDll, EntryPoint = "ups_env_rename_db", CallingConvention = CallingConvention.Cdecl)] static public extern int EnvRenameDatabase(IntPtr handle, short oldName, short newName); [DllImport(UpscaleNativeDll, EntryPoint = "ups_env_erase_db", CallingConvention = CallingConvention.Cdecl)] static public extern int EnvEraseDatabase(IntPtr handle, short name, int flags); [DllImport(UpscaleNativeDll, EntryPoint = "ups_env_flush", CallingConvention = CallingConvention.Cdecl)] static public extern int EnvFlush(IntPtr handle, int flags); [DllImport(UpscaleNativeDll, EntryPoint = "ups_env_get_database_names", CallingConvention = CallingConvention.Cdecl)] static public extern int EnvGetDatabaseNamesLow(IntPtr handle, IntPtr dbnames, ref int count); static public int EnvGetDatabaseNames(IntPtr handle, out short[] names) { // alloc space for 2000 database names int count = 2000; IntPtr array = Marshal.AllocHGlobal(2 * count); int st = EnvGetDatabaseNamesLow(handle, array, ref count); if (st != 0) { Marshal.FreeHGlobal(array); names = null; return st; } names = new short[count]; Marshal.Copy(array, names, 0, count); Marshal.FreeHGlobal(array); return 0; } [DllImport(UpscaleNativeDll, EntryPoint = "ups_env_close", CallingConvention = CallingConvention.Cdecl)] static public extern int EnvClose(IntPtr handle, int flags); [DllImport(UpscaleNativeDll, EntryPoint = "ups_txn_begin", CallingConvention = CallingConvention.Cdecl)] static public extern int TxnBegin(out IntPtr txnhandle, IntPtr envhandle, String filename, IntPtr reserved, int flags); [DllImport(UpscaleNativeDll, EntryPoint = "ups_txn_commit", CallingConvention = CallingConvention.Cdecl)] static public extern int TxnCommit(IntPtr handle, int flags); [DllImport(UpscaleNativeDll, EntryPoint = "ups_txn_abort", CallingConvention = CallingConvention.Cdecl)] static public extern int TxnAbort(IntPtr handle, int flags); [DllImport(UpscaleNativeDll, EntryPoint = "ups_db_get_error", CallingConvention = CallingConvention.Cdecl)] static public extern int GetLastError(IntPtr handle); // TODO this is new, but lots of effort b/c of complex // marshalling. if you need this function pls drop me a mail. /* [DllImport(UpscaleNativeDll, EntryPoint = "ups_db_get_parameters", CallingConvention = CallingConvention.Cdecl)] static public extern int GetParameters(IntPtr handle, Parameter[] parameters); */ [DllImport(UpscaleNativeDll, EntryPoint = "ups_db_get_env", CallingConvention = CallingConvention.Cdecl)] static public extern IntPtr GetEnv(IntPtr handle); [DllImport(UpscaleNativeDll, EntryPoint = "ups_register_compare", CallingConvention = CallingConvention.Cdecl)] static public extern int RegisterCompare(String name, CompareFunc foo); [DllImport(UpscaleNativeDll, EntryPoint = "ups_env_select_range", CallingConvention = CallingConvention.Cdecl)] static public extern int EnvSelectRange(IntPtr handle, String query, IntPtr begin, IntPtr end, out IntPtr result); [DllImport(UpscaleNativeDll, EntryPoint = "ups_db_set_compare_func", CallingConvention = CallingConvention.Cdecl)] static public extern int SetCompareFunc(IntPtr handle, CompareFunc foo); [DllImport(UpscaleNativeDll, EntryPoint = "ups_db_find", CallingConvention = CallingConvention.Cdecl)] static private extern int FindLow(IntPtr handle, IntPtr txnhandle, ref KeyStruct key, ref RecordStruct record, int flags); static public unsafe int Find(IntPtr handle, IntPtr txnhandle, ref byte[] keydata, ref byte[] recdata, int flags) { KeyStruct key = new KeyStruct(); RecordStruct record = new RecordStruct(); key.size = (short)keydata.Length; fixed (byte *bk = keydata) { key.data = bk; int st = FindLow(handle, txnhandle, ref key, ref record, flags); if (st != 0) return st; // I didn't find a way to avoid the copying... IntPtr recData = new IntPtr(record.data); byte[] newRecData = new byte[record.size]; Marshal.Copy(recData, newRecData, 0, record.size); recdata = newRecData; // also copy the key data if approx. matching was requested if ((flags & (UpsConst.UPS_FIND_LT_MATCH | UpsConst.UPS_FIND_GT_MATCH)) != 0) { IntPtr keyData = new IntPtr(key.data); byte[] newKeyData = new byte[key.size]; Marshal.Copy(keyData, newKeyData, 0, key.size); keydata = newKeyData; } return 0; } } [DllImport(UpscaleNativeDll, EntryPoint = "ups_db_insert", CallingConvention = CallingConvention.Cdecl)] static private extern int InsertLow(IntPtr handle, IntPtr txnhandle, ref KeyStruct key, ref RecordStruct record, int flags); static public unsafe int Insert(IntPtr handle, IntPtr txnhandle, byte[] keyData, byte[] recordData, int flags) { KeyStruct key = new KeyStruct(); RecordStruct record = new RecordStruct(); fixed (byte* br = recordData, bk = keyData) { record.data = br; record.size = recordData.GetLength(0); key.data = bk; key.size = (short)keyData.GetLength(0); return InsertLow(handle, txnhandle, ref key, ref record, flags); } } static public unsafe int InsertRecNo(IntPtr handle, IntPtr txnhandle, ref byte[] keydata, byte[] recordData, int flags) { KeyStruct key = new KeyStruct(); RecordStruct record = new RecordStruct(); fixed (byte* br = recordData) { record.data = br; record.size = recordData.GetLength(0); key.data = null; key.size = 0; int st = InsertLow(handle, txnhandle, ref key, ref record, flags); if (st != 0) return st; IntPtr keyData = new IntPtr(key.data); byte[] newKeyData = new byte[key.size]; Marshal.Copy(keyData, newKeyData, 0, key.size); keydata = newKeyData; return 0; } } [DllImport(UpscaleNativeDll, EntryPoint = "ups_db_erase", CallingConvention = CallingConvention.Cdecl)] static private extern int EraseLow(IntPtr handle, IntPtr txnhandle, ref KeyStruct key, int flags); static public unsafe int Erase(IntPtr handle, IntPtr txnhandle, byte[] data, int flags) { KeyStruct key = new KeyStruct(); fixed (byte* b = data) { key.data = b; key.size = (short)data.GetLength(0); return EraseLow(handle, txnhandle, ref key, flags); } } [DllImport(UpscaleNativeDll, EntryPoint = "ups_db_count", CallingConvention = CallingConvention.Cdecl)] static public extern int GetCount(IntPtr handle, IntPtr txnhandle, int flags, out Int64 count); [DllImport(UpscaleNativeDll, EntryPoint = "ups_db_close", CallingConvention = CallingConvention.Cdecl)] static public extern int Close(IntPtr handle, int flags); [DllImport(UpscaleNativeDll, EntryPoint = "ups_cursor_create", CallingConvention = CallingConvention.Cdecl)] static public extern int CursorCreate(out IntPtr chandle, IntPtr dbhandle, IntPtr txnhandle, int flags); [DllImport(UpscaleNativeDll, EntryPoint = "ups_cursor_clone", CallingConvention = CallingConvention.Cdecl)] static public extern int CursorClone(IntPtr handle, out IntPtr clone); [DllImport(UpscaleNativeDll, EntryPoint = "ups_cursor_move", CallingConvention = CallingConvention.Cdecl)] static private extern int CursorMoveLow(IntPtr handle, IntPtr key, IntPtr record, int flags); [DllImport(UpscaleNativeDll, EntryPoint = "ups_cursor_move", CallingConvention = CallingConvention.Cdecl)] static private extern int CursorMoveLow(IntPtr handle, ref KeyStruct key, IntPtr record, int flags); [DllImport(UpscaleNativeDll, EntryPoint = "ups_cursor_move", CallingConvention = CallingConvention.Cdecl)] static private extern int CursorMoveLow(IntPtr handle, IntPtr key, ref RecordStruct record, int flags); [DllImport(UpscaleNativeDll, EntryPoint = "ups_cursor_move", CallingConvention = CallingConvention.Cdecl)] static private extern int CursorMoveLow(IntPtr handle, ref KeyStruct key, ref RecordStruct record, int flags); static public int CursorMove(IntPtr handle, int flags) { return CursorMoveLow(handle, IntPtr.Zero, IntPtr.Zero, flags); } static unsafe public byte[] CursorGetRecord(IntPtr handle, int flags) { RecordStruct record = new RecordStruct(); int st = CursorMoveLow(handle, IntPtr.Zero, ref record, flags); if (st == 0) { // I didn't found a way to avoid the copying... IntPtr recData = new IntPtr(record.data); byte[] newArray = new byte[record.size]; Marshal.Copy(recData, newArray, 0, record.size); return newArray; } throw new DatabaseException(st); } static unsafe public byte[] CursorGetKey(IntPtr handle, int flags) { KeyStruct key = new KeyStruct(); int st = CursorMoveLow(handle, ref key, IntPtr.Zero, flags); if (st == 0) { // I didn't found a way to avoid the copying... IntPtr keyData = new IntPtr(key.data); byte[] newArray = new byte[key.size]; Marshal.Copy(keyData, newArray, 0, key.size); return newArray; } throw new DatabaseException(st); } static unsafe public int CursorGet(IntPtr handle, int flags, ref byte[] keyArray, ref byte[] recordArray) { KeyStruct key = new KeyStruct(); RecordStruct record = new RecordStruct(); int st = CursorMoveLow(handle, ref key, ref record, flags); if (st == 0) { IntPtr keyData = new IntPtr(key.data); keyArray = new byte[key.size]; Marshal.Copy(keyData, keyArray, 0, key.size); IntPtr recData = new IntPtr(record.data); recordArray = new byte[record.size]; Marshal.Copy(recData, recordArray, 0, record.size); } return st; } [DllImport(UpscaleNativeDll, EntryPoint = "ups_cursor_overwrite", CallingConvention = CallingConvention.Cdecl)] static private extern int CursorOverwriteLow(IntPtr handle, ref RecordStruct record, int flags); static unsafe public int CursorOverwrite(IntPtr handle, byte[] data, int flags) { RecordStruct record = new RecordStruct(); fixed (byte* b = data) { record.data = b; record.size = data.GetLength(0); return CursorOverwriteLow(handle, ref record, flags); } } [DllImport(UpscaleNativeDll, EntryPoint = "ups_cursor_find", CallingConvention = CallingConvention.Cdecl)] static private extern int CursorFindLow(IntPtr handle, ref KeyStruct key, ref RecordStruct record, int flags); static unsafe public int CursorFind(IntPtr handle, ref byte[] keydata, ref byte[] recdata, int flags) { KeyStruct key = new KeyStruct(); RecordStruct record = new RecordStruct(); fixed (byte* bk = keydata) { key.data = bk; key.size = (short)keydata.Length; int st = CursorFindLow(handle, ref key, ref record, flags); if (st != 0) return st; // I didn't found a way to avoid the copying... IntPtr recData = new IntPtr(record.data); byte[] newRecData = new byte[record.size]; Marshal.Copy(recData, newRecData, 0, record.size); recdata = newRecData; // also copy the key data if approx. matching was requested if ((flags & (UpsConst.UPS_FIND_LT_MATCH | UpsConst.UPS_FIND_GT_MATCH)) != 0) { IntPtr keyData = new IntPtr(key.data); byte[] newKeyData = new byte[key.size]; Marshal.Copy(keyData, newKeyData, 0, key.size); keydata = newKeyData; } return 0; } } [DllImport(UpscaleNativeDll, EntryPoint = "ups_cursor_insert", CallingConvention = CallingConvention.Cdecl)] static private extern int CursorInsertLow(IntPtr handle, ref KeyStruct key, ref RecordStruct record, int flags); static public unsafe int CursorInsert(IntPtr handle, byte[] keyData, byte[] recordData, int flags) { RecordStruct record = new RecordStruct(); KeyStruct key = new KeyStruct(); fixed (byte *br = recordData, bk = keyData) { record.data = br; record.size = recordData.GetLength(0); key.data = bk; key.size = (short)keyData.GetLength(0); return CursorInsertLow(handle, ref key, ref record, flags); } } [DllImport(UpscaleNativeDll, EntryPoint = "ups_cursor_erase", CallingConvention = CallingConvention.Cdecl)] static public extern int CursorErase(IntPtr handle, int flags); [DllImport(UpscaleNativeDll, EntryPoint = "ups_cursor_get_duplicate_count", CallingConvention = CallingConvention.Cdecl)] static public extern int CursorGetDuplicateCount(IntPtr handle, out int count, int flags); [DllImport(UpscaleNativeDll, EntryPoint = "ups_cursor_close", CallingConvention = CallingConvention.Cdecl)] static public extern int CursorClose(IntPtr handle); [DllImport(UpscaleNativeDll, EntryPoint = "uqi_result_get_row_count", CallingConvention = CallingConvention.Cdecl)] static public extern int ResultGetRowCount(IntPtr handle); [DllImport(UpscaleNativeDll, EntryPoint = "uqi_result_get_key_type", CallingConvention = CallingConvention.Cdecl)] static public extern int ResultGetKeyType(IntPtr handle); [DllImport(UpscaleNativeDll, EntryPoint = "uqi_result_get_record_type", CallingConvention = CallingConvention.Cdecl)] static public extern int ResultGetRecordType(IntPtr handle); [DllImport(UpscaleNativeDll, EntryPoint = "uqi_result_get_key", CallingConvention = CallingConvention.Cdecl)] static private extern void ResultGetKeyLow(IntPtr handle, int row, ref KeyStruct key); static unsafe public byte[] ResultGetKey(IntPtr handle, int row) { KeyStruct key = new KeyStruct(); ResultGetKeyLow(handle, row, ref key); IntPtr pdata = new IntPtr(key.data); byte[] data = new byte[key.size]; Marshal.Copy(pdata, data, 0, key.size); return data; } [DllImport(UpscaleNativeDll, EntryPoint = "uqi_result_get_record", CallingConvention = CallingConvention.Cdecl)] static private extern void ResultGetRecordLow(IntPtr handle, int row, ref RecordStruct record); static unsafe public byte[] ResultGetRecord(IntPtr handle, int row) { RecordStruct record = new RecordStruct(); ResultGetRecordLow(handle, row, ref record); IntPtr pdata = new IntPtr(record.data); byte[] data = new byte[record.size]; Marshal.Copy(pdata, data, 0, record.size); return data; } [DllImport(UpscaleNativeDll, EntryPoint = "uqi_result_close", CallingConvention = CallingConvention.Cdecl)] static public extern void ResultClose(IntPtr handle); } }
using System; using System.Diagnostics; using IBits = YAF.Lucene.Net.Util.IBits; namespace YAF.Lucene.Net.Codecs.Lucene3x { /* * 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 FieldInfo = YAF.Lucene.Net.Index.FieldInfo; using FieldInfos = YAF.Lucene.Net.Index.FieldInfos; using IndexInput = YAF.Lucene.Net.Store.IndexInput; using IndexOptions = YAF.Lucene.Net.Index.IndexOptions; using Term = YAF.Lucene.Net.Index.Term; /// <summary> /// @lucene.experimental /// </summary> [Obsolete("(4.0)")] internal class SegmentTermDocs { //protected SegmentReader parent; private readonly FieldInfos fieldInfos; private readonly TermInfosReader tis; protected IBits m_liveDocs; protected IndexInput m_freqStream; protected int m_count; protected internal int m_df; internal int doc = 0; internal int freq; private int skipInterval; private int maxSkipLevels; private Lucene3xSkipListReader skipListReader; private long freqBasePointer; private long proxBasePointer; private long skipPointer; private bool haveSkipped; protected bool m_currentFieldStoresPayloads; protected IndexOptions m_indexOptions; public SegmentTermDocs(IndexInput freqStream, TermInfosReader tis, FieldInfos fieldInfos) { this.m_freqStream = (IndexInput)freqStream.Clone(); this.tis = tis; this.fieldInfos = fieldInfos; skipInterval = tis.SkipInterval; maxSkipLevels = tis.MaxSkipLevels; } public virtual void Seek(Term term) { TermInfo ti = tis.Get(term); Seek(ti, term); } public virtual IBits LiveDocs { get { return this.m_liveDocs; // LUCENENET specific - per MSDN, a property must always have a getter } set { this.m_liveDocs = value; } } public virtual void Seek(SegmentTermEnum segmentTermEnum) { TermInfo ti; Term term; // use comparison of fieldinfos to verify that termEnum belongs to the same segment as this SegmentTermDocs if (segmentTermEnum.fieldInfos == fieldInfos) // optimized case { term = segmentTermEnum.Term(); ti = segmentTermEnum.TermInfo(); } // punt case else { term = segmentTermEnum.Term(); ti = tis.Get(term); } Seek(ti, term); } internal virtual void Seek(TermInfo ti, Term term) { m_count = 0; FieldInfo fi = fieldInfos.FieldInfo(term.Field); this.m_indexOptions = (fi != null) ? fi.IndexOptions : IndexOptions.DOCS_AND_FREQS_AND_POSITIONS; m_currentFieldStoresPayloads = (fi != null) && fi.HasPayloads; if (ti == null) { m_df = 0; } else { m_df = ti.DocFreq; doc = 0; freqBasePointer = ti.FreqPointer; proxBasePointer = ti.ProxPointer; skipPointer = freqBasePointer + ti.SkipOffset; m_freqStream.Seek(freqBasePointer); haveSkipped = false; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { m_freqStream.Dispose(); if (skipListReader != null) { skipListReader.Dispose(); } } } public int Doc { get { return doc; } } public int Freq { get { return freq; } } protected internal virtual void SkippingDoc() { } public virtual bool Next() { while (true) { if (m_count == m_df) { return false; } int docCode = m_freqStream.ReadVInt32(); if (m_indexOptions == IndexOptions.DOCS_ONLY) { doc += docCode; } else { doc += (int)((uint)docCode >> 1); // shift off low bit if ((docCode & 1) != 0) // if low bit is set { freq = 1; // freq is one } else { freq = m_freqStream.ReadVInt32(); // else read freq Debug.Assert(freq != 1); } } m_count++; if (m_liveDocs == null || m_liveDocs.Get(doc)) { break; } SkippingDoc(); } return true; } /// <summary> /// Optimized implementation. </summary> public virtual int Read(int[] docs, int[] freqs) { int length = docs.Length; if (m_indexOptions == IndexOptions.DOCS_ONLY) { return ReadNoTf(docs, freqs, length); } else { int i = 0; while (i < length && m_count < m_df) { // manually inlined call to next() for speed int docCode = m_freqStream.ReadVInt32(); doc += (int)((uint)docCode >> 1); // shift off low bit if ((docCode & 1) != 0) // if low bit is set { freq = 1; // freq is one } else { freq = m_freqStream.ReadVInt32(); // else read freq } m_count++; if (m_liveDocs == null || m_liveDocs.Get(doc)) { docs[i] = doc; freqs[i] = freq; ++i; } } return i; } } private int ReadNoTf(int[] docs, int[] freqs, int length) { int i = 0; while (i < length && m_count < m_df) { // manually inlined call to next() for speed doc += m_freqStream.ReadVInt32(); m_count++; if (m_liveDocs == null || m_liveDocs.Get(doc)) { docs[i] = doc; // Hardware freq to 1 when term freqs were not // stored in the index freqs[i] = 1; ++i; } } return i; } /// <summary> /// Overridden by <see cref="SegmentTermPositions"/> to skip in prox stream. </summary> protected internal virtual void SkipProx(long proxPointer, int payloadLength) { } /// <summary> /// Optimized implementation. </summary> public virtual bool SkipTo(int target) { // don't skip if the target is close (within skipInterval docs away) if ((target - skipInterval) >= doc && m_df >= skipInterval) // optimized case { if (skipListReader == null) { skipListReader = new Lucene3xSkipListReader((IndexInput)m_freqStream.Clone(), maxSkipLevels, skipInterval); // lazily clone } if (!haveSkipped) // lazily initialize skip stream { skipListReader.Init(skipPointer, freqBasePointer, proxBasePointer, m_df, m_currentFieldStoresPayloads); haveSkipped = true; } int newCount = skipListReader.SkipTo(target); if (newCount > m_count) { m_freqStream.Seek(skipListReader.FreqPointer); SkipProx(skipListReader.ProxPointer, skipListReader.PayloadLength); doc = skipListReader.Doc; m_count = newCount; } } // done skipping, now just scan do { if (!Next()) { return false; } } while (target > doc); return true; } } }
/* text.c - Text manipulation functions * Copyright (c) 1995-1997 Stefan Jokisch * * This file is part of Frotz. * * Frotz is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Frotz is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ using zword = System.UInt16; using zbyte = System.Byte; using Frotz.Constants; namespace Frotz.Generic { internal static class Text { enum string_type { LOW_STRING, ABBREVIATION, HIGH_STRING, EMBEDDED_STRING, VOCABULARY }; private static zword[] decoded = null; private static zword[] encoded = null; private static int resolution; /* * According to Matteo De Luigi <matteo.de.luigi@libero.it>, * 0xab and 0xbb were in each other's proper positions. * Sat Apr 21, 2001 */ static zword[] zscii_to_latin1 = { 0x0e4, 0x0f6, 0x0fc, 0x0c4, 0x0d6, 0x0dc, 0x0df, 0x0bb, 0x0ab, 0x0eb, 0x0ef, 0x0ff, 0x0cb, 0x0cf, 0x0e1, 0x0e9, 0x0ed, 0x0f3, 0x0fa, 0x0fd, 0x0c1, 0x0c9, 0x0cd, 0x0d3, 0x0da, 0x0dd, 0x0e0, 0x0e8, 0x0ec, 0x0f2, 0x0f9, 0x0c0, 0x0c8, 0x0cc, 0x0d2, 0x0d9, 0x0e2, 0x0ea, 0x0ee, 0x0f4, 0x0fb, 0x0c2, 0x0ca, 0x0ce, 0x0d4, 0x0db, 0x0e5, 0x0c5, 0x0f8, 0x0d8, 0x0e3, 0x0f1, 0x0f5, 0x0c3, 0x0d1, 0x0d5, 0x0e6, 0x0c6, 0x0e7, 0x0c7, 0x0fe, 0x0f0, 0x0de, 0x0d0, 0x0a3, 0x153, 0x152, 0x0a1, 0x0bf }; /* * init_text * * Initialize text variables. * */ internal static void init_text() { decoded = null; encoded = null; resolution = 0; } /* * translate_from_zscii * * Map a ZSCII character into Unicode. * */ internal static zword translate_from_zscii(zbyte c) { if (c == 0xfc) return CharCodes.ZC_MENU_CLICK; if (c == 0xfd) return CharCodes.ZC_DOUBLE_CLICK; if (c == 0xfe) return CharCodes.ZC_SINGLE_CLICK; if (c >= 0x9b && main.story_id != Story.BEYOND_ZORK) { if (main.hx_unicode_table != 0) { /* game has its own Unicode table */ zbyte N; FastMem.LOW_BYTE(main.hx_unicode_table, out N); if (c - 0x9b < N) { zword addr = (zword)(main.hx_unicode_table + 1 + 2 * (c - 0x9b)); zword unicode; FastMem.LOW_WORD(addr, out unicode); if (unicode < 0x20) return '?'; return unicode; } else return '?'; } else /* game uses standard set */ if (c <= 0xdf) { return zscii_to_latin1[c - 0x9b]; } else return '?'; } return (zword)c; }/* translate_from_zscii */ /* * unicode_to_zscii * * Convert a Unicode character to ZSCII, returning 0 on failure. * */ internal static zbyte unicode_to_zscii(zword c) { int i; if (c >= CharCodes.ZC_LATIN1_MIN) { if (main.hx_unicode_table != 0) { /* game has its own Unicode table */ zbyte N; FastMem.LOW_BYTE(main.hx_unicode_table, out N); for (i = 0x9b; i < 0x9b + N; i++) { zword addr = (zword)(main.hx_unicode_table + 1 + 2 * (i - 0x9b)); zword unicode; FastMem.LOW_WORD(addr, out unicode); if (c == unicode) return (zbyte)i; } return 0; } else { /* game uses standard set */ for (i = 0x9b; i <= 0xdf; i++) if (c == zscii_to_latin1[i - 0x9b]) return (zbyte)i; return 0; } } return (zbyte)c; }/* unicode_to_zscii */ /* * translate_to_zscii * * Map a Unicode character onto the ZSCII alphabet. * */ internal static zbyte translate_to_zscii(zword c) { if (c == CharCodes.ZC_SINGLE_CLICK) return 0xfe; if (c == CharCodes.ZC_DOUBLE_CLICK) return 0xfd; if (c == CharCodes.ZC_MENU_CLICK) return 0xfc; if (c == 0) return 0; c = unicode_to_zscii(c); if (c == 0) c = '?'; return (zbyte)c; }/* translate_to_zscii */ /* * alphabet * * Return a character from one of the three character sets. * */ static zword alphabet(int set, int index) { if (main.h_version > ZMachine.V1 && set == 2 && index == 1) return 0x0D; /* always newline */ if (main.h_alphabet != 0) { /* game uses its own alphabet */ zbyte c; zword addr = (zword)(main.h_alphabet + 26 * set + index); FastMem.LOW_BYTE(addr, out c); return translate_from_zscii(c); } else /* game uses default alphabet */ if (set == 0) return (zword)('a' + index); else if (set == 1) return (zword)('A' + index); else if (main.h_version == ZMachine.V1) return " 0123456789.,!?_#'\"/\\<-:()"[index]; else return " ^0123456789.,!?_#'\"/\\-:()"[index]; }/* alphabet */ /* * find_resolution * * Find the number of bytes used for dictionary resolution. * */ internal static void find_resolution() { zword dct = main.h_dictionary; zbyte sep_count; zbyte entry_len; FastMem.LOW_BYTE(dct, out sep_count); dct += (zword)(1 + sep_count); /* skip word separators */ FastMem.LOW_BYTE(dct, out entry_len); resolution = (main.h_version <= ZMachine.V3) ? 2 : 3; if (2 * resolution > entry_len) { Err.runtime_error(ErrorCodes.ERR_DICT_LEN); } decoded = new zword[3 * resolution + 1]; encoded = new zword[resolution]; }/* find_resolution */ /* * load_string * * Copy a ZSCII string from the memory to the global "decoded" string. * */ internal static void load_string(zword addr, zword length) { int i = 0; if (resolution == 0) find_resolution(); while (i < 3 * resolution) if (i < length) { zbyte c; FastMem.LOW_BYTE(addr, out c); addr++; decoded[i++] = Text.translate_from_zscii(c); } else decoded[i++] = 0; }/* load_string */ /* * encode_text * * Encode the Unicode text in the global "decoded" string then write * the result to the global "encoded" array. (This is used to look up * words in the dictionary.) Up to V3 the vocabulary resolution is * two, and from V4 it is three Z-characters. * Because each word contains three Z-characters, that makes six or * nine Z-characters respectively. Longer words are chopped to the * proper size, shorter words are are padded out with 5's. For word * completion we pad with 0s and 31s, the minimum and maximum * Z-characters. * */ static zword[] again = { 'a', 'g', 'a', 'i', 'n', 0, 0, 0, 0 }; static zword[] examine = { 'e', 'x', 'a', 'm', 'i', 'n', 'e', 0, 0 }; static zword[] wait = { 'w', 'a', 'i', 't', 0, 0, 0, 0, 0 }; internal static void encode_text(int padding) { zbyte[] zchars; // zbyte *zchars; // const zword *ptr; zword c; int i = 0; int ptr = 0; if (resolution == 0) find_resolution(); zchars = new zbyte[3 * (resolution + 1)]; // ptr = decoded; /* Expand abbreviations that some old Infocom games lack */ if (main.option_expand_abbreviations && main.h_version <= ZMachine.V8) { if (padding == 0x05 && decoded[1] == 0) switch (decoded[0]) { case 'g': decoded = again; break; case 'x': decoded = examine; break; case 'z': decoded = wait; break; } } /* Translate string to a sequence of Z-characters */ while (i < 3 * resolution) if ( (ptr < decoded.Length) && (c = decoded[ptr++]) != 0) { int index, set; zbyte c2; if (c == 32) { zchars[i++] = 0; continue; } /* Search character in the alphabet */ for (set = 0; set < 3; set++) for (index = 0; index < 26; index++) if (c == alphabet(set, index)) goto letter_found; /* Character not found, store its ZSCII value */ c2 = translate_to_zscii(c); zchars[i++] = 5; zchars[i++] = 6; zchars[i++] = (zbyte)(c2 >> 5); zchars[i++] = (zbyte)(c2 & 0x1f); continue; letter_found: /* Character found, store its index */ if (set != 0) zchars[i++] = (zbyte)(((main.h_version <= ZMachine.V2) ? 1 : 3) + set); zchars[i++] = (zbyte)(index + 6); } else zchars[i++] = (zbyte)padding; /* Three Z-characters make a 16bit word */ for (i = 0; i < resolution; i++) encoded[i] = (zword)( (zchars[3 * i + 0] << 10) | (zchars[3 * i + 1] << 5) | (zchars[3 * i + 2])); encoded[resolution - 1] |= 0x8000; }/* encode_text */ /* * z_check_unicode, test if a unicode character can be printed (bit 0) and read (bit 1). * * zargs[0] = Unicode * */ internal static void z_check_unicode () { zword c = Process.zargs[0]; zword result = 0; if (c <= 0x1f) { if ((c == 0x08) || (c == 0x0d) || (c == 0x1b)) result = 2; } else if (c <= 0x7e) result = 3; else result = os_.check_unicode (Screen.get_window_font(main.cwin), c); Process.store (result); }/* z_check_unicode */ /* * z_encode_text, encode a ZSCII string for use in a dictionary. * * zargs[0] = address of text buffer * zargs[1] = length of ASCII string * zargs[2] = offset of ASCII string within the text buffer * zargs[3] = address to store encoded text in * * This is a V5+ opcode and therefore the dictionary resolution must be * three 16bit words. * */ internal static void z_encode_text () { int i; load_string ((zword) (Process.zargs[0] + Process.zargs[2]), Process.zargs[1]); encode_text (0x05); for (i = 0; i < resolution; i++) FastMem.storew ((zword) (Process.zargs[3] + 2 * i), encoded[i]); }/* z_encode_text */ /* * decode_text * * Convert encoded text to Unicode. The encoded text consists of 16bit * words. Every word holds 3 Z-characters (5 bits each) plus a spare * bit to mark the last word. The Z-characters translate to ZSCII by * looking at the current current character set. Some select another * character set, others refer to abbreviations. * * There are several different string types: * * LOW_STRING - from the lower 64KB (byte address) * ABBREVIATION - from the abbreviations table (word address) * HIGH_STRING - from the end of the memory map (packed address) * EMBEDDED_STRING - from the instruction stream (at PC) * VOCABULARY - from the dictionary (byte address) * * The last type is only used for word completion. * */ private static int ptrDt = 0; static void decode_text(string_type st, zword addr) { // zword* ptr; long byte_addr; zword c2; zword code; zbyte c, prev_c = 0; int shift_state = 0; int shift_lock = 0; int status = 0; // ptr = NULL; /* makes compilers shut up */ byte_addr = 0; if (resolution == 0) find_resolution(); /* Calculate the byte address if necessary */ if (st == string_type.ABBREVIATION) byte_addr = (long)addr << 1; else if (st == string_type.HIGH_STRING) { if (main.h_version <= ZMachine.V3) byte_addr = (long)addr << 1; else if (main.h_version <= ZMachine.V5) byte_addr = (long)addr << 2; else if (main.h_version <= ZMachine.V7) byte_addr = ((long)addr << 2) + ((long)main.h_strings_offset << 3); else /* (h_version <= V8) */ byte_addr = (long)addr << 3; if (byte_addr >= main.story_size) Err.runtime_error(ErrorCodes.ERR_ILL_PRINT_ADDR); } /* Loop until a 16bit word has the highest bit set */ if (st == string_type.VOCABULARY) ptrDt = 0; do { int i; /* Fetch the next 16bit word */ if (st == string_type.LOW_STRING || st == string_type.VOCABULARY) { FastMem.LOW_WORD(addr, out code); addr += 2; } else if (st == string_type.HIGH_STRING || st == string_type.ABBREVIATION) { FastMem.HIGH_WORD(byte_addr, out code); byte_addr += 2; } else FastMem.CODE_WORD(out code); /* Read its three Z-characters */ for (i = 10; i >= 0; i -= 5) { zword abbr_addr; zword ptr_addr; zword zc; c = (zbyte)((code >> i) & 0x1f); switch (status) { case 0: /* normal operation */ if (shift_state == 2 && c == 6) status = 2; else if (main.h_version == ZMachine.V1 && c == 1) Buffer.new_line(); else if (main.h_version >= ZMachine.V2 && shift_state == 2 && c == 7) Buffer.new_line(); else if (c >= 6) outchar(st, alphabet(shift_state, c - 6)); else if (c == 0) outchar(st, ' '); else if (main.h_version >= ZMachine.V2 && c == 1) status = 1; else if (main.h_version >= ZMachine.V3 && c <= 3) status = 1; else { shift_state = (shift_lock + (c & 1) + 1) % 3; if (main.h_version <= ZMachine.V2 && c >= 4) shift_lock = shift_state; break; } shift_state = shift_lock; break; case 1: /* abbreviation */ ptr_addr = (zword)(main.h_abbreviations + 64 * (prev_c - 1) + 2 * c); FastMem.LOW_WORD(ptr_addr, out abbr_addr); decode_text(string_type.ABBREVIATION, abbr_addr); status = 0; break; case 2: /* ZSCII character - first part */ status = 3; break; case 3: /* ZSCII character - second part */ zc = (zword)((prev_c << 5) | c); c2 = translate_from_zscii((zbyte)zc); // TODO This doesn't seem right outchar(st, c2); status = 0; break; } prev_c = c; } } while (!((code & 0x8000) > 0)); if (st == string_type.VOCABULARY) ptrDt = 0; }/* decode_text */ //#undef outchar /* * z_new_line, print a new line. * * no zargs used * */ internal static void z_new_line() { Buffer.new_line(); }/* z_new_line */ /* * z_print, print a string embedded in the instruction stream. * * no zargs used * */ internal static void z_print() { decode_text(string_type.EMBEDDED_STRING, 0); }/* z_print */ /* * z_print_addr, print a string from the lower 64KB. * * zargs[0] = address of string to print * */ internal static void z_print_addr() { decode_text(string_type.LOW_STRING, Process.zargs[0]); }/* z_print_addr */ /* * z_print_char print a single ZSCII character. * * zargs[0] = ZSCII character to be printed * */ internal static void z_print_char() { Buffer.print_char(Text.translate_from_zscii((zbyte)Process.zargs[0])); }/* z_print_char */ /* * z_print_form, print a formatted table. * * zargs[0] = address of formatted table to be printed * */ internal static void z_print_form () { zword count; zword addr = Process.zargs[0]; bool first = true; for (;;) { FastMem.LOW_WORD (addr, out count); addr += 2; if (count == 0) break; if (!first) Buffer.new_line (); while (count-- > 0) { zbyte c; FastMem.LOW_BYTE(addr, out c); addr++; Buffer.print_char (translate_from_zscii (c)); } first = false ; } }/* z_print_form */ /* * print_num * * Print a signed 16bit number. * */ internal static void print_num(zword value) { int i; /* Print sign */ if ((short)value < 0) { Buffer.print_char('-'); value = (zword)(-(short)value); } /* Print absolute value */ for (i = 10000; i != 0; i /= 10) if (value >= i || i == 1) Buffer.print_char((zword)('0' + (value / i) % 10)); }/* print_num */ /* * z_print_num, print a signed number. * * zargs[0] = number to print * */ internal static void z_print_num() { print_num(Process.zargs[0]); }/* z_print_num */ /* * print_object * * Print an object description. * */ internal static void print_object(zword object_var) { zword addr = CObject.object_name(object_var); zword code = 0x94a5; zbyte length; FastMem.LOW_BYTE(addr, out length); addr++; if (length != 0) FastMem.LOW_WORD(addr, out code); if (code == 0x94a5) { /* encoded text 0x94a5 == empty string */ print_string("object#"); /* supply a generic name */ print_num(object_var); /* for anonymous objects */ } else decode_text(string_type.LOW_STRING, addr); }/* print_object */ /* * z_print_obj, print an object description. * * zargs[0] = number of object to be printed * */ internal static void z_print_obj() { print_object(Process.zargs[0]); }/* z_print_obj */ /* * z_print_paddr, print the string at the given packed address. * * zargs[0] = packed address of string to be printed * */ internal static void z_print_paddr() { decode_text(string_type.HIGH_STRING, Process.zargs[0]); }/* z_print_paddr */ /* * z_print_ret, print the string at PC, print newline then return true. * * no zargs used * */ internal static void z_print_ret() { decode_text(string_type.EMBEDDED_STRING, 0); Buffer.new_line(); Process.ret(1); }/* z_print_ret */ /* * print_string * * Print a string of ASCII characters. * */ internal static void print_string(string s) { foreach (char c in s) { if (c == '\n') Buffer.new_line(); else Buffer.print_char(c); } }/* print_string */ /* * z_print_unicode * * zargs[0] = Unicode * */ internal static void z_print_unicode () { if (Process.zargs[0] < 0x20) Buffer.print_char ('?'); else Buffer.print_char (Process.zargs[0]); }/* z_print_unicode */ /* * lookup_text * * Scan a dictionary searching for the given word. The first argument * can be * * 0x00 - find the first word which is >= the given one * 0x05 - find the word which exactly matches the given one * 0x1f - find the last word which is <= the given one * * The return value is 0 if the search fails. * */ internal static zword lookup_text(int padding, zword dct) { zword entry_addr; zword entry_count; zword entry; zword addr; zbyte entry_len; zbyte sep_count; int entry_number; int lower, upper; int i; bool sorted; if (resolution == 0) find_resolution(); Text.encode_text(padding); FastMem.LOW_BYTE(dct, out sep_count); /* skip word separators */ dct += (zword)(1 + sep_count); FastMem.LOW_BYTE(dct, out entry_len); /* get length of entries */ dct += 1; FastMem.LOW_WORD(dct, out entry_count); /* get number of entries */ dct += 2; if ((short)entry_count < 0) { /* bad luck, entries aren't sorted */ entry_count = (zword)(-(short)entry_count); sorted = false; } else sorted = true; /* entries are sorted */ lower = 0; upper = entry_count - 1; while (lower <= upper) { if (sorted) /* binary search */ entry_number = (lower + upper) / 2; else /* linear search */ entry_number = lower; entry_addr = (zword)(dct + entry_number * entry_len); /* Compare word to dictionary entry */ addr = entry_addr; for (i = 0; i < resolution; i++) { FastMem.LOW_WORD(addr, out entry); if (encoded[i] != entry) goto continuing; addr += 2; } return entry_addr; /* exact match found, return now */ continuing: if (sorted) /* binary search */ if (encoded[i] > entry) lower = entry_number + 1; else upper = entry_number - 1; else lower++; /* linear search */ } /* No exact match has been found */ if (padding == 0x05) return 0; entry_number = (padding == 0x00) ? lower : upper; if (entry_number == -1 || entry_number == entry_count) return 0; return (zword)(dct + entry_number * entry_len); }/* lookup_text */ /* * tokenise_text * * Translate a single word to a token and append it to the token * buffer. Every token consists of the address of the dictionary * entry, the length of the word and the offset of the word from * the start of the text buffer. Unknown words cause empty slots * if the flag is set (such that the text can be scanned several * times with different dictionaries); otherwise they are zero. * */ static void tokenise_text(zword text, zword length, zword from, zword parse, zword dct, bool flag) { zword addr; zbyte token_max, token_count; FastMem.LOW_BYTE(parse, out token_max); parse++; FastMem.LOW_BYTE(parse, out token_count); if (token_count < token_max) { /* sufficient space left for token? */ FastMem.storeb(parse++, (zbyte)(token_count + 1)); load_string((zword)(text + from), length); addr = lookup_text(0x05, dct); if (addr != 0 || !flag) { parse += (zword)(4 * token_count); // Will parse get updated properly? FastMem.storew((zword)(parse + 0), addr); FastMem.storeb((zword)(parse + 2), (zbyte)length); FastMem.storeb((zword)(parse + 3), (zbyte)from); } } }/* tokenise_text */ /* * tokenise_line * * Split an input line into words and translate the words to tokens. * */ internal static void tokenise_line(zword text, zword token, zword dct, bool flag) { zword addr1; zword addr2; zbyte length; zbyte c; length = 0; /* makes compilers shut up */ /* Use standard dictionary if the given dictionary is zero */ if (dct == 0) dct = main.h_dictionary; /* Remove all tokens before inserting new ones */ FastMem.storeb((zword)(token + 1), 0); /* Move the first pointer across the text buffer searching for the beginning of a word. If this succeeds, store the position in a second pointer. Move the first pointer searching for the end of the word. When it is found, "tokenise" the word. Continue until the end of the buffer is reached. */ addr1 = text; addr2 = 0; if (main.h_version >= ZMachine.V5) { addr1++; FastMem.LOW_BYTE(addr1, out length); } do { zword sep_addr; zbyte sep_count; zbyte separator; /* Fetch next ZSCII character */ addr1++; if (main.h_version >= ZMachine.V5 && addr1 == text + 2 + length) c = 0; else FastMem.LOW_BYTE(addr1, out c); /* Check for separator */ sep_addr = dct; FastMem.LOW_BYTE(sep_addr, out sep_count); sep_addr++; do { FastMem.LOW_BYTE(sep_addr, out separator); sep_addr++; } while (c != separator && --sep_count != 0); /* This could be the start or the end of a word */ if (sep_count == 0 && c != ' ' && c != 0) { if (addr2 == 0) addr2 = addr1; } else if (addr2 != 0) { tokenise_text( text, (zword)(addr1 - addr2), (zword)(addr2 - text), token, dct, flag); addr2 = 0; } /* Translate separator (which is a word in its own right) */ if (sep_count != 0) tokenise_text( text, (zword)(1), (zword)(addr1 - text), token, dct, flag); } while (c != 0); }/* tokenise_line */ /* * z_tokenise, make a lexical analysis of a ZSCII string. * * zargs[0] = address of string to analyze * zargs[1] = address of token buffer * zargs[2] = address of dictionary (optional) * zargs[3] = set when unknown words cause empty slots (optional) * */ internal static void z_tokenise() { /* Supply default arguments */ if (Process.zargc < 3) Process.zargs[2] = 0; if (Process.zargc < 4) Process.zargs[3] = 0; /* Call tokenise_line to do the real work */ tokenise_line(Process.zargs[0], Process.zargs[1], Process.zargs[2], Process.zargs[3] != 0); }/* z_tokenise */ /* * completion * * Scan the vocabulary to complete the last word on the input line * (similar to "tcsh" under Unix). The return value is * * 2 ==> completion is impossible * 1 ==> completion is ambiguous * 0 ==> completion is successful * * The function also returns a string in its second argument. In case * of 2, the string is empty; in case of 1, the string is the longest * extension of the last word on the input line that is common to all * possible completions (for instance, if the last word on the input * is "fo" and its only possible completions are "follow" and "folly" * then the string is "ll"); in case of 0, the string is an extension * to the last word that results in the only possible completion. * */ public static int completion (string buffer, out string result) { zword minaddr; zword maxaddr; //zword *ptr; char c; int len; int i; for (int j = 0; j < decoded.Length; j++) { decoded[j] = 0; } result = ""; var temp = new System.Text.StringBuilder(); if (resolution == 0) find_resolution(); /* Copy last word to "decoded" string */ len = 0; int pos = 0; while ((pos < buffer.Length && (c = buffer[pos++]) != 0)) { if (c != ' ') { if (len < 3 * resolution) decoded[len++] = c; } else len = 0; } decoded[len] = 0; /* Search the dictionary for first and last possible extensions */ minaddr = lookup_text (0x00, main.h_dictionary); maxaddr = lookup_text (0x1f, main.h_dictionary); if (minaddr == 0 || maxaddr == 0 || minaddr > maxaddr) return 2; /* Copy first extension to "result" string */ decode_text (string_type.VOCABULARY, minaddr); // ptr = result; for (i = len; (c = (char)decoded[i]) != 0; i++) temp.Append(c); /* Merge second extension with "result" string */ decode_text (string_type.VOCABULARY, maxaddr); int ptr = 0; for (i = len; (c = (char)decoded[i]) != 0; i++, ptr++) { if (ptr < temp.Length -1 && temp[ptr] != c) break; } temp.Length = ptr; /* Search was ambiguous or successful */ result = temp.ToString(); return (minaddr == maxaddr) ? 0 : 1; }/* completion */ /* * unicode_tolower * * Convert a Unicode character to lowercase. * Taken from Zip2000 by Kevin Bracey. * */ // TODO There were all unsigned char arrays; and they were all consts private static zword[] tolower_basic_latin = { // 0x100 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F, 0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F, 0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0x3E,0x3F, 0x40,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F, 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x5B,0x5C,0x5D,0x5E,0x5F, 0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F, 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x7F, 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xD7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xDF, 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF }; private static zword[] tolower_latin_extended_a = { // 0x80 0x01,0x01,0x03,0x03,0x05,0x05,0x07,0x07,0x09,0x09,0x0B,0x0B,0x0D,0x0D,0x0F,0x0F, 0x11,0x11,0x13,0x13,0x15,0x15,0x17,0x17,0x19,0x19,0x1B,0x1B,0x1D,0x1D,0x1F,0x1F, 0x21,0x21,0x23,0x23,0x25,0x25,0x27,0x27,0x29,0x29,0x2B,0x2B,0x2D,0x2D,0x2F,0x2F, 0x00,0x31,0x33,0x33,0x35,0x35,0x37,0x37,0x38,0x3A,0x3A,0x3C,0x3C,0x3E,0x3E,0x40, 0x40,0x42,0x42,0x44,0x44,0x46,0x46,0x48,0x48,0x49,0x4B,0x4B,0x4D,0x4D,0x4F,0x4F, 0x51,0x51,0x53,0x53,0x55,0x55,0x57,0x57,0x59,0x59,0x5B,0x5B,0x5D,0x5D,0x5F,0x5F, 0x61,0x61,0x63,0x63,0x65,0x65,0x67,0x67,0x69,0x69,0x6B,0x6B,0x6D,0x6D,0x6F,0x6F, 0x71,0x71,0x73,0x73,0x75,0x75,0x77,0x77,0x00,0x7A,0x7A,0x7C,0x7C,0x7E,0x7E,0x7F }; private static zword[] tolower_greek = { //0x50 0x80,0x81,0x82,0x83,0x84,0x85,0xAC,0x87,0xAD,0xAE,0xAF,0x8B,0xCC,0x8D,0xCD,0xCE, 0x90,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, 0xC0,0xC1,0xA2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xAC,0xAD,0xAE,0xAF, 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF }; private static zword[] tolower_cyrillic = { // 0x60 0x00,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x5B,0x5C,0x5D,0x5E,0x5F, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0x3E,0x3F, 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0x3E,0x3F, 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F, 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x5B,0x5C,0x5D,0x5E,0x5F }; internal static zword unicode_tolower(zword c) { if (c < 0x0100) c = tolower_basic_latin[c]; else if (c == 0x0130) c = 0x0069; /* Capital I with dot -> lower case i */ else if (c == 0x0178) c = 0x00FF; /* Capital Y diaeresis -> lower case y diaeresis */ else if (c < 0x0180) c = (zword)(tolower_latin_extended_a[c - 0x100] + 0x100); else if (c >= 0x380 && c < 0x3D0) c = (zword)(tolower_greek[c - 0x380] + 0x300); else if (c >= 0x400 && c < 0x460) c = (zword)(tolower_cyrillic[c - 0x400] + 0x400); return c; } private static void outchar(string_type st, zword c) { if (st == string_type.VOCABULARY) { decoded[ptrDt++] = c; } else { Buffer.print_char(c); } } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.dll // Description: The data access libraries for the DotSpatial project. // // ******************************************************************************************************** // // The Original Code is DotSpatial // // The Initial Developer of this Original Code is Ted Dunsford. Created in January, 2008. // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using DotSpatial.Projections; namespace DotSpatial.Data { /// <summary> /// This is a generic shapefile that is inherited by other specific shapefile types. /// </summary> public abstract class Shapefile : FeatureSet { #region Private Variables // Stores extents and some very basic info common to all shapefiles private AttributeTable _attributeTable; #endregion #region Constructors /// <summary> /// When creating a new shapefile, this simply prevents the basic values from being null. /// </summary> protected Shapefile() { Configure(); } /// <summary> /// Creates a new shapefile that has a specific feature type. /// </summary> /// <param name="featureType">FeatureType of the features inside this shapefile.</param> /// <param name="shapeType">ShapeType of the features inside this shapefile.</param> protected Shapefile(FeatureType featureType, ShapeType shapeType) : base(featureType) { Attributes = new AttributeTable(); Header = new ShapefileHeader { FileLength = 100, ShapeType = shapeType }; } /// <summary> /// Creates a new instance of a shapefile based on a fileName. /// </summary> /// <param name="fileName">File name the shapefile is based on.</param> protected Shapefile(string fileName) { base.Filename = fileName; Configure(); } private void Configure() { Attributes = new AttributeTable(); Header = new ShapefileHeader(); IndexMode = true; } #endregion /// <summary> /// The buffer size is an integer value in bytes specifying how large a piece of memory can be used at any one time. /// Reading and writing from the disk is faster when done all at once. The larger this number the more effective /// the disk management, but the more ram will be required (and the more likely to trip an out of memory error). /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int BufferSize { get; set; } = 1; /// <summary> /// Gets whether or not the attributes have all been loaded into the data table. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override bool AttributesPopulated { get { return _attributeTable.AttributesPopulated; } set { _attributeTable.AttributesPopulated = value; } } /// <summary> /// This re-directs the DataTable to work with the attribute Table instead. /// </summary> public override DataTable DataTable { get { return _attributeTable.Table; } set { _attributeTable.Table = value; } } /// <summary> /// A general header structure that stores some basic information about the shapefile. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public ShapefileHeader Header { get; set; } /// <summary> /// Gets or sets the attribute Table used by this shapefile. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public AttributeTable Attributes { get { return _attributeTable; } set { if (_attributeTable == value) return; if (_attributeTable != null) { _attributeTable.AttributesFilled -= AttributeTableAttributesFilled; } _attributeTable = value; if (_attributeTable != null) { _attributeTable.AttributesFilled += AttributeTableAttributesFilled; } } } /// <summary> /// Gets the count of members that match the expression /// </summary> /// <param name="expressions">The string expression to test</param> /// <param name="progressHandler">THe progress handler that can also cancel the counting</param> /// <param name="maxSampleSize">The integer maximum sample size from which to draw counts. If this is negative, it will not be used.</param> /// <returns>The integer count of the members that match the expression.</returns> public override int[] GetCounts(string[] expressions, ICancelProgressHandler progressHandler, int maxSampleSize) { if (AttributesPopulated) return base.GetCounts(expressions, progressHandler, maxSampleSize); int[] counts = new int[expressions.Length]; // The most common case would be no filter expression, in which case the count is simply the number of shapes. bool requiresRun = false; for (int iex = 0; iex < expressions.Length; iex++) { if (!string.IsNullOrEmpty(expressions[iex])) { requiresRun = true; } else { counts[iex] = NumRows(); } } if (!requiresRun) return counts; AttributePager ap = new AttributePager(this, 5000); ProgressMeter pm = new ProgressMeter(progressHandler, "Calculating Counts", ap.NumPages()); // Don't bother to use a sampling approach if the number of rows is on the same order of magnitude as the number of samples. if (maxSampleSize > 0 && maxSampleSize < NumRows() / 2) { DataTable sample = new DataTable(); sample.Columns.AddRange(GetColumns()); Dictionary<int, int> usedRows = new Dictionary<int, int>(); int samplesPerPage = maxSampleSize / ap.NumPages(); Random rnd = new Random(DateTime.Now.Millisecond); for (int page = 0; page < ap.NumPages(); page++) { for (int i = 0; i < samplesPerPage; i++) { int row; do { row = rnd.Next(ap.StartIndex, ap.StartIndex + ap.PageSize); } while (usedRows.ContainsKey(row)); usedRows.Add(row, row); sample.Rows.Add(ap.Row(row).ItemArray); } ap.MoveNext(); pm.CurrentValue = page; if (progressHandler.Cancel) break; } for (int i = 0; i < expressions.Length; i++) { try { DataRow[] dr = sample.Select(expressions[i]); counts[i] += dr.Length; } catch (Exception ex) { Debug.WriteLine(ex); } } pm.Reset(); return counts; } for (int page = 0; page < ap.NumPages(); page++) { for (int i = 0; i < expressions.Length; i++) { DataRow[] dr = ap[page].Select(expressions[i]); counts[i] += dr.Length; } pm.CurrentValue = page; if (progressHandler.Cancel) break; } pm.Reset(); return counts; } /// <summary> /// This makes the assumption that the organization of the feature list has not /// changed since loading the attribute content. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AttributeTableAttributesFilled(object sender, EventArgs e) { if (IndexMode) return; for (int fid = 0; fid < Features.Count; fid++) { if (fid < _attributeTable.Table.Rows.Count) { Features[fid].DataRow = _attributeTable.Table.Rows[fid]; } } SetupFeatureLookup(); } /// <summary> /// This will return the correct shapefile type by reading the fileName. /// </summary> /// <param name="fileName">A string specifying the file with the extension .shp to open.</param> /// <returns>A correct shapefile object which is exclusively for reading the .shp data</returns> public static new Shapefile OpenFile(string fileName) { return OpenFile(fileName, DataManager.DefaultDataManager.ProgressHandler); } /// <summary> /// This will return the correct shapefile type by reading the fileName. /// </summary> /// <param name="fileName">A string specifying the file with the extension .shp to open.</param> /// <param name="progressHandler">receives progress messages and overrides the ProgressHandler on the DataManager.DefaultDataManager</param> /// <exception cref="NotImplementedException">Throws a NotImplementedException if the ShapeType of the loaded file is NullShape or MultiPatch.</exception> /// <returns>A correct shapefile object which is exclusively for reading the .shp data</returns> public static new Shapefile OpenFile(string fileName, IProgressHandler progressHandler) { var ext = Path.GetExtension(fileName)?.ToLower(); if (ext != ".shp" && ext != ".shx" && ext != ".dbf") throw new ArgumentException(string.Format(DataStrings.FileExtensionNotSupportedByShapefileDataProvider, ext)); string name = Path.ChangeExtension(fileName, ".shp"); var head = new ShapefileHeader(); head.Open(name); switch (head.ShapeType) { case ShapeType.MultiPatch: case ShapeType.NullShape: throw new NotImplementedException(DataStrings.ShapeTypeNotYetSupported); case ShapeType.MultiPoint: case ShapeType.MultiPointM: case ShapeType.MultiPointZ: var mpsf = new MultiPointShapefile(); mpsf.Open(name, progressHandler); return mpsf; case ShapeType.Point: case ShapeType.PointM: case ShapeType.PointZ: var psf = new PointShapefile(); psf.Open(name, progressHandler); return psf; case ShapeType.Polygon: case ShapeType.PolygonM: case ShapeType.PolygonZ: var pgsf = new PolygonShapefile(); pgsf.Open(name, progressHandler); return pgsf; case ShapeType.PolyLine: case ShapeType.PolyLineM: case ShapeType.PolyLineZ: var lsf = new LineShapefile(); lsf.Open(name, progressHandler); return lsf; } return null; } /// <summary> /// saves a single row to the data source. /// </summary> /// <param name="index">the integer row (or FID) index</param> /// <param name="values">The object array holding the new values to store.</param> public override void Edit(int index, Dictionary<string, object> values) { _attributeTable.Edit(index, values); } /// <summary> /// saves a single row to the data source. /// </summary> /// <param name="index">the integer row (or FID) index</param> /// <param name="values">The object array holding the new values to store.</param> public override void Edit(int index, DataRow values) { _attributeTable.Edit(index, values); } /// <summary> /// Saves the new row to the data source and updates the file with new content. /// </summary> /// <param name="values">The values organized against the dictionary of field names.</param> public override void AddRow(Dictionary<string, object> values) { _attributeTable.AddRow(values); } /// <summary> /// Saves the new row to the data source and updates the file with new content. /// </summary> /// <param name="values">The values organized against the dictionary of field names.</param> public override void AddRow(DataRow values) { _attributeTable.AddRow(values); } /// <inheritdoc /> public override DataTable GetAttributes(int startIndex, int numRows) { return _attributeTable.SupplyPageOfData(startIndex, numRows); } /// <summary> /// Converts a page of content from a DataTable format, saving it back to the source. /// </summary> /// <param name="startIndex">The 0 based integer index representing the first row in the file (corresponding to the 0 row of the data table)</param> /// <param name="pageValues">The DataTable representing the rows to set. If the row count is larger than the dataset, this will add the rows instead.</param> public new void SetAttributes(int startIndex, DataTable pageValues) { // overridden in sub-classes _attributeTable.SetAttributes(startIndex, pageValues); } /// <inheritdoc /> public override List<IFeature> SelectByAttribute(string filterExpression) { if (!_attributeTable.AttributesPopulated) { _attributeTable.Fill(_attributeTable.NumRecords); } if (FeatureLookup.Count == 0) { SetupFeatureLookup(); } return base.SelectByAttribute(filterExpression); } /// <summary> /// Reads the attributes from the specified attribute Table. /// </summary> public override void FillAttributes() { _attributeTable.AttributesPopulated = false; // attributeTable.Table fills itself if attributes are not populated DataTable = _attributeTable.Table; base.AttributesPopulated = true; // Link the data rows to the vectors in this object } /// <summary> /// Sets up the feature lookup, if it has not been already. /// </summary> private void SetupFeatureLookup() { for (var i = 0; i < _attributeTable.Table.Rows.Count; i++) { Features[i].DataRow = _attributeTable.Table.Rows[i]; FeatureLookup[Features[i].DataRow] = Features[i]; } } /// <summary> /// This doesn't rewrite the entire header or erase the existing content. This simply replaces the file length /// in the file with the new file length. This is generally because we want to write the header first, /// but don't know the total length of a new file until cycling through the entire file. It is easier, therefore /// to update the length after editing. /// </summary> /// <param name="fileName">A string fileName</param> /// <param name="length">The integer length of the file in 16-bit words</param> public static void WriteFileLength(string fileName, int length) { using (var fs = new FileStream(fileName, FileMode.Open)) { WriteFileLength(fs, length); } } /// <summary> /// Operates on abritrary stream. /// This doesn't rewrite the entire header or erase the existing content. This simply replaces the file length /// in the file with the new file length. This is generally because we want to write the header first, /// but don't know the total length of a new file until cycling through the entire file. It is easier, therefore /// to update the length after editing. /// Note: performs seek /// </summary> /// <param name="stream">stream to edit</param> /// <param name="length">The integer length of the file in 16-bit words</param> public static void WriteFileLength(Stream stream, int length) { stream.Seek(0, SeekOrigin.Begin); byte[] headerData = new byte[28]; WriteBytes(headerData, 0, 9994, false); // Byte 0 File Code 9994 Integer Big // Bytes 4 - 20 are unused WriteBytes(headerData, 24, length, false); // Byte 24 File Length File Length Integer Big var bw = new BinaryWriter(stream); // no using to avoid closing the stream // Actually write our byte array to the file bw.Write(headerData); } /// <summary> /// Reads 4 bytes from the specified byte array starting with offset. /// If IsBigEndian = true, then this flips the order of the byte values. /// </summary> /// <param name="value">An array of bytes that is at least 4 bytes in length from the startIndex</param> /// <param name="startIndex">A 0 based integer index where the double value begins</param> /// <param name="isLittleEndian">If this is true, then the order of the bytes is reversed before being converted to a double</param> /// <returns>A double created from reading the byte array</returns> public static int ToInt(byte[] value, ref int startIndex, bool isLittleEndian) { // Some systems run BigEndian by default, others run little endian. // The parameter specifies the byte order that should exist on the file. // The BitConverter tells us what our system will do by default. if (isLittleEndian != BitConverter.IsLittleEndian) { // The byte order of the value to post doesn't match our system, so reverse the byte order. byte[] flipBytes = new byte[4]; Array.Copy(value, startIndex, flipBytes, 0, 4); Array.Reverse(flipBytes); startIndex += 4; return BitConverter.ToInt32(flipBytes, 0); } startIndex += 4; return BitConverter.ToInt32(value, startIndex); } /// <summary> /// Reads 8 bytes from the specified byte array starting with offset. /// If IsBigEndian = true, then this flips the order of the byte values. /// </summary> /// <param name="value">An array of bytes that is at least 8 bytes in length from the startIndex</param> /// <param name="startIndex">A 0 based integer index where the double value begins</param> /// <param name="isLittleEndian">If this is true, then the order of the bytes is reversed before being converted to a double</param> /// <returns>A double created from reading the byte array</returns> public static double ToDouble(byte[] value, ref int startIndex, bool isLittleEndian) { // Some systems run BigEndian by default, others run little endian. // The parameter specifies the byte order that should exist on the file. // The BitConverter tells us what our system will do by default. if (isLittleEndian != BitConverter.IsLittleEndian) { byte[] flipBytes = new byte[8]; Array.Copy(value, startIndex, flipBytes, 0, 8); Array.Reverse(flipBytes); startIndex += 8; return BitConverter.ToDouble(flipBytes, 0); } startIndex += 8; return BitConverter.ToDouble(value, startIndex); } /// <summary> /// Converts the double value into bytes and inserts them starting at startIndex into the destArray /// </summary> /// <param name="destArray">A byte array where the values should be written</param> /// <param name="startIndex">The starting index where the values should be inserted</param> /// <param name="value">The double value to convert</param> /// <param name="isLittleEndian">Specifies whether the value should be written as big or little endian</param> public static void WriteBytes(byte[] destArray, int startIndex, double value, bool isLittleEndian) { // Some systems run BigEndian by default, others run little endian. // The parameter specifies the byte order that should exist on the file. // The BitConverter tells us what our system will do by default. if (isLittleEndian != BitConverter.IsLittleEndian) { byte[] flipBytes = BitConverter.GetBytes(value); Array.Reverse(flipBytes); Array.Copy(flipBytes, 0, destArray, startIndex, 8); } else { byte[] flipBytes = BitConverter.GetBytes(value); Array.Copy(flipBytes, 0, destArray, startIndex, 8); } } /// <summary> /// Converts the double value into bytes and inserts them starting at startIndex into the destArray. /// This will correct this system's natural byte order to reflect what is required to match the /// shapefiles specification. /// </summary> /// <param name="destArray">A byte array where the values should be written</param> /// <param name="startIndex">The starting index where the values should be inserted</param> /// <param name="value">The integer value to convert</param> /// <param name="isLittleEndian">Specifies whether the value should be written as big or little endian</param> public static void WriteBytes(byte[] destArray, int startIndex, int value, bool isLittleEndian) { // Some systems run BigEndian by default, others run little endian. // The parameter specifies the byte order that should exist on the file. // The BitConverter tells us what our system will do by default. if (isLittleEndian != BitConverter.IsLittleEndian) { byte[] flipBytes = BitConverter.GetBytes(value); Array.Reverse(flipBytes); Array.Copy(flipBytes, 0, destArray, startIndex, 4); } else { byte[] flipBytes = BitConverter.GetBytes(value); Array.Copy(flipBytes, 0, destArray, startIndex, 4); } } /// <summary> /// Reads the entire index file in order to get a breakdown of how shapes are broken up. /// </summary> /// <param name="fileName">A string fileName of the .shx file to read.</param> /// <returns>A List of ShapeHeaders that give offsets and lengths so that reading can be optimized</returns> public List<ShapeHeader> ReadIndexFile(string fileName) { string shxFilename = fileName; string ext = Path.GetExtension(fileName); if (ext != ".shx") { shxFilename = Path.ChangeExtension(fileName, ".shx"); } if (shxFilename == null) { throw new NullReferenceException(DataStrings.ArgumentNull_S.Replace("%S", fileName)); } if (!File.Exists(shxFilename)) { throw new FileNotFoundException(DataStrings.FileNotFound_S.Replace("%S", shxFilename)); } var fileLen = new FileInfo(shxFilename).Length; if (fileLen == 100) { // the file is empty so we are done reading return Enumerable.Empty<ShapeHeader>().ToList(); } // Use a the length of the file to dimension the byte array using (var fs = new FileStream(shxFilename, FileMode.Open, FileAccess.Read, FileShare.Read, 65536)) { // Skip the header and begin reading from the first record fs.Seek(100, SeekOrigin.Begin); Header.ShxLength = (int)(fileLen / 2); var length = (int)(fileLen - 100); var numRecords = length / 8; // Each record consists of 2 Big-endian integers for a total of 8 bytes. // This will store the header elements that we read from the file. var result = new List<ShapeHeader>(numRecords); for (var i = 0; i < numRecords; i++) { result.Add(new ShapeHeader { Offset = fs.ReadInt32(Endian.BigEndian), ContentLength = fs.ReadInt32(Endian.BigEndian) }); } return result; } } /// <summary> /// Ensures that the attribute table will have information that matches the current table of attribute information. /// </summary> public void UpdateAttributes() { if (Attributes == null) return; string newFile = Path.ChangeExtension(Filename, "dbf"); if (!AttributesPopulated && File.Exists(Attributes.Filename)) { if (!newFile.Equals(Attributes.Filename)) { // only switch to the new file, if we aren't using it already if (File.Exists(newFile)) File.Delete(newFile); File.Copy(Attributes.Filename, newFile); Attributes.Filename = newFile; } return; } InitAttributeTable(); Attributes.SaveAs(newFile, true); } /// <summary> /// Exports the dbf file content to a stream. /// </summary> /// <returns>A stream that contains the dbf file content.</returns> protected Stream ExportDbfToStream() { InitAttributeTable(); return Attributes?.ExportDbfToStream(); } /// <summary> /// Creates the Attributes Table if it does not already exist. /// </summary> private void InitAttributeTable() { // The Attributes either don't exist or have been loaded and will now replace the ones in the file. if (Attributes == null || Attributes.Table != null && Attributes.Table.Columns.Count > 0) return; // Only add an FID field if there are no attributes at all. DataTable newTable = new DataTable(); newTable.Columns.Add("FID"); // Added by JamesP@esdm.co.uk - Index mode has no attributes and no features - so Features.count is Null and so was not adding any rows and failing int numRows = IndexMode ? ShapeIndices.Count : Features.Count; for (int i = 0; i < numRows; i++) { DataRow dr = newTable.NewRow(); dr["FID"] = i; newTable.Rows.Add(dr); } Attributes.Table = newTable; } /// <summary> /// This uses the fileName of this shapefile to read the prj file of the same name /// and stores the result in the Projection class. /// </summary> public void ReadProjection() { var prjFile = Path.ChangeExtension(Filename, ".prj"); Projection = File.Exists(prjFile) ? ProjectionInfo.Open(prjFile) : new ProjectionInfo(); } /// <summary> /// Automatically uses the fileName of this shapefile to save the projection /// </summary> public void SaveProjection() { var prjFile = Path.ChangeExtension(Filename, ".prj"); if (File.Exists(prjFile)) File.Delete(prjFile); Projection?.SaveAs(prjFile); } /// <summary> /// Reads just the content requested in order to satisfy the paging ability of VirtualMode for the DataGridView /// </summary> /// <param name="startIndex">The integer lower page boundary</param> /// <param name="numRows">The integer number of attribute rows to return for the page</param> /// <param name="fieldNames">The list or array of fieldnames to return.</param> /// <returns>A DataTable populated with data rows with only the specified values.</returns> public override DataTable GetAttributes(int startIndex, int numRows, IEnumerable<string> fieldNames) { if (AttributesPopulated) return base.GetAttributes(startIndex, numRows, fieldNames); DataTable result = new DataTable(); DataColumn[] columns = GetColumns(); // Always add FID in this paging scenario. result.Columns.Add("FID", typeof(int)); var fields = fieldNames as IList<string> ?? fieldNames.ToList(); foreach (string name in fields) { foreach (var col in columns) { if (string.Equals(col.ColumnName, name, StringComparison.CurrentCultureIgnoreCase)) { result.Columns.Add(col); break; } } } for (int i = 0; i < numRows; i++) { DataRow dr = result.NewRow(); dr["FID"] = startIndex + i; result.Rows.Add(dr); } // Most use cases with an expression use only one or two fieldnames. Tailor for better // performance in that case, at the cost of performance in the "read all " case. // The other overload without fieldnames specified is designed for that case. foreach (string field in fields) { if (field == "FID") continue; object[] values = _attributeTable.SupplyPageOfData(startIndex, numRows, field); for (int i = 0; i < numRows; i++) { result.Rows[i][field] = values[i]; } } return result; } /// <summary> /// The number of rows /// </summary> /// <returns></returns> public override int NumRows() { // overridden in sub-classes return _attributeTable.NumRecords; } /// <summary> /// This gets a copy of the actual internal list of columns. /// This should never be used to make changes to the column collection. /// </summary> public override DataColumn[] GetColumns() { return _attributeTable.Columns .Select(_ => (DataColumn)new Field(_.ColumnName, _.TypeCharacter, _.Length, _.DecimalCount)) .ToArray(); } /// <summary> /// Checks whether the shapefile can be saved with the given fileName. /// </summary> /// <param name="fileName">File name to save.</param> /// <param name="overwrite">Indicates whether the file may be overwritten.</param> protected void EnsureValidFileToSave(string fileName, bool overwrite) { string dir = Path.GetDirectoryName(fileName); if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) { Directory.CreateDirectory(dir); } else if (File.Exists(fileName)) { if (fileName != Filename && !overwrite) throw new ArgumentOutOfRangeException(string.Format(DataStrings.FileExistsOverwritingNotAllowed, fileName)); File.Delete(fileName); var shx = Path.ChangeExtension(fileName, ".shx"); if (File.Exists(shx)) File.Delete(shx); } } /// <summary> /// Updates the Header with the shape type that corresponds to this shapefiles CoordinateType. /// </summary> protected virtual void SetHeaderShapeType() { throw new NotImplementedException(); } /// <summary> /// Saves the file to a new location. /// </summary> /// <param name="fileName">The fileName to save.</param> /// <param name="overwrite">Boolean that specifies whether or not to overwrite the existing file.</param> public override void SaveAs(string fileName, bool overwrite) { EnsureValidFileToSave(fileName, overwrite); Filename = fileName; HeaderSaveAs(fileName); StreamLengthPair streamLengthPair; using (var shpStream = new FileStream(Filename, FileMode.Append, FileAccess.Write, FileShare.None, 10000000)) using (var shxStream = new FileStream(Header.ShxFilename, FileMode.Append, FileAccess.Write, FileShare.None, 10000000)) { streamLengthPair = PopulateShpAndShxStreams(shpStream, shxStream, IndexMode); } WriteFileLength(Filename, streamLengthPair.ShpLength); WriteFileLength(Header.ShxFilename, streamLengthPair.ShxLength); UpdateAttributes(); SaveProjection(); } /// <summary> /// Saves the header to a new location. /// </summary> /// <param name="fileName">File to save.</param> protected void HeaderSaveAs(string fileName) { UpdateHeader(); Header.SaveAs(fileName); } /// <summary> /// Updates the Header. /// </summary> protected void UpdateHeader() { SetHeaderShapeType(); InvalidateEnvelope(); Header.SetExtent(Extent); Header.ShxLength = IndexMode ? ShapeIndices.Count * 4 + 50 : Features.Count * 4 + 50; } /// <summary> /// Populates the given streams for the shp and shx file. /// </summary> /// <param name="shpStream">Stream that is used to write the shp file.</param> /// <param name="shxStream">Stream that is used to write the shx file.</param> /// <param name="indexed">Indicates whether the streams are populated in IndexMode.</param> /// <returns>The lengths of the streams in bytes.</returns> protected virtual StreamLengthPair PopulateShpAndShxStreams(Stream shpStream, Stream shxStream, bool indexed) { throw new NotImplementedException(); } /// <inheritdoc /> public override ShapefilePackage ExportShapefilePackage() { UpdateHeader(); ShapefilePackage package = new ShapefilePackage { DbfFile = ExportDbfToStream(), ShpFile = Header.ExportShpHeaderToStream(), ShxFile = Header.ExportShxHeaderToStream() }; StreamLengthPair streamLengthPair = PopulateShpAndShxStreams(package.ShpFile, package.ShxFile, IndexMode); // write file length WriteFileLength(package.ShpFile, streamLengthPair.ShpLength); WriteFileLength(package.ShxFile, streamLengthPair.ShxLength); package.ShpFile.Seek(0, SeekOrigin.Begin); package.ShxFile.Seek(0, SeekOrigin.Begin); if (Projection != null) { package.PrjFile = new MemoryStream(); StreamWriter projWriter = new StreamWriter(package.PrjFile); projWriter.WriteLine(Projection.ToEsriString()); projWriter.Flush(); package.PrjFile.Seek(0, SeekOrigin.Begin); } return package; } /// <summary> /// StreamLengthPair is used to get the length of the shp and shx file from PopulateShpAndShxStreams and update the file length inside the corresponding stream. /// </summary> protected internal class StreamLengthPair { internal int ShpLength { get; set; } internal int ShxLength { get; set; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Extensions.EnumExtensions; using osuTK; using osu.Game.Audio; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Rulesets.Mania.MathUtils; using osu.Game.Rulesets.Mania.Objects; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using osu.Framework.Extensions.IEnumerableExtensions; namespace osu.Game.Rulesets.Mania.Beatmaps.Patterns.Legacy { internal class HitObjectPatternGenerator : PatternGenerator { public PatternType StairType { get; private set; } private readonly PatternType convertType; public HitObjectPatternGenerator(FastRandom random, HitObject hitObject, ManiaBeatmap beatmap, Pattern previousPattern, double previousTime, Vector2 previousPosition, double density, PatternType lastStair, IBeatmap originalBeatmap) : base(random, hitObject, beatmap, previousPattern, originalBeatmap) { StairType = lastStair; TimingControlPoint timingPoint = beatmap.ControlPointInfo.TimingPointAt(hitObject.StartTime); EffectControlPoint effectPoint = beatmap.ControlPointInfo.EffectPointAt(hitObject.StartTime); var positionData = hitObject as IHasPosition; float positionSeparation = ((positionData?.Position ?? Vector2.Zero) - previousPosition).Length; double timeSeparation = hitObject.StartTime - previousTime; if (timeSeparation <= 80) { // More than 187 BPM convertType |= PatternType.ForceNotStack | PatternType.KeepSingle; } else if (timeSeparation <= 95) { // More than 157 BPM convertType |= PatternType.ForceNotStack | PatternType.KeepSingle | lastStair; } else if (timeSeparation <= 105) { // More than 140 BPM convertType |= PatternType.ForceNotStack | PatternType.LowProbability; } else if (timeSeparation <= 125) { // More than 120 BPM convertType |= PatternType.ForceNotStack; } else if (timeSeparation <= 135 && positionSeparation < 20) { // More than 111 BPM stream convertType |= PatternType.Cycle | PatternType.KeepSingle; } else if (timeSeparation <= 150 && positionSeparation < 20) { // More than 100 BPM stream convertType |= PatternType.ForceStack | PatternType.LowProbability; } else if (positionSeparation < 20 && density >= timingPoint.BeatLength / 2.5) { // Low density stream convertType |= PatternType.Reverse | PatternType.LowProbability; } else if (density < timingPoint.BeatLength / 2.5 || effectPoint.KiaiMode) { // High density } else convertType |= PatternType.LowProbability; if (!convertType.HasFlagFast(PatternType.KeepSingle)) { if (HitObject.Samples.Any(s => s.Name == HitSampleInfo.HIT_FINISH) && TotalColumns != 8) convertType |= PatternType.Mirror; else if (HitObject.Samples.Any(s => s.Name == HitSampleInfo.HIT_CLAP)) convertType |= PatternType.Gathered; } } public override IEnumerable<Pattern> Generate() { Pattern generateCore() { var pattern = new Pattern(); if (TotalColumns == 1) { addToPattern(pattern, 0); return pattern; } int lastColumn = PreviousPattern.HitObjects.FirstOrDefault()?.Column ?? 0; if (convertType.HasFlagFast(PatternType.Reverse) && PreviousPattern.HitObjects.Any()) { // Generate a new pattern by copying the last hit objects in reverse-column order for (int i = RandomStart; i < TotalColumns; i++) { if (PreviousPattern.ColumnHasObject(i)) addToPattern(pattern, RandomStart + TotalColumns - i - 1); } return pattern; } if (convertType.HasFlagFast(PatternType.Cycle) && PreviousPattern.HitObjects.Count() == 1 // If we convert to 7K + 1, let's not overload the special key && (TotalColumns != 8 || lastColumn != 0) // Make sure the last column was not the centre column && (TotalColumns % 2 == 0 || lastColumn != TotalColumns / 2)) { // Generate a new pattern by cycling backwards (similar to Reverse but for only one hit object) int column = RandomStart + TotalColumns - lastColumn - 1; addToPattern(pattern, column); return pattern; } if (convertType.HasFlagFast(PatternType.ForceStack) && PreviousPattern.HitObjects.Any()) { // Generate a new pattern by placing on the already filled columns for (int i = RandomStart; i < TotalColumns; i++) { if (PreviousPattern.ColumnHasObject(i)) addToPattern(pattern, i); } return pattern; } if (PreviousPattern.HitObjects.Count() == 1) { if (convertType.HasFlagFast(PatternType.Stair)) { // Generate a new pattern by placing on the next column, cycling back to the start if there is no "next" int targetColumn = lastColumn + 1; if (targetColumn == TotalColumns) targetColumn = RandomStart; addToPattern(pattern, targetColumn); return pattern; } if (convertType.HasFlagFast(PatternType.ReverseStair)) { // Generate a new pattern by placing on the previous column, cycling back to the end if there is no "previous" int targetColumn = lastColumn - 1; if (targetColumn == RandomStart - 1) targetColumn = TotalColumns - 1; addToPattern(pattern, targetColumn); return pattern; } } if (convertType.HasFlagFast(PatternType.KeepSingle)) return generateRandomNotes(1); if (convertType.HasFlagFast(PatternType.Mirror)) { if (ConversionDifficulty > 6.5) return generateRandomPatternWithMirrored(0.12, 0.38, 0.12); if (ConversionDifficulty > 4) return generateRandomPatternWithMirrored(0.12, 0.17, 0); return generateRandomPatternWithMirrored(0.12, 0, 0); } if (ConversionDifficulty > 6.5) { if (convertType.HasFlagFast(PatternType.LowProbability)) return generateRandomPattern(0.78, 0.42, 0, 0); return generateRandomPattern(1, 0.62, 0, 0); } if (ConversionDifficulty > 4) { if (convertType.HasFlagFast(PatternType.LowProbability)) return generateRandomPattern(0.35, 0.08, 0, 0); return generateRandomPattern(0.52, 0.15, 0, 0); } if (ConversionDifficulty > 2) { if (convertType.HasFlagFast(PatternType.LowProbability)) return generateRandomPattern(0.18, 0, 0, 0); return generateRandomPattern(0.45, 0, 0, 0); } return generateRandomPattern(0, 0, 0, 0); } var p = generateCore(); foreach (var obj in p.HitObjects) { if (convertType.HasFlagFast(PatternType.Stair) && obj.Column == TotalColumns - 1) StairType = PatternType.ReverseStair; if (convertType.HasFlagFast(PatternType.ReverseStair) && obj.Column == RandomStart) StairType = PatternType.Stair; } return p.Yield(); } /// <summary> /// Generates random notes. /// <para> /// This will generate as many as it can up to <paramref name="noteCount"/>, accounting for /// any stacks if <see cref="convertType"/> is forcing no stacks. /// </para> /// </summary> /// <param name="noteCount">The amount of notes to generate.</param> /// <returns>The <see cref="Pattern"/> containing the hit objects.</returns> private Pattern generateRandomNotes(int noteCount) { var pattern = new Pattern(); bool allowStacking = !convertType.HasFlagFast(PatternType.ForceNotStack); if (!allowStacking) noteCount = Math.Min(noteCount, TotalColumns - RandomStart - PreviousPattern.ColumnWithObjects); int nextColumn = GetColumn((HitObject as IHasXPosition)?.X ?? 0, true); for (int i = 0; i < noteCount; i++) { nextColumn = allowStacking ? FindAvailableColumn(nextColumn, nextColumn: getNextColumn, patterns: pattern) : FindAvailableColumn(nextColumn, nextColumn: getNextColumn, patterns: new[] { pattern, PreviousPattern }); addToPattern(pattern, nextColumn); } return pattern; int getNextColumn(int last) { if (convertType.HasFlagFast(PatternType.Gathered)) { last++; if (last == TotalColumns) last = RandomStart; } else last = GetRandomColumn(); return last; } } /// <summary> /// Whether this hit object can generate a note in the special column. /// </summary> private bool hasSpecialColumn => HitObject.Samples.Any(s => s.Name == HitSampleInfo.HIT_CLAP) && HitObject.Samples.Any(s => s.Name == HitSampleInfo.HIT_FINISH); /// <summary> /// Generates a random pattern. /// </summary> /// <param name="p2">Probability for 2 notes to be generated.</param> /// <param name="p3">Probability for 3 notes to be generated.</param> /// <param name="p4">Probability for 4 notes to be generated.</param> /// <param name="p5">Probability for 5 notes to be generated.</param> /// <returns>The <see cref="Pattern"/> containing the hit objects.</returns> private Pattern generateRandomPattern(double p2, double p3, double p4, double p5) { var pattern = new Pattern(); pattern.Add(generateRandomNotes(getRandomNoteCount(p2, p3, p4, p5))); if (RandomStart > 0 && hasSpecialColumn) addToPattern(pattern, 0); return pattern; } /// <summary> /// Generates a random pattern which has both normal and mirrored notes. /// </summary> /// <param name="centreProbability">The probability for a note to be added to the centre column.</param> /// <param name="p2">Probability for 2 notes to be generated.</param> /// <param name="p3">Probability for 3 notes to be generated.</param> /// <returns>The <see cref="Pattern"/> containing the hit objects.</returns> private Pattern generateRandomPatternWithMirrored(double centreProbability, double p2, double p3) { if (convertType.HasFlagFast(PatternType.ForceNotStack)) return generateRandomPattern(1 / 2f + p2 / 2, p2, (p2 + p3) / 2, p3); var pattern = new Pattern(); int noteCount = getRandomNoteCountMirrored(centreProbability, p2, p3, out var addToCentre); int columnLimit = (TotalColumns % 2 == 0 ? TotalColumns : TotalColumns - 1) / 2; int nextColumn = GetRandomColumn(upperBound: columnLimit); for (int i = 0; i < noteCount; i++) { nextColumn = FindAvailableColumn(nextColumn, upperBound: columnLimit, patterns: pattern); // Add normal note addToPattern(pattern, nextColumn); // Add mirrored note addToPattern(pattern, RandomStart + TotalColumns - nextColumn - 1); } if (addToCentre) addToPattern(pattern, TotalColumns / 2); if (RandomStart > 0 && hasSpecialColumn) addToPattern(pattern, 0); return pattern; } /// <summary> /// Generates a count of notes to be generated from a list of probabilities. /// </summary> /// <param name="p2">Probability for 2 notes to be generated.</param> /// <param name="p3">Probability for 3 notes to be generated.</param> /// <param name="p4">Probability for 4 notes to be generated.</param> /// <param name="p5">Probability for 5 notes to be generated.</param> /// <returns>The amount of notes to be generated.</returns> private int getRandomNoteCount(double p2, double p3, double p4, double p5) { switch (TotalColumns) { case 2: p2 = 0; p3 = 0; p4 = 0; p5 = 0; break; case 3: p2 = Math.Min(p2, 0.1); p3 = 0; p4 = 0; p5 = 0; break; case 4: p2 = Math.Min(p2, 0.23); p3 = Math.Min(p3, 0.04); p4 = 0; p5 = 0; break; case 5: p3 = Math.Min(p3, 0.15); p4 = Math.Min(p4, 0.03); p5 = 0; break; } if (HitObject.Samples.Any(s => s.Name == HitSampleInfo.HIT_CLAP)) p2 = 1; return GetRandomNoteCount(p2, p3, p4, p5); } /// <summary> /// Generates a count of notes to be generated from a list of probabilities. /// </summary> /// <param name="centreProbability">The probability for a note to be added to the centre column.</param> /// <param name="p2">Probability for 2 notes to be generated.</param> /// <param name="p3">Probability for 3 notes to be generated.</param> /// <param name="addToCentre">Whether to add a note to the centre column.</param> /// <returns>The amount of notes to be generated. The note to be added to the centre column will NOT be part of this count.</returns> private int getRandomNoteCountMirrored(double centreProbability, double p2, double p3, out bool addToCentre) { switch (TotalColumns) { case 2: centreProbability = 0; p2 = 0; p3 = 0; break; case 3: centreProbability = Math.Min(centreProbability, 0.03); p2 = 0; p3 = 0; break; case 4: centreProbability = 0; // Stable requires rngValue > x, which is an inverse-probability. Lazer uses true probability (1 - x). // But multiplying this value by 2 (stable) is not the same operation as dividing it by 2 (lazer), // so it needs to be converted to from a probability and then back after the multiplication. p2 = 1 - Math.Max((1 - p2) * 2, 0.8); p3 = 0; break; case 5: centreProbability = Math.Min(centreProbability, 0.03); p3 = 0; break; case 6: centreProbability = 0; // Stable requires rngValue > x, which is an inverse-probability. Lazer uses true probability (1 - x). // But multiplying this value by 2 (stable) is not the same operation as dividing it by 2 (lazer), // so it needs to be converted to from a probability and then back after the multiplication. p2 = 1 - Math.Max((1 - p2) * 2, 0.5); p3 = 1 - Math.Max((1 - p3) * 2, 0.85); break; } // The stable values were allowed to exceed 1, which indicate <0% probability. // These values needs to be clamped otherwise GetRandomNoteCount() will throw an exception. p2 = Math.Clamp(p2, 0, 1); p3 = Math.Clamp(p3, 0, 1); double centreVal = Random.NextDouble(); int noteCount = GetRandomNoteCount(p2, p3); addToCentre = TotalColumns % 2 != 0 && noteCount != 3 && centreVal > 1 - centreProbability; return noteCount; } /// <summary> /// Constructs and adds a note to a pattern. /// </summary> /// <param name="pattern">The pattern to add to.</param> /// <param name="column">The column to add the note to.</param> private void addToPattern(Pattern pattern, int column) { pattern.Add(new Note { StartTime = HitObject.StartTime, Samples = HitObject.Samples, Column = column }); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Management.Automation.Language; using Microsoft.Management.Infrastructure; namespace System.Management.Automation.Runspaces { using System; using System.Collections.ObjectModel; using Debug = System.Management.Automation.Diagnostics; /// <summary> /// Define a parameter for <see cref="Command"/> /// </summary> public sealed class CommandParameter { #region Public constructors /// <summary> /// Create a named parameter with a null value. /// </summary> /// <param name="name">Parameter name.</param> /// <exception cref="ArgumentNullException"> /// name is null. /// </exception> /// <exception cref="ArgumentException"> /// Name length is zero after trimming whitespace. /// </exception> public CommandParameter(string name) : this(name, null) { if (name == null) { throw PSTraceSource.NewArgumentNullException("name"); } } /// <summary> /// Create a named parameter. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="value">Parameter value.</param> /// <exception cref="ArgumentException"> /// Name is non null and name length is zero after trimming whitespace. /// </exception> public CommandParameter(string name, object value) { if (name != null) { if (string.IsNullOrWhiteSpace(name)) { throw PSTraceSource.NewArgumentException("name"); } Name = name; } else { Name = null; } Value = value; } #endregion Public constructors #region Public properties /// <summary> /// Gets the parameter name. /// </summary> public string Name { get; } /// <summary> /// Gets the value of the parameter. /// </summary> public object Value { get; } #endregion Public properties #region Private Fields #endregion Private Fields #region Conversion from and to CommandParameterInternal internal static CommandParameter FromCommandParameterInternal(CommandParameterInternal internalParameter) { if (internalParameter == null) { throw PSTraceSource.NewArgumentNullException("internalParameter"); } // we want the name to preserve 1) dashes, 2) colons, 3) followed-by-space information string name = null; if (internalParameter.ParameterNameSpecified) { name = internalParameter.ParameterText; if (internalParameter.SpaceAfterParameter) { name = name + " "; } Diagnostics.Assert(name != null, "'name' variable should be initialized at this point"); Diagnostics.Assert(name[0].IsDash(), "first character in parameter name must be a dash"); Diagnostics.Assert(name.Trim().Length != 1, "Parameter name has to have some non-whitespace characters in it"); } if (internalParameter.ParameterAndArgumentSpecified) { return new CommandParameter(name, internalParameter.ArgumentValue); } if (name != null) // either a switch parameter or first part of parameter+argument { return new CommandParameter(name); } // either a positional argument or second part of parameter+argument return new CommandParameter(null, internalParameter.ArgumentValue); } internal static CommandParameterInternal ToCommandParameterInternal(CommandParameter publicParameter, bool forNativeCommand) { if (publicParameter == null) { throw PSTraceSource.NewArgumentNullException("publicParameter"); } string name = publicParameter.Name; object value = publicParameter.Value; Debug.Assert((name == null) || (name.Trim().Length != 0), "Parameter name has to null or have some non-whitespace characters in it"); if (name == null) { return CommandParameterInternal.CreateArgument(value); } string parameterText; if (!name[0].IsDash()) { parameterText = forNativeCommand ? name : "-" + name; return CommandParameterInternal.CreateParameterWithArgument( /*parameterAst*/null, name, parameterText, /*argumentAst*/null, value, true); } // if first character of name is '-', then we try to fake the original token // reconstructing dashes, colons and followed-by-space information // find the last non-whitespace character bool spaceAfterParameter = false; int endPosition = name.Length; while ((endPosition > 0) && char.IsWhiteSpace(name[endPosition - 1])) { spaceAfterParameter = true; endPosition--; } Debug.Assert(endPosition > 0, "parameter name should have some non-whitespace characters in it"); // now make sure that parameterText doesn't have whitespace at the end, parameterText = name.Substring(0, endPosition); // parameterName should contain only the actual name of the parameter (no whitespace, colons, dashes) bool hasColon = (name[endPosition - 1] == ':'); var parameterName = parameterText.Substring(1, parameterText.Length - (hasColon ? 2 : 1)); // At this point we have rebuilt the token. There are 3 strings that might be different: // name = nameToken.Script = "-foo: " <- needed to fake FollowedBySpace=true (i.e. for "testecho.exe -a:b -c: d") // tokenString = nameToken.TokenText = "-foo:" <- needed to preserve full token text (i.e. for write-output) // nameToken.Data = "foo" <- needed to preserve name of parameter so parameter binding works // Now we just need to use the token to build appropriate CommandParameterInternal object // is this a name+value pair, or is it just a name (of a parameter)? if (!hasColon && value == null) { // just a name return CommandParameterInternal.CreateParameter(parameterName, parameterText); } // name+value pair return CommandParameterInternal.CreateParameterWithArgument( /*parameterAst*/null, parameterName, parameterText, /*argumentAst*/null, value, spaceAfterParameter); } #endregion #region Serialization / deserialization for remoting /// <summary> /// Creates a CommandParameter object from a PSObject property bag. /// PSObject has to be in the format returned by ToPSObjectForRemoting method. /// </summary> /// <param name="parameterAsPSObject">PSObject to rehydrate.</param> /// <returns> /// CommandParameter rehydrated from a PSObject property bag /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown if the PSObject is null. /// </exception> /// <exception cref="System.Management.Automation.Remoting.PSRemotingDataStructureException"> /// Thrown when the PSObject is not in the expected format /// </exception> internal static CommandParameter FromPSObjectForRemoting(PSObject parameterAsPSObject) { if (parameterAsPSObject == null) { throw PSTraceSource.NewArgumentNullException("parameterAsPSObject"); } string name = RemotingDecoder.GetPropertyValue<string>(parameterAsPSObject, RemoteDataNameStrings.ParameterName); object value = RemotingDecoder.GetPropertyValue<object>(parameterAsPSObject, RemoteDataNameStrings.ParameterValue); return new CommandParameter(name, value); } /// <summary> /// Returns this object as a PSObject property bag /// that can be used in a remoting protocol data object. /// </summary> /// <returns>This object as a PSObject property bag.</returns> internal PSObject ToPSObjectForRemoting() { PSObject parameterAsPSObject = RemotingEncoder.CreateEmptyPSObject(); parameterAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ParameterName, this.Name)); parameterAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ParameterValue, this.Value)); return parameterAsPSObject; } #endregion #region Win Blue Extensions #if !CORECLR // PSMI Not Supported On CSS internal CimInstance ToCimInstance() { CimInstance c = InternalMISerializer.CreateCimInstance("PS_Parameter"); CimProperty nameProperty = InternalMISerializer.CreateCimProperty("Name", this.Name, Microsoft.Management.Infrastructure.CimType.String); c.CimInstanceProperties.Add(nameProperty); Microsoft.Management.Infrastructure.CimType cimType = CimConverter.GetCimType(this.Value.GetType()); CimProperty valueProperty; if (cimType == Microsoft.Management.Infrastructure.CimType.Unknown) { valueProperty = InternalMISerializer.CreateCimProperty("Value", (object)PSMISerializer.Serialize(this.Value), Microsoft.Management.Infrastructure.CimType.Instance); } else { valueProperty = InternalMISerializer.CreateCimProperty("Value", this.Value, cimType); } c.CimInstanceProperties.Add(valueProperty); return c; } #endif #endregion Win Blue Extensions } /// <summary> /// Defines a collection of parameters. /// </summary> public sealed class CommandParameterCollection : Collection<CommandParameter> { // TODO: this class needs a mechanism to lock further changes /// <summary> /// Create a new empty instance of this collection type. /// </summary> public CommandParameterCollection() { } /// <summary> /// Add a parameter with given name and default null value. /// </summary> /// <param name="name">Name of the parameter.</param> /// <exception cref="ArgumentNullException"> /// name is null. /// </exception> /// <exception cref="ArgumentException"> /// Name length is zero after trimming whitespace. /// </exception> public void Add(string name) { Add(new CommandParameter(name)); } /// <summary> /// Add a parameter with given name and value. /// </summary> /// <param name="name">Name of the parameter.</param> /// <param name="value">Value of the parameter.</param> /// <exception cref="ArgumentNullException"> /// Both name and value are null. One of these must be non-null. /// </exception> /// <exception cref="ArgumentException"> /// Name is non null and name length is zero after trimming whitespace. /// </exception> public void Add(string name, object value) { Add(new CommandParameter(name, value)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Diagnostics; using System.IO; using System.Management.Automation; using Xunit; namespace PSTests.Parallel { public static class PlatformTests { [Fact] public static void TestIsCoreCLR() { Assert.True(Platform.IsCoreCLR); } #if Unix [Fact] public static void TestGetUserName() { var startInfo = new ProcessStartInfo { FileName = @"/usr/bin/env", Arguments = "whoami", RedirectStandardOutput = true, UseShellExecute = false }; using (Process process = Process.Start(startInfo)) { // Get output of call to whoami without trailing newline string username = process.StandardOutput.ReadToEnd().Trim(); process.WaitForExit(); // The process should return an exit code of 0 on success Assert.Equal(0, process.ExitCode); // It should be the same as what our platform code returns Assert.Equal(username, Platform.Unix.UserName()); } } [Fact] public static void TestGetMachineName() { var startInfo = new ProcessStartInfo { FileName = @"/usr/bin/env", Arguments = "hostname", RedirectStandardOutput = true, UseShellExecute = false }; using (Process process = Process.Start(startInfo)) { // Get output of call to hostname without trailing newline string hostname = process.StandardOutput.ReadToEnd().Trim(); process.WaitForExit(); // The process should return an exit code of 0 on success Assert.Equal(0, process.ExitCode); // It should be the same as what our platform code returns Assert.Equal(hostname, Environment.MachineName); } } [Fact] public static void TestGetFQDN() { var startInfo = new ProcessStartInfo { FileName = @"/usr/bin/env", Arguments = "hostname --fqdn", RedirectStandardOutput = true, UseShellExecute = false }; using (Process process = Process.Start(startInfo)) { // Get output of call to hostname without trailing newline string hostname = process.StandardOutput.ReadToEnd().Trim(); process.WaitForExit(); // The process should return an exit code of 0 on success Assert.Equal(0, process.ExitCode); // It should be the same as what our platform code returns Assert.Equal(hostname, Platform.NonWindowsGetHostName()); } } [Fact] public static void TestIsExecutable() { Assert.True(Platform.NonWindowsIsExecutable("/bin/ls")); } [Fact] public static void TestIsNotExecutable() { Assert.False(Platform.NonWindowsIsExecutable("/etc/hosts")); } [Fact] public static void TestDirectoryIsNotExecutable() { Assert.False(Platform.NonWindowsIsExecutable("/etc")); } [Fact] public static void TestFileIsNotHardLink() { string path = @"/tmp/nothardlink"; if (File.Exists(path)) { File.Delete(path); } File.Create(path); FileSystemInfo fd = new FileInfo(path); // Since this is the only reference to the file, it is not considered a // hardlink by our API (though all files are hardlinks on Linux) Assert.False(Platform.NonWindowsIsHardLink(fd)); File.Delete(path); } [Fact] public static void TestFileIsHardLink() { string path = @"/tmp/originallink"; if (File.Exists(path)) { File.Delete(path); } File.Create(path); string link = "/tmp/newlink"; if (File.Exists(link)) { File.Delete(link); } var startInfo = new ProcessStartInfo { FileName = @"/usr/bin/env", Arguments = "ln " + path + " " + link, RedirectStandardOutput = true, UseShellExecute = false }; using (Process process = Process.Start(startInfo)) { process.WaitForExit(); Assert.Equal(0, process.ExitCode); } // Since there are now two references to the file, both are considered // hardlinks by our API (though all files are hardlinks on Linux) FileSystemInfo fd = new FileInfo(path); Assert.True(Platform.NonWindowsIsHardLink(fd)); fd = new FileInfo(link); Assert.True(Platform.NonWindowsIsHardLink(fd)); File.Delete(path); File.Delete(link); } [Fact] public static void TestDirectoryIsNotHardLink() { string path = @"/tmp"; FileSystemInfo fd = new FileInfo(path); Assert.False(Platform.NonWindowsIsHardLink(fd)); } [Fact] public static void TestNonExistentIsHardLink() { // A file that should *never* exist on a test machine: string path = @"/tmp/ThisFileShouldNotExistOnTestMachines"; // If the file exists, then there's a larger issue that needs to be looked at Assert.False(File.Exists(path)); // Convert `path` string to FileSystemInfo data type. And now, it should return true FileSystemInfo fd = new FileInfo(path); Assert.False(Platform.NonWindowsIsHardLink(fd)); } [Fact] public static void TestFileIsSymLink() { string path = @"/tmp/originallink"; if (File.Exists(path)) { File.Delete(path); } File.Create(path); string link = "/tmp/newlink"; if (File.Exists(link)) { File.Delete(link); } var startInfo = new ProcessStartInfo { FileName = @"/usr/bin/env", Arguments = "ln -s " + path + " " + link, RedirectStandardOutput = true, UseShellExecute = false }; using (Process process = Process.Start(startInfo)) { process.WaitForExit(); Assert.Equal(0, process.ExitCode); } FileSystemInfo fd = new FileInfo(path); Assert.False(Platform.NonWindowsIsSymLink(fd)); fd = new FileInfo(link); Assert.True(Platform.NonWindowsIsSymLink(fd)); File.Delete(path); File.Delete(link); } #endif } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Linq; using System.Windows.Forms; namespace DotSpatial.Symbology.Forms { /// <summary> /// SelectByAttributes /// </summary> public partial class SelectByAttributes : Form { #region Fields private IFeatureLayer _activeLayer; private IFeatureLayer[] _layersToSelect; private IFrame _mapFrame; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="SelectByAttributes"/> class. /// </summary> public SelectByAttributes() { InitializeComponent(); Configure(); } /// <summary> /// Initializes a new instance of the <see cref="SelectByAttributes"/> class. /// </summary> /// <param name="mapFrame">The MapFrame containing the layers</param> public SelectByAttributes(IFrame mapFrame) { _mapFrame = mapFrame; InitializeComponent(); Configure(); } /// <summary> /// Initializes a new instance of the <see cref="SelectByAttributes"/> class. /// </summary> /// <param name="layersToSelect">Layers to select</param> public SelectByAttributes(params IFeatureLayer[] layersToSelect) { if (layersToSelect == null) throw new ArgumentNullException(nameof(layersToSelect)); _layersToSelect = layersToSelect; InitializeComponent(); Configure(); } #endregion #region Properties /// <summary> /// Gets or sets the map frame to use for this control /// </summary> public IFrame MapFrame { get { return _mapFrame; } set { _layersToSelect = null; _mapFrame = value; Configure(); } } #endregion #region Methods private void ApplyFilter() { string filter = sqlQueryControl1.ExpressionText; if (_activeLayer != null) { try { _activeLayer.SelectByAttribute(filter, GetSelectMode()); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); MessageBox.Show(SymbologyFormsMessageStrings.SelectByAttributes_ErrorWhileAttemptingToApplyExpression); } } } private void BtnApplyClick(object sender, EventArgs e) { ApplyFilter(); } private void BtnCloseClick(object sender, EventArgs e) { Close(); } private void BtnOkClick(object sender, EventArgs e) { ApplyFilter(); Close(); } private void CmbLayersSelectedIndexChanged(object sender, EventArgs e) { DataRowView drv = cmbLayers.SelectedValue as DataRowView; if (drv != null) { _activeLayer = drv.Row["Value"] as IFeatureLayer; } else { _activeLayer = cmbLayers.SelectedValue as IFeatureLayer; } if (_activeLayer == null) return; if (!_activeLayer.DataSet.AttributesPopulated && _activeLayer.DataSet.NumRows() < 50000) { _activeLayer.DataSet.FillAttributes(); } if (_activeLayer.EditMode || _activeLayer.DataSet.AttributesPopulated) { sqlQueryControl1.Table = _activeLayer.DataSet.DataTable; } else { sqlQueryControl1.AttributeSource = _activeLayer.DataSet; } } private void Configure() { DataTable dt = new DataTable(); dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("Value", typeof(IFeatureLayer)); IEnumerable<ILayer> layersSource; if (_layersToSelect != null) { layersSource = _layersToSelect; } else if (_mapFrame != null) { layersSource = _mapFrame; } else { layersSource = Enumerable.Empty<ILayer>(); } foreach (var layer in layersSource.OfType<IFeatureLayer>()) { DataRow dr = dt.NewRow(); dr["Name"] = layer.LegendText; dr["Value"] = layer; dt.Rows.Add(dr); } cmbLayers.DataSource = dt; cmbLayers.DisplayMember = "Name"; cmbLayers.ValueMember = "Value"; cmbMethod.SelectedIndex = 0; if (cmbLayers.Items.Count > 0) { cmbLayers.SelectedIndex = 0; } } private ModifySelectionMode GetSelectMode() { switch (cmbMethod.SelectedIndex) { case 0: return ModifySelectionMode.Replace; case 1: return ModifySelectionMode.Append; case 2: return ModifySelectionMode.Subtract; case 3: return ModifySelectionMode.SelectFrom; } return ModifySelectionMode.Replace; } #endregion } }
// Copyright (c) 2012 DotNetAnywhere // // 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; #if LOCALTEST using System.Collections; using System.Collections.Generic; namespace System_.Collections.Generic { #else namespace System.Collections.Generic { #endif public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, IDictionary, ICollection, IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>> { public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDisposable, IDictionaryEnumerator, IEnumerator { Dictionary<TKey, TValue> dict; private int curSlot, curItem; internal Enumerator(Dictionary<TKey, TValue> dictionary) { this.dict = dictionary; this.curSlot = -1; this.curItem = 0; } public bool MoveNext() { do { if (this.curSlot >= this.dict.capacity) { return false; } if (this.curSlot < 0 || this.dict.keys[this.curSlot] == null || this.curItem > this.dict.keys[this.curSlot].Count) { this.curSlot++; this.curItem = 0; } else { this.curItem++; } if (this.curSlot >= this.dict.capacity) { return false; } } while (this.dict.keys[this.curSlot] == null || this.curItem >= dict.keys[this.curSlot].Count); return true; } public KeyValuePair<TKey, TValue> Current { get { return new KeyValuePair<TKey, TValue>( this.dict.keys[this.curSlot][this.curItem], this.dict.values[this.curSlot][this.curItem] ); } } object IEnumerator.Current { get { return this.Current; } } void IEnumerator.Reset() { this.curSlot = -1; this.curItem = 0; } DictionaryEntry IDictionaryEnumerator.Entry { get { return new DictionaryEntry( this.dict.keys[this.curSlot][this.curItem], this.dict.values[this.curSlot][this.curItem] ); } } object IDictionaryEnumerator.Key { get { return dict.keys[this.curSlot][this.curItem]; } } object IDictionaryEnumerator.Value { get { return this.dict.values[this.curSlot][this.curItem]; } } public void Dispose() { this.dict = null; } } public sealed class KeyCollection : ICollection<TKey>, IEnumerable<TKey>, IEnumerable, ICollection, IReadOnlyCollection<TKey> { public struct Enumerator : IEnumerator<TKey>, IDisposable, IEnumerator { private Dictionary<TKey, TValue>.Enumerator hostEnumerator; internal Enumerator(Dictionary<TKey, TValue> host) { this.hostEnumerator = host.GetEnumerator(); } public void Dispose() { this.hostEnumerator.Dispose(); } public bool MoveNext() { return this.hostEnumerator.MoveNext(); } public TKey Current { get { return this.hostEnumerator.Current.Key; } } object IEnumerator.Current { get { return this.hostEnumerator.Current.Key; } } void IEnumerator.Reset() { ((IEnumerator)this.hostEnumerator).Reset(); } } private Dictionary<TKey, TValue> dictionary; public KeyCollection(Dictionary<TKey, TValue> dictionary) { if (dictionary == null) { throw new ArgumentException("dictionary"); } this.dictionary = dictionary; } public void CopyTo(TKey[] array, int index) { throw new NotImplementedException(); } public Enumerator GetEnumerator() { return new Enumerator(this.dictionary); } void ICollection<TKey>.Add(TKey item) { throw new NotSupportedException("this is a read-only collection"); } void ICollection<TKey>.Clear() { throw new NotSupportedException("this is a read-only collection"); } bool ICollection<TKey>.Contains(TKey item) { return this.dictionary.ContainsKey(item); } bool ICollection<TKey>.Remove(TKey item) { throw new NotSupportedException("this is a read-only collection"); } IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() { return this.GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { this.CopyTo((TKey[])array, index); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public int Count { get { return this.dictionary.Count; } } bool ICollection<TKey>.IsReadOnly { get { return true; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return ((ICollection)this.dictionary).SyncRoot; } } } public sealed class ValueCollection : ICollection<TValue>, IEnumerable<TValue>, IEnumerable, ICollection, IReadOnlyCollection<TValue> { public struct Enumerator : IEnumerator<TValue>, IDisposable, IEnumerator { private Dictionary<TKey, TValue>.Enumerator hostEnumerator; internal Enumerator(Dictionary<TKey, TValue> host) { this.hostEnumerator = host.GetEnumerator(); } public void Dispose() { this.hostEnumerator.Dispose(); } public bool MoveNext() { return this.hostEnumerator.MoveNext(); } public TValue Current { get { return this.hostEnumerator.Current.Value; } } object IEnumerator.Current { get { return this.hostEnumerator.Current.Value; } } void IEnumerator.Reset() { ((IEnumerator)this.hostEnumerator).Reset(); } } private Dictionary<TKey, TValue> dictionary; public ValueCollection(Dictionary<TKey, TValue> dictionary) { if (dictionary == null) { throw new ArgumentException("dictionary"); } this.dictionary = dictionary; } public void CopyTo(TValue[] array, int index) { throw new NotImplementedException(); } public Enumerator GetEnumerator() { return new Enumerator(this.dictionary); } void ICollection<TValue>.Add(TValue item) { throw new NotSupportedException("this is a read-only collection"); } void ICollection<TValue>.Clear() { throw new NotSupportedException("this is a read-only collection"); } bool ICollection<TValue>.Contains(TValue item) { return this.dictionary.ContainsValue(item); } bool ICollection<TValue>.Remove(TValue item) { throw new NotSupportedException("this is a read-only collection"); } IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator() { return this.GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { this.CopyTo((TValue[])array, index); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public int Count { get { return this.dictionary.Count; } } bool ICollection<TValue>.IsReadOnly { get { return true; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return ((ICollection)this.dictionary).SyncRoot; } } } private static int[] capacities = { 11, 23, 47, 97, 191, 379, 757, 1511, 3023, 6047, 12097, 24179, 48353, 96731 }; private List<TKey>[] keys; private List<TValue>[] values; private int capacity, capacityIndex, count; private IEqualityComparer<TKey> comparer; public Dictionary() { this.Init(0, null); } public Dictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { } public Dictionary(IEqualityComparer<TKey> comparer) { this.Init(0, comparer); } public Dictionary(int capacity) { this.Init(capacity, null); } public Dictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) { this.Init(dictionary.Count, comparer); foreach (var item in dictionary) { this.Add(item.Key, item.Value); } } public Dictionary(int capacity, IEqualityComparer<TKey> comparer) { this.Init(capacity, comparer); } private void Init(int initialCapacity, IEqualityComparer<TKey> comparer) { // Initialise the comparer this.comparer = comparer ?? EqualityComparer<TKey>.Default; // Initialise the capacity of the dictionary this.capacityIndex = -1; for (int i = 0; i < capacities.Length; i++) { if (initialCapacity <= capacities[i]) { this.capacityIndex = i; this.capacity = capacities[i]; break; } } if (this.capacityIndex == -1) { // If the capacity is off the end of the scale, then just use the capacity given this.capacity = initialCapacity; this.capacityIndex = capacities.Length; } this.Clear(); } private int GetSlot(TKey key) { uint hash = (uint)this.comparer.GetHashCode(key); return (int)(hash % (uint)this.capacity); } public void Add(TKey key, TValue value) { Add(key, value, false); } private void Add(TKey key, TValue value, bool replace) { if (key == null) { throw new ArgumentNullException(); } int slot = this.GetSlot(key); List<TKey> keySlot = this.keys[slot]; if (keySlot != null) { // There are element(s) at this index, so see if this key is already in this dictionary // Can't use keySlot.IndexOf() because it doesn't honour the comparer for (int i = keySlot.Count - 1; i >= 0; i--) { if (this.comparer.Equals(keySlot[i], key)) { // The key is already in this dictionary if (replace) { this.values[slot][i] = value; return; } else { throw new ArgumentException("Key already exists in dictionary"); } } } // Key not already in dictionary, so carry on } this.count++; if (this.count > this.capacity) { // Increase capacity List<TKey>[] currentKeys = this.keys; List<TValue>[] currentValues = this.values; this.capacityIndex++; this.capacity = (this.capacityIndex >= capacities.Length) ? this.capacity * 2 + 1 : capacities[this.capacityIndex]; this.Clear(); // Add all the items in this dictionary to the enlarged dictionary lists. for (int slotIdx = currentKeys.Length - 1; slotIdx >= 0; slotIdx--) { List<TKey> currentKeySlot = currentKeys[slotIdx]; if (currentKeySlot != null) { List<TValue> currentValueSlot = currentValues[slotIdx]; for (int listIdx = currentKeySlot.Count - 1; listIdx >= 0; listIdx--) { this.Add(currentKeySlot[listIdx], currentValueSlot[listIdx], false); } } } // Reload these values, as they will have changed due to dictionary capacity resizing slot = GetSlot(key); keySlot = this.keys[slot]; } List<TValue> valueSlot; if (keySlot == null) { // There are no elements at this index, so create a new list for the element being added this.keys[slot] = keySlot = new List<TKey>(1); this.values[slot] = valueSlot = new List<TValue>(1); } else { valueSlot = this.values[slot]; } keySlot.Add(key); valueSlot.Add(value); } public TValue this[TKey key] { get { TValue value; if (this.TryGetValue(key, out value)) { return value; } throw new KeyNotFoundException(key.ToString()); } set { Add(key, value, true); } } public bool TryGetValue(TKey key, out TValue value) { if (key == null) { throw new ArgumentNullException(); } int slot = this.GetSlot(key); List<TKey> keySlot = this.keys[slot]; if (keySlot != null) { // Can't use keySlot.IndexOf() because it doesn't honour the comparer for (int i = keySlot.Count - 1; i >= 0; i--) { if (this.comparer.Equals(keySlot[i], key)) { value = this.values[slot][i]; return true; } } } value = default(TValue); return false; } public bool ContainsKey(TKey key) { TValue dummy; return (TryGetValue(key, out dummy)); } public bool ContainsValue(TValue value) { Enumerator e = new Enumerator(this); while (e.MoveNext()) { if (e.Current.Value.Equals(value)) { return true; } } return false; } public bool Remove(TKey key) { int slot = this.GetSlot(key); List<TKey> keySlot = this.keys[slot]; if (keySlot != null) { // Can't use keySlot.IndexOf() because it doesn't honour the comparer for (int i = keySlot.Count - 1; i >= 0; i--) { if (this.comparer.Equals(keySlot[i], key)) { keySlot.RemoveAt(i); this.values[slot].RemoveAt(i); this.count--; return true; } } } return false; } public IEqualityComparer<TKey> Comparer { get { return this.comparer; } } public int Count { get { return this.count; } } public KeyCollection Keys { get { return new KeyCollection(this); } } public ValueCollection Values { get { return new ValueCollection(this); } } public bool IsReadOnly { get { return false; } } public void Clear() { this.keys = new List<TKey>[this.capacity]; this.values = new List<TValue>[this.capacity]; this.count = 0; } public Enumerator GetEnumerator() { return new Enumerator(this); } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return Keys; } } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return Values; } } IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys { get { return Keys; } } IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values { get { return Values; } } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { this.Add(item.Key, item.Value); } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { return this.ContainsKey(item.Key); } void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { throw new Exception("The method or operation is not implemented."); } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { return this.Remove(item.Key); } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this); } public bool IsFixedSize { get { return false; } } object IDictionary.this[object key] { get { return this[(TKey)key]; } set { this[(TKey)key] = (TValue)value; } } ICollection IDictionary.Keys { get { return Keys; } } ICollection IDictionary.Values { get { return Values; } } void IDictionary.Add(object key, object value) { Add((TKey)key, (TValue)value); } bool IDictionary.Contains(object key) { return ContainsKey((TKey)key); } IDictionaryEnumerator IDictionary.GetEnumerator() { return new Enumerator(this); } void IDictionary.Remove(object key) { Remove((TKey)key); } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return this; } } public void CopyTo(Array array, int index) { throw new Exception("The method or operation is not implemented."); } } }
/* This version of ObjImporter first reads through the entire file, getting a count of how large * the final arrays will be, and then uses standard arrays for everything (as opposed to ArrayLists * or any other fancy things). */ using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; public class ObjImporter { private struct meshStruct { public Vector3[] vertices; public Vector3[] normals; public Vector2[] uv; public Vector2[] uv1; public Vector2[] uv2; public int[] triangles; public int[] faceVerts; public int[] faceUVs; public Vector3[] faceData; public string name; public string fileName; } // Use this for initialization public Mesh ImportFile (string filePath) { meshStruct newMesh = createMeshStruct(filePath); populateMeshStruct(ref newMesh); Vector3[] newVerts = new Vector3[newMesh.faceData.Length]; Vector2[] newUVs = new Vector2[newMesh.faceData.Length]; Vector3[] newNormals = new Vector3[newMesh.faceData.Length]; int i = 0; /* The following foreach loops through the facedata and assigns the appropriate vertex, uv, or normal * for the appropriate Unity mesh array. */ foreach (Vector3 v in newMesh.faceData) { newVerts[i] = newMesh.vertices[(int)v.x - 1]; if (v.y >= 1) newUVs[i] = newMesh.uv[(int)v.y - 1]; if (v.z >= 1) newNormals[i] = newMesh.normals[(int)v.z - 1]; i++; } Mesh mesh = new Mesh(); mesh.vertices = newVerts; mesh.uv = newUVs; mesh.normals = newNormals; mesh.triangles = newMesh.triangles; mesh.RecalculateBounds(); ; return mesh; } private static meshStruct createMeshStruct(string filename) { int triangles = 0; int vertices = 0; int vt = 0; int vn = 0; int face = 0; meshStruct mesh = new meshStruct(); mesh.fileName = filename; StreamReader stream = File.OpenText(filename); string entireText = stream.ReadToEnd(); stream.Close(); using (StringReader reader = new StringReader(entireText)) { string currentText = reader.ReadLine(); char[] splitIdentifier = { ' ' }; string[] brokenString; while (currentText != null) { if (!currentText.StartsWith("f ") && !currentText.StartsWith("v ") && !currentText.StartsWith("vt ") && !currentText.StartsWith("vn ")) { currentText = reader.ReadLine(); if (currentText != null) { currentText = currentText.Replace(" ", " "); } } else { currentText = currentText.Trim(); //Trim the current line brokenString = currentText.Split(splitIdentifier, 50); //Split the line into an array, separating the original line by blank spaces switch (brokenString[0]) { case "v": vertices++; break; case "vt": vt++; break; case "vn": vn++; break; case "f": face = face + brokenString.Length - 1; triangles = triangles + 3 * (brokenString.Length - 2); /*brokenString.Length is 3 or greater since a face must have at least 3 vertices. For each additional vertice, there is an additional triangle in the mesh (hence this formula).*/ break; } currentText = reader.ReadLine(); if (currentText != null) { currentText = currentText.Replace(" ", " "); } } } } mesh.triangles = new int[triangles]; mesh.vertices = new Vector3[vertices]; mesh.uv = new Vector2[vt]; mesh.normals = new Vector3[vn]; mesh.faceData = new Vector3[face]; return mesh; } private static void populateMeshStruct(ref meshStruct mesh) { StreamReader stream = File.OpenText(mesh.fileName); string entireText = stream.ReadToEnd(); stream.Close(); using (StringReader reader = new StringReader(entireText)) { string currentText = reader.ReadLine(); char[] splitIdentifier = { ' ' }; char[] splitIdentifier2 = { '/' }; string[] brokenString; string[] brokenBrokenString; int f = 0; int f2 = 0; int v = 0; int vn = 0; int vt = 0; int vt1 = 0; int vt2 = 0; while (currentText != null) { if (!currentText.StartsWith("f ") && !currentText.StartsWith("v ") && !currentText.StartsWith("vt ") && !currentText.StartsWith("vn ") && !currentText.StartsWith("g ") && !currentText.StartsWith("usemtl ") && !currentText.StartsWith("mtllib ") && !currentText.StartsWith("vt1 ") && !currentText.StartsWith("vt2 ") && !currentText.StartsWith("vc ") && !currentText.StartsWith("usemap ")) { currentText = reader.ReadLine(); if (currentText != null) { currentText = currentText.Replace(" ", " "); } } else { currentText = currentText.Trim(); brokenString = currentText.Split(splitIdentifier, 50); switch (brokenString[0]) { case "g": break; case "usemtl": break; case "usemap": break; case "mtllib": break; case "v": mesh.vertices[v] = new Vector3(System.Convert.ToSingle(brokenString[1]), System.Convert.ToSingle(brokenString[2]), System.Convert.ToSingle(brokenString[3])); v++; break; case "vt": mesh.uv[vt] = new Vector2(System.Convert.ToSingle(brokenString[1]), System.Convert.ToSingle(brokenString[2])); vt++; break; case "vt1": mesh.uv[vt1] = new Vector2(System.Convert.ToSingle(brokenString[1]), System.Convert.ToSingle(brokenString[2])); vt1++; break; case "vt2": mesh.uv[vt2] = new Vector2(System.Convert.ToSingle(brokenString[1]), System.Convert.ToSingle(brokenString[2])); vt2++; break; case "vn": mesh.normals[vn] = new Vector3(System.Convert.ToSingle(brokenString[1]), System.Convert.ToSingle(brokenString[2]), System.Convert.ToSingle(brokenString[3])); vn++; break; case "vc": break; case "f": int j = 1; List<int> intArray = new List<int>(); while (j < brokenString.Length && ("" + brokenString[j]).Length > 0) { Vector3 temp = new Vector3(); brokenBrokenString = brokenString[j].Split(splitIdentifier2, 3); //Separate the face into individual components (vert, uv, normal) temp.x = System.Convert.ToInt32(brokenBrokenString[0]); if (brokenBrokenString.Length > 1) //Some .obj files skip UV and normal { if (brokenBrokenString[1] != "") //Some .obj files skip the uv and not the normal { temp.y = System.Convert.ToInt32(brokenBrokenString[1]); } temp.z = System.Convert.ToInt32(brokenBrokenString[2]); } j++; mesh.faceData[f2] = temp; intArray.Add(f2); f2++; } j = 1; while (j + 2 < brokenString.Length) //Create triangles out of the face data. There will generally be more than 1 triangle per face. { mesh.triangles[f] = intArray[0]; f++; mesh.triangles[f] = intArray[j]; f++; mesh.triangles[f] = intArray[j+1]; f++; j++; } break; } currentText = reader.ReadLine(); if (currentText != null) { currentText = currentText.Replace(" ", " "); //Some .obj files insert double spaces, this removes them. } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using Signum.Utilities.Reflection; using System.Collections; using Signum.Utilities; using System.Runtime.Serialization; using System.Globalization; using System.ComponentModel; using Signum.Entities.Basics; using System.Linq.Expressions; namespace Signum.Entities.DynamicQuery { [Serializable] public class ResultColumn :ISerializable { Column column; public Column Column => column; int index; public int Index { get { return index; } internal set { index = value; } } IList values; public IList Values => values; public ResultColumn(Column column, IList values) { this.column = column; this.values = values; } #pragma warning disable CS8618, IDE0051 // Non-nullable field is uninitialized. ResultColumn(SerializationInfo info, StreamingContext context) { foreach (SerializationEntry entry in info) { switch (entry.Name) { case "column": column = (Column)entry.Value!; break; case "valuesList": values = (IList)entry.Value!; break; case "valuesString": values = Split((string)entry.Value!, GetValueDeserializer()); break; } } } #pragma warning restore CS8618, IDE0051 // Non-nullable field is uninitialized. GenericInvoker<Func<int, IList>> listBuilder = new GenericInvoker<Func<int, IList>>(num => new List<int>(num)); private IList Split(string concatenated, Func<string, object> deserialize) { string[] splitted = concatenated.Split('|'); IList result = listBuilder.GetInvoker(column.Type)(splitted.Length); for (int i = 1; i < splitted.Length - 1; i++) { string str = splitted[i]; if (string.IsNullOrEmpty(str)) result.Add(null); else result.Add(deserialize(str)); } return result; } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("column", column); Func<object, string>? serializer = GetValueSerializer(); if (serializer == null) info.AddValue("valuesList", values); else { string result = Join(values, serializer); info.AddValue("valuesString", result); } } static string Join(IList values, Func<object, string> serializer) { StringBuilder sb = new StringBuilder(); sb.Append('|'); foreach (var item in values) { if (item != null) sb.Append(serializer(item)); sb.Append('|'); } return sb.ToString(); } Func<string, object> GetValueDeserializer() { if (column.Type.IsLite()) { var type = column.Type.GetGenericArguments()[0]; return str => DeserializeLite(Decode(str), type); } if (column.Type == typeof(string)) return str => str == "&&" ? "&" : str == "&" ? "" : Decode(str); var uType = column.Type.UnNullify(); if (uType.IsEnum) { return str => Enum.ToObject(uType, int.Parse(str)); } switch (Type.GetTypeCode(uType)) { case TypeCode.Boolean: return str => str == "1"; case TypeCode.Byte: return str => Byte.Parse(str, CultureInfo.InvariantCulture); case TypeCode.Decimal: return str => Decimal.Parse(str, CultureInfo.InvariantCulture); case TypeCode.Double: return str => Double.Parse(str, CultureInfo.InvariantCulture); case TypeCode.Int16: return str => Int16.Parse(str, CultureInfo.InvariantCulture); case TypeCode.Int32: return str => Int32.Parse(str, CultureInfo.InvariantCulture); case TypeCode.Int64: return str => Int64.Parse(str, CultureInfo.InvariantCulture); case TypeCode.SByte: return str => SByte.Parse(str, CultureInfo.InvariantCulture); case TypeCode.Single: return str => Single.Parse(str, CultureInfo.InvariantCulture); case TypeCode.UInt16: return str => UInt16.Parse(str, CultureInfo.InvariantCulture); case TypeCode.UInt32: return str => UInt32.Parse(str, CultureInfo.InvariantCulture); case TypeCode.UInt64: return str => UInt32.Parse(str, CultureInfo.InvariantCulture); case TypeCode.DateTime: return str => DateTime.ParseExact(str, "O", CultureInfo.InvariantCulture); } throw new InvalidOperationException("Impossible to deserialize a ResultColumn of {0}".FormatWith(column.Type)); } Func<object, string>? GetValueSerializer() { if (column.Type.IsLite()) { var type = column.Type.GetGenericArguments()[0]; return obj => Encode(SerializeLite(obj, type)); } if (column.Type == typeof(string)) return obj => { string str = (string)obj; return str == "&" ? "&&" : str == "" ? "&" : Encode(str); }; if (column.Type.UnNullify().IsEnum) return obj => Convert.ChangeType(obj, typeof(int))!.ToString()!; switch (Type.GetTypeCode(column.Type.UnNullify())) { case TypeCode.Boolean: return obj => ((bool)obj) ? "1" : "0"; case TypeCode.Byte: case TypeCode.Decimal: case TypeCode.Double: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.SByte: case TypeCode.Single: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return obj => ((IFormattable)obj).ToString(null, CultureInfo.InvariantCulture); case TypeCode.DateTime: return obj => ((DateTime)obj).ToString("O", CultureInfo.InvariantCulture); } return null; } static string Encode(string p) { return p.Replace("{%%}", "{%%%}").Replace("|", "{%%}"); } static string Decode(string p) { return p.Replace("{%%}", "|").Replace("{%%%}", "{%%}"); } static string SerializeLite(object obj, Type defaultEntityType) { var lite = ((Lite<Entity>)obj); return lite.Id + ";" + (lite.EntityType == defaultEntityType ? null : TypeEntity.GetCleanName(lite.EntityType)) + ";" + lite.ToString(); } static object DeserializeLite(string str, Type defaultEntityType) { string idStr = str.Before(';'); string tmp = str.After(';'); string typeStr = tmp.Before(';'); string toStr = tmp.After(';'); Type type = string.IsNullOrEmpty(typeStr) ? defaultEntityType : TypeEntity.TryGetType(typeStr)!; return Lite.Create(type, PrimaryKey.Parse(idStr, type), toStr); } public override string ToString() => "Col" + this.Index + ": " + this.Column.ToString(); } [Serializable] public class ResultTable { internal ResultColumn? entityColumn; public ColumnDescription? EntityColumn { get { return entityColumn == null ? null : ((ColumnToken)entityColumn.Column.Token).Column; } } public bool HasEntities { get { return entityColumn != null; } } ResultColumn[] columns; public ResultColumn[] Columns { get { return columns; } } [NonSerialized] ResultRow[] rows; public ResultRow[] Rows { get { return rows; } } public ResultTable(ResultColumn[] columns, int? totalElements, Pagination pagination) { this.entityColumn = columns.Where(c => c.Column is _EntityColumn).SingleOrDefaultEx(); this.columns = columns.Where(c => !(c.Column is _EntityColumn) && c.Column.Token.IsAllowed() == null).ToArray(); int rowCount = columns.Select(a => a.Values.Count).Distinct().SingleEx(() => "Count"); for (int i = 0; i < Columns.Length; i++) Columns[i].Index = i; this.rows = 0.To(rowCount).Select(i => new ResultRow(i, this)).ToArray(); this.totalElements = totalElements; this.pagination = pagination; } //[OnDeserialized] //private void OnDeserialized(StreamingContext context) //{ // CreateIndices(columns); //} public DataTable ToDataTable(DataTableValueConverter? converter = null) { var defConverter = converter ?? new InvariantDataTableValueConverter(); DataTable dt = new DataTable("Table"); dt.Columns.AddRange(Columns.Select(c => new DataColumn(c.Column.Name, defConverter.ConvertType(c.Column))).ToArray()); foreach (var row in Rows) { dt.Rows.Add(Columns.Select((c, i) => defConverter.ConvertValue(row[i], c.Column)).ToArray()); } return dt; } public DataTable ToDataTablePivot(int rowColumnIndex, int columnColumnIndex, int valueIndex, DataTableValueConverter? converter = null) { var defConverter = converter ?? new InvariantDataTableValueConverter(); string Null = "- NULL -"; Dictionary<object, Dictionary<object, object?>> dictionary = this.Rows .AgGroupToDictionary( row => row[rowColumnIndex] ?? Null, gr => gr.ToDictionaryEx( row => row[columnColumnIndex] ?? Null, row => row[valueIndex]) ); var allColumns = dictionary.Values.SelectMany(d => d.Keys).Distinct(); var rowColumn = this.Columns[rowColumnIndex]; var valueColumn = this.Columns[valueIndex]; var result = new DataTable(); result.Columns.Add(new DataColumn( rowColumn.Column.DisplayName, defConverter.ConvertType(rowColumn.Column))); foreach (var item in allColumns) result.Columns.Add(new DataColumn(item.ToString(), defConverter.ConvertType(valueColumn.Column))); foreach (var kvp in dictionary) { result.Rows.Add( allColumns.Select(val => defConverter.ConvertValue(kvp.Value.TryGetCN(val), valueColumn.Column)) .PreAnd(defConverter.ConvertValue(kvp.Key, rowColumn.Column)) .ToArray()); } return result; } int? totalElements; public int? TotalElements { get { return totalElements; } } Pagination pagination; public Pagination Pagination { get { return pagination; } } public int? TotalPages { get { return Pagination is Pagination.Paginate ? ((Pagination.Paginate)Pagination).TotalPages(TotalElements!.Value) : (int?)null; } } public int? StartElementIndex { get { return Pagination is Pagination.Paginate ? ((Pagination.Paginate)Pagination).StartElementIndex() : (int?)null; } } public int? EndElementIndex { get { return Pagination is Pagination.Paginate ? ((Pagination.Paginate)Pagination).EndElementIndex(Rows.Count()) : (int?)null; } } } public abstract class DataTableValueConverter { public abstract Type ConvertType(Column column); public abstract object? ConvertValue(object? value, Column column); } public class NiceDataTableValueConverter : DataTableValueConverter { public override Type ConvertType(Column column) { var type = column.Type; if (type.IsLite()) return typeof(string); if (type.UnNullify().IsEnum) return typeof(string); if (type.UnNullify() == typeof(DateTime) && column.Format != "g") return typeof(string); return type.UnNullify(); } public override object? ConvertValue(object? value, Column column) { if (value is Lite<Entity>) return ((Lite<Entity>)value).ToString(); if (value is Enum) return ((Enum)value).NiceToString(); if (value is DateTime && column.Token.Format != "g") return ((DateTime)value).ToString(column.Token.Format); return value; } } public class InvariantDataTableValueConverter : NiceDataTableValueConverter { public override Type ConvertType(Column column) { var type = column.Token.Type; if (type.IsLite()) return typeof(string); if (type.UnNullify().IsEnum) return typeof(string); return type.UnNullify(); } public override object? ConvertValue(object? value, Column column) { var type = column.Token.Type; if (value is Lite<Entity>) return ((Lite<Entity>)value).KeyLong(); if (value is Enum) return ((Enum)value).ToString(); return value; } } [Serializable] public class ResultRow : INotifyPropertyChanged { public readonly int Index; public readonly ResultTable Table; bool isDirty; public bool IsDirty { get { return isDirty; } set { isDirty = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsDirty")); } } public object? this[int columnIndex] { get { return Table.Columns[columnIndex].Values[Index]; } } public object? this[ResultColumn column] { get { return column.Values[Index]; } } internal ResultRow(int index, ResultTable table) { this.Index = index; this.Table = table; } public Lite<Entity> Entity { get { return (Lite<Entity>)Table.entityColumn!.Values[Index]!; } } public Lite<Entity>? TryEntity { get { return Table.entityColumn == null ? null : (Lite<Entity>?)Table.entityColumn.Values[Index]; } } public T GetValue<T>(string columnName) { return (T)this[Table.Columns.Where(c => c.Column.Name == columnName).SingleEx(() => columnName)]!; } public T GetValue<T>(int columnIndex) { return (T)this[columnIndex]!; } public T GetValue<T>(ResultColumn column) { return (T)this[column]!; } public object?[] GetValues(ResultColumn[] columnArray) { var result = new object?[columnArray.Length]; for (int i = 0; i < columnArray.Length; i++) { result[i] = this[columnArray[i]]; } return result; } public event PropertyChangedEventHandler? PropertyChanged; } }
using System; namespace MonoBrick.NXT { /// <summary> /// McMotor class /// </summary> public class McMotor : Motor { private enum MotorControlMode{ HoldBrake = 0x01, SpeedRegulation = 0x02, SmoothStart = 0x04 } private MotorControlMotorPort mcPort = MotorControlMotorPort.PortA; private MotorControlProxy mcProxy = null; internal MotorControlMotorPort MCPort{ get{ return mcPort;} set{ mcPort = value;} } internal MotorControlProxy MCProxy{ get{ return mcProxy;} set{ mcProxy = value;} } /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.Motor"/> class. /// </summary> public McMotor() {} /// <summary> /// Move the motor to a relative position /// </summary> /// <param name='speed'> /// Speed of the motor -100 to 100 /// </param> /// <param name='degrees'> /// The relative position of the motor /// </param> new public void On(sbyte speed, UInt32 degrees){ On (speed,degrees,false, false); } /// <summary> /// Move the motor to a relative position /// </summary> /// <param name='speed'> /// Speed of the motor -100 to 100 /// </param> /// <param name='degrees'> /// The relative position of the motor /// </param> /// <param name='reply'> /// If set to <c>true</c> the brick will send a reply /// </param> new public void On(sbyte speed, UInt32 degrees, bool reply){ On (speed,degrees,false, reply); } /// <summary> /// Move the motor to a relative position /// </summary> /// <param name='speed'> /// Speed of the motor -100 to 100 /// </param> /// <param name='degrees'> /// The relative position of the motor /// </param> /// <param name='hold'> /// If set to <c>true</c> the motor will actively /// hold the position after finishing. /// </param> /// <param name='reply'> /// If set to <c>true</c> the brick will send a reply /// </param> public void On (sbyte speed, UInt32 degrees, bool hold, bool reply) { if (degrees == 0) { base.On (speed, degrees, reply); } if (speed > 100) speed = 100; if (speed < -100) speed = -100; int speedTemp = speed; if (speedTemp < 0) speedTemp = 100 - speedTemp; string powerMotorControl = speedTemp.ToString ().PadLeft (3, '0'); // Translate tachoLimit to MotorControl-format. long tachoLimit = System.Math.Abs(degrees); string tachoLimitMotorControl = tachoLimit.ToString ().PadLeft (6, '0'); // Call MotorControl. char mode = '6'; if (hold) { mode = '7'; } mcProxy.SendControlledMotorCommand(mcPort, powerMotorControl, tachoLimitMotorControl, mode); } /// <summary> /// Moves the motor to an absolute position /// </summary> /// <param name='speed'> /// Speed of the motor 0 to 100 /// </param> /// <param name='position'> /// Absolute position /// </param> /// <param name='hold'> /// If set to <c>true</c> the motor will actively /// hold the position after finishing. /// </param> /// <param name='reply'> /// If set to <c>true</c> the brick will send a reply /// </param> public void MoveTo(byte speed, Int32 position, bool hold, bool reply){ Int32 move = position - GetTachoCount(); if (speed > 100) speed = 100; //if (speed < -100) speed = -100; int speedTemp = (move > 0 ? speed : -speed); if (speedTemp < 0) speedTemp = 100 - speedTemp; string powerMotorControl = speedTemp.ToString().PadLeft(3, '0'); // Translate position to MotorControl-format. string tachoLimitMotorControl = System.Math.Abs(move).ToString().PadLeft(6, '0'); // Call MotorControl. char mode = '6'; if (hold) { mode = '7'; } mcProxy.SendControlledMotorCommand(mcPort, powerMotorControl, tachoLimitMotorControl, mode); } /// <summary> /// Moves the motor to an absolute position /// </summary> /// <param name='speed'> /// Speed of the motor -100 to 100 /// </param> /// <param name='position'> /// Absolute position /// </param> new public void MoveTo(byte speed, Int32 position){ MoveTo(speed,position, false, false); } /// <summary> /// Moves the motor to an absolute position /// </summary> /// <param name='speed'> /// Speed of the motor -100 to 100 /// </param> /// <param name='position'> /// Absolute position /// </param> /// <param name='reply'> /// If set to <c>true</c> the brick will send a reply /// </param> new public void MoveTo(byte speed, Int32 position, bool reply){ MoveTo(speed,position, false, reply); } /// <summary> /// Determines whether this motor is running. /// </summary> /// <returns> /// <c>true</c> if this motor is running; otherwise, <c>false</c>. /// </returns> new public bool IsRunning() { return !mcProxy.IsMotorReady(mcPort); } } /// <summary> /// Mc sync motor. /// </summary> public class McSyncMotor { private enum MotorControlMode{ HoldBrake = 0x01, SpeedRegulation = 0x02, SmoothStart = 0x04 } private MotorControlMotorPort mcPort = MotorControlMotorPort.PortsAB; private MotorControlProxy mcProxy = null; internal MotorControlMotorPort MCPort{ get{ return mcPort;} set{ mcPort = value;} } internal MotorControlProxy MCProxy{ get{ return mcProxy;} set{ mcProxy = value;} } /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.Motor"/> class. /// </summary> public McSyncMotor() {} /// <summary> /// Move the motor to a relative position /// </summary> /// <param name='speed'> /// Speed of the motor -100 to 100 /// </param> /// <param name='degrees'> /// The relative position of the motor /// </param> public void On(sbyte speed, UInt32 degrees){ On (speed,degrees,false, false); } /// <summary> /// Move the motor to a relative position /// </summary> /// <param name='speed'> /// Speed of the motor -100 to 100 /// </param> /// <param name='degrees'> /// The relative position of the motor /// </param> /// <param name='reply'> /// If set to <c>true</c> the brick will send a reply /// </param> public void On(sbyte speed, UInt32 degrees, bool reply){ On (speed,degrees,false, reply); } /// <summary> /// Move the motor to a relative position /// </summary> /// <param name='speed'> /// Speed of the motor -100 to 100 /// </param> /// <param name='degrees'> /// The relative position of the motor /// </param> /// <param name='hold'> /// If set to <c>true</c> the motor will actively /// hold the position after finishing. /// </param> /// <param name='reply'> /// If set to <c>true</c> the brick will send a reply /// </param> public void On (sbyte speed, UInt32 degrees, bool hold, bool reply) { if (degrees == 0) { //TODO: Throw exception } if (speed > 100) speed = 100; if (speed < -100) speed = -100; int speedTemp = speed; if (speedTemp < 0) speedTemp = 100 - speedTemp; string powerMotorControl = speedTemp.ToString ().PadLeft (3, '0'); // Translate tachoLimit to MotorControl-format. long tachoLimit = System.Math.Abs(degrees); string tachoLimitMotorControl = tachoLimit.ToString ().PadLeft (6, '0'); // Call MotorControl. char mode = '6'; if (hold) { mode = '7'; } mcProxy.SendControlledMotorCommand(mcPort, powerMotorControl, tachoLimitMotorControl, mode); } /// <summary> /// Determines whether this motor is running. /// </summary> /// <returns> /// <c>true</c> if this motor is running; otherwise, <c>false</c>. /// </returns> public bool IsRunning() { return !mcProxy.IsMotorReady(mcPort); } } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: api@infopluscommerce.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// JobType /// </summary> [DataContract] public partial class JobType : IEquatable<JobType> { /// <summary> /// Initializes a new instance of the <see cref="JobType" /> class. /// </summary> [JsonConstructorAttribute] protected JobType() { } /// <summary> /// Initializes a new instance of the <see cref="JobType" /> class. /// </summary> /// <param name="Name">Name (required).</param> /// <param name="Description">Description.</param> /// <param name="JobCode">JobCode.</param> /// <param name="IsActive">IsActive (default to false).</param> public JobType(string Name = null, string Description = null, string JobCode = null, bool? IsActive = null) { // to ensure "Name" is required (not null) if (Name == null) { throw new InvalidDataException("Name is a required property for JobType and cannot be null"); } else { this.Name = Name; } this.Description = Description; this.JobCode = JobCode; // use default value if no "IsActive" provided if (IsActive == null) { this.IsActive = false; } else { this.IsActive = IsActive; } } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public int? Id { get; private set; } /// <summary> /// Gets or Sets ClientId /// </summary> [DataMember(Name="clientId", EmitDefaultValue=false)] public int? ClientId { get; private set; } /// <summary> /// Gets or Sets CreateDate /// </summary> [DataMember(Name="createDate", EmitDefaultValue=false)] public DateTime? CreateDate { get; private set; } /// <summary> /// Gets or Sets ModifyDate /// </summary> [DataMember(Name="modifyDate", EmitDefaultValue=false)] public DateTime? ModifyDate { get; private set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets Description /// </summary> [DataMember(Name="description", EmitDefaultValue=false)] public string Description { get; set; } /// <summary> /// Gets or Sets JobCode /// </summary> [DataMember(Name="jobCode", EmitDefaultValue=false)] public string JobCode { get; set; } /// <summary> /// Gets or Sets IsActive /// </summary> [DataMember(Name="isActive", EmitDefaultValue=false)] public bool? IsActive { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class JobType {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" ClientId: ").Append(ClientId).Append("\n"); sb.Append(" CreateDate: ").Append(CreateDate).Append("\n"); sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Description: ").Append(Description).Append("\n"); sb.Append(" JobCode: ").Append(JobCode).Append("\n"); sb.Append(" IsActive: ").Append(IsActive).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as JobType); } /// <summary> /// Returns true if JobType instances are equal /// </summary> /// <param name="other">Instance of JobType to be compared</param> /// <returns>Boolean</returns> public bool Equals(JobType other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.ClientId == other.ClientId || this.ClientId != null && this.ClientId.Equals(other.ClientId) ) && ( this.CreateDate == other.CreateDate || this.CreateDate != null && this.CreateDate.Equals(other.CreateDate) ) && ( this.ModifyDate == other.ModifyDate || this.ModifyDate != null && this.ModifyDate.Equals(other.ModifyDate) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.Description == other.Description || this.Description != null && this.Description.Equals(other.Description) ) && ( this.JobCode == other.JobCode || this.JobCode != null && this.JobCode.Equals(other.JobCode) ) && ( this.IsActive == other.IsActive || this.IsActive != null && this.IsActive.Equals(other.IsActive) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.ClientId != null) hash = hash * 59 + this.ClientId.GetHashCode(); if (this.CreateDate != null) hash = hash * 59 + this.CreateDate.GetHashCode(); if (this.ModifyDate != null) hash = hash * 59 + this.ModifyDate.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.Description != null) hash = hash * 59 + this.Description.GetHashCode(); if (this.JobCode != null) hash = hash * 59 + this.JobCode.GetHashCode(); if (this.IsActive != null) hash = hash * 59 + this.IsActive.GetHashCode(); return hash; } } } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Cookie.cs // // 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. #pragma warning disable 1717 namespace Org.Apache.Http.Cookie { /// <summary> /// <para>Ths interface represents a cookie attribute handler responsible for parsing, validating, and matching a specific cookie attribute, such as path, domain, port, etc.</para><para>Different cookie specifications can provide a specific implementation for this class based on their cookie handling rules.</para><para><para> (Samit Jain)</para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/CookieAttributeHandler /// </java-name> [Dot42.DexImport("org/apache/http/cookie/CookieAttributeHandler", AccessFlags = 1537)] public partial interface ICookieAttributeHandler /* scope: __dot42__ */ { /// <summary> /// <para>Parse the given cookie attribute value and update the corresponding org.apache.http.cookie.Cookie property.</para><para></para> /// </summary> /// <java-name> /// parse /// </java-name> [Dot42.DexImport("parse", "(Lorg/apache/http/cookie/SetCookie;Ljava/lang/String;)V", AccessFlags = 1025)] void Parse(global::Org.Apache.Http.Cookie.ISetCookie cookie, string value) /* MethodBuilder.Create */ ; /// <summary> /// <para>Peforms cookie validation for the given attribute value.</para><para></para> /// </summary> /// <java-name> /// validate /// </java-name> [Dot42.DexImport("validate", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)V", AccessFlags = 1025)] void Validate(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ; /// <summary> /// <para>Matches the given value (property of the destination host where request is being submitted) with the corresponding cookie attribute.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the match is successful; <code>false</code> otherwise </para> /// </returns> /// <java-name> /// match /// </java-name> [Dot42.DexImport("match", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)Z", AccessFlags = 1025)] bool Match(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ; } /// <summary> /// <para>This interface represents a <code>SetCookie</code> response header sent by the origin server to the HTTP agent in order to maintain a conversational state.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/SetCookie /// </java-name> [Dot42.DexImport("org/apache/http/cookie/SetCookie", AccessFlags = 1537)] public partial interface ISetCookie : global::Org.Apache.Http.Cookie.ICookie /* scope: __dot42__ */ { /// <java-name> /// setValue /// </java-name> [Dot42.DexImport("setValue", "(Ljava/lang/String;)V", AccessFlags = 1025)] void SetValue(string value) /* MethodBuilder.Create */ ; /// <summary> /// <para>If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described using this comment.</para><para><para>getComment() </para></para> /// </summary> /// <java-name> /// setComment /// </java-name> [Dot42.DexImport("setComment", "(Ljava/lang/String;)V", AccessFlags = 1025)] void SetComment(string comment) /* MethodBuilder.Create */ ; /// <summary> /// <para>Sets expiration date. </para><para><b>Note:</b> the object returned by this method is considered immutable. Changing it (e.g. using setTime()) could result in undefined behaviour. Do so at your peril.</para><para><para>Cookie::getExpiryDate </para></para> /// </summary> /// <java-name> /// setExpiryDate /// </java-name> [Dot42.DexImport("setExpiryDate", "(Ljava/util/Date;)V", AccessFlags = 1025)] void SetExpiryDate(global::Java.Util.Date expiryDate) /* MethodBuilder.Create */ ; /// <summary> /// <para>Sets the domain attribute.</para><para><para>Cookie::getDomain </para></para> /// </summary> /// <java-name> /// setDomain /// </java-name> [Dot42.DexImport("setDomain", "(Ljava/lang/String;)V", AccessFlags = 1025)] void SetDomain(string domain) /* MethodBuilder.Create */ ; /// <summary> /// <para>Sets the path attribute.</para><para><para>Cookie::getPath </para></para> /// </summary> /// <java-name> /// setPath /// </java-name> [Dot42.DexImport("setPath", "(Ljava/lang/String;)V", AccessFlags = 1025)] void SetPath(string path) /* MethodBuilder.Create */ ; /// <summary> /// <para>Sets the secure attribute of the cookie. </para><para>When <code>true</code> the cookie should only be sent using a secure protocol (https). This should only be set when the cookie's originating server used a secure protocol to set the cookie's value.</para><para><para>isSecure() </para></para> /// </summary> /// <java-name> /// setSecure /// </java-name> [Dot42.DexImport("setSecure", "(Z)V", AccessFlags = 1025)] void SetSecure(bool secure) /* MethodBuilder.Create */ ; /// <summary> /// <para>Sets the version of the cookie specification to which this cookie conforms.</para><para><para>Cookie::getVersion </para></para> /// </summary> /// <java-name> /// setVersion /// </java-name> [Dot42.DexImport("setVersion", "(I)V", AccessFlags = 1025)] void SetVersion(int version) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Cookie specification registry that can be used to obtain the corresponding cookie specification implementation for a given type of type or version of cookie.</para><para><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/CookieSpecRegistry /// </java-name> [Dot42.DexImport("org/apache/http/cookie/CookieSpecRegistry", AccessFlags = 49)] public sealed partial class CookieSpecRegistry /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public CookieSpecRegistry() /* MethodBuilder.Create */ { } /// <summary> /// <para>Registers a CookieSpecFactory with the given identifier. If a specification with the given name already exists it will be overridden. This nameis the same one used to retrieve the CookieSpecFactory from getCookieSpec(String).</para><para><para>#getCookieSpec(String) </para></para> /// </summary> /// <java-name> /// register /// </java-name> [Dot42.DexImport("register", "(Ljava/lang/String;Lorg/apache/http/cookie/CookieSpecFactory;)V", AccessFlags = 33)] public void Register(string name, global::Org.Apache.Http.Cookie.ICookieSpecFactory factory) /* MethodBuilder.Create */ { } /// <summary> /// <para>Unregisters the CookieSpecFactory with the given ID.</para><para></para> /// </summary> /// <java-name> /// unregister /// </java-name> [Dot42.DexImport("unregister", "(Ljava/lang/String;)V", AccessFlags = 33)] public void Unregister(string id) /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets the cookie specification with the given ID.</para><para></para> /// </summary> /// <returns> /// <para>cookie specification</para> /// </returns> /// <java-name> /// getCookieSpec /// </java-name> [Dot42.DexImport("getCookieSpec", "(Ljava/lang/String;Lorg/apache/http/params/HttpParams;)Lorg/apache/http/cookie/Co" + "okieSpec;", AccessFlags = 33)] public global::Org.Apache.Http.Cookie.ICookieSpec GetCookieSpec(string name, global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Cookie.ICookieSpec); } /// <summary> /// <para>Gets the cookie specification with the given name.</para><para></para> /// </summary> /// <returns> /// <para>cookie specification</para> /// </returns> /// <java-name> /// getCookieSpec /// </java-name> [Dot42.DexImport("getCookieSpec", "(Ljava/lang/String;)Lorg/apache/http/cookie/CookieSpec;", AccessFlags = 33)] public global::Org.Apache.Http.Cookie.ICookieSpec GetCookieSpec(string name) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Cookie.ICookieSpec); } /// <summary> /// <para>Obtains a list containing names of all registered cookie specs in their default order.</para><para>Note that the DEFAULT policy (if present) is likely to be the same as one of the other policies, but does not have to be.</para><para></para> /// </summary> /// <returns> /// <para>list of registered cookie spec names </para> /// </returns> /// <java-name> /// getSpecNames /// </java-name> [Dot42.DexImport("getSpecNames", "()Ljava/util/List;", AccessFlags = 33, Signature = "()Ljava/util/List<Ljava/lang/String;>;")] public global::Java.Util.IList<string> GetSpecNames() /* MethodBuilder.Create */ { return default(global::Java.Util.IList<string>); } /// <summary> /// <para>Populates the internal collection of registered cookie specs with the content of the map passed as a parameter.</para><para></para> /// </summary> /// <java-name> /// setItems /// </java-name> [Dot42.DexImport("setItems", "(Ljava/util/Map;)V", AccessFlags = 33, Signature = "(Ljava/util/Map<Ljava/lang/String;Lorg/apache/http/cookie/CookieSpecFactory;>;)V")] public void SetItems(global::Java.Util.IMap<string, global::Org.Apache.Http.Cookie.ICookieSpecFactory> map) /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains a list containing names of all registered cookie specs in their default order.</para><para>Note that the DEFAULT policy (if present) is likely to be the same as one of the other policies, but does not have to be.</para><para></para> /// </summary> /// <returns> /// <para>list of registered cookie spec names </para> /// </returns> /// <java-name> /// getSpecNames /// </java-name> public global::Java.Util.IList<string> SpecNames { [Dot42.DexImport("getSpecNames", "()Ljava/util/List;", AccessFlags = 33, Signature = "()Ljava/util/List<Ljava/lang/String;>;")] get{ return GetSpecNames(); } } } /// <summary> /// <para>This interface represents a <code>SetCookie2</code> response header sent by the origin server to the HTTP agent in order to maintain a conversational state.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/SetCookie2 /// </java-name> [Dot42.DexImport("org/apache/http/cookie/SetCookie2", AccessFlags = 1537)] public partial interface ISetCookie2 : global::Org.Apache.Http.Cookie.ISetCookie /* scope: __dot42__ */ { /// <summary> /// <para>If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described by the information at this URL. </para> /// </summary> /// <java-name> /// setCommentURL /// </java-name> [Dot42.DexImport("setCommentURL", "(Ljava/lang/String;)V", AccessFlags = 1025)] void SetCommentURL(string commentURL) /* MethodBuilder.Create */ ; /// <summary> /// <para>Sets the Port attribute. It restricts the ports to which a cookie may be returned in a Cookie request header. </para> /// </summary> /// <java-name> /// setPorts /// </java-name> [Dot42.DexImport("setPorts", "([I)V", AccessFlags = 1025)] void SetPorts(int[] ports) /* MethodBuilder.Create */ ; /// <summary> /// <para>Set the Discard attribute.</para><para>Note: <code>Discard</code> attribute overrides <code>Max-age</code>.</para><para><para>isPersistent() </para></para> /// </summary> /// <java-name> /// setDiscard /// </java-name> [Dot42.DexImport("setDiscard", "(Z)V", AccessFlags = 1025)] void SetDiscard(bool discard) /* MethodBuilder.Create */ ; } /// <summary> /// <para>HTTP "magic-cookie" represents a piece of state information that the HTTP agent and the target server can exchange to maintain a session.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/Cookie /// </java-name> [Dot42.DexImport("org/apache/http/cookie/Cookie", AccessFlags = 1537)] public partial interface ICookie /* scope: __dot42__ */ { /// <summary> /// <para>Returns the name.</para><para></para> /// </summary> /// <returns> /// <para>String name The name </para> /// </returns> /// <java-name> /// getName /// </java-name> [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1025)] string GetName() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the value.</para><para></para> /// </summary> /// <returns> /// <para>String value The current value. </para> /// </returns> /// <java-name> /// getValue /// </java-name> [Dot42.DexImport("getValue", "()Ljava/lang/String;", AccessFlags = 1025)] string GetValue() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the comment describing the purpose of this cookie, or <code>null</code> if no such comment has been defined.</para><para></para> /// </summary> /// <returns> /// <para>comment </para> /// </returns> /// <java-name> /// getComment /// </java-name> [Dot42.DexImport("getComment", "()Ljava/lang/String;", AccessFlags = 1025)] string GetComment() /* MethodBuilder.Create */ ; /// <summary> /// <para>If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described by the information at this URL. </para> /// </summary> /// <java-name> /// getCommentURL /// </java-name> [Dot42.DexImport("getCommentURL", "()Ljava/lang/String;", AccessFlags = 1025)] string GetCommentURL() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the expiration Date of the cookie, or <code>null</code> if none exists. </para><para><b>Note:</b> the object returned by this method is considered immutable. Changing it (e.g. using setTime()) could result in undefined behaviour. Do so at your peril. </para><para></para> /// </summary> /// <returns> /// <para>Expiration Date, or <code>null</code>. </para> /// </returns> /// <java-name> /// getExpiryDate /// </java-name> [Dot42.DexImport("getExpiryDate", "()Ljava/util/Date;", AccessFlags = 1025)] global::Java.Util.Date GetExpiryDate() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns <code>false</code> if the cookie should be discarded at the end of the "session"; <code>true</code> otherwise.</para><para></para> /// </summary> /// <returns> /// <para><code>false</code> if the cookie should be discarded at the end of the "session"; <code>true</code> otherwise </para> /// </returns> /// <java-name> /// isPersistent /// </java-name> [Dot42.DexImport("isPersistent", "()Z", AccessFlags = 1025)] bool IsPersistent() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns domain attribute of the cookie.</para><para></para> /// </summary> /// <returns> /// <para>the value of the domain attribute </para> /// </returns> /// <java-name> /// getDomain /// </java-name> [Dot42.DexImport("getDomain", "()Ljava/lang/String;", AccessFlags = 1025)] string GetDomain() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the path attribute of the cookie</para><para></para> /// </summary> /// <returns> /// <para>The value of the path attribute. </para> /// </returns> /// <java-name> /// getPath /// </java-name> [Dot42.DexImport("getPath", "()Ljava/lang/String;", AccessFlags = 1025)] string GetPath() /* MethodBuilder.Create */ ; /// <summary> /// <para>Get the Port attribute. It restricts the ports to which a cookie may be returned in a Cookie request header. </para> /// </summary> /// <java-name> /// getPorts /// </java-name> [Dot42.DexImport("getPorts", "()[I", AccessFlags = 1025)] int[] GetPorts() /* MethodBuilder.Create */ ; /// <summary> /// <para>Indicates whether this cookie requires a secure connection.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if this cookie should only be sent over secure connections, <code>false</code> otherwise. </para> /// </returns> /// <java-name> /// isSecure /// </java-name> [Dot42.DexImport("isSecure", "()Z", AccessFlags = 1025)] bool IsSecure() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the version of the cookie specification to which this cookie conforms.</para><para></para> /// </summary> /// <returns> /// <para>the version of the cookie. </para> /// </returns> /// <java-name> /// getVersion /// </java-name> [Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)] int GetVersion() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns true if this cookie has expired. </para> /// </summary> /// <returns> /// <para><code>true</code> if the cookie has expired. </para> /// </returns> /// <java-name> /// isExpired /// </java-name> [Dot42.DexImport("isExpired", "(Ljava/util/Date;)Z", AccessFlags = 1025)] bool IsExpired(global::Java.Util.Date date) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Constants and static helpers related to the HTTP state management.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/SM /// </java-name> [Dot42.DexImport("org/apache/http/cookie/SM", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class ISMConstants /* scope: __dot42__ */ { /// <java-name> /// COOKIE /// </java-name> [Dot42.DexImport("COOKIE", "Ljava/lang/String;", AccessFlags = 25)] public const string COOKIE = "Cookie"; /// <java-name> /// COOKIE2 /// </java-name> [Dot42.DexImport("COOKIE2", "Ljava/lang/String;", AccessFlags = 25)] public const string COOKIE2 = "Cookie2"; /// <java-name> /// SET_COOKIE /// </java-name> [Dot42.DexImport("SET_COOKIE", "Ljava/lang/String;", AccessFlags = 25)] public const string SET_COOKIE = "Set-Cookie"; /// <java-name> /// SET_COOKIE2 /// </java-name> [Dot42.DexImport("SET_COOKIE2", "Ljava/lang/String;", AccessFlags = 25)] public const string SET_COOKIE2 = "Set-Cookie2"; } /// <summary> /// <para>Constants and static helpers related to the HTTP state management.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/SM /// </java-name> [Dot42.DexImport("org/apache/http/cookie/SM", AccessFlags = 1537)] public partial interface ISM /* scope: __dot42__ */ { } /// <summary> /// <para>Signals that a cookie is in some way invalid or illegal in a given context</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/MalformedCookieException /// </java-name> [Dot42.DexImport("org/apache/http/cookie/MalformedCookieException", AccessFlags = 33)] public partial class MalformedCookieException : global::Org.Apache.Http.ProtocolException /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new MalformedCookieException with a <code>null</code> detail message. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public MalformedCookieException() /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new MalformedCookieException with a specified message string.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public MalformedCookieException(string message) /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new MalformedCookieException with the specified detail message and cause.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)] public MalformedCookieException(string message, global::System.Exception cause) /* MethodBuilder.Create */ { } } /// <summary> /// <para>CookieOrigin class incapsulates details of an origin server that are relevant when parsing, validating or matching HTTP cookies.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/CookieOrigin /// </java-name> [Dot42.DexImport("org/apache/http/cookie/CookieOrigin", AccessFlags = 49)] public sealed partial class CookieOrigin /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Ljava/lang/String;ILjava/lang/String;Z)V", AccessFlags = 1)] public CookieOrigin(string host, int port, string path, bool secure) /* MethodBuilder.Create */ { } /// <java-name> /// getHost /// </java-name> [Dot42.DexImport("getHost", "()Ljava/lang/String;", AccessFlags = 1)] public string GetHost() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getPath /// </java-name> [Dot42.DexImport("getPath", "()Ljava/lang/String;", AccessFlags = 1)] public string GetPath() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getPort /// </java-name> [Dot42.DexImport("getPort", "()I", AccessFlags = 1)] public int GetPort() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// isSecure /// </java-name> [Dot42.DexImport("isSecure", "()Z", AccessFlags = 1)] public bool IsSecure() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal CookieOrigin() /* TypeBuilder.AddDefaultConstructor */ { } /// <java-name> /// getHost /// </java-name> public string Host { [Dot42.DexImport("getHost", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetHost(); } } /// <java-name> /// getPath /// </java-name> public string Path { [Dot42.DexImport("getPath", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetPath(); } } /// <java-name> /// getPort /// </java-name> public int Port { [Dot42.DexImport("getPort", "()I", AccessFlags = 1)] get{ return GetPort(); } } } /// <summary> /// <para>This cookie comparator can be used to compare identity of cookies.</para><para>Cookies are considered identical if their names are equal and their domain attributes match ignoring case. </para><para><para> </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/CookieIdentityComparator /// </java-name> [Dot42.DexImport("org/apache/http/cookie/CookieIdentityComparator", AccessFlags = 33, Signature = "Ljava/lang/Object;Ljava/io/Serializable;Ljava/util/Comparator<Lorg/apache/http/co" + "okie/Cookie;>;")] public partial class CookieIdentityComparator : global::Java.Io.ISerializable, global::Java.Util.IComparator<global::Org.Apache.Http.Cookie.ICookie> /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public CookieIdentityComparator() /* MethodBuilder.Create */ { } /// <java-name> /// compare /// </java-name> [Dot42.DexImport("compare", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/Cookie;)I", AccessFlags = 1)] public virtual int Compare(global::Org.Apache.Http.Cookie.ICookie c1, global::Org.Apache.Http.Cookie.ICookie c2) /* MethodBuilder.Create */ { return default(int); } [Dot42.DexImport("java/util/Comparator", "equals", "(Ljava/lang/Object;)Z", AccessFlags = 1025)] public override bool Equals(object @object) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(bool); } } /// <summary> /// <para>This cookie comparator ensures that multiple cookies satisfying a common criteria are ordered in the <code>Cookie</code> header such that those with more specific Path attributes precede those with less specific.</para><para>This comparator assumes that Path attributes of two cookies path-match a commmon request-URI. Otherwise, the result of the comparison is undefined. </para><para><para> </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/CookiePathComparator /// </java-name> [Dot42.DexImport("org/apache/http/cookie/CookiePathComparator", AccessFlags = 33, Signature = "Ljava/lang/Object;Ljava/io/Serializable;Ljava/util/Comparator<Lorg/apache/http/co" + "okie/Cookie;>;")] public partial class CookiePathComparator : global::Java.Io.ISerializable, global::Java.Util.IComparator<global::Org.Apache.Http.Cookie.ICookie> /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public CookiePathComparator() /* MethodBuilder.Create */ { } /// <java-name> /// compare /// </java-name> [Dot42.DexImport("compare", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/Cookie;)I", AccessFlags = 1)] public virtual int Compare(global::Org.Apache.Http.Cookie.ICookie c1, global::Org.Apache.Http.Cookie.ICookie c2) /* MethodBuilder.Create */ { return default(int); } [Dot42.DexImport("java/util/Comparator", "equals", "(Ljava/lang/Object;)Z", AccessFlags = 1025)] public override bool Equals(object @object) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(bool); } } /// <summary> /// <para>ClientCookie extends the standard Cookie interface with additional client specific functionality such ability to retrieve original cookie attributes exactly as they were specified by the origin server. This is important for generating the <code>Cookie</code> header because some cookie specifications require that the <code>Cookie</code> header should include certain attributes only if they were specified in the <code>Set-Cookie</code> header.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/ClientCookie /// </java-name> [Dot42.DexImport("org/apache/http/cookie/ClientCookie", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IClientCookieConstants /* scope: __dot42__ */ { /// <java-name> /// VERSION_ATTR /// </java-name> [Dot42.DexImport("VERSION_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string VERSION_ATTR = "version"; /// <java-name> /// PATH_ATTR /// </java-name> [Dot42.DexImport("PATH_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string PATH_ATTR = "path"; /// <java-name> /// DOMAIN_ATTR /// </java-name> [Dot42.DexImport("DOMAIN_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string DOMAIN_ATTR = "domain"; /// <java-name> /// MAX_AGE_ATTR /// </java-name> [Dot42.DexImport("MAX_AGE_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_AGE_ATTR = "max-age"; /// <java-name> /// SECURE_ATTR /// </java-name> [Dot42.DexImport("SECURE_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string SECURE_ATTR = "secure"; /// <java-name> /// COMMENT_ATTR /// </java-name> [Dot42.DexImport("COMMENT_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string COMMENT_ATTR = "comment"; /// <java-name> /// EXPIRES_ATTR /// </java-name> [Dot42.DexImport("EXPIRES_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string EXPIRES_ATTR = "expires"; /// <java-name> /// PORT_ATTR /// </java-name> [Dot42.DexImport("PORT_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string PORT_ATTR = "port"; /// <java-name> /// COMMENTURL_ATTR /// </java-name> [Dot42.DexImport("COMMENTURL_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string COMMENTURL_ATTR = "commenturl"; /// <java-name> /// DISCARD_ATTR /// </java-name> [Dot42.DexImport("DISCARD_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string DISCARD_ATTR = "discard"; } /// <summary> /// <para>ClientCookie extends the standard Cookie interface with additional client specific functionality such ability to retrieve original cookie attributes exactly as they were specified by the origin server. This is important for generating the <code>Cookie</code> header because some cookie specifications require that the <code>Cookie</code> header should include certain attributes only if they were specified in the <code>Set-Cookie</code> header.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/ClientCookie /// </java-name> [Dot42.DexImport("org/apache/http/cookie/ClientCookie", AccessFlags = 1537)] public partial interface IClientCookie : global::Org.Apache.Http.Cookie.ICookie /* scope: __dot42__ */ { /// <java-name> /// getAttribute /// </java-name> [Dot42.DexImport("getAttribute", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1025)] string GetAttribute(string name) /* MethodBuilder.Create */ ; /// <java-name> /// containsAttribute /// </java-name> [Dot42.DexImport("containsAttribute", "(Ljava/lang/String;)Z", AccessFlags = 1025)] bool ContainsAttribute(string name) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Defines the cookie management specification. </para><para>Cookie management specification must define <ul><li><para>rules of parsing "Set-Cookie" header </para></li><li><para>rules of validation of parsed cookies </para></li><li><para>formatting of "Cookie" header </para></li></ul>for a given host, port and path of origin</para><para><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/CookieSpec /// </java-name> [Dot42.DexImport("org/apache/http/cookie/CookieSpec", AccessFlags = 1537)] public partial interface ICookieSpec /* scope: __dot42__ */ { /// <summary> /// <para>Returns version of the state management this cookie specification conforms to.</para><para></para> /// </summary> /// <returns> /// <para>version of the state management specification </para> /// </returns> /// <java-name> /// getVersion /// </java-name> [Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)] int GetVersion() /* MethodBuilder.Create */ ; /// <summary> /// <para>Parse the <code>"Set-Cookie"</code> Header into an array of Cookies.</para><para>This method will not perform the validation of the resultant Cookies</para><para><para>validate</para></para> /// </summary> /// <returns> /// <para>an array of <code>Cookie</code>s parsed from the header </para> /// </returns> /// <java-name> /// parse /// </java-name> [Dot42.DexImport("parse", "(Lorg/apache/http/Header;Lorg/apache/http/cookie/CookieOrigin;)Ljava/util/List;", AccessFlags = 1025, Signature = "(Lorg/apache/http/Header;Lorg/apache/http/cookie/CookieOrigin;)Ljava/util/List<Lo" + "rg/apache/http/cookie/Cookie;>;")] global::Java.Util.IList<global::Org.Apache.Http.Cookie.ICookie> Parse(global::Org.Apache.Http.IHeader header, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ; /// <summary> /// <para>Validate the cookie according to validation rules defined by the cookie specification.</para><para></para> /// </summary> /// <java-name> /// validate /// </java-name> [Dot42.DexImport("validate", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)V", AccessFlags = 1025)] void Validate(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ; /// <summary> /// <para>Determines if a Cookie matches the target location.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the cookie should be submitted with a request with given attributes, <code>false</code> otherwise. </para> /// </returns> /// <java-name> /// match /// </java-name> [Dot42.DexImport("match", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)Z", AccessFlags = 1025)] bool Match(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ; /// <summary> /// <para>Create <code>"Cookie"</code> headers for an array of Cookies.</para><para></para> /// </summary> /// <returns> /// <para>a Header for the given Cookies. </para> /// </returns> /// <java-name> /// formatCookies /// </java-name> [Dot42.DexImport("formatCookies", "(Ljava/util/List;)Ljava/util/List;", AccessFlags = 1025, Signature = "(Ljava/util/List<Lorg/apache/http/cookie/Cookie;>;)Ljava/util/List<Lorg/apache/ht" + "tp/Header;>;")] global::Java.Util.IList<global::Org.Apache.Http.IHeader> FormatCookies(global::Java.Util.IList<global::Org.Apache.Http.Cookie.ICookie> cookies) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns a request header identifying what version of the state management specification is understood. May be <code>null</code> if the cookie specification does not support <code>Cookie2</code> header. </para> /// </summary> /// <java-name> /// getVersionHeader /// </java-name> [Dot42.DexImport("getVersionHeader", "()Lorg/apache/http/Header;", AccessFlags = 1025)] global::Org.Apache.Http.IHeader GetVersionHeader() /* MethodBuilder.Create */ ; } /// <summary> /// <para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/CookieSpecFactory /// </java-name> [Dot42.DexImport("org/apache/http/cookie/CookieSpecFactory", AccessFlags = 1537)] public partial interface ICookieSpecFactory /* scope: __dot42__ */ { /// <java-name> /// newInstance /// </java-name> [Dot42.DexImport("newInstance", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/cookie/CookieSpec;", AccessFlags = 1025)] global::Org.Apache.Http.Cookie.ICookieSpec NewInstance(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ ; } }
using System; using System.ComponentModel; using System.Net; namespace Hydra.Framework.AsyncSockets { // //********************************************************************** /// <summary> /// <c>ServerInfo</c> class describs the location of the server on the net and /// the port it's listens to. /// </summary> //********************************************************************** // public sealed class ServerInfo : System.IDisposable { #region Private Member Variables // //********************************************************************** /// <summary> /// Indicated whether the server's location is valid or not(not testing port number). /// </summary> //********************************************************************** // private readonly bool m_IsLegal; // //********************************************************************** /// <summary> /// Holds all the server location and port data. /// </summary> //********************************************************************** // private IPEndPoint m_ServerPoint; /// <summary> /// Server IP Address Construct /// </summary> private IPAddress m_ServerAddress; /// <summary> /// Port Number for the Server /// </summary> private int m_ServerPort; // //********************************************************************** /// <summary> /// Indicator for the type of the server. /// </summary> //********************************************************************** // private bool m_IsServer; #endregion #region Constructors // //********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="T:ServerInfo"/> class. /// </summary> //********************************************************************** // public ServerInfo() { } #endregion #region Public properties // //********************************************************************** /// <summary> /// Gets a value indicating whether this instance is legal. /// </summary> /// <value><c>true</c> if this instance is legal; otherwise, <c>false</c>.</value> //********************************************************************** // [Category("Misc"), Description("Indicates whether the server is legal.")] public bool IsLegal { get { return m_IsLegal; } } // //********************************************************************** /// <summary> /// Gets all the servers location and port data. /// </summary> /// <value>The server end point.</value> //********************************************************************** // [Category("Data"), Description("Gets all the server location and port data.")] public IPEndPoint ServerEndPoint { get { return m_ServerPoint; } } // //********************************************************************** /// <summary> /// Gets the port number that the server listens to. /// </summary> /// <value>The port numner.</value> //********************************************************************** // [Category("Data"), Description("Gets the port number that the server listens to.")] public int PortNumner { get { return m_ServerPort; } } // //********************************************************************** /// <summary> /// Gets the IP address of the server. /// </summary> /// <value>The IP address.</value> //********************************************************************** // [Category("Data"), Description("Gets the IP address of the server.")] public IPAddress IPAddress { get { return m_ServerAddress; } } // //********************************************************************** /// <summary> /// Gets the IP address of the server. /// </summary> /// <value>The IP.</value> //********************************************************************** // [Category("Data"), Description("Gets the IP address of the server.")] public string IP { get { return m_ServerAddress.ToString(); } } // //********************************************************************** /// <summary> /// Indicates if the server is of <c>Server</c> type. /// </summary> /// <value><c>true</c> if this instance is server; otherwise, <c>false</c>.</value> //********************************************************************** // [Category("Misc"), Description("Indicates if the server is of Server type.")] public bool IsServer { get { return m_IsServer; } } #endregion #region public functions // //********************************************************************** /// <summary> /// Creates new instance of <c>ServerInfo</c> object. /// </summary> /// <param name="ServerLocation">The <c>IPEndPoint</c> of the server.</param> /// <param name="IsServer">Is the server is a <c>Server</c> type.</param> //********************************************************************** // public ServerInfo(IPEndPoint ServerLocation, bool IsServer) { try { m_ServerPoint = ServerLocation; Dns.Resolve(ServerLocation.Address.ToString()); m_IsLegal = true; } catch (Exception) { m_IsLegal = false; } finally { m_IsServer = IsServer; } } // //********************************************************************** /// <summary> /// Creates new instance of <c>ServerInfo</c> object. /// </summary> /// <param name="ServerIP">The IP of the server machine or /// the name of the machine (on local neteork).</param> /// <param name="PortNumber">The port number that the server listen on.</param> /// <param name="IsServer">Is the server is a <c>Server</c> type.</param> //********************************************************************** // public ServerInfo(String ServerIP, int PortNumber, bool IsServer) { try { IPAddress[] list = Dns.GetHostAddresses(ServerIP); if (list != null && list.Length > 0) m_ServerAddress = list[0]; m_ServerPort = PortNumber; m_ServerPoint = new IPEndPoint(Dns.Resolve(ServerIP).AddressList[0], PortNumber); m_IsLegal = true; } catch (Exception) { m_IsLegal = false; } finally { m_IsServer = IsServer; } } // //********************************************************************** /// <summary> /// Creates new instance of <c>ServerInfo</c> object. /// </summary> /// <param name="ServerIP">The IP of the server machine.</param> /// <param name="PortNumber">The port number that the server listen on.</param> /// <param name="IsServer">Is the server is a <c>Server</c> type.</param> //********************************************************************** // public ServerInfo(IPAddress ServerIP, int PortNumber, bool IsServer) { try { m_ServerPoint = new IPEndPoint(Dns.Resolve(ServerIP.ToString()).AddressList[0], PortNumber); m_IsLegal = true; } catch (Exception) { m_IsLegal = false; } finally { m_IsServer = IsServer; } } // //********************************************************************** /// <summary> /// Returns the string representation of the object. /// </summary> /// <returns>string representation of the object.</returns> //********************************************************************** // public override string ToString() { return (this.IP + " on port " + this.PortNumner); } #endregion #region IDisposable Implementation // //********************************************************************** /// <summary> /// Releases resources. /// </summary> //********************************************************************** // public void Dispose() { m_ServerPoint = null; } #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; using Xunit.Abstractions; using System.IO; using System.Xml.Schema; namespace System.Xml.Tests { //[TestCase(Name = "TC_SchemaSet_Includes", Desc = "")] public class TC_SchemaSet_Includes : TC_SchemaSetBase { private ITestOutputHelper _output; public TC_SchemaSet_Includes(ITestOutputHelper output) { _output = output; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v1.6 - Include: A(ns-a) include B(ns-a) which includes C(ns-a) ", Priority = 2, Params = new object[] { "include_v7_a.xsd", 1, "ns-a:e3" })] [InlineData("include_v7_a.xsd", 1, "ns-a:e3")] //[Variation(Desc = "v1.5 - Include: A with NS includes B and C with no NS", Priority = 2, Params = new object[] { "include_v6_a.xsd", 1, "ns-a:e3" })] [InlineData("include_v6_a.xsd", 1, "ns-a:e3")] //[Variation(Desc = "v1.4 - Include: A with NS includes B and C with no NS, B also includes C", Priority = 2, Params = new object[] { "include_v5_a.xsd", 1, "ns-a:e3" })] [InlineData("include_v5_a.xsd", 1, "ns-a:e3")] //[Variation(Desc = "v1.3 - Include: A with NS includes B with no NS, which includes C with no NS", Priority = 2, Params = new object[] { "include_v4_a.xsd", 1, "ns-a:c-e2" })] [InlineData("include_v4_a.xsd", 1, "ns-a:c-e2")] //[Variation(Desc = "v1.2 - Include: A with no NS includes B with no NS", Priority = 0, Params = new object[] { "include_v3_a.xsd", 1, "e2" })] [InlineData("include_v3_a.xsd", 1, "e2")] //[Variation(Desc = "v1.1 - Include: A with NS includes B with no NS", Priority = 0, Params = new object[] { "include_v1_a.xsd", 1, "ns-a:e2" })] [InlineData("include_v1_a.xsd", 1, "ns-a:e2")] [Theory] public void v1(object param0, object param1, object param2) { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); XmlSchema schema = sc.Add(null, Path.Combine(TestData._Root, param0.ToString())); // param as filename CError.Compare(sc.Count, param1, "AddCount"); //compare the count CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); sc.Compile(); CError.Compare(sc.IsCompiled, true, "IsCompiled"); CError.Compare(sc.Count, param1, "Count"); // Check that B's data is present in the NS for A foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals(param2.ToString())) return; Assert.True(false); } //----------------------------------------------------------------------------------- //[Variation(Desc = "v2 - Include: A with NS includes B with a diff NS (INVALID)", Priority = 1)] [InlineData()] [Theory] public void v2() { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); XmlSchema schema = new XmlSchema(); sc.Add(null, TestData._XsdNoNs); CError.Compare(sc.Count, 1, "AddCount"); CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); sc.Compile(); CError.Compare(sc.IsCompiled, true, "IsCompiled"); CError.Compare(sc.Count, 1, "Count"); try { schema = sc.Add(null, Path.Combine(TestData._Root, "include_v2.xsd")); } catch (XmlSchemaException) { // no schema should be addded to the set. CError.Compare(sc.Count, 1, "Count"); CError.Compare(sc.IsCompiled, true, "IsCompiled"); return; } Assert.True(false); } //----------------------------------------------------------------------------------- //[Variation(Desc = "v3 - Include: A(ns-a) which includes B(ns-a) twice", Priority = 2)] [InlineData()] [Theory] public void v8() { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); int elem_count = 0; XmlSchema schema = sc.Add(null, Path.Combine(TestData._Root, "include_v8_a.xsd")); CError.Compare(sc.Count, 1, "AddCount"); CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); sc.Compile(); CError.Compare(sc.IsCompiled, true, "IsCompiled"); CError.Compare(sc.Count, 1, "Count"); // Check that C's data is present in A's NS foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("ns-a:e2")) elem_count++; CError.Compare(elem_count, 1, "ns-a:e2"); return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v4 - Include: A(ns-a) which includes B(No NS) twice", Priority = 2)] [InlineData()] [Theory] public void v9() { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); int elem_count = 0; XmlSchema schema = sc.Add(null, Path.Combine(TestData._Root, "include_v9_a.xsd")); CError.Compare(sc.Count, 1, "AddCount"); CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); sc.Compile(); CError.Compare(sc.Count, 1, "Count"); CError.Compare(sc.IsCompiled, true, "IsCompiled"); // Check that C's data is present in A's NS foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("ns-a:e2")) elem_count++; CError.Compare(elem_count, 1, "ns-a:e2"); return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v5 - Include: A,B,C all include each other, all with no ns and refer each others' types", Priority = 2)] [InlineData()] [Theory] public void v10() { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); int elem_count = 0; XmlSchema schema = sc.Add(null, Path.Combine(TestData._Root, "include_v10_a.xsd")); CError.Compare(sc.Count, 1, "AddCount"); CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); sc.Compile(); CError.Compare(sc.IsCompiled, true, "IsCompiled"); CError.Compare(sc.Count, 1, "Count"); // Check that C's data is present in A's NS foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("c-e2")) elem_count++; CError.Compare(elem_count, 1, "c-e2"); elem_count = 0; // Check that B's data is present in A's NS foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("b-e1")) elem_count++; CError.Compare(elem_count, 1, "b-e1"); return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v6 - Include: A,B,C all include each other, all with same ns and refer each others' types", Priority = 2)] [InlineData()] [Theory] public void v11() { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); int elem_count = 0; XmlSchema schema = sc.Add(null, Path.Combine(TestData._Root, "include_v11_a.xsd")); CError.Compare(sc.Count, 1, "AddCount"); CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); sc.Compile(); CError.Compare(sc.Count, 1, "Count"); CError.Compare(sc.IsCompiled, true, "IsCompiled"); // Check that A's data foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("ns-a:e1")) elem_count++; CError.Compare(elem_count, 1, "ns-a:e1"); elem_count = 0; // Check B's data foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("ns-a:e2")) elem_count++; CError.Compare(elem_count, 1, "ns-a:e2"); elem_count = 0; // Check C's data foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("ns-a:e3")) elem_count++; CError.Compare(elem_count, 1, "ns-a:e3"); return; } //[Variation(Desc = "v12 - 20008213 SOM: SourceUri property on a chameleon include is not set", Priority = 1)] [InlineData()] [Theory] public void v12() { bool succeeded = false; XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); XmlSchema a = ss.Add(null, Path.Combine(TestData._Root, "include_v12_a.xsd")); CError.Compare(ss.Count, 1, "AddCount"); CError.Compare(ss.IsCompiled, false, "AddIsCompiled"); ss.Compile(); CError.Compare(ss.Count, 1, "Count"); CError.Compare(ss.IsCompiled, true, "IsCompiled"); foreach (XmlSchemaExternal s in a.Includes) { if (String.IsNullOrEmpty(s.Schema.SourceUri)) { CError.Compare(false, "Unexpected null uri"); } else if (s.Schema.SourceUri.EndsWith("include_v12_b.xsd")) { succeeded = true; } } Assert.True(succeeded); } /******** reprocess compile include **********/ //[Variation(Desc = "v101.6 - Include: A(ns-a) include B(ns-a) which includes C(ns-a) ", Priority = 2, Params = new object[] { "include_v7_a.xsd", 1, "ns-a:e3" })] [InlineData("include_v7_a.xsd", 1, "ns-a:e3")] //[Variation(Desc = "v101.5 - Include: A with NS includes B and C with no NS", Priority = 2, Params = new object[] { "include_v6_a.xsd", 1, "ns-a:e3" })] [InlineData("include_v6_a.xsd", 1, "ns-a:e3")] //[Variation(Desc = "v101.4 - Include: A with NS includes B and C with no NS, B also includes C", Priority = 2, Params = new object[] { "include_v5_a.xsd", 1, "ns-a:e3" })] [InlineData("include_v5_a.xsd", 1, "ns-a:e3")] //[Variation(Desc = "v101.3 - Include: A with NS includes B with no NS, which includes C with no NS", Priority = 2, Params = new object[] { "include_v4_a.xsd", 1, "ns-a:c-e2" })] [InlineData("include_v4_a.xsd", 1, "ns-a:c-e2")] //[Variation(Desc = "v101.2 - Include: A with no NS includes B with no NS", Priority = 0, Params = new object[] { "include_v3_a.xsd", 1, "e2" })] [InlineData("include_v3_a.xsd", 1, "e2")] //[Variation(Desc = "v101.1 - Include: A with NS includes B with no NS", Priority = 0, Params = new object[] { "include_v1_a.xsd", 1, "ns-a:e2" })] [InlineData("include_v1_a.xsd", 1, "ns-a:e2")] [Theory] public void v101(object param0, object param1, object param2) { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); XmlSchema schema = sc.Add(null, Path.Combine(TestData._Root, param0.ToString())); // param as filename CError.Compare(sc.Count, param1, "AddCount"); //compare the count CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); sc.Reprocess(schema); CError.Compare(sc.IsCompiled, false, "ReprocessIsCompiled"); CError.Compare(sc.Count, param1, "ReprocessCount"); sc.Compile(); CError.Compare(sc.IsCompiled, true, "IsCompiled"); CError.Compare(sc.Count, param1, "Count"); // Check that B's data is present in the NS for A foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals(param2.ToString())) return; Assert.True(false); } //----------------------------------------------------------------------------------- //[Variation(Desc = "v102 - Include: A with NS includes B with a diff NS (INVALID)", Priority = 1)] [InlineData()] [Theory] public void v102() { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); XmlSchema schema = new XmlSchema(); sc.Add(null, TestData._XsdNoNs); CError.Compare(sc.Count, 1, "AddCount"); CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); try { sc.Reprocess(schema); Assert.True(false); } catch (ArgumentException) { } CError.Compare(sc.IsCompiled, false, "ReprocessIsCompiled"); CError.Compare(sc.Count, 1, "ReprocessCount"); sc.Compile(); CError.Compare(sc.IsCompiled, true, "IsCompiled"); CError.Compare(sc.Count, 1, "Count"); try { schema = sc.Add(null, Path.Combine(TestData._Root, "include_v2.xsd")); } catch (XmlSchemaException) { // no schema should be addded to the set. CError.Compare(sc.Count, 1, "Count"); CError.Compare(sc.IsCompiled, true, "IsCompiled"); try { sc.Reprocess(schema); Assert.True(false); } catch (ArgumentException) { } CError.Compare(sc.IsCompiled, true, "ReprocessIsCompiled"); CError.Compare(sc.Count, 1, "ReprocessCount"); return; } Assert.True(false); } //----------------------------------------------------------------------------------- //[Variation(Desc = "v103 - Include: A(ns-a) which includes B(ns-a) twice", Priority = 2)] [InlineData()] [Theory] public void v103() { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); int elem_count = 0; XmlSchema schema = sc.Add(null, Path.Combine(TestData._Root, "include_v8_a.xsd")); CError.Compare(sc.Count, 1, "AddCount"); CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); sc.Reprocess(schema); CError.Compare(sc.IsCompiled, false, "ReprocessIsCompiled"); CError.Compare(sc.Count, 1, "ReprocessCount"); sc.Compile(); CError.Compare(sc.IsCompiled, true, "IsCompiled"); CError.Compare(sc.Count, 1, "Count"); // Check that C's data is present in A's NS foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("ns-a:e2")) elem_count++; CError.Compare(elem_count, 1, "ns-a:e2"); return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v104 - Include: A(ns-a) which includes B(No NS) twice", Priority = 2)] [InlineData()] [Theory] public void v104() { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); int elem_count = 0; XmlSchema schema = sc.Add(null, Path.Combine(TestData._Root, "include_v9_a.xsd")); CError.Compare(sc.Count, 1, "AddCount"); CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); sc.Reprocess(schema); CError.Compare(sc.IsCompiled, false, "ReprocessIsCompiled"); CError.Compare(sc.Count, 1, "ReprocessCount"); sc.Compile(); CError.Compare(sc.Count, 1, "Count"); CError.Compare(sc.IsCompiled, true, "IsCompiled"); // Check that C's data is present in A's NS foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("ns-a:e2")) elem_count++; CError.Compare(elem_count, 1, "ns-a:e2"); return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v105 - Include: A,B,C all include each other, all with no ns and refer each others' types", Priority = 2)] [InlineData()] [Theory] public void v105() { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); int elem_count = 0; XmlSchema schema = sc.Add(null, Path.Combine(TestData._Root, "include_v10_a.xsd")); CError.Compare(sc.Count, 1, "AddCount"); CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); sc.Reprocess(schema); CError.Compare(sc.IsCompiled, false, "ReprocessIsCompiled"); CError.Compare(sc.Count, 1, "ReprocessCount"); sc.Compile(); CError.Compare(sc.IsCompiled, true, "IsCompiled"); CError.Compare(sc.Count, 1, "Count"); // Check that C's data is present in A's NS foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("c-e2")) elem_count++; CError.Compare(elem_count, 1, "c-e2"); elem_count = 0; // Check that B's data is present in A's NS foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("b-e1")) elem_count++; CError.Compare(elem_count, 1, "b-e1"); return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v106 - Include: A,B,C all include each other, all with same ns and refer each others' types", Priority = 2)] [InlineData()] [Theory] public void v106() { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); int elem_count = 0; XmlSchema schema = sc.Add(null, Path.Combine(TestData._Root, "include_v11_a.xsd")); CError.Compare(sc.Count, 1, "AddCount"); CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); sc.Reprocess(schema); CError.Compare(sc.IsCompiled, false, "ReprocessIsCompiled"); CError.Compare(sc.Count, 1, "ReprocessCount"); sc.Compile(); CError.Compare(sc.Count, 1, "Count"); CError.Compare(sc.IsCompiled, true, "IsCompiled"); // Check that A's data foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("ns-a:e1")) elem_count++; CError.Compare(elem_count, 1, "ns-a:e1"); elem_count = 0; // Check B's data foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("ns-a:e2")) elem_count++; CError.Compare(elem_count, 1, "ns-a:e2"); elem_count = 0; // Check C's data foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("ns-a:e3")) elem_count++; CError.Compare(elem_count, 1, "ns-a:e3"); return; } //[Variation(Desc = "v112 - 20008213 SOM: SourceUri property on a chameleon include is not set", Priority = 1)] [InlineData()] [Theory] public void v107() { bool succeeded = false; XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); XmlSchema a = ss.Add(null, Path.Combine(TestData._Root, "include_v12_a.xsd")); CError.Compare(ss.Count, 1, "AddCount"); CError.Compare(ss.IsCompiled, false, "AddIsCompiled"); ss.Reprocess(a); CError.Compare(ss.IsCompiled, false, "ReprocessIsCompiled"); CError.Compare(ss.Count, 1, "ReprocessCount"); ss.Compile(); CError.Compare(ss.Count, 1, "Count"); CError.Compare(ss.IsCompiled, true, "IsCompiled"); foreach (XmlSchemaExternal s in a.Includes) { if (String.IsNullOrEmpty(s.Schema.SourceUri)) { CError.Compare(false, "Unexpected null uri"); } else if (s.Schema.SourceUri.EndsWith("include_v12_b.xsd")) { succeeded = true; } } Assert.True(succeeded); } /******** compile reprocess include **********/ //[Variation(Desc = "v201.6 - Include: A(ns-a) include B(ns-a) which includes C(ns-a) ", Priority = 2, Params = new object[] { "include_v7_a.xsd", 1, "ns-a:e3" })] [InlineData("include_v7_a.xsd", 1, "ns-a:e3")] //[Variation(Desc = "v201.5 - Include: A with NS includes B and C with no NS", Priority = 2, Params = new object[] { "include_v6_a.xsd", 1, "ns-a:e3" })] [InlineData("include_v6_a.xsd", 1, "ns-a:e3")] //[Variation(Desc = "v201.4 - Include: A with NS includes B and C with no NS, B also includes C", Priority = 2, Params = new object[] { "include_v5_a.xsd", 1, "ns-a:e3" })] [InlineData("include_v5_a.xsd", 1, "ns-a:e3")] //[Variation(Desc = "v201.3 - Include: A with NS includes B with no NS, which includes C with no NS", Priority = 2, Params = new object[] { "include_v4_a.xsd", 1, "ns-a:c-e2" })] [InlineData("include_v4_a.xsd", 1, "ns-a:c-e2")] //[Variation(Desc = "v201.2 - Include: A with no NS includes B with no NS", Priority = 0, Params = new object[] { "include_v3_a.xsd", 1, "e2" })] [InlineData("include_v3_a.xsd", 1, "e2")] //[Variation(Desc = "v201.1 - Include: A with NS includes B with no NS", Priority = 0, Params = new object[] { "include_v1_a.xsd", 1, "ns-a:e2" })] [InlineData("include_v1_a.xsd", 1, "ns-a:e2")] [Theory] public void v201(object param0, object param1, object param2) { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); XmlSchema schema = sc.Add(null, Path.Combine(TestData._Root, param0.ToString())); // param as filename CError.Compare(sc.Count, param1, "AddCount"); //compare the count CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); sc.Compile(); CError.Compare(sc.IsCompiled, true, "IsCompiled"); CError.Compare(sc.Count, param1, "Count"); sc.Reprocess(schema); CError.Compare(sc.IsCompiled, false, "ReprocessIsCompiled"); CError.Compare(sc.Count, param1, "ReprocessCount"); // Check that B's data is present in the NS for A foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals(param2.ToString())) return; Assert.True(false); } //----------------------------------------------------------------------------------- //[Variation(Desc = "v202 - Include: A with NS includes B with a diff NS (INVALID)", Priority = 1)] [InlineData()] [Theory] public void v202() { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); XmlSchema schema = new XmlSchema(); sc.Add(null, TestData._XsdNoNs); CError.Compare(sc.Count, 1, "AddCount"); CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); sc.Compile(); CError.Compare(sc.IsCompiled, true, "IsCompiled"); CError.Compare(sc.Count, 1, "Count"); try { sc.Reprocess(schema); Assert.True(false); } catch (ArgumentException) { } CError.Compare(sc.IsCompiled, true, "ReprocessIsCompiled"); CError.Compare(sc.Count, 1, "ReprocessCount"); try { schema = sc.Add(null, Path.Combine(TestData._Root, "include_v2.xsd")); } catch (XmlSchemaException) { // no schema should be addded to the set. CError.Compare(sc.Count, 1, "Count"); CError.Compare(sc.IsCompiled, true, "IsCompiled"); try { sc.Reprocess(schema); Assert.True(false); } catch (ArgumentException) { } CError.Compare(sc.IsCompiled, true, "ReprocessIsCompiled"); CError.Compare(sc.Count, 1, "ReprocessCount"); return; } Assert.True(false); } //----------------------------------------------------------------------------------- //[Variation(Desc = "v203 - Include: A(ns-a) which includes B(ns-a) twice", Priority = 2)] [InlineData()] [Theory] public void v203() { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); int elem_count = 0; XmlSchema schema = sc.Add(null, Path.Combine(TestData._Root, "include_v8_a.xsd")); CError.Compare(sc.Count, 1, "AddCount"); CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); sc.Compile(); CError.Compare(sc.IsCompiled, true, "IsCompiled"); CError.Compare(sc.Count, 1, "Count"); sc.Reprocess(schema); CError.Compare(sc.IsCompiled, false, "ReprocessIsCompiled"); CError.Compare(sc.Count, 1, "ReprocessCount"); // Check that C's data is present in A's NS foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("ns-a:e2")) elem_count++; CError.Compare(elem_count, 1, "ns-a:e2"); return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v204 - Include: A(ns-a) which includes B(No NS) twice", Priority = 2)] [InlineData()] [Theory] public void v204() { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); int elem_count = 0; XmlSchema schema = sc.Add(null, Path.Combine(TestData._Root, "include_v9_a.xsd")); CError.Compare(sc.Count, 1, "AddCount"); CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); sc.Compile(); CError.Compare(sc.Count, 1, "Count"); CError.Compare(sc.IsCompiled, true, "IsCompiled"); sc.Reprocess(schema); CError.Compare(sc.IsCompiled, false, "ReprocessIsCompiled"); CError.Compare(sc.Count, 1, "ReprocessCount"); // Check that C's data is present in A's NS foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("ns-a:e2")) elem_count++; CError.Compare(elem_count, 1, "ns-a:e2"); return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v205 - Include: A,B,C all include each other, all with no ns and refer each others' types", Priority = 2)] [InlineData()] [Theory] public void v205() { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); int elem_count = 0; XmlSchema schema = sc.Add(null, Path.Combine(TestData._Root, "include_v10_a.xsd")); CError.Compare(sc.Count, 1, "AddCount"); CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); sc.Compile(); CError.Compare(sc.IsCompiled, true, "IsCompiled"); CError.Compare(sc.Count, 1, "Count"); sc.Reprocess(schema); CError.Compare(sc.IsCompiled, false, "ReprocessIsCompiled"); CError.Compare(sc.Count, 1, "ReprocessCount"); // Check that C's data is present in A's NS foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("c-e2")) elem_count++; CError.Compare(elem_count, 1, "c-e2"); elem_count = 0; // Check that B's data is present in A's NS foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("b-e1")) elem_count++; CError.Compare(elem_count, 1, "b-e1"); return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v206 - Include: A,B,C all include each other, all with same ns and refer each others' types", Priority = 2)] [InlineData()] [Theory] public void v206() { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); int elem_count = 0; XmlSchema schema = sc.Add(null, Path.Combine(TestData._Root, "include_v11_a.xsd")); CError.Compare(sc.Count, 1, "AddCount"); CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); sc.Compile(); CError.Compare(sc.Count, 1, "Count"); CError.Compare(sc.IsCompiled, true, "IsCompiled"); sc.Reprocess(schema); CError.Compare(sc.IsCompiled, false, "ReprocessIsCompiled"); CError.Compare(sc.Count, 1, "ReprocessCount"); // Check that A's data foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("ns-a:e1")) elem_count++; CError.Compare(elem_count, 1, "ns-a:e1"); elem_count = 0; // Check B's data foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("ns-a:e2")) elem_count++; CError.Compare(elem_count, 1, "ns-a:e2"); elem_count = 0; // Check C's data foreach (object obj in schema.Elements.Names) if ((obj.ToString()).Equals("ns-a:e3")) elem_count++; CError.Compare(elem_count, 1, "ns-a:e3"); return; } //[Variation(Desc = "v212 - 20008213 SOM: SourceUri property on a chameleon include is not set", Priority = 1)] [InlineData()] [Theory] public void v207() { bool succeeded = false; XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); XmlSchema a = ss.Add(null, Path.Combine(TestData._Root, "include_v12_a.xsd")); CError.Compare(ss.Count, 1, "AddCount"); CError.Compare(ss.IsCompiled, false, "AddIsCompiled"); ss.Compile(); CError.Compare(ss.Count, 1, "Count"); CError.Compare(ss.IsCompiled, true, "IsCompiled"); ss.Reprocess(a); CError.Compare(ss.IsCompiled, false, "ReprocessIsCompiled"); CError.Compare(ss.Count, 1, "ReprocessCount"); foreach (XmlSchemaExternal s in a.Includes) { if (String.IsNullOrEmpty(s.Schema.SourceUri)) { CError.Compare(false, "Unexpected null uri"); } else if (s.Schema.SourceUri.EndsWith("include_v12_b.xsd")) { succeeded = true; } } Assert.True(succeeded); } } }
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 Client.Main.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.ActionDescriptor.ReturnType; 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; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; #if SRM namespace System.Reflection.Metadata.Ecma335 #else namespace Roslyn.Reflection.Metadata.Ecma335 #endif { #if SRM public #endif static class CodedIndex { private static int ToCodedIndex(this int rowId, HasCustomAttribute tag) => (rowId << (int)HasCustomAttribute.__bits) | (int)tag; private static int ToCodedIndex(this int rowId, HasConstant tag) => (rowId << (int)HasConstant.__bits) | (int)tag; private static int ToCodedIndex(this int rowId, CustomAttributeType tag) => (rowId << (int)CustomAttributeType.__bits) | (int)tag; private static int ToCodedIndex(this int rowId, HasDeclSecurity tag) => (rowId << (int)HasDeclSecurity.__bits) | (int)tag; private static int ToCodedIndex(this int rowId, HasFieldMarshal tag) => (rowId << (int)HasFieldMarshal.__bits) | (int)tag; private static int ToCodedIndex(this int rowId, HasSemantics tag) => (rowId << (int)HasSemantics.__bits) | (int)tag; private static int ToCodedIndex(this int rowId, Implementation tag) => (rowId << (int)Implementation.__bits) | (int)tag; private static int ToCodedIndex(this int rowId, MemberForwarded tag) => (rowId << (int)MemberForwarded.__bits) | (int)tag; private static int ToCodedIndex(this int rowId, MemberRefParent tag) => (rowId << (int)MemberRefParent.__bits) | (int)tag; private static int ToCodedIndex(this int rowId, MethodDefOrRef tag) => (rowId << (int)MethodDefOrRef.__bits) | (int)tag; private static int ToCodedIndex(this int rowId, ResolutionScope tag) => (rowId << (int)ResolutionScope.__bits) | (int)tag; private static int ToCodedIndex(this int rowId, TypeDefOrRefOrSpec tag) => (rowId << (int)TypeDefOrRefOrSpec.__bits) | (int)tag; private static int ToCodedIndex(this int rowId, TypeOrMethodDef tag) => (rowId << (int)TypeOrMethodDef.__bits) | (int)tag; private static int ToCodedIndex(this int rowId, HasCustomDebugInformation tag) => (rowId << (int)HasCustomDebugInformation.__bits) | (int)tag; public static int ToHasCustomAttribute(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToHasCustomAttributeTag(handle.Kind)); public static int ToHasConstant(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToHasConstantTag(handle.Kind)); public static int ToCustomAttributeType(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToCustomAttributeTypeTag(handle.Kind)); public static int ToHasDeclSecurity(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToHasDeclSecurityTag(handle.Kind)); public static int ToHasFieldMarshal(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToHasFieldMarshalTag(handle.Kind)); public static int ToHasSemantics(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToHasSemanticsTag(handle.Kind)); public static int ToImplementation(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToImplementationTag(handle.Kind)); public static int ToMemberForwarded(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToMemberForwardedTag(handle.Kind)); public static int ToMemberRefParent(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToMemberRefParentTag(handle.Kind)); public static int ToMethodDefOrRef(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToMethodDefOrRefTag(handle.Kind)); public static int ToResolutionScope(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToResolutionScopeTag(handle.Kind)); public static int ToTypeDefOrRefOrSpec(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToTypeDefOrRefOrSpecTag(handle.Kind)); public static int ToTypeOrMethodDef(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToTypeOrMethodDefTag(handle.Kind)); public static int ToHasCustomDebugInformation(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToHasCustomDebugInformationTag(handle.Kind)); private enum HasCustomAttribute { MethodDef = 0, Field = 1, TypeRef = 2, TypeDef = 3, Param = 4, InterfaceImpl = 5, MemberRef = 6, Module = 7, DeclSecurity = 8, Property = 9, Event = 10, StandAloneSig = 11, ModuleRef = 12, TypeSpec = 13, Assembly = 14, AssemblyRef = 15, File = 16, ExportedType = 17, ManifestResource = 18, GenericParam = 19, GenericParamConstraint = 20, MethodSpec = 21, __bits = 5 } private static HasCustomAttribute ToHasCustomAttributeTag(HandleKind kind) { switch (kind) { case HandleKind.MethodDefinition: return HasCustomAttribute.MethodDef; case HandleKind.FieldDefinition: return HasCustomAttribute.Field; case HandleKind.TypeReference: return HasCustomAttribute.TypeRef; case HandleKind.TypeDefinition: return HasCustomAttribute.TypeDef; case HandleKind.Parameter: return HasCustomAttribute.Param; case HandleKind.InterfaceImplementation: return HasCustomAttribute.InterfaceImpl; case HandleKind.MemberReference: return HasCustomAttribute.MemberRef; case HandleKind.ModuleDefinition: return HasCustomAttribute.Module; case HandleKind.DeclarativeSecurityAttribute: return HasCustomAttribute.DeclSecurity; case HandleKind.PropertyDefinition: return HasCustomAttribute.Property; case HandleKind.EventDefinition: return HasCustomAttribute.Event; case HandleKind.StandaloneSignature: return HasCustomAttribute.StandAloneSig; case HandleKind.ModuleReference: return HasCustomAttribute.ModuleRef; case HandleKind.TypeSpecification: return HasCustomAttribute.TypeSpec; case HandleKind.AssemblyDefinition: return HasCustomAttribute.Assembly; case HandleKind.AssemblyReference: return HasCustomAttribute.AssemblyRef; case HandleKind.AssemblyFile: return HasCustomAttribute.File; case HandleKind.ExportedType: return HasCustomAttribute.ExportedType; case HandleKind.ManifestResource: return HasCustomAttribute.ManifestResource; case HandleKind.GenericParameter: return HasCustomAttribute.GenericParam; case HandleKind.GenericParameterConstraint: return HasCustomAttribute.GenericParamConstraint; case HandleKind.MethodSpecification: return HasCustomAttribute.MethodSpec; default: throw new ArgumentException($"Unexpected kind of handle: {kind}"); } } private enum HasConstant { Field = 0, Param = 1, Property = 2, __bits = 2, __mask = (1 << __bits) - 1 } private static HasConstant ToHasConstantTag(HandleKind kind) { switch (kind) { case HandleKind.FieldDefinition: return HasConstant.Field; case HandleKind.Parameter: return HasConstant.Param; case HandleKind.PropertyDefinition: return HasConstant.Property; default: throw new ArgumentException($"Unexpected kind of handle: {kind}"); } } private enum CustomAttributeType { MethodDef = 2, MemberRef = 3, __bits = 3 } private static CustomAttributeType ToCustomAttributeTypeTag(HandleKind kind) { switch (kind) { case HandleKind.MethodDefinition: return CustomAttributeType.MethodDef; case HandleKind.MemberReference: return CustomAttributeType.MemberRef; default: throw new ArgumentException($"Unexpected kind of handle: {kind}"); } } private enum HasDeclSecurity { TypeDef = 0, MethodDef = 1, Assembly = 2, __bits = 2, __mask = (1 << __bits) - 1 } private static HasDeclSecurity ToHasDeclSecurityTag(HandleKind kind) { switch (kind) { case HandleKind.TypeDefinition: return HasDeclSecurity.TypeDef; case HandleKind.MethodDefinition: return HasDeclSecurity.MethodDef; case HandleKind.AssemblyDefinition: return HasDeclSecurity.Assembly; default: throw new ArgumentException($"Unexpected kind of handle: {kind}"); } } private enum HasFieldMarshal { Field = 0, Param = 1, __bits = 1, __mask = (1 << __bits) - 1 } private static HasFieldMarshal ToHasFieldMarshalTag(HandleKind kind) { switch (kind) { case HandleKind.FieldDefinition: return HasFieldMarshal.Field; case HandleKind.Parameter: return HasFieldMarshal.Param; default: throw new ArgumentException($"Unexpected kind of handle: {kind}"); } } private enum HasSemantics { Event = 0, Property = 1, __bits = 1 } private static HasSemantics ToHasSemanticsTag(HandleKind kind) { switch (kind) { case HandleKind.EventDefinition: return HasSemantics.Event; case HandleKind.PropertyDefinition: return HasSemantics.Property; default: throw new ArgumentException($"Unexpected kind of handle: {kind}"); } } private enum Implementation { File = 0, AssemblyRef = 1, ExportedType = 2, __bits = 2 } private static Implementation ToImplementationTag(HandleKind kind) { switch (kind) { case HandleKind.AssemblyFile: return Implementation.File; case HandleKind.AssemblyReference: return Implementation.AssemblyRef; case HandleKind.ExportedType: return Implementation.ExportedType; default: throw new ArgumentException($"Unexpected kind of handle: {kind}"); } } private enum MemberForwarded { Field = 0, MethodDef = 1, __bits = 1 } private static MemberForwarded ToMemberForwardedTag(HandleKind kind) { switch (kind) { case HandleKind.FieldDefinition: return MemberForwarded.Field; case HandleKind.MethodDefinition: return MemberForwarded.MethodDef; default: throw new ArgumentException($"Unexpected kind of handle: {kind}"); } } private enum MemberRefParent { TypeDef = 0, TypeRef = 1, ModuleRef = 2, MethodDef = 3, TypeSpec = 4, __bits = 3 } private static MemberRefParent ToMemberRefParentTag(HandleKind kind) { switch (kind) { case HandleKind.TypeDefinition: return MemberRefParent.TypeDef; case HandleKind.TypeReference: return MemberRefParent.TypeRef; case HandleKind.ModuleReference: return MemberRefParent.ModuleRef; case HandleKind.MethodDefinition: return MemberRefParent.MethodDef; case HandleKind.TypeSpecification: return MemberRefParent.TypeSpec; default: throw new ArgumentException($"Unexpected kind of handle: {kind}"); } } private enum MethodDefOrRef { MethodDef = 0, MemberRef = 1, __bits = 1 } private static MethodDefOrRef ToMethodDefOrRefTag(HandleKind kind) { switch (kind) { case HandleKind.MethodDefinition: return MethodDefOrRef.MethodDef; case HandleKind.MemberReference: return MethodDefOrRef.MemberRef; default: throw new ArgumentException($"Unexpected kind of handle: {kind}"); } } private enum ResolutionScope { Module = 0, ModuleRef = 1, AssemblyRef = 2, TypeRef = 3, __bits = 2 } private static ResolutionScope ToResolutionScopeTag(HandleKind kind) { switch (kind) { case HandleKind.ModuleDefinition: return ResolutionScope.Module; case HandleKind.ModuleReference: return ResolutionScope.ModuleRef; case HandleKind.AssemblyReference: return ResolutionScope.AssemblyRef; case HandleKind.TypeReference: return ResolutionScope.TypeRef; default: throw new ArgumentException($"Unexpected kind of handle: {kind}"); } } private enum TypeDefOrRefOrSpec { TypeDef = 0, TypeRef = 1, TypeSpec = 2, __bits = 2 } private static TypeDefOrRefOrSpec ToTypeDefOrRefOrSpecTag(HandleKind kind) { switch (kind) { case HandleKind.TypeDefinition: return TypeDefOrRefOrSpec.TypeDef; case HandleKind.TypeReference: return TypeDefOrRefOrSpec.TypeRef; case HandleKind.TypeSpecification: return TypeDefOrRefOrSpec.TypeSpec; default: throw new ArgumentException($"Unexpected kind of handle: {kind}"); } } private enum TypeOrMethodDef { TypeDef = 0, MethodDef = 1, __bits = 1 } private static TypeOrMethodDef ToTypeOrMethodDefTag(HandleKind kind) { switch (kind) { case HandleKind.TypeDefinition: return TypeOrMethodDef.TypeDef; case HandleKind.MethodDefinition: return TypeOrMethodDef.MethodDef; default: throw new ArgumentException($"Unexpected kind of handle: {kind}"); } } private enum HasCustomDebugInformation { MethodDef = 0, Field = 1, TypeRef = 2, TypeDef = 3, Param = 4, InterfaceImpl = 5, MemberRef = 6, Module = 7, DeclSecurity = 8, Property = 9, Event = 10, StandAloneSig = 11, ModuleRef = 12, TypeSpec = 13, Assembly = 14, AssemblyRef = 15, File = 16, ExportedType = 17, ManifestResource = 18, GenericParam = 19, GenericParamConstraint = 20, MethodSpec = 21, Document = 22, LocalScope = 23, LocalVariable = 24, LocalConstant = 25, ImportScope = 26, __bits = 5 } private static HasCustomDebugInformation ToHasCustomDebugInformationTag(HandleKind kind) { switch (kind) { case HandleKind.MethodDefinition: return HasCustomDebugInformation.MethodDef; case HandleKind.FieldDefinition: return HasCustomDebugInformation.Field; case HandleKind.TypeReference: return HasCustomDebugInformation.TypeRef; case HandleKind.TypeDefinition: return HasCustomDebugInformation.TypeDef; case HandleKind.Parameter: return HasCustomDebugInformation.Param; case HandleKind.InterfaceImplementation: return HasCustomDebugInformation.InterfaceImpl; case HandleKind.MemberReference: return HasCustomDebugInformation.MemberRef; case HandleKind.ModuleDefinition: return HasCustomDebugInformation.Module; case HandleKind.DeclarativeSecurityAttribute: return HasCustomDebugInformation.DeclSecurity; case HandleKind.PropertyDefinition: return HasCustomDebugInformation.Property; case HandleKind.EventDefinition: return HasCustomDebugInformation.Event; case HandleKind.StandaloneSignature: return HasCustomDebugInformation.StandAloneSig; case HandleKind.ModuleReference: return HasCustomDebugInformation.ModuleRef; case HandleKind.TypeSpecification: return HasCustomDebugInformation.TypeSpec; case HandleKind.AssemblyDefinition: return HasCustomDebugInformation.Assembly; case HandleKind.AssemblyReference: return HasCustomDebugInformation.AssemblyRef; case HandleKind.AssemblyFile: return HasCustomDebugInformation.File; case HandleKind.ExportedType: return HasCustomDebugInformation.ExportedType; case HandleKind.ManifestResource: return HasCustomDebugInformation.ManifestResource; case HandleKind.GenericParameter: return HasCustomDebugInformation.GenericParam; case HandleKind.GenericParameterConstraint: return HasCustomDebugInformation.GenericParamConstraint; case HandleKind.MethodSpecification: return HasCustomDebugInformation.MethodSpec; case HandleKind.Document: return HasCustomDebugInformation.Document; case HandleKind.LocalScope: return HasCustomDebugInformation.LocalScope; case (HandleKind)0x33: return HasCustomDebugInformation.LocalVariable; // TODO case HandleKind.LocalConstant: return HasCustomDebugInformation.LocalConstant; case HandleKind.ImportScope: return HasCustomDebugInformation.ImportScope; default: throw new ArgumentException($"Unexpected kind of handle: {kind}"); } } } }
/** The new controller will go through a basic round robin free-inject&throttle test to obtain each application's sensitivity to throttling. The number of this test can be specified through config.apps_test_freq. If the application is not sensitive(small ipc differnece), it will be put into an always-throttled cluster. The old mechanism that divides applications into low and high cluster is still intact. The additional cluster is just the always throttled cluster. The controller tests the application sensitivity every several sampling periods(config.sampling_period_freq). **/ //#define DEBUG_NETUTIL //#define DEBUG #define DEBUG_CLUSTER #define DEBUG_CLUSTER2 using System; using System.Collections.Generic; namespace ICSimulator { public class Controller_Three_Level_Cluster: Controller_Adaptive_Cluster { public static int num_throttle_periods; public static int num_test_phases; public static bool isTestPhase; //nodes in these clusters are always throttled without given it a free injection slot! public static Cluster throttled_cluster; public static Cluster low_intensity_cluster; /* Stats for applications' sensitivity to throttling test */ public static double[] ipc_accum_diff=new double[Config.N]; //total ipc retired during every free injection slot public static double[] ipc_free=new double[Config.N]; public static double[] ipc_throttled=new double[Config.N]; public static ulong[] ins_free=new ulong[Config.N]; public static ulong[] ins_throttled=new ulong[Config.N]; public static int[] last_free_nodes=new int[Config.N]; //override the cluster_pool defined in Batch Controller! public static new UniformBatchClusterPool cluster_pool; string getName(int ID) { return Simulator.network.workload.getName(ID); } void writeNode(int ID) { Console.Write("{0} ({1}) ", ID, getName(ID)); } public Controller_Three_Level_Cluster() { isThrottling = false; for (int i = 0; i < Config.N; i++) { //initialization on stats for the test ipc_accum_diff[i]=0.0; ipc_free[i]=0.0; ipc_throttled[i]=0.0; ins_free[i]=0; ins_throttled[i]=0; last_free_nodes[i]=0; //test phase timing num_throttle_periods=0; num_test_phases=0; isTestPhase=false; MPKI[i]=0.0; num_ins_last_epoch[i]=0; m_isThrottled[i]=false; L1misses[i]=0; lastNetUtil = 0; } throttled_cluster=new Cluster(); low_intensity_cluster=new Cluster(); cluster_pool=new UniformBatchClusterPool(Config.cluster_MPKI_threshold); } public override void doThrottling() { //All nodes in the low intensity can alway freely inject. int [] low_nodes=low_intensity_cluster.allNodes(); if(low_nodes.Length>0 && isTestPhase==true) { low_intensity_cluster.printCluster(); throw new Exception("ERROR: Low nodes exist during sensitivity test phase."); } if(low_nodes.Length>0) { #if DEBUG_CLUSTER2 Console.WriteLine("\n:: cycle {0} ::", Simulator.CurrentRound); Console.Write("\nLow nodes *NOT* throttled: "); #endif foreach (int node in low_nodes) { #if DEBUG_CLUSTER2 writeNode(node); #endif setThrottleRate(node,false); m_nodeStates[node] = NodeState.Low; } } //Throttle all the high other nodes int [] high_nodes=cluster_pool.allNodes(); #if DEBUG_CLUSTER2 Console.Write("\nAll high other nodes: "); #endif foreach (int node in high_nodes) { #if DEBUG_CLUSTER2 writeNode(node); #endif setThrottleRate(node,true); m_nodeStates[node] = NodeState.HighOther; } //Unthrottle all the nodes in the free-injecting cluster int [] nodes=cluster_pool.nodesInNextCluster(); #if DEBUG_CLUSTER2 Console.Write("\nUnthrottling cluster nodes: "); #endif if(nodes.Length>0) { //Clear the vector for last free nodes Array.Clear(last_free_nodes,0,last_free_nodes.Length); foreach (int node in nodes) { ins_free[node]=(ulong)Simulator.stats.insns_persrc[node].Count; last_free_nodes[node]=1; setThrottleRate(node,false); m_nodeStates[node] = NodeState.HighGolden; Simulator.stats.throttle_time_bysrc[node].Add(); #if DEBUG_CLUSTER2 writeNode(node); #endif } } /* Throttle nodes in always throttled mode. */ int [] throttled_nodes=throttled_cluster.allNodes(); if(throttled_nodes.Length>0 && isTestPhase==true) { throttled_cluster.printCluster(); throw new Exception("ERROR: Throttled nodes exist during sensitivity test phase."); } if(throttled_nodes.Length>0) { #if DEBUG_CLUSTER2 Console.Write("\nAlways Throttled nodes: "); #endif foreach (int node in throttled_nodes) { setThrottleRate(node,true); //TODO: need another state for throttled throttled_nodes m_nodeStates[node] = NodeState.AlwaysThrottled; Simulator.stats.always_throttle_time_bysrc[node].Add(); #if DEBUG_CLUSTER2 writeNode(node); #endif } } #if DEBUG_CLUSTER2 Console.Write("\n*NOT* Throttled nodes: "); for(int i=0;i<Config.N;i++) if(!m_isThrottled[i]) writeNode(i); Console.Write("\n"); #endif } public void collectIPCDiff() { #if DEBUG_CLUSTER Console.WriteLine("\n***COLLECT IPC DIFF*** CYCLE{0}",Simulator.CurrentRound); #endif int free_inj_count=Config.throttle_sampling_period/Config.interval_length/Config.N; int throttled_inj_count=(Config.throttle_sampling_period/Config.interval_length)-free_inj_count; for(int i=0;i<Config.N;i++) { ipc_free[i]/=free_inj_count; ipc_throttled[i]/=throttled_inj_count; double temp_ipc_diff; if(ipc_free[i]==0) temp_ipc_diff=0; else temp_ipc_diff=(ipc_free[i]==0)?0:(ipc_free[i]-ipc_throttled[i])/ipc_throttled[i]; //record the % difference ipc_accum_diff[i]+=temp_ipc_diff; Simulator.stats.ipc_diff_bysrc[i].Add(temp_ipc_diff); #if DEBUG_CLUSTER Console.Write("id:"); writeNode(i); Console.WriteLine("ipc_free:{0} ipc_th:{1} ipc free gain:{2}%", ipc_free[i],ipc_throttled[i],(int)(temp_ipc_diff*100)); #endif //Reset //ipc_accum_diff[i]=0.0; ipc_free[i]=0.0; ipc_throttled[i]=0.0; ins_free[i]=0; ins_throttled[i]=0; last_free_nodes[i]=0; } } public void updateInsCount() { #if DEBUG_CLUSTER Console.WriteLine("***Update instructions count*** CYCLE{0}",Simulator.CurrentRound); #endif for(int node=0;node<Config.N;node++) { /* Calculate IPC during the last free-inject and throtttled interval */ if(ins_throttled[node]==0) ins_throttled[node]=(ulong)Simulator.stats.insns_persrc[node].Count; if(last_free_nodes[node]==1) { ulong ins_retired=(ulong)Simulator.stats.insns_persrc[node].Count-ins_free[node]; ipc_free[node]+=(double)ins_retired/Config.interval_length; #if DEBUG_CLUSTER Console.Write("Free calc: Node "); writeNode(node); Console.WriteLine(" w/ ins {0}->{2} retired {1}::IPC accum:{3}", ins_free[node],ins_retired,Simulator.stats.insns_persrc[node].Count, ipc_free[node]); #endif } else { ulong ins_retired=(ulong)Simulator.stats.insns_persrc[node].Count-ins_throttled[node]; ipc_throttled[node]+=(double)ins_retired/Config.interval_length; } ins_throttled[node]=(ulong)Simulator.stats.insns_persrc[node].Count; } } /* Need to have a better dostep function along with RR monitor phase. * Also need to change setthrottle and dothrottle*/ public override void doStep() { //Gather stats at the beginning of next sampling period. if(isTestPhase==true) { if (isThrottling && Simulator.CurrentRound > (ulong)Config.warmup_cyc && (Simulator.CurrentRound % (ulong)Config.interval_length) == 0) updateInsCount(); //Obtain the ipc difference between free injection and throttled. if (isThrottling && Simulator.CurrentRound > (ulong)Config.warmup_cyc && (Simulator.CurrentRound % (ulong)Config.throttle_sampling_period) == 0) collectIPCDiff(); } //sampling period: Examine the network state and determine whether to throttle or not if (Simulator.CurrentRound > (ulong)Config.warmup_cyc && (Simulator.CurrentRound % (ulong)Config.throttle_sampling_period) == 0) { setThrottling(); lastNetUtil = Simulator.stats.netutil.Total; resetStat(); } //once throttle mode is turned on. Let each cluster run for a certain time interval //to ensure fairness. Otherwise it's throttled most of the time. if (isThrottling && Simulator.CurrentRound > (ulong)Config.warmup_cyc && (Simulator.CurrentRound % (ulong)Config.interval_length) == 0) doThrottling(); } public override void setThrottling() { #if DEBUG_NETUTIL Console.Write("\n:: cycle {0} ::", Simulator.CurrentRound); #endif //get the MPKI value for (int i = 0; i < Config.N; i++) { prev_MPKI[i]=MPKI[i]; if(num_ins_last_epoch[i]==0) MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.insns_persrc[i].Count); else { if(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]>0) MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]); else if(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]==0) MPKI[i]=0; else throw new Exception("MPKI error!"); } } recordStats(); if(isThrottling) { double netutil=((double)(Simulator.stats.netutil.Total-lastNetUtil)/(double)Config.throttle_sampling_period); #if DEBUG_NETUTIL Console.WriteLine("In throttle mode: avg netUtil = {0} thres at {1}", netutil,Config.netutil_throttling_threshold); #endif /* TODO: * 1.If the netutil remains high, lower the threshold value for each cluster * to reduce the netutil further more and create a new pool/schedule for * all the clusters. How to raise it back? * Worst case: 1 app per cluster. * * 2.Find the difference b/w the current netutil and the threshold. * Then increase the throttle rate for each cluster based on that difference. * * 3.maybe add stalling clusters? * */ isThrottling=false; //un-throttle the network for(int i=0;i<Config.N;i++) setThrottleRate(i,false); //Clear all the clusters #if DEBUG_CLUSTER Console.WriteLine("cycle {0} ___Clear clusters___",Simulator.CurrentRound); #endif cluster_pool.removeAllClusters(); throttled_cluster.removeAllNodes(); low_intensity_cluster.removeAllNodes(); double diff=netutil-Config.netutil_throttling_threshold; //Option1: adjust the mpki thresh for each cluster //if netutil within range of 10% increase MPKI boundary for each cluster if(Config.adaptive_cluster_mpki) { double new_MPKI_thresh=cluster_pool.clusterThreshold(); if(diff<0.10) new_MPKI_thresh+=10; else if(diff>0.2) new_MPKI_thresh-=20; cluster_pool.changeThresh(new_MPKI_thresh); } //Option2: adjust the throttle rate // // //Use alpha*total_MPKI+base to find the optimal netutil for performance //0.5 is the baseline netutil threshold //0.03 is calculated empricically using some base cases to find this number b/w total_mpki and target netutil double total_mpki=0.0; for(int i=0;i<Config.N;i++) total_mpki+=MPKI[i]; double target_netutil=(0.03*total_mpki+50)/100; //50% baseline if(Config.alpha) { //within 2% range if(netutil<(0.98*target_netutil)) Config.RR_throttle_rate-=0.02; else if(netutil>(1.02*target_netutil)) if(Config.RR_throttle_rate<0.95)//max is 95% Config.RR_throttle_rate+=0.01; //if target is too high, only throttle max to 95% inj rate if(target_netutil>0.9) Config.RR_throttle_rate=0.95; } //Trying to force 60-70% netutil if(Config.adaptive_rate) { if(diff<0.1) Config.RR_throttle_rate-=0.02; else if(diff>0.2) if(Config.RR_throttle_rate<0.95) Config.RR_throttle_rate+=0.01; } #if DEBUG_NETUTIL Console.WriteLine("Netutil diff: {2}-{3}={1} New th rate:{0} New MPKI thresh: {6} Target netutil:{4} Total MPKI:{5}", Config.RR_throttle_rate,diff, netutil,Config.netutil_throttling_threshold,target_netutil,total_mpki,cluster_pool.clusterThreshold()); #endif Simulator.stats.total_th_rate.Add(Config.RR_throttle_rate); } #if DEBUG_CLUSTER Console.WriteLine("***SET THROTTLING Thresh trigger point*** CYCLE{0}",Simulator.CurrentRound); #endif //TODO: test phase can also reduce the mpki,so...might not have consecutive test phases if (thresholdTrigger()) // an abstract fn() that trigger whether to start throttling or not { #if DEBUG_CLUSTER Console.WriteLine("Congested!! Trigger throttling! isTest {0}, num th {1}, num samp {2}", isTestPhase,num_test_phases,num_throttle_periods); #endif #if DEBUG_CLUSTER Console.WriteLine("cycle {0} ___Clear clusters___",Simulator.CurrentRound); #endif cluster_pool.removeAllClusters(); throttled_cluster.removeAllNodes(); low_intensity_cluster.removeAllNodes(); ///////State Trasition //Initial state if(num_throttle_periods==0&&num_test_phases==0&&Config.use_ipc_delta) isTestPhase=true; //From test->cluster throttling if(isTestPhase && num_test_phases==Config.apps_test_freq) { isTestPhase=false; num_test_phases=0; } //From cluster throttling->test if(num_throttle_periods==Config.sampling_period_freq&&Config.use_ipc_delta) { //reset ipc_accum_diff for(int node_id=0;node_id<Config.N;node_id++) ipc_accum_diff[node_id]=0.0; isTestPhase=true; num_throttle_periods=0; } ///////Cluster Distribution if(isTestPhase==true) { num_test_phases++; //Add every node to high cluster int total_high = 0; double total_mpki=0.0; for (int i = 0; i < Config.N; i++) { total_mpki+=MPKI[i]; cluster_pool.addNewNodeUniform(i,MPKI[i]); total_high++; #if DEBUG Console.Write("#ON#:Node {0} with MPKI {1} ",i,MPKI[i]); #endif } Simulator.stats.total_sum_mpki.Add(total_mpki); #if DEBUG Console.WriteLine(")"); #endif //if no node needs to be throttled, set throttling to false isThrottling = (total_high>0)?true:false; #if DEBUG_CLUSTER cluster_pool.printClusterPool(); #endif } else { //Increment the number of throttle periods so that the test phase can kick back //in after certain number of throttle periods. num_throttle_periods++; List<int> sortedList = new List<int>(); double total_mpki=0.0; double small_mpki=0.0; double current_allow=0.0; int total_high=0; for(int i=0;i<Config.N;i++) { sortedList.Add(i); total_mpki+=MPKI[i]; //stats recording-see what's the total mpki composed by low/med apps if(MPKI[i]<=30) small_mpki+=MPKI[i]; } //sort by mpki sortedList.Sort(CompareByMpki); #if DEBUG_CLUSTER for(int i=0;i<Config.N;i++) Console.WriteLine("ID:{0} MPKI:{1}",sortedList[i],MPKI[sortedList[i]]); Console.WriteLine("*****total MPKI: {0}",total_mpki); Console.WriteLine("*****total MPKIs of apps with MPKI<30: {0}\n",small_mpki); #endif //find the first few apps that will be allowed to run freely without being throttled for(int list_index=0;list_index<Config.N;list_index++) { int node_id=sortedList[list_index]; //add the node that has no performance gain from free injection slot to //always throttled cluster. double ipc_avg_diff=ipc_accum_diff[node_id]/Config.apps_test_freq; #if DEBUG_CLUSTER Console.WriteLine("Node {0} with ipc diff {1}",node_id,ipc_avg_diff*100); #endif //If an application doesn't fit into one cluster, it will always be throttled if((Config.use_ipc_delta && ipc_avg_diff<Config.sensitivity_threshold) || (Config.use_cluster_threshold && MPKI[node_id]>Config.cluster_MPKI_threshold)) { #if DEBUG_CLUSTER Console.WriteLine("->Throttled node: {0}",node_id); #endif throttled_cluster.addNode(node_id,MPKI[node_id]); } else { if(withInRange(current_allow+MPKI[node_id],Config.free_total_MPKI)) { #if DEBUG_CLUSTER Console.WriteLine("->Low node: {0}",node_id); #endif low_intensity_cluster.addNode(node_id,MPKI[node_id]); current_allow+=MPKI[node_id]; continue; } else { #if DEBUG_CLUSTER Console.WriteLine("->High node: {0}",node_id); #endif cluster_pool.addNewNode(node_id,MPKI[node_id]); total_high++; } } } //randomly start a cluster to begin with instead of always the first one cluster_pool.randClusterId(); #if DEBUG_CLUSTER Console.WriteLine("total high: {0}\n",total_high); #endif //STATS Simulator.stats.allowed_sum_mpki.Add(current_allow); Simulator.stats.total_sum_mpki.Add(total_mpki); sortedList.Clear(); isThrottling = (total_high>0)?true:false; #if DEBUG_CLUSTER cluster_pool.printClusterPool(); #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. using System.Globalization; using System.IO; using System.Linq; using Xunit; namespace System.Diagnostics.Tests { public class EventLogTests : FileCleanupTestBase { [ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))] public void EventLogReinitializationException() { using (EventLog eventLog = new EventLog()) { eventLog.BeginInit(); Assert.Throws<InvalidOperationException>(() => eventLog.BeginInit()); eventLog.EndInit(); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))] public void ClearLog() { string log = "ClearTest"; string source = "Source_" + nameof(ClearLog); try { EventLog.CreateEventSource(source, log); using (EventLog eventLog = new EventLog()) { eventLog.Source = source; Helpers.Retry(() => eventLog.Clear()); Assert.Equal(0, Helpers.Retry((() => eventLog.Entries.Count))); Helpers.Retry(() => eventLog.WriteEntry("Writing to event log.")); Helpers.WaitForEventLog(eventLog, 1); Assert.Equal(1, Helpers.Retry((() => eventLog.Entries.Count))); } } finally { EventLog.DeleteEventSource(source); Helpers.Retry(() => EventLog.Delete(log)); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))] public void ApplicationEventLog_Count() { using (EventLog eventLog = new EventLog("Application")) { Assert.InRange(Helpers.Retry((() => eventLog.Entries.Count)), 1, int.MaxValue); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))] public void DeleteLog() { string log = "DeleteTest"; string source = "Source_" + nameof(DeleteLog); try { EventLog.CreateEventSource(source, log); Assert.True(EventLog.Exists(log)); } finally { EventLog.DeleteEventSource(source); Helpers.Retry(() => EventLog.Delete(log)); Assert.False(EventLog.Exists(log)); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))] public void CheckLogName_Get() { using (EventLog eventLog = new EventLog("Application")) { Assert.False(string.IsNullOrEmpty(eventLog.LogDisplayName)); if (CultureInfo.CurrentCulture.Name.Split('-')[0] == "en" ) Assert.Equal("Application", eventLog.LogDisplayName); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))] public void CheckMachineName_Get() { using (EventLog eventLog = new EventLog("Application")) { Assert.Equal(".", eventLog.MachineName); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))] public void GetLogDisplayName_NotSet_Throws() { using (EventLog eventLog = new EventLog()) { eventLog.Log = Guid.NewGuid().ToString("N"); Assert.Throws<InvalidOperationException>(() => eventLog.LogDisplayName); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))] public void GetLogDisplayName_Set() { using (EventLog eventLog = new EventLog()) { eventLog.Log = "Application"; Assert.False(string.IsNullOrEmpty(eventLog.LogDisplayName)); if (CultureInfo.CurrentCulture.Name.Split('-')[0] == "en" ) Assert.Equal("Application", eventLog.LogDisplayName); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))] public void EventLogs_Get() { Assert.Throws<ArgumentException>(() => EventLog.GetEventLogs("")); EventLog[] eventLogCollection = EventLog.GetEventLogs(); Assert.Contains(eventLogCollection, eventlog => eventlog.Log.Equals("Application")); Assert.Contains(eventLogCollection, eventlog => eventlog.Log.Equals("System")); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))] public void GetMaxKilobytes_Set() { string source = "Source_" + nameof(GetMaxKilobytes_Set); string log = "maxKilobytesLog"; try { EventLog.CreateEventSource(source, log); using (EventLog eventLog = new EventLog()) { eventLog.Source = source; eventLog.MaximumKilobytes = 0x400; Assert.Equal(0x400, eventLog.MaximumKilobytes); } } finally { EventLog.DeleteEventSource(source); Helpers.Retry(() => EventLog.Delete(log)); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))] public void MaxKilobytesOutOfRangeException() { using (EventLog eventLog = new EventLog()) { eventLog.Log = "Application"; Assert.Throws<ArgumentOutOfRangeException>(() => eventLog.MaximumKilobytes = 2); Assert.Throws<ArgumentOutOfRangeException>(() => eventLog.MaximumKilobytes = 0x3FFFC1); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))] public void OverflowAndRetention_Set() { string source = "Source_" + nameof(OverflowAndRetention_Set); string log = "Overflow_Set"; try { EventLog.CreateEventSource(source, log); using (EventLog eventLog = new EventLog()) { eventLog.Source = source; // The second argument is only used when the overflow policy is set to OverWrite Older eventLog.ModifyOverflowPolicy(OverflowAction.DoNotOverwrite, 1); Assert.Equal(OverflowAction.DoNotOverwrite, eventLog.OverflowAction); // -1 means overflow action is donot OverWrite Assert.Equal(-1, eventLog.MinimumRetentionDays); } } finally { EventLog.DeleteEventSource(source); Helpers.Retry(() => EventLog.Delete(log)); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))] public void Overflow_OverWriteOlderAndRetention_Set() { string source = "Source_" + nameof(OverflowAndRetention_Set); string log = "Overflow_Set"; int retentionDays = 30; // A number between 0 and 365 should work try { EventLog.CreateEventSource(source, log); using (EventLog eventLog = new EventLog()) { eventLog.Source = source; // The second argument is only used when the overflow policy is set to OverWrite Older eventLog.ModifyOverflowPolicy(OverflowAction.OverwriteOlder, retentionDays); Assert.Equal(OverflowAction.OverwriteOlder, eventLog.OverflowAction); Assert.Equal(retentionDays, eventLog.MinimumRetentionDays); } } finally { EventLog.DeleteEventSource(source); Helpers.Retry(() => EventLog.Delete(log)); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))] public void OverflowAndRetentionDaysOutOfRange() { using (EventLog eventLog = new EventLog()) { eventLog.Log = "Application"; Assert.Throws<ArgumentOutOfRangeException>(() => eventLog.ModifyOverflowPolicy(OverflowAction.OverwriteOlder, 400)); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))] public void MachineName_Set() { string source = "Source_" + nameof(MachineName_Set); using (EventLog eventLog = new EventLog()) { eventLog.Log = "Application"; eventLog.MachineName = Environment.MachineName.ToLowerInvariant(); try { EventLog.CreateEventSource(source, eventLog.LogDisplayName); Assert.Equal(eventLog.MachineName, Environment.MachineName.ToLowerInvariant()); Assert.True(EventLog.SourceExists(source, Environment.MachineName.ToLowerInvariant())); } finally { EventLog.DeleteEventSource(source); } } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))] public void RegisterDisplayLogName() { string log = "DisplayName"; string source = "Source_" + nameof(RegisterDisplayLogName); string messageFile = GetTestFilePath(); long DisplayNameMsgId = 42; // It could be any number EventSourceCreationData sourceData = new EventSourceCreationData(source, log); try { EventLog.CreateEventSource(sourceData); log = EventLog.LogNameFromSourceName(source, "."); using (EventLog eventLog = new EventLog(log, ".", source)) { if (messageFile.Length > 0) { eventLog.RegisterDisplayName(messageFile, DisplayNameMsgId); } Assert.Equal(log, eventLog.LogDisplayName); } } finally { EventLog.DeleteEventSource(source); Helpers.Retry(() => EventLog.Delete(log)); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))] public void InvalidFormatOrNullLogName() { Assert.Throws<ArgumentNullException>(() => new EventLog(null)); Assert.Throws<ArgumentException>(() => new EventLog("?")); } [ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))] public void EventLog_EnableRaisingEvents_DefaultFalse() { using (EventLog eventLog = new EventLog("log")) { Assert.False(eventLog.EnableRaisingEvents); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))] public void InvalidFormatOrNullDeleteLogName() { Assert.Throws<ArgumentException>(() => EventLog.Delete(null)); Assert.Throws<InvalidOperationException>(() => EventLog.Delete("?")); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))] public void InvalidLogExistsLogName() { Assert.False(EventLog.Exists(null)); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))] public void InvalidMachineName() { Assert.Throws<ArgumentException>(() => EventLog.Exists("Application", "")); Assert.Throws<ArgumentException>(() => EventLog.Delete("", "")); Assert.Throws<ArgumentException>(() => EventLog.DeleteEventSource("", "")); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))] public void LogDisplayNameDefault() { string source = "Source_" + nameof(LogDisplayNameDefault); string log = "MyLogDisplay"; try { EventLog.CreateEventSource(source, log); using (EventLog eventlog = new EventLog()) { eventlog.Source = source; Assert.Equal(log, eventlog.LogDisplayName); } } finally { EventLog.DeleteEventSource(source); Helpers.Retry(() => EventLog.Delete(log)); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))] public void GetMessageUsingEventMessageDLL() { if (CultureInfo.CurrentCulture.ToString() != "en-US") { return; } using (EventLog eventlog = new EventLog("Security")) { eventlog.Source = "Security"; Assert.Contains("", eventlog.Entries.LastOrDefault()?.Message ?? ""); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void GetEventLogEntriesTest() { foreach (var eventLog in EventLog.GetEventLogs()) { // Accessing eventlog properties should not throw. Assert.True(Helpers.Retry(() => eventLog.Entries.Count) >= 0); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public void GetEventLogContainsSecurityLogTest() { EventLog[] eventlogs = EventLog.GetEventLogs(); Assert.Contains("Security", eventlogs.Select(t => t.Log), StringComparer.OrdinalIgnoreCase); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.NetCore.Analyzers.Runtime.InstantiateArgumentExceptionsCorrectlyAnalyzer, Microsoft.NetCore.Analyzers.Runtime.InstantiateArgumentExceptionsCorrectlyFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.NetCore.Analyzers.Runtime.InstantiateArgumentExceptionsCorrectlyAnalyzer, Microsoft.NetCore.Analyzers.Runtime.InstantiateArgumentExceptionsCorrectlyFixer>; namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests { public class InstantiateArgumentExceptionsCorrectlyTests { [Fact] public async Task ArgumentException_NoArguments_WarnsAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentException(); } }", GetCSharpNoArgumentsExpectedResult(6, 31, "ArgumentException")); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentException() End Sub End Class", GetBasicNoArgumentsExpectedResult(4, 31, "ArgumentException")); } [Fact] public async Task ArgumentException_EmptyParameterNameArgument_WarnsAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentNullException(""""); } }", GetCSharpIncorrectParameterNameExpectedResult(6, 31, "Test", "", "paramName", "ArgumentNullException")); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentNullException("""") End Sub End Class", GetBasicIncorrectParameterNameExpectedResult(4, 31, "Test", "", "paramName", "ArgumentNullException")); } [Fact] public async Task ArgumentNullException_SpaceParameterArgument_WarnsAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentNullException("" ""); } }", GetCSharpIncorrectParameterNameExpectedResult(6, 31, "Test", " ", "paramName", "ArgumentNullException")); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentNullException("" "") End Sub End Class", GetBasicIncorrectParameterNameExpectedResult(4, 31, "Test", " ", "paramName", "ArgumentNullException")); } [Fact] public async Task ArgumentNullException_NameofNonParameter_WarnsAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { var v = new object(); throw new System.ArgumentNullException(nameof(v)); } }", GetCSharpIncorrectParameterNameExpectedResult(7, 31, "Test", "v", "paramName", "ArgumentNullException")); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Dim v As New Object() Throw New System.ArgumentNullException(NameOf(v)) End Sub End Class", GetBasicIncorrectParameterNameExpectedResult(5, 31, "Test", "v", "paramName", "ArgumentNullException")); } [Fact] public async Task ArgumentException_ParameterNameAsMessage_WarnsAndCodeFixesWithNameOfAsync() { await VerifyCS.VerifyCodeFixAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentException(""first""); } }", GetCSharpIncorrectMessageExpectedResult(6, 31, "Test", "first", "message", "ArgumentException"), @" public class Class { public void Test(string first) { throw new System.ArgumentException(null, nameof(first)); } }"); await VerifyVB.VerifyCodeFixAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentException(""first"") End Sub End Class", GetBasicIncorrectMessageExpectedResult(4, 15, "Test", "first", "message", "ArgumentException"), @" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentException(Nothing, NameOf(first)) End Sub End Class"); } [Fact] public async Task ArgumentException_ReversedArguments_WarnsAndCodeFixesWithNameOfAsync() { await VerifyCS.VerifyCodeFixAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentException(""first"", ""first is incorrect""); } }", GetCSharpIncorrectMessageExpectedResult(6, 31, "Test", "first", "message", "ArgumentException"), @" public class Class { public void Test(string first) { throw new System.ArgumentException(""first is incorrect"", nameof(first)); } }"); await VerifyVB.VerifyCodeFixAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentException(""first"", ""first is incorrect"") End Sub End Class", GetBasicIncorrectMessageExpectedResult(4, 15, "Test", "first", "message", "ArgumentException"), @" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentException(""first is incorrect"", NameOf(first)) End Sub End Class"); } [Fact] public async Task ArgumentException_ParameterWithNameofAsMessage_WarnsAndCodeFixesAsync() { await VerifyCS.VerifyCodeFixAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentException(nameof(first)); } }", GetCSharpIncorrectMessageExpectedResult(6, 31, "Test", "first", "message", "ArgumentException") , @" public class Class { public void Test(string first) { throw new System.ArgumentException(null, nameof(first)); } }"); } [Fact] public async Task ArgumentException_ReversedArgumentsWithNameof_WarnsAndCodeFixesAsync() { await VerifyCS.VerifyCodeFixAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentException(nameof(first), ""first is incorrect""); } }", GetCSharpIncorrectMessageExpectedResult(6, 31, "Test", "first", "message", "ArgumentException"), @" public class Class { public void Test(string first) { throw new System.ArgumentException(""first is incorrect"", nameof(first)); } }"); } [Fact] public async Task ArgumentException_Reversed3Arguments_WarnsAndCodeFixesAsync() { await VerifyCS.VerifyCodeFixAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentException(""first"", ""first is incorrect"", null); } }", GetCSharpIncorrectMessageExpectedResult(6, 31, "Test", "first", "message", "ArgumentException"), @" public class Class { public void Test(string first) { throw new System.ArgumentException(""first is incorrect"", nameof(first), null); } }"); await VerifyVB.VerifyCodeFixAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentException(""first"", ""first is incorrect"", Nothing) End Sub End Class", GetBasicIncorrectMessageExpectedResult(4, 15, "Test", "first", "message", "ArgumentException"), @" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentException(""first is incorrect"", NameOf(first), Nothing) End Sub End Class"); } [Fact] public async Task ArgumentNullException_NoArguments_WarnsAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentNullException(); } }", GetCSharpNoArgumentsExpectedResult(6, 31, "ArgumentNullException")); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentNullException() End Sub End Class", GetBasicNoArgumentsExpectedResult(4, 31, "ArgumentNullException")); } [Fact] public async Task ArgumentNullException_MessageAsParameterName_WarnsAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentNullException(""first is null""); } }", GetCSharpIncorrectParameterNameExpectedResult(6, 31, "Test", "first is null", "paramName", "ArgumentNullException")); } [Fact] public async Task ArgumentNullException_ReversedArguments_WarnsAndCodeFixesAsync() { await VerifyCS.VerifyCodeFixAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentNullException(""first is null"", ""first""); } }", GetCSharpIncorrectMessageExpectedResult(6, 31, "Test", "first", "message", "ArgumentNullException"), @" public class Class { public void Test(string first) { throw new System.ArgumentNullException(nameof(first), ""first is null""); } }"); await VerifyVB.VerifyCodeFixAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentNullException(""first is null"", ""first"") End Sub End Class", GetBasicIncorrectMessageExpectedResult(4, 15, "Test", "first", "message", "ArgumentNullException"), @" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentNullException(NameOf(first), ""first is null"") End Sub End Class"); } [Fact] public async Task ArgumentOutOfRangeException_NoArguments_WarnsAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentOutOfRangeException(); } }", GetCSharpNoArgumentsExpectedResult(6, 31, "ArgumentOutOfRangeException")); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentOutOfRangeException() End Sub End Class", GetBasicNoArgumentsExpectedResult(4, 31, "ArgumentOutOfRangeException")); } [Fact] public async Task ArgumentOutOfRangeException_MessageAsParameterName_WarnsAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentOutOfRangeException(""first is out of range""); } }", GetCSharpIncorrectParameterNameExpectedResult(6, 31, "Test", "first is out of range", "paramName", "ArgumentOutOfRangeException")); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentOutOfRangeException(""first is out of range"") End Sub End Class", GetBasicIncorrectParameterNameExpectedResult(4, 31, "Test", "first is out of range", "paramName", "ArgumentOutOfRangeException")); } [Fact] public async Task ArgumentOutOfRangeException_ReversedArguments_WarnsAndCodeFixesAsync() { await VerifyCS.VerifyCodeFixAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentOutOfRangeException(""first is out of range"", ""first""); } }", GetCSharpIncorrectMessageExpectedResult(6, 31, "Test", "first", "message", "ArgumentOutOfRangeException"), @" public class Class { public void Test(string first) { throw new System.ArgumentOutOfRangeException(nameof(first), ""first is out of range""); } }"); await VerifyVB.VerifyCodeFixAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentOutOfRangeException(""first is out of range"", ""first"") End Sub End Class", GetBasicIncorrectMessageExpectedResult(4, 15, "Test", "first", "message", "ArgumentOutOfRangeException"), @" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentOutOfRangeException(NameOf(first), ""first is out of range"") End Sub End Class"); } [Fact] public async Task ArgumentOutOfRangeException_Reversed3Arguments_WarnsAndCodeFixesAsync() { await VerifyCS.VerifyCodeFixAsync(@" public class Class { public void Test(string first) { var val = new object(); throw new System.ArgumentOutOfRangeException(""first is out of range"", val, ""first""); } }", GetCSharpIncorrectMessageExpectedResult(7, 31, "Test", "first", "message", "ArgumentOutOfRangeException"), @" public class Class { public void Test(string first) { var val = new object(); throw new System.ArgumentOutOfRangeException(nameof(first), val, ""first is out of range""); } }"); await VerifyVB.VerifyCodeFixAsync(@" Public Class [MyClass] Public Sub Test(first As String) Dim val = New Object() Throw New System.ArgumentOutOfRangeException(""first is out of range"", val, ""first"") End Sub End Class", GetBasicIncorrectMessageExpectedResult(5, 15, "Test", "first", "message", "ArgumentOutOfRangeException"), @" Public Class [MyClass] Public Sub Test(first As String) Dim val = New Object() Throw New System.ArgumentOutOfRangeException(NameOf(first), val, ""first is out of range"") End Sub End Class"); } [Fact] public async Task DuplicateWaitObjectException_NoArguments_WarnsAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.DuplicateWaitObjectException(); } }", GetCSharpNoArgumentsExpectedResult(6, 31, "DuplicateWaitObjectException")); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.DuplicateWaitObjectException() End Sub End Class", GetBasicNoArgumentsExpectedResult(4, 31, "DuplicateWaitObjectException")); } [Fact] public async Task DuplicateWaitObjectException_MessageAsParameterName_WarnsAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.DuplicateWaitObjectException(""first is duplicate""); } }", GetCSharpIncorrectParameterNameExpectedResult(6, 31, "Test", "first is duplicate", "parameterName", "DuplicateWaitObjectException")); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.DuplicateWaitObjectException(""first is duplicate"") End Sub End Class", GetBasicIncorrectParameterNameExpectedResult(4, 31, "Test", "first is duplicate", "parameterName", "DuplicateWaitObjectException")); } [Fact] public async Task DuplicateWaitObjectException_ReversedArguments_WarnsAndCodeFixesAsync() { await VerifyCS.VerifyCodeFixAsync(@" public class Class { public void Test(string first) { throw new System.DuplicateWaitObjectException(""first is duplicate"", ""first""); } }", GetCSharpIncorrectMessageExpectedResult(6, 31, "Test", "first", "message", "DuplicateWaitObjectException"), @" public class Class { public void Test(string first) { throw new System.DuplicateWaitObjectException(nameof(first), ""first is duplicate""); } }"); await VerifyVB.VerifyCodeFixAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.DuplicateWaitObjectException(""first is duplicate"", ""first"") End Sub End Class", GetBasicIncorrectMessageExpectedResult(4, 15, "Test", "first", "message", "DuplicateWaitObjectException"), @" Public Class [MyClass] Public Sub Test(first As String) Throw New System.DuplicateWaitObjectException(NameOf(first), ""first is duplicate"") End Sub End Class"); } [Fact] public async Task ArgumentNullException_ParentHasNoParameter_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test() { throw new System.ArgumentNullException(""Invalid argument""); } }"); } [Fact] public async Task ArgumentException_ParentHasNoParameter_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test() { throw new System.ArgumentException(""Invalid argument"", ""test""); } }"); } [Fact] public async Task ArgumentException_VariableUsed_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string paramName, string message) { throw new System.ArgumentException(paramName, message); } }"); } [Fact] public async Task ArgumentException_NoArguments_ParentMethod_HasNoParameter_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test() { throw new System.ArgumentException(); } }"); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test() Throw New System.ArgumentException() End Sub End Class"); } [Fact] public async Task ArgumentException_CorrectMessage_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentException(""first is incorrect""); } }"); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentException(""first is incorrect"") End Sub End Class"); } [Fact] public async Task ArgumentException_GenericParameterName_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test<TEnum>(TEnum first) { throw new System.ArgumentException(""first is incorrect"", nameof(TEnum)); } }"); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(Of TEnum)(ByVal first As TEnum) Throw New System.ArgumentException(""first is incorrect"", NameOf(TEnum)) End Sub End Class"); } [Fact] public async Task ArgumentException_GenericParameterName_WrongPosition_WarnsAndCodeFixesAsync() { await VerifyCS.VerifyCodeFixAsync(@" public class Class { public void Test<TEnum>(TEnum first) { throw new System.ArgumentException(""TEnum""); } }", GetCSharpIncorrectMessageExpectedResult(6, 31, "Test", "TEnum", "message", "ArgumentException"), @" public class Class { public void Test<TEnum>(TEnum first) { throw new System.ArgumentException(null, nameof(TEnum)); } }"); await VerifyVB.VerifyCodeFixAsync(@" Public Class [MyClass] Public Sub Test(Of TEnum)(ByVal first As TEnum) Throw New System.ArgumentException(""TEnum"") End Sub End Class", GetBasicIncorrectMessageExpectedResult(4, 15, "Test", "TEnum", "message", "ArgumentException"), @" Public Class [MyClass] Public Sub Test(Of TEnum)(ByVal first As TEnum) Throw New System.ArgumentException(Nothing, NameOf(TEnum)) End Sub End Class"); } [Theory] [InlineData("public", "dotnet_code_quality.api_surface = private", false)] [InlineData("private", "dotnet_code_quality.api_surface = internal, public", false)] [InlineData("public", "dotnet_code_quality.CA2208.api_surface = private, public", true)] [InlineData("public", "dotnet_code_quality.CA2208.api_surface = internal, private", false)] [InlineData("public", "dotnet_code_quality.CA2208.api_surface = Friend, Private", false)] [InlineData("public", @"dotnet_code_quality.api_surface = all dotnet_code_quality.CA2208.api_surface = private", false)] [InlineData("public", "dotnet_code_quality.api_surface = public", true)] [InlineData("public", "dotnet_code_quality.api_surface = internal, public", true)] [InlineData("public", "dotnet_code_quality.CA2208.api_surface = public", true)] [InlineData("public", "dotnet_code_quality.CA2208.api_surface = all", true)] [InlineData("public", "dotnet_code_quality.CA2208.api_surface = public, private", true)] [InlineData("public", @"dotnet_code_quality.api_surface = internal dotnet_code_quality.CA2208.api_surface = public", true)] [InlineData("public", "", true)] [InlineData("protected", "", true)] [InlineData("private", "", true)] [InlineData("protected", "dotnet_code_quality.CA2208.api_surface = public", true)] public async Task EditorConfigConfiguration_ApiSurfaceOption_TestAsync(string accessibility, string editorConfigText, bool expectDiagnostic) { var exception = expectDiagnostic ? @"[|new System.ArgumentNullException(""first is null"")|]" : @"new System.ArgumentNullException(""first is null"")"; await new VerifyCS.Test { TestState = { Sources = { $@" public class C {{ {accessibility} void Test(string first) {{ throw {exception}; }} }}" }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} ") } }, MarkupOptions = MarkupOptions.UseFirstDescriptor }.RunAsync(); exception = expectDiagnostic ? @"[|New System.ArgumentNullException(""first is null"")|]" : @"New System.ArgumentNullException(""first is null"")"; await new VerifyVB.Test { TestState = { Sources = { $@" Public Class C {accessibility} Sub Test(first As String) Throw {exception} End Sub End Class" }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} ") } }, MarkupOptions = MarkupOptions.UseFirstDescriptor }.RunAsync(); } [Fact] public async Task EditorConfigConfiguredPublic_PrivateMethods_TriggeringOtherRules_DoesNotWarnAsync() { await new VerifyCS.Test { TestState = { Sources = { $@" public class C {{ private void Test(string first) {{ throw new System.ArgumentNullException(); }} private void TestFlipped(string first) {{ throw new System.ArgumentException(nameof(first), ""message""); }} }}" }, AnalyzerConfigFiles = { ("/.editorconfig", @"root = true [*] dotnet_code_quality.CA2208.api_surface = public") } }, MarkupOptions = MarkupOptions.UseFirstDescriptor }.RunAsync(); } [Fact] public async Task ArgumentException_CorrectMessageAndParameterName_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentException(""first is incorrect"", ""first""); } }"); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentException(""first is incorrect"", ""first"") End Sub End Class"); } [Fact] public async Task ArgumentNullException_CorrectParameterName_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentNullException(""first""); } }"); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentNullException(""first"") End Sub End Class"); } [Fact] public async Task ArgumentNullException_VariableUsed_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { string str = ""Hi there""; public void Test(string first) { throw new System.ArgumentNullException(str); } }"); } [Fact] public async Task ArgumentNullException_NameofParameter_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentNullException(nameof(first)); } }"); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentNullException(NameOf(first)) End Sub End Class"); } [Fact] public async Task ArgumentNull_CorrectParameterNameAndMessage_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentNullException(""first"", ""first is null""); } }"); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentNullException(""first"", ""first is null"") End Sub End Class"); } [Fact] public async Task ArgumentOutOfRangeException_CorrectParameterName_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentOutOfRangeException(""first""); } }"); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentOutOfRangeException(""first"") End Sub End Class"); } [Fact] public async Task ArgumentOutOfRangeException_CorrectParameterNameAndMessage_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.ArgumentOutOfRangeException(""first"", ""first is out of range""); } }"); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.DuplicateWaitObjectException(""first"", ""first is out of range"") End Sub End Class"); } [Fact] public async Task DuplicateWaitObjectException_CorrectParameterName_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.DuplicateWaitObjectException(""first""); } }"); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.DuplicateWaitObjectException(""first"") End Sub End Class"); } [Fact] public async Task DuplicateWaitObjectException_CorrectParameterNameAndMessage_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.DuplicateWaitObjectException(""first"", ""first is duplicate""); } }"); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.DuplicateWaitObjectException(""first"", ""first is duplicate"") End Sub End Class"); } [Fact] public async Task ArgumentExceptionType_NotHavingConstructorWithParameterName_NoArgument_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.Text.DecoderFallbackException (); } }"); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.Text.DecoderFallbackException () End Sub End Class"); } [Fact] public async Task ArgumentExceptionType_NotHavingConstructor_WithParameterName_WithArgument_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test(string first) { throw new System.Text.DecoderFallbackException (""first""); } }"); await VerifyVB.VerifyAnalyzerAsync(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.Text.DecoderFallbackException (""first"") End Sub End Class"); } [Fact, WorkItem(1824, "https://github.com/dotnet/roslyn-analyzers/issues/1824")] public async Task ArgumentNullException_LocalFunctionParameter_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test() { void Validate(string a) { if (a == null) throw new System.ArgumentNullException(nameof(a)); } } }"); } [Fact, WorkItem(1824, "https://github.com/dotnet/roslyn-analyzers/issues/1824")] public async Task ArgumentNullException_NestedLocalFunctionParameter_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test() { void Validate(string a) { void ValidateNested() { if (a == null) throw new System.ArgumentNullException(nameof(a)); } } } }"); } [Fact, WorkItem(1824, "https://github.com/dotnet/roslyn-analyzers/issues/1824")] public async Task ArgumentNullException_LambdaParameter_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { public void Test() { System.Action<string> lambda = a => { if (a == null) throw new System.ArgumentNullException(nameof(a)); }; } }"); } [Fact, WorkItem(1561, "https://github.com/dotnet/roslyn-analyzers/issues/1561")] public async Task ArgumentOutOfRangeException_PropertyName_DoesNotWarnAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class Class1 { private int _size; public int Size { get => _size; set { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(Size)); } _size = value; } } }"); } private static DiagnosticResult GetCSharpNoArgumentsExpectedResult(int line, int column, string typeName) => #pragma warning disable RS0030 // Do not used banned APIs VerifyCS.Diagnostic(InstantiateArgumentExceptionsCorrectlyAnalyzer.RuleNoArguments) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(typeName); private static DiagnosticResult GetBasicNoArgumentsExpectedResult(int line, int column, string typeName) => #pragma warning disable RS0030 // Do not used banned APIs VerifyVB.Diagnostic(InstantiateArgumentExceptionsCorrectlyAnalyzer.RuleNoArguments) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(typeName); private static DiagnosticResult GetCSharpIncorrectMessageExpectedResult(int line, int column, params string[] args) => #pragma warning disable RS0030 // Do not used banned APIs VerifyCS.Diagnostic(InstantiateArgumentExceptionsCorrectlyAnalyzer.RuleIncorrectMessage) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(args); private static DiagnosticResult GetBasicIncorrectMessageExpectedResult(int line, int column, params string[] args) => #pragma warning disable RS0030 // Do not used banned APIs VerifyVB.Diagnostic(InstantiateArgumentExceptionsCorrectlyAnalyzer.RuleIncorrectMessage) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(args); private static DiagnosticResult GetCSharpIncorrectParameterNameExpectedResult(int line, int column, params string[] args) => #pragma warning disable RS0030 // Do not used banned APIs VerifyCS.Diagnostic(InstantiateArgumentExceptionsCorrectlyAnalyzer.RuleIncorrectParameterName) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(args); private static DiagnosticResult GetBasicIncorrectParameterNameExpectedResult(int line, int column, params string[] args) => #pragma warning disable RS0030 // Do not used banned APIs VerifyVB.Diagnostic(InstantiateArgumentExceptionsCorrectlyAnalyzer.RuleIncorrectParameterName) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(args); } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.MessageAgent.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using System.Threading; using Novell.Directory.Ldap.Utilclass; namespace Novell.Directory.Ldap { internal class MessageAgent { private void InitBlock() { messages = new MessageVector(5, 5); } /// <summary> /// empty and return all messages owned by this agent /// </summary> internal virtual object[] RemoveAll() { return messages.RemoveAll(); } /// <summary> /// Get a list of message ids controlled by this agent /// </summary> /// <returns> /// an array of integers representing the message ids /// </returns> internal virtual int[] MessageIDs { get { var size = messages.Count; var ids = new int[size]; Message info; for (var i = 0; i < size; i++) { info = (Message) messages[i]; ids[i] = info.MessageID; } return ids; } } /// <summary> /// Get the maessage agent number for debugging /// </summary> /// <returns> /// the agent number /// </returns> internal virtual string AgentName { /*packge*/ get { return name; } } /// <summary> Get a count of all messages queued</summary> internal virtual int Count { get { var count = 0; var msgs = messages.ToArray(); for (var i = 0; i < msgs.Length; i++) { var m = (Message) msgs[i]; count += m.Count; } return count; } } private MessageVector messages; private int indexLastRead; private static object nameLock; // protect agentNum private static int agentNum = 0; // Debug, agent number private string name; // String name for debug internal MessageAgent() { InitBlock(); // Get a unique agent id for debug } /// <summary> /// merges two message agents /// </summary> /// <param name="fromAgent"> /// the agent to be merged into this one /// </param> internal void merge(MessageAgent fromAgent) { var msgs = fromAgent.RemoveAll(); for (var i = 0; i < msgs.Length; i++) { messages.Add(msgs[i]); ((Message) msgs[i]).Agent = this; } lock (messages) { if (msgs.Length > 1) { Monitor.PulseAll(messages); // wake all threads waiting for messages } else if (msgs.Length == 1) { Monitor.Pulse(messages); // only wake one thread } } } /// <summary> /// Wakes up any threads waiting for messages in the message agent /// </summary> internal void sleepersAwake(bool all) { lock (messages) { if (all) Monitor.PulseAll(messages); else Monitor.Pulse(messages); } } /// <summary> /// Returns true if any responses are queued for any of the agent's messages /// return false if no responses are queued, otherwise true /// </summary> internal bool isResponseReceived() { var size = messages.Count; var next = indexLastRead + 1; Message info; for (var i = 0; i < size; i++) { if (next == size) { next = 0; } info = (Message) messages[next]; if (info.hasReplies()) { return true; } } return false; } /// <summary> /// Returns true if any responses are queued for the specified msgId /// return false if no responses are queued, otherwise true /// </summary> internal bool isResponseReceived(int msgId) { try { var info = messages.FindMessageById(msgId); return info.hasReplies(); } catch (FieldAccessException) { return false; } } /// <summary> /// Abandon the request associated with MsgId /// </summary> /// <param name="msgId"> /// the message id to abandon /// </param> /// <param name="cons"> /// constraints associated with this request /// </param> internal void Abandon(int msgId, LdapConstraints cons) //, boolean informUser) { Message info = null; try { // Send abandon request and remove from connection list info = messages.FindMessageById(msgId); SupportClass.VectorRemoveElement(messages, info); // This message is now dead info.Abandon(cons, null); } catch (FieldAccessException ex) { Logger.Log.LogWarning("Exception swallowed", ex); } } /// <summary> Abandon all requests on this MessageAgent</summary> internal void AbandonAll() { var size = messages.Count; Message info; for (var i = 0; i < size; i++) { info = (Message) messages[i]; // Message complete and no more replies, remove from id list SupportClass.VectorRemoveElement(messages, info); info.Abandon(null, null); } } /// <summary> /// Indicates whether a specific operation is complete /// </summary> /// <returns> /// true if a specific operation is complete /// </returns> internal bool isComplete(int msgid) { try { var info = messages.FindMessageById(msgid); if (!info.Complete) { return false; } } catch (FieldAccessException ex) { // return true, if no message, it must be complete Logger.Log.LogWarning("Exception swallowed", ex); } return true; } /// <summary> /// Returns the Message object for a given messageID /// </summary> /// <param name="msgid"> /// the message ID. /// </param> internal Message getMessage(int msgid) { return messages.FindMessageById(msgid); } /// <summary> /// Send a request to the server. A Message class is created /// for the specified request which causes the message to be sent. /// The request is added to the list of messages being managed by /// this agent. /// </summary> /// <param name="conn"> /// the connection that identifies the server. /// </param> /// <param name="msg"> /// the LdapMessage to send /// </param> /// <param name="timeOut"> /// the interval to wait for the message to complete or /// <code>null</code> if infinite. /// </param> /// <param name="queue"> /// the LdapMessageQueue associated with this request. /// </param> internal void sendMessage(Connection conn, LdapMessage msg, int timeOut, LdapMessageQueue queue, BindProperties bindProps) { // creating a messageInfo causes the message to be sent // and a timer to be started if needed. var message = new Message(msg, timeOut, conn, this, queue, bindProps); messages.Add(message); message.sendMessage(); // Now send message to server } /// <summary> /// Returns a response queued, or waits if none queued /// </summary> // internal System.Object getLdapMessage(System.Int32 msgId) internal object getLdapMessage(int msgId) { return getLdapMessage(new Integer32(msgId)); } internal object getLdapMessage(Integer32 msgId) { object rfcMsg; // If no messages for this agent, just return null if (messages.Count == 0) { return null; } if (msgId != null) { // Request messages for a specific ID try { // Get message for this ID // Message info = messages.findMessageById(msgId); var info = messages.FindMessageById(msgId.intValue); rfcMsg = info.waitForReply(); // blocks for a response if (!info.acceptsReplies() && !info.hasReplies()) { // Message complete and no more replies, remove from id list SupportClass.VectorRemoveElement(messages, info); info.Abandon(null, null); // Get rid of resources } return rfcMsg; } catch (FieldAccessException) { // no such message id return null; } } // A msgId was NOT specified, any message will do lock (messages) { while (true) { var next = indexLastRead + 1; Message info; for (var i = 0; i < messages.Count; i++) { if (next >= messages.Count) { next = 0; } info = (Message) messages[next]; indexLastRead = next++; rfcMsg = info.Reply; // Check this request is complete if (!info.acceptsReplies() && !info.hasReplies()) { // Message complete & no more replies, remove from id list SupportClass.VectorRemoveElement(messages, info); // remove from list info.Abandon(null, null); // Get rid of resources // Start loop at next message that is now moved // to the current position in the Vector. i -= 1; } if (rfcMsg != null) { // We got a reply return rfcMsg; } } // end for loop */ // Messages can be removed in this loop, we we must // check if any messages left for this agent if (messages.Count == 0) { return null; } // No data, wait for something to come in. Monitor.Wait(messages); } /* end while */ } /* end synchronized */ } /// <summary> Debug code to print messages in message vector</summary> private void debugDisplayMessages() { } static MessageAgent() { nameLock = new object(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Client.Datastream { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Apache.Ignite.Core.Client; using Apache.Ignite.Core.Client.Datastream; using Apache.Ignite.Core.Datastream; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Datastream; using BinaryWriter = Apache.Ignite.Core.Impl.Binary.BinaryWriter; /// <summary> /// Thin client data streamer. /// </summary> internal sealed class DataStreamerClient<TK, TV> : IDataStreamerClient<TK, TV> { /** Streamer flags. */ [Flags] private enum Flags : byte { AllowOverwrite = 0x01, SkipStore = 0x02, KeepBinary = 0x04, Flush = 0x08, Close = 0x10 } /** */ private const int ServerBufferSizeAuto = -1; /** */ private const int MaxRetries = 16; /** */ private readonly ClientFailoverSocket _socket; /** */ private readonly int _cacheId; /** */ private readonly string _cacheName; /** */ private readonly DataStreamerClientOptions<TK, TV> _options; /** */ private readonly ConcurrentDictionary<ClientSocket, DataStreamerClientPerNodeBuffer<TK, TV>> _buffers = new ConcurrentDictionary<ClientSocket, DataStreamerClientPerNodeBuffer<TK, TV>>(); /** */ [SuppressMessage("Microsoft.Design", "CA2213:DisposableFieldsShouldBeDisposed", Justification = "WaitHandle is not used in ReaderWriterLockSlim, no need to dispose.")] private readonly ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim(); /** Cached flags. */ private readonly Flags _flags; /** */ private readonly ConcurrentStack<DataStreamerClientEntry<TK, TV>[]> _arrayPool = new ConcurrentStack<DataStreamerClientEntry<TK, TV>[]>(); private readonly Timer _autoFlushTimer; /** */ private int _arraysAllocated; /** */ private long _entriesSent; /** Exception. When set, the streamer is closed. */ private volatile Exception _exception; /** Cancelled flag. */ private volatile bool _cancelled; /// <summary> /// Initializes a new instance of <see cref="DataStreamerClient{TK,TV}"/>. /// </summary> /// <param name="socket">Socket.</param> /// <param name="cacheName">Cache name.</param> /// <param name="options">Options.</param> public DataStreamerClient( ClientFailoverSocket socket, string cacheName, DataStreamerClientOptions<TK, TV> options) { Debug.Assert(socket != null); Debug.Assert(!string.IsNullOrEmpty(cacheName)); // Copy to prevent modification. _options = new DataStreamerClientOptions<TK, TV>(options); _socket = socket; _cacheName = cacheName; _cacheId = BinaryUtils.GetCacheId(cacheName); _flags = GetFlags(_options); var interval = _options.AutoFlushInterval; if (interval != TimeSpan.Zero) { _autoFlushTimer = new Timer(_ => AutoFlush(), null, interval, interval); } } /** <inheritdoc /> */ public void Dispose() { Close(cancel: false); } /** <inheritdoc /> */ public string CacheName { get { return _cacheName; } } /** <inheritdoc /> */ public bool IsClosed { get { return _exception != null; } } /** <inheritdoc /> */ public DataStreamerClientOptions<TK, TV> Options { get { // Copy to prevent modification. return new DataStreamerClientOptions<TK, TV>(_options); } } /** <inheritdoc /> */ public void Add(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); Add(new DataStreamerClientEntry<TK, TV>(key, val)); } /** <inheritdoc /> */ public void Remove(TK key) { IgniteArgumentCheck.NotNull(key, "key"); if (!_options.AllowOverwrite) { throw new IgniteClientException("DataStreamer can't remove data when AllowOverwrite is false."); } Add(new DataStreamerClientEntry<TK, TV>(key)); } /** <inheritdoc /> */ public void Flush() { FlushAsync().Wait(); } /** <inheritdoc /> */ public Task FlushAsync() { ThrowIfClosed(); return FlushInternalAsync(); } /** <inheritdoc /> */ public void Close(bool cancel) { CloseAsync(cancel).Wait(); } /** <inheritdoc /> */ public Task CloseAsync(bool cancel) { _rwLock.EnterWriteLock(); try { if (_exception != null) { // Already closed. return TaskRunner.CompletedTask; } _exception = new ObjectDisposedException("DataStreamerClient", "Data streamer has been disposed"); if (_autoFlushTimer != null) { _autoFlushTimer.Dispose(); } if (cancel) { // Disregard current buffers, stop all retry loops. _cancelled = true; return TaskRunner.CompletedTask; } return FlushInternalAsync(); } finally { _rwLock.ExitWriteLock(); } } /** <inheritdoc /> */ public override string ToString() { return string.Format("{0} [CacheName={1}, IsClosed={2}]", GetType().Name, CacheName, IsClosed); } /// <summary> /// Gets the count of sent entries. /// </summary> internal long EntriesSent { get { return Interlocked.CompareExchange(ref _entriesSent, -1, -1); } } /// <summary> /// Gets the count of allocated arrays. /// </summary> internal int ArraysAllocated { get { return Interlocked.CompareExchange(ref _arraysAllocated, -1, -1); } } /// <summary> /// Gets the count of pooled arrays. /// </summary> internal int ArraysPooled { get { return _arrayPool.Count; } } /// <summary> /// Gets the pooled entry array. /// </summary> internal DataStreamerClientEntry<TK, TV>[] GetPooledArray() { DataStreamerClientEntry<TK,TV>[] res; if (_arrayPool.TryPop(out res)) { // Reset buffer and return. Array.Clear(res, 0, res.Length); return res; } Interlocked.Increment(ref _arraysAllocated); res = new DataStreamerClientEntry<TK, TV>[_options.PerNodeBufferSize]; return res; } /// <summary> /// Returns entry array to the pool. /// </summary> internal void ReturnPooledArray(DataStreamerClientEntry<TK, TV>[] buffer) { _arrayPool.Push(buffer); } /// <summary> /// Adds an entry to the streamer. /// </summary> private void Add(DataStreamerClientEntry<TK, TV> entry) { if (!_rwLock.TryEnterReadLock(0)) { throw new ObjectDisposedException("DataStreamerClient", "Data streamer has been disposed"); } try { ThrowIfClosed(); AddNoLock(entry); } finally { _rwLock.ExitReadLock(); } } /// <summary> /// Adds an entry without RW lock. /// </summary> private void AddNoLock(DataStreamerClientEntry<TK, TV> entry) { var retries = MaxRetries; while (!_cancelled) { try { var socket = _socket.GetAffinitySocket(_cacheId, entry.Key) ?? _socket.GetSocket(); var buffer = GetOrAddPerNodeBuffer(socket); if (buffer.Add(entry)) { return; } } catch (Exception e) { if (ShouldRetry(e) && retries --> 0) { continue; } throw; } } } /// <summary> /// Flushes the streamer asynchronously. /// </summary> private Task FlushInternalAsync() { if (_buffers.IsEmpty) { return TaskRunner.CompletedTask; } var tasks = new List<Task>(_buffers.Count); foreach (var pair in _buffers) { var buffer = pair.Value; var task = buffer.FlushAllAsync(); if (task != null && !task.IsCompleted) { tasks.Add(task); } } return TaskRunner.WhenAll(tasks.ToArray()); } /// <summary> /// Flushes the specified buffer asynchronously. /// </summary> internal Task FlushBufferAsync( DataStreamerClientBuffer<TK, TV> buffer, ClientSocket socket, SemaphoreSlim semaphore) { semaphore.Wait(); var tcs = new TaskCompletionSource<object>(); FlushBufferInternalAsync(buffer, socket, tcs); return tcs.Task.ContWith(t => { semaphore.Release(); _exception = _exception ?? t.Exception; return t.Result; }, TaskContinuationOptions.ExecuteSynchronously); } /// <summary> /// Flushes the specified buffer asynchronously. /// </summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Any exception should be propagated to TaskCompletionSource.")] private void FlushBufferInternalAsync( DataStreamerClientBuffer<TK, TV> buffer, ClientSocket socket, TaskCompletionSource<object> tcs) { try { socket.DoOutInOpAsync( ClientOp.DataStreamerStart, ctx => WriteBuffer(buffer, ctx.Writer), ctx => (object)null, syncCallback: true) .ContWith( t => FlushBufferCompleteOrRetry(buffer, socket, tcs, t.Exception), TaskContinuationOptions.ExecuteSynchronously); } catch (Exception exception) { FlushBufferCompleteOrRetry(buffer, socket, tcs, exception); } } /// <summary> /// Completes or retries the buffer flush operation. /// </summary> private void FlushBufferCompleteOrRetry( DataStreamerClientBuffer<TK, TV> buffer, ClientSocket socket, TaskCompletionSource<object> tcs, Exception exception) { if (exception == null) { // Successful flush. Interlocked.Add(ref _entriesSent, buffer.Count); ReturnPooledArray(buffer.Entries); tcs.SetResult(null); return; } if (_cancelled || (!socket.IsDisposed && !ShouldRetry(exception))) { // Socket is still connected: this error does not need to be retried. ReturnPooledArray(buffer.Entries); tcs.SetException(exception); return; } // Release receiver thread, perform retry on a separate thread. ThreadPool.QueueUserWorkItem(_ => FlushBufferRetry(buffer, socket, tcs)); } /// <summary> /// Retries the buffer flush operation. /// </summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Any exception should be propagated to TaskCompletionSource.")] private void FlushBufferRetry( DataStreamerClientBuffer<TK, TV> buffer, ClientSocket failedSocket, TaskCompletionSource<object> tcs) { try { // Connection failed. Remove disconnected socket from the map. DataStreamerClientPerNodeBuffer<TK, TV> removed; _buffers.TryRemove(failedSocket, out removed); // Re-add entries to other buffers. ReAddEntriesAndReturnBuffer(buffer); if (removed != null) { var remaining = removed.Close(); while (remaining != null) { if (remaining.MarkFlushed()) { ReAddEntriesAndReturnBuffer(remaining); } remaining = remaining.Previous; } } // Note: if initial flush was caused by full buffer, not requested by the user, // we don't need to force flush everything here - just re-add entries to other buffers. FlushInternalAsync().ContWith(flushTask => flushTask.SetAsResult(tcs)); } catch (Exception e) { tcs.SetException(e); } } /// <summary> /// Re-adds obsolete buffer entries to new buffers and returns the array to the pool. /// </summary> private void ReAddEntriesAndReturnBuffer(DataStreamerClientBuffer<TK, TV> buffer) { var count = buffer.Count; var entries = buffer.Entries; for (var i = 0; i < count; i++) { var entry = entries[i]; if (!entry.IsEmpty) { AddNoLock(entry); } } ReturnPooledArray(entries); } /// <summary> /// Writes buffer data to the specified writer. /// </summary> private void WriteBuffer(DataStreamerClientBuffer<TK, TV> buffer, BinaryWriter w) { w.WriteInt(_cacheId); w.WriteByte((byte) _flags); w.WriteInt(ServerBufferSizeAuto); // Server per-node buffer size. w.WriteInt(ServerBufferSizeAuto); // Server per-thread buffer size. if (_options.Receiver != null) { var rcvHolder = new StreamReceiverHolder(_options.Receiver, (rec, grid, cache, stream, keepBinary) => StreamReceiverHolder.InvokeReceiver((IStreamReceiver<TK, TV>) rec, grid, cache, stream, keepBinary)); w.WriteObjectDetached(rcvHolder); w.WriteByte(ClientPlatformId.Dotnet); } else { w.WriteObject<object>(null); } var count = buffer.Count; w.WriteInt(count); var entries = buffer.Entries; for (var i = 0; i < count; i++) { var entry = entries[i]; if (entry.IsEmpty) { continue; } w.WriteObjectDetached(entry.Key); if (entry.Remove) { w.WriteObject<object>(null); } else { w.WriteObjectDetached(entry.Val); } } } /// <summary> /// Gets or adds per-node buffer for the specified socket. /// </summary> private DataStreamerClientPerNodeBuffer<TK, TV> GetOrAddPerNodeBuffer(ClientSocket socket) { DataStreamerClientPerNodeBuffer<TK,TV> res; if (_buffers.TryGetValue(socket, out res)) { return res; } var candidate = new DataStreamerClientPerNodeBuffer<TK, TV>(this, socket); res = _buffers.GetOrAdd(socket, candidate); if (res != candidate) { // Another thread won - return array to the pool. ReturnPooledArray(candidate.Close().Entries); } return res; } /// <summary> /// Throws an exception if current streamer instance is closed. /// </summary> private void ThrowIfClosed() { var ex = _exception; if (ex == null) { return; } if (ex is ObjectDisposedException) { throw new ObjectDisposedException("Streamer is closed."); } throw new IgniteClientException("Streamer is closed with error, check inner exception for details.", ex); } /// <summary> /// Performs timer-based automatic flush. /// </summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Streamer will be closed if an exception occurs during automated flush. " + "Timer thread should not throw.")] private void AutoFlush() { if (_exception != null) { return; } // Prevent multiple parallel timer calls. if (!Monitor.TryEnter(_autoFlushTimer)) { return; } try { // Initiate flush, don't wait for completion. FlushInternalAsync(); } catch (Exception) { // Ignore. } finally { Monitor.Exit(_autoFlushTimer); } } /// <summary> /// Gets a value indicating whether flush should be retried after the specified exception. /// </summary> private static bool ShouldRetry(Exception exception) { while (exception.InnerException != null) { exception = exception.InnerException; } if (exception is SocketException || exception is IOException) { return true; } var clientEx = exception as IgniteClientException; if (clientEx != null && clientEx.StatusCode == ClientStatusCode.InvalidNodeState) { return true; } return false; } /// <summary> /// Gets the flags. /// </summary> private static Flags GetFlags(DataStreamerClientOptions options) { var flags = Flags.Flush | Flags.Close; if (options.AllowOverwrite) { flags |= Flags.AllowOverwrite; } if (options.SkipStore) { flags |= Flags.SkipStore; } if (options.ReceiverKeepBinary) { flags |= Flags.KeepBinary; } return flags; } } }
using GitTools.Testing; using GitVersion.Configuration; using GitVersion.Extensions; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; using GitVersionCore.Tests.Helpers; using LibGit2Sharp; using NUnit.Framework; namespace GitVersionCore.Tests.IntegrationTests { [TestFixture] public class ReleaseBranchScenarios : TestBase { [Test] public void NoMergeBacksToDevelopInCaseThereAreNoChangesInReleaseBranch() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeACommit(); fixture.BranchTo("develop"); fixture.Repository.MakeCommits(3); var releaseBranch = fixture.Repository.CreateBranch("release/1.0.0"); fixture.Checkout("master"); fixture.Repository.MergeNoFF("release/1.0.0"); fixture.Repository.ApplyTag("1.0.0"); fixture.Checkout("develop"); fixture.Repository.Branches.Remove(releaseBranch); fixture.AssertFullSemver("1.1.0-alpha.0"); } [Test] public void NoMergeBacksToDevelopInCaseThereAreChangesInReleaseBranch() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeACommit(); fixture.BranchTo("develop"); fixture.Repository.MakeCommits(3); fixture.BranchTo("release/1.0.0"); fixture.Repository.MakeACommit(); // Merge to master fixture.Checkout("master"); fixture.Repository.MergeNoFF("release/1.0.0"); fixture.Repository.ApplyTag("1.0.0"); // Merge to develop fixture.Checkout("develop"); fixture.Repository.MergeNoFF("release/1.0.0"); fixture.AssertFullSemver("1.1.0-alpha.2"); fixture.Repository.MakeACommit(); fixture.Repository.Branches.Remove("release/1.0.0"); fixture.AssertFullSemver("1.1.0-alpha.3"); } [Test] public void CanTakeVersionFromReleaseBranch() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.3"); fixture.Repository.MakeCommits(5); fixture.Repository.CreateBranch("release-2.0.0"); fixture.Checkout("release-2.0.0"); fixture.AssertFullSemver("2.0.0-beta.1+0"); fixture.Repository.MakeCommits(2); fixture.AssertFullSemver("2.0.0-beta.1+2"); } [Test] public void CanTakeVersionFromReleasesBranch() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.3"); fixture.Repository.MakeCommits(5); fixture.Repository.CreateBranch("releases/2.0.0"); fixture.Checkout("releases/2.0.0"); fixture.AssertFullSemver("2.0.0-beta.1+0"); fixture.Repository.MakeCommits(2); fixture.AssertFullSemver("2.0.0-beta.1+2"); } [Test] public void CanTakePreReleaseVersionFromReleasesBranchWithNumericPreReleaseTag() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeCommits(5); fixture.Repository.CreateBranch("releases/2.0.0"); fixture.Checkout("releases/2.0.0"); fixture.Repository.ApplyTag("v2.0.0-1"); var variables = fixture.GetVersion(); Assert.AreEqual("2.0.0-1", variables.FullSemVer); } [Test] public void ReleaseBranchWithNextVersionSetInConfig() { var config = new Config { NextVersion = "2.0.0" }; using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeCommits(5); fixture.BranchTo("release-2.0.0"); fixture.AssertFullSemver("2.0.0-beta.1+0", config); fixture.Repository.MakeCommits(2); fixture.AssertFullSemver("2.0.0-beta.1+2", config); } [Test] public void CanTakeVersionFromReleaseBranchWithTagOverridden() { var config = new Config { Branches = { { "release", new BranchConfig { Tag = "rc" } } } }; using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.3"); fixture.Repository.MakeCommits(5); fixture.Repository.CreateBranch("release-2.0.0"); fixture.Checkout("release-2.0.0"); fixture.AssertFullSemver("2.0.0-rc.1+0", config); fixture.Repository.MakeCommits(2); fixture.AssertFullSemver("2.0.0-rc.1+2", config); } [Test] public void CanHandleReleaseBranchWithStability() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.3"); fixture.Repository.CreateBranch("develop"); fixture.Repository.MakeCommits(5); fixture.Repository.CreateBranch("release-2.0.0-Final"); fixture.Checkout("release-2.0.0-Final"); fixture.AssertFullSemver("2.0.0-beta.1+0"); fixture.Repository.MakeCommits(2); fixture.AssertFullSemver("2.0.0-beta.1+2"); } [Test] public void WhenReleaseBranchOffDevelopIsMergedIntoMasterAndDevelopVersionIsTakenWithIt() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.3"); fixture.Repository.CreateBranch("develop"); fixture.Repository.MakeCommits(1); fixture.Repository.CreateBranch("release-2.0.0"); fixture.Checkout("release-2.0.0"); fixture.Repository.MakeCommits(4); fixture.Checkout("master"); fixture.Repository.MergeNoFF("release-2.0.0", Generate.SignatureNow()); fixture.AssertFullSemver("2.0.0+0"); fixture.Repository.MakeCommits(2); fixture.AssertFullSemver("2.0.0+2"); } [Test] public void WhenReleaseBranchOffMasterIsMergedIntoMasterVersionIsTakenWithIt() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.3"); fixture.Repository.MakeCommits(1); fixture.Repository.CreateBranch("release-2.0.0"); fixture.Checkout("release-2.0.0"); fixture.Repository.MakeCommits(4); fixture.Checkout("master"); fixture.Repository.MergeNoFF("release-2.0.0", Generate.SignatureNow()); fixture.AssertFullSemver("2.0.0+0"); } [Test] public void MasterVersioningContinuousCorrectlyAfterMergingReleaseBranch() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.3"); fixture.Repository.MakeCommits(1); fixture.Repository.CreateBranch("release-2.0.0"); fixture.Checkout("release-2.0.0"); fixture.Repository.MakeCommits(4); fixture.Checkout("master"); fixture.Repository.MergeNoFF("release-2.0.0", Generate.SignatureNow()); fixture.AssertFullSemver("2.0.0+0"); fixture.Repository.ApplyTag("2.0.0"); fixture.Repository.MakeCommits(1); fixture.AssertFullSemver("2.0.1+1"); } [Test] public void WhenReleaseBranchIsMergedIntoDevelopHighestVersionIsTakenWithIt() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.3"); fixture.Repository.CreateBranch("develop"); fixture.Repository.MakeCommits(1); fixture.Repository.CreateBranch("release-2.0.0"); fixture.Checkout("release-2.0.0"); fixture.Repository.MakeCommits(4); fixture.Checkout("develop"); fixture.Repository.MergeNoFF("release-2.0.0", Generate.SignatureNow()); fixture.Repository.CreateBranch("release-1.0.0"); fixture.Checkout("release-1.0.0"); fixture.Repository.MakeCommits(4); fixture.Checkout("develop"); fixture.Repository.MergeNoFF("release-1.0.0", Generate.SignatureNow()); fixture.AssertFullSemver("2.1.0-alpha.11"); } [Test] public void WhenReleaseBranchIsMergedIntoMasterHighestVersionIsTakenWithIt() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.3"); fixture.Repository.MakeCommits(1); fixture.Repository.CreateBranch("release-2.0.0"); fixture.Checkout("release-2.0.0"); fixture.Repository.MakeCommits(4); fixture.Checkout("master"); fixture.Repository.MergeNoFF("release-2.0.0", Generate.SignatureNow()); fixture.Repository.CreateBranch("release-1.0.0"); fixture.Checkout("release-1.0.0"); fixture.Repository.MakeCommits(4); fixture.Checkout("master"); fixture.Repository.MergeNoFF("release-1.0.0", Generate.SignatureNow()); fixture.AssertFullSemver("2.0.0+5"); } [Test] public void WhenReleaseBranchIsMergedIntoMasterHighestVersionIsTakenWithItEvenWithMoreThanTwoActiveBranches() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.3"); fixture.Repository.MakeCommits(1); fixture.Repository.CreateBranch("release-3.0.0"); fixture.Checkout("release-3.0.0"); fixture.Repository.MakeCommits(4); fixture.Checkout("master"); fixture.Repository.MergeNoFF("release-3.0.0", Generate.SignatureNow()); fixture.Repository.CreateBranch("release-2.0.0"); fixture.Checkout("release-2.0.0"); fixture.Repository.MakeCommits(4); fixture.Checkout("master"); fixture.Repository.MergeNoFF("release-2.0.0", Generate.SignatureNow()); fixture.Repository.CreateBranch("release-1.0.0"); fixture.Checkout("release-1.0.0"); fixture.Repository.MakeCommits(4); fixture.Checkout("master"); fixture.Repository.MergeNoFF("release-1.0.0", Generate.SignatureNow()); fixture.AssertFullSemver("3.0.0+10"); } [Test] public void WhenMergingReleaseBackToDevShouldNotResetBetaVersion() { using var fixture = new EmptyRepositoryFixture(); const string taggedVersion = "1.0.3"; fixture.Repository.MakeATaggedCommit(taggedVersion); fixture.Repository.CreateBranch("develop"); fixture.Checkout("develop"); fixture.Repository.MakeCommits(1); fixture.AssertFullSemver("1.1.0-alpha.1"); fixture.Repository.CreateBranch("release-2.0.0"); fixture.Checkout("release-2.0.0"); fixture.Repository.MakeCommits(1); fixture.AssertFullSemver("2.0.0-beta.1+1"); //tag it to bump to beta 2 fixture.Repository.ApplyTag("2.0.0-beta1"); fixture.Repository.MakeCommits(1); fixture.AssertFullSemver("2.0.0-beta.2+2"); //merge down to develop fixture.Checkout("develop"); fixture.Repository.MergeNoFF("release-2.0.0", Generate.SignatureNow()); //but keep working on the release fixture.Checkout("release-2.0.0"); fixture.AssertFullSemver("2.0.0-beta.2+2"); fixture.MakeACommit(); fixture.AssertFullSemver("2.0.0-beta.2+3"); } [Test] public void HotfixOffReleaseBranchShouldNotResetCount() { var config = new Config { VersioningMode = VersioningMode.ContinuousDeployment }; using var fixture = new EmptyRepositoryFixture(); const string taggedVersion = "1.0.3"; fixture.Repository.MakeATaggedCommit(taggedVersion); fixture.Repository.CreateBranch("develop"); fixture.Checkout("develop"); fixture.Repository.MakeCommits(1); fixture.Repository.CreateBranch("release-2.0.0"); fixture.Checkout("release-2.0.0"); fixture.Repository.MakeCommits(1); fixture.AssertFullSemver("2.0.0-beta.1", config); //tag it to bump to beta 2 fixture.Repository.MakeCommits(4); fixture.AssertFullSemver("2.0.0-beta.5", config); //merge down to develop fixture.Repository.CreateBranch("hotfix-2.0.0"); fixture.Repository.MakeCommits(2); //but keep working on the release fixture.Checkout("release-2.0.0"); fixture.Repository.MergeNoFF("hotfix-2.0.0", Generate.SignatureNow()); fixture.Repository.Branches.Remove(fixture.Repository.Branches["hotfix-2.0.0"]); fixture.AssertFullSemver("2.0.0-beta.7", config); } [Test] public void MergeOnReleaseBranchShouldNotResetCount() { var config = new Config { AssemblyVersioningScheme = AssemblyVersioningScheme.MajorMinorPatchTag, VersioningMode = VersioningMode.ContinuousDeployment, }; using var fixture = new EmptyRepositoryFixture(); const string taggedVersion = "1.0.3"; fixture.Repository.MakeATaggedCommit(taggedVersion); fixture.Repository.CreateBranch("develop"); fixture.Checkout("develop"); fixture.Repository.MakeACommit(); fixture.Repository.CreateBranch("release/2.0.0"); fixture.Repository.CreateBranch("release/2.0.0-xxx"); fixture.Checkout("release/2.0.0-xxx"); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("2.0.0-beta.1", config); fixture.Checkout("release/2.0.0"); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("2.0.0-beta.1", config); fixture.Repository.MergeNoFF("release/2.0.0-xxx"); fixture.AssertFullSemver("2.0.0-beta.2", config); } [Test] public void CommitOnDevelopAfterReleaseBranchMergeToDevelopShouldNotResetCount() { var config = new Config { VersioningMode = VersioningMode.ContinuousDeployment }; using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit("initial"); fixture.BranchTo("develop"); // Create release from develop fixture.BranchTo("release-2.0.0"); fixture.AssertFullSemver("2.0.0-beta.0", config); // Make some commits on release fixture.MakeACommit("release 1"); fixture.MakeACommit("release 2"); fixture.AssertFullSemver("2.0.0-beta.2", config); // First forward merge release to develop fixture.Checkout("develop"); fixture.MergeNoFF("release-2.0.0"); // Make some new commit on release fixture.Checkout("release-2.0.0"); fixture.Repository.MakeACommit("release 3 - after first merge"); fixture.AssertFullSemver("2.0.0-beta.3", config); // Make new commit on develop fixture.Checkout("develop"); // Checkout to release (no new commits) fixture.Checkout("release-2.0.0"); fixture.AssertFullSemver("2.0.0-beta.3", config); fixture.Checkout("develop"); fixture.Repository.MakeACommit("develop after merge"); // Checkout to release (no new commits) fixture.Checkout("release-2.0.0"); fixture.AssertFullSemver("2.0.0-beta.3", config); // Make some new commit on release fixture.Repository.MakeACommit("release 4"); fixture.Repository.MakeACommit("release 5"); fixture.AssertFullSemver("2.0.0-beta.5", config); // Second merge release to develop fixture.Checkout("develop"); fixture.Repository.MergeNoFF("release-2.0.0", Generate.SignatureNow()); // Checkout to release (no new commits) fixture.Checkout("release-2.0.0"); fixture.AssertFullSemver("2.0.0-beta.5", config); } [Test] public void CommitBeetweenMergeReleaseToDevelopShouldNotResetCount() { var config = new Config { VersioningMode = VersioningMode.ContinuousDeployment }; using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeACommit("initial"); fixture.Repository.CreateBranch("develop"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.CreateBranch("release-2.0.0"); Commands.Checkout(fixture.Repository, "release-2.0.0"); fixture.AssertFullSemver("2.0.0-beta.0", config); // Make some commits on release var commit1 = fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("2.0.0-beta.2", config); // Merge release to develop - emulate commit beetween other person release commit push and this commit merge to develop Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.Merge(commit1, Generate.SignatureNow(), new MergeOptions { FastForwardStrategy = FastForwardStrategy.NoFastForward }); fixture.Repository.MergeNoFF("release-2.0.0", Generate.SignatureNow()); // Check version on release after merge to develop Commands.Checkout(fixture.Repository, "release-2.0.0"); fixture.AssertFullSemver("2.0.0-beta.2", config); // Check version on release after making some new commits fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("2.0.0-beta.4", config); } public void ReleaseBranchShouldUseBranchNameVersionDespiteBumpInPreviousCommit() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0"); fixture.Repository.MakeACommit("+semver:major"); fixture.Repository.MakeACommit(); fixture.BranchTo("release/2.0"); fixture.AssertFullSemver("2.0.0-beta.1+2"); } [Test] public void ReleaseBranchWithACommitShouldUseBranchNameVersionDespiteBumpInPreviousCommit() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0"); fixture.Repository.MakeACommit("+semver:major"); fixture.Repository.MakeACommit(); fixture.BranchTo("release/2.0"); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("2.0.0-beta.1+3"); } [Test] public void ReleaseBranchedAtCommitWithSemverMessageShouldUseBranchNameVersion() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0"); fixture.Repository.MakeACommit("+semver:major"); fixture.BranchTo("release/2.0"); fixture.AssertFullSemver("2.0.0-beta.1+1"); } [Test] public void FeatureFromReleaseBranchShouldNotResetCount() { var config = new Config { VersioningMode = VersioningMode.ContinuousDeployment }; using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeACommit("initial"); fixture.Repository.CreateBranch("develop"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.CreateBranch("release-2.0.0"); Commands.Checkout(fixture.Repository, "release-2.0.0"); fixture.AssertFullSemver("2.0.0-beta.0", config); // Make some commits on release fixture.Repository.MakeCommits(10); fixture.AssertFullSemver("2.0.0-beta.10", config); // Create feature from release fixture.BranchTo("feature/xxx"); fixture.Repository.MakeACommit("feature 1"); fixture.Repository.MakeACommit("feature 2"); // Check version on release Commands.Checkout(fixture.Repository, "release-2.0.0"); fixture.AssertFullSemver("2.0.0-beta.10", config); fixture.Repository.MakeACommit("release 11"); fixture.AssertFullSemver("2.0.0-beta.11", config); // Make new commit on feature Commands.Checkout(fixture.Repository, "feature/xxx"); fixture.Repository.MakeACommit("feature 3"); // Checkout to release (no new commits) Commands.Checkout(fixture.Repository, "release-2.0.0"); fixture.AssertFullSemver("2.0.0-beta.11", config); // Merge feature to release fixture.Repository.MergeNoFF("feature/xxx", Generate.SignatureNow()); fixture.AssertFullSemver("2.0.0-beta.15", config); fixture.Repository.MakeACommit("release 13 - after feature merge"); fixture.AssertFullSemver("2.0.0-beta.16", config); } [Test] public void AssemblySemFileVerShouldBeWeightedByPreReleaseWeight() { var config = new ConfigurationBuilder() .Add(new Config { AssemblyFileVersioningFormat = "{Major}.{Minor}.{Patch}.{WeightedPreReleaseNumber}", Branches = { { "release", new BranchConfig { PreReleaseWeight = 1000 } } } }) .Build(); using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.3"); fixture.Repository.MakeCommits(5); fixture.Repository.CreateBranch("release-2.0.0"); fixture.Checkout("release-2.0.0"); var variables = fixture.GetVersion(config); Assert.AreEqual(variables.AssemblySemFileVer, "2.0.0.1001"); } [Test] public void AssemblySemFileVerShouldBeWeightedByDefaultPreReleaseWeight() { var config = new ConfigurationBuilder() .Add(new Config { AssemblyFileVersioningFormat = "{Major}.{Minor}.{Patch}.{WeightedPreReleaseNumber}", }) .Build(); using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.3"); fixture.Repository.MakeCommits(5); fixture.Repository.CreateBranch("release-2.0.0"); fixture.Checkout("release-2.0.0"); var variables = fixture.GetVersion(config); Assert.AreEqual(variables.AssemblySemFileVer, "2.0.0.30001"); } /// <summary> /// Create a feature branch from a release branch, and merge back, then delete it /// </summary> [Test] public void FeatureOnReleaseFeatureBranchDeleted() { var config = new Config { AssemblyVersioningScheme = AssemblyVersioningScheme.MajorMinorPatchTag, VersioningMode = VersioningMode.ContinuousDeployment }; using var fixture = new EmptyRepositoryFixture(); var release450 = "release/4.5.0"; var featureBranch = "feature/some-bug-fix"; fixture.Repository.MakeACommit("initial"); fixture.Repository.CreateBranch("develop"); Commands.Checkout(fixture.Repository, "develop"); // begin the release branch fixture.Repository.CreateBranch(release450); Commands.Checkout(fixture.Repository, release450); fixture.AssertFullSemver("4.5.0-beta.0", config); fixture.Repository.CreateBranch(featureBranch); Commands.Checkout(fixture.Repository, featureBranch); fixture.Repository.MakeACommit("blabla"); // commit 1 Commands.Checkout(fixture.Repository, release450); fixture.Repository.MergeNoFF(featureBranch, Generate.SignatureNow()); // commit 2 fixture.Repository.Branches.Remove(featureBranch); fixture.AssertFullSemver("4.5.0-beta.2", config); } /// <summary> /// Create a feature branch from a release branch, and merge back, but don't delete it /// </summary> [Test] public void FeatureOnReleaseFeatureBranchNotDeleted() { var config = new Config { AssemblyVersioningScheme = AssemblyVersioningScheme.MajorMinorPatchTag, VersioningMode = VersioningMode.ContinuousDeployment }; using var fixture = new EmptyRepositoryFixture(); var release450 = "release/4.5.0"; var featureBranch = "feature/some-bug-fix"; fixture.Repository.MakeACommit("initial"); fixture.Repository.CreateBranch("develop"); Commands.Checkout(fixture.Repository, "develop"); // begin the release branch fixture.Repository.CreateBranch(release450); Commands.Checkout(fixture.Repository, release450); fixture.AssertFullSemver("4.5.0-beta.0", config); fixture.Repository.CreateBranch(featureBranch); Commands.Checkout(fixture.Repository, featureBranch); fixture.Repository.MakeACommit("blabla"); // commit 1 Commands.Checkout(fixture.Repository, release450); fixture.Repository.MergeNoFF(featureBranch, Generate.SignatureNow()); // commit 2 fixture.AssertFullSemver("4.5.0-beta.2", config); } } }
/* * Copyright (C) 2009 JavaRosa ,Copyright (C) 2014 Simbacode * * 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 org.javarosa.core.model.condition; using org.javarosa.core.model.condition.pivot; using org.javarosa.core.model.instance; using org.javarosa.core.model.utils; using org.javarosa.core.util; using org.javarosa.core.util.externalizable; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace org.javarosa.xpath.expr { /** * Representation of an xpath function expression. * * All of the built-in xpath functions are included here, as well as the xpath type conversion logic * * Evaluation of functions can delegate out to custom function handlers that must be registered at * runtime. * * @author Acellam Guy , Drew Roos * */ public class XPathFuncExpr : XPathExpression { public XPathQName id; //name of the function public XPathExpression[] args; //argument list public XPathFuncExpr() { } //for deserialization public XPathFuncExpr(XPathQName id, XPathExpression[] args) { this.id = id; this.args = args; } public String ToString() { StringBuilder sb = new StringBuilder(); sb.Append("{func-expr:"); sb.Append(id.ToString()); sb.Append(",{"); for (int i = 0; i < args.Length; i++) { sb.Append(args[i].ToString()); if (i < args.Length - 1) sb.Append(","); } sb.Append("}}"); return sb.ToString(); } public Boolean Equals(Object o) { if (o is XPathFuncExpr) { XPathFuncExpr x = (XPathFuncExpr)o; //Shortcuts for very easily comprable values if (!id.Equals(x.id) || args.Length != x.args.Length) { return false; } return ExtUtil.arrayEquals(args, x.args); } else { return false; } } public void readExternal(BinaryReader in_renamed, PrototypeFactory pf) { id = (XPathQName)ExtUtil.read(in_renamed, typeof(XPathQName)); ArrayList v = (ArrayList)ExtUtil.read(in_renamed, new ExtWrapListPoly(), pf); args = new XPathExpression[v.Count]; for (int i = 0; i < args.Length; i++) args[i] = (XPathExpression)v[i]; } public void writeExternal(BinaryWriter out_renamed) { ArrayList v = new ArrayList(); for (int i = 0; i < args.Length; i++) v.Add(args[i]); ExtUtil.write(out_renamed, id); ExtUtil.write(out_renamed, new ExtWrapListPoly(v)); } /** * Evaluate the function call. * * First check if the function is a member of the built-in function suite. If not, then check * for any custom handlers registered to handler the function. If not, throw and exception. * * Both function name and appropriate arguments are taken into account when finding a suitable * handler. For built-in functions, the number of arguments must match; for custom functions, * the supplied arguments must match one of the function prototypes defined by the handler. * */ public override Object eval(FormInstance model, EvaluationContext evalContext) { String name = id.ToString(); Object[] argVals = new Object[args.Length]; Hashtable funcHandlers = evalContext.FunctionHandlers; for (int i = 0; i < args.Length; i++) { argVals[i] = args[i].eval(model, evalContext); } //check built-in functions if (name.Equals("true") && args.Length == 0) { return Boolean.TrueString; } else if (name.Equals("false") && args.Length == 0) { return Boolean.FalseString; } else if (name.Equals("Boolean") && args.Length == 1) { return toBoolean(argVals[0]); } else if (name.Equals("number") && args.Length == 1) { return toNumeric(argVals[0]); } else if (name.Equals("int") && args.Length == 1) { //non-standard return toInt(argVals[0]); } else if (name.Equals("string") && args.Length == 1) { return ToString(argVals[0]); } else if (name.Equals("date") && args.Length == 1) { //non-standard return toDate(argVals[0]); } else if (name.Equals("not") && args.Length == 1) { return boolNot(argVals[0]); } else if (name.Equals("Boolean-from-string") && args.Length == 1) { return boolStr(argVals[0]); } else if (name.Equals("format-date") && args.Length == 2) { return dateStr(argVals[0], argVals[1]); } else if (name.Equals("if") && args.Length == 3) { //non-standard return ifThenElse(argVals[0], argVals[1], argVals[2]); } else if ((name.Equals("selected") || name.Equals("is-selected")) && args.Length == 2) { //non-standard return multiSelected(argVals[0], argVals[1]); } else if (name.Equals("count-selected") && args.Length == 1) { //non-standard return countSelected(argVals[0]); } else if (name.Equals("coalesce") && args.Length == 2) { return (!isNull(argVals[0]) ? argVals[0] : argVals[1]); } else if (name.Equals("count") && args.Length == 1) { return count(argVals[0]); } else if (name.Equals("sum") && args.Length == 1) { if (argVals[0] is XPathNodeset) { return sum(((XPathNodeset)argVals[0]).toArgList()); } else { throw new XPathTypeMismatchException("not a nodeset"); } } else if (name.Equals("today") && args.Length == 0) { DateTime dt = new DateTime(); return DateUtils.roundDate(ref dt); } else if (name.Equals("now") && args.Length == 0) { return new DateTime(); } else if (name.Equals("concat")) { if (args.Length == 1 && argVals[0] is XPathNodeset) { return join("", ((XPathNodeset)argVals[0]).toArgList()); } else { return join("", argVals); } } else if (name.Equals("join") && args.Length >= 1) { if (args.Length == 2 && argVals[1] is XPathNodeset) { return join(argVals[0], ((XPathNodeset)argVals[1]).toArgList()); } else { return join(argVals[0], subsetArgList(argVals, 1)); } } else if (name.Equals("substr") && (args.Length == 2 || args.Length == 3)) { return Substring(argVals[0], argVals[1], args.Length == 3 ? argVals[2] : null); } else if (name.Equals("string-length") && args.Length == 1) { return stringLength(argVals[0]); } else if (name.Equals("checklist") && args.Length >= 2) { //non-standard if (args.Length == 3 && argVals[2] is XPathNodeset) { return checklist(argVals[0], argVals[1], ((XPathNodeset)argVals[2]).toArgList()); } else { return checklist(argVals[0], argVals[1], subsetArgList(argVals, 2)); } } else if (name.Equals("weighted-checklist") && args.Length >= 2 && args.Length % 2 == 0) { //non-standard if (args.Length == 4 && argVals[2] is XPathNodeset && argVals[3] is XPathNodeset) { Object[] factors = ((XPathNodeset)argVals[2]).toArgList(); Object[] weights = ((XPathNodeset)argVals[3]).toArgList(); if (factors.Length != weights.Length) { throw new XPathTypeMismatchException("weighted-checklist: nodesets not same length"); } return checklistWeighted(argVals[0], argVals[1], factors, weights); } else { return checklistWeighted(argVals[0], argVals[1], subsetArgList(argVals, 2, 2), subsetArgList(argVals, 3, 2)); } } else if (name.Equals("regex") && args.Length == 2) { //non-standard return regex(argVals[0], argVals[1]); } else if (name.Equals("depend") && args.Length >= 1) { //non-standard return argVals[0]; } else if (name.Equals("random") && args.Length == 0) { //non-standard //calculated expressions may be recomputed w/o warning! use with caution!! return MathUtils.getRand().NextDouble(); } else if (name.Equals("uuid") && (args.Length == 0 || args.Length == 1)) { //non-standard //calculated expressions may be recomputed w/o warning! use with caution!! if (args.Length == 0) { return PropertyUtils.genUUID(); } int len = (int)toInt(argVals[0]); return PropertyUtils.genGUID(len); } else { //check for custom handler IFunctionHandler handler = (IFunctionHandler)funcHandlers[name]; if (handler != null) { return evalCustomFunction(handler, argVals); } else { throw new XPathUnhandledException("function \'" + name + "\'"); } } } /** * Given a handler registered to handle the function, try to coerce the function arguments into * one of the prototypes defined by the handler. If no suitable prototype found, throw an eval * exception. Otherwise, evaluate. * * Note that if the handler supports 'raw args', it will receive the full, unaltered argument * list if no prototype matches. (this lets functions support variable-length argument lists) * * @param handler * @param args * @return */ private static Object evalCustomFunction(IFunctionHandler handler, Object[] args) { ArrayList prototypes = handler.Prototypes; IEnumerator e = prototypes.GetEnumerator(); Object[] typedArgs = null; while (typedArgs == null && e.MoveNext()) { typedArgs = matchPrototype(args, (Type[])e.Current); } if (typedArgs != null) { return handler.eval(typedArgs, new EvaluationContext()); } else if (handler.rawArgs()) { return handler.eval(args, new EvaluationContext()); //should we have support for expanding nodesets here? } else { throw new XPathTypeMismatchException("for function \'" + handler.Name + "\'"); } } /** * Given a prototype defined by the function handler, attempt to coerce the function arguments * to match that prototype (checking # args, type conversion, etc.). If it is coercible, return * the type-converted argument list -- these will be the arguments used to evaluate the function. * If not coercible, return null. * * @param args * @param prototype * @return */ private static Object[] matchPrototype(Object[] args, Type[] prototype) { Object[] typed = null; if (prototype.Length == args.Length) { typed = new Object[args.Length]; for (int i = 0; i < prototype.Length; i++) { typed[i] = null; //how to handle type conversions of custom types? if (prototype[i].IsAssignableFrom(args[i].GetType())) { typed[i] = args[i]; } else { try { if (prototype[i] == typeof(Boolean)) { typed[i] = toBoolean(args[i]); } else if (prototype[i] == typeof(Double)) { typed[i] = toNumeric(args[i]); } else if (prototype[i] == typeof(String)) { typed[i] = ToString(args[i]); } else if (prototype[i] == typeof(DateTime)) { typed[i] = toDate(args[i]); } } catch (XPathTypeMismatchException xptme) { /* swallow type mismatch exception */ } } if (typed[i] == null) return null; } } return typed; } /******** HANDLERS FOR BUILT-IN FUNCTIONS ******** * * the functions below are the handlers for the built-in xpath function suite * * if you add a function to the suite, it should adhere to the following pattern: * * * the function takes in its arguments as objects (DO NOT cast the arguments when calling * the handler up in eval() (i.e., return stringLength((String)argVals[0]) <--- NO!) * * * the function converts the generic argument(s) to the desired type using the built-in * xpath type conversion functions (toBoolean(), toNumeric(), toString(), toDate()) * * * the function MUST return an object of type Boolean, Double, String, or Date; it may * never return null (instead return the empty string or NaN) * * * the function may throw exceptions, but should try as hard as possible not to, and if * it must, strive to make it an XPathException * */ public static Boolean isNull(Object o) { if (o == null) { return true; //true 'null' values aren't allowed in the xpath engine, but whatever } else if (o is String && ((String)o).Length == 0) { return true; } else if (o is Double && Double.IsNaN((Double)o)) { return true; } else { return false; } } public static Double stringLength(Object o) { String s = ToString(o); if (s == null) { return 0.0D; } return s.Length; } /** * convert a value to a Boolean using xpath's type conversion rules * * @param o * @return */ public static Boolean toBoolean(Object o) { Boolean val = false; o = unpack(o); if (o is Boolean) { val = (Boolean)o; } else if (o is Double) { double d = ((Double)o); val = (Boolean)(Math.Abs(d) > 1.0e-12 && !Double.IsNaN(d)); } else if (o is String) { String s = (String)o; val = (Boolean)(s.Length > 0); } else if (o is DateTime) { val = true; } else if (o is IExprDataType) { val = ((IExprDataType)o).toBoolean(); } if (val != null) { return val; } else { throw new XPathTypeMismatchException("converting to Boolean"); } } /** * convert a value to a number using xpath's type conversion rules (note that xpath itself makes * no distinction between integer and floating point numbers) * * @param o * @return */ public static Double toNumeric(Object o) { Double val = 0.0; o = unpack(o); if (o is Boolean) { val = (Double)(((Boolean)o) ? 1 : 0); } else if (o is Double) { val = (Double)o; } else if (o is String) { /* annoying, but the xpath spec doesn't recognize scientific notation, or +/-Infinity * when converting a string to a number */ String s = (String)o; double d; try { s = s.Trim(); for (int i = 0; i < s.Length; i++) { char c = s[i]; if (c != '-' && c != '.' && (c < '0' || c > '9')) throw new FormatException(); } d = Double.Parse(s); val = (Double)(d); } catch (FormatException nfe) { val = (Double)(Double.NaN); } } else if (o is DateTime) { DateTime dt = (DateTime)o; val = (Double)(DateUtils.daysSinceEpoch(ref dt)); } else if (o is IExprDataType) { val = ((IExprDataType)o).toNumeric(); } if (val != null) { return val; } else { throw new XPathTypeMismatchException("converting to numeric"); } } /** * convert a number to an integer by truncating the fractional part. if non-numeric, coerce the * value to a number first. note that the resulting return value is still a Double, as required * by the xpath engine * * @param o * @return */ public static Double toInt(Object o) { Double val = toNumeric(o); if (Double.IsInfinity(val) || Double.IsNaN(val)) { return val; } else if (val >= long.MaxValue || val <= long.MinValue) { return val; } else { long l = (long)val; Double dbl = (Double)(l); if (l == 0 && (val < 0.0 || val.Equals((Double)(-0.0)))) { dbl = (Double)(-0.0); } return dbl; } } /** * convert a value to a string using xpath's type conversion rules * * @param o * @return */ public static String ToString(Object o) { String val = null; o = unpack(o); if (o is Boolean) { val = (((Boolean)o) ? "true" : "false"); } else if (o is Double) { double d = ((Double)o); if (Double.IsNaN(d)) { val = "NaN"; } else if (Math.Abs(d) < 1.0e-12) { val = "0"; } else if (Double.IsInfinity(d)) { val = (d < 0 ? "-" : "") + "Infinity"; } else if (Math.Abs(d - (int)d) < 1.0e-12) { val = ((int)d).ToString(); } else { val = d.ToString(); } } else if (o is String) { val = (String)o; } else if (o is DateTime) { DateTime dt = (DateTime)o; val = DateUtils.formatDate(ref dt, DateUtils.FORMAT_ISO8601); } else if (o is IExprDataType) { val = ((IExprDataType)o).ToString(); } if (val != null) { return val; } else { throw new XPathTypeMismatchException("converting to string"); } } /** * convert a value to a date. note that xpath has no intrinsic representation of dates, so this * is off-spec. dates convert to strings as 'yyyy-mm-dd', convert to numbers as # of days since * the unix epoch, and convert to Booleans always as 'true' * * string and int conversions are reversable, however: * * cannot convert bool to date * * empty string and NaN (xpath's 'null values') go unchanged, instead of being converted * into a date (which would cause an error, since Date has no null value (other than java * null, which the xpath engine can't handle)) * * note, however, than non-empty strings that aren't valid dates _will_ cause an error * during conversion * * @param o * @return */ public static Object toDate(Object o) { o = unpack(o); if (o is Double) { Double n = toInt(o); if (Double.IsNaN(n)) { return n; } if (Double.IsInfinity(n) || n > int.MaxValue || n < int.MinValue) { throw new XPathTypeMismatchException("converting out-of-range value to date"); } DateTime dt = DateUtils.getDate(1970, 1, 1); return DateUtils.dateAdd(ref dt, (int)n); } else if (o is String) { String s = (String)o; if (s.Length == 0) { return s; } DateTime d = DateUtils.parseDateTime(s); if (d == null) { throw new XPathTypeMismatchException("converting to date"); } else { return d; } } else if (o is DateTime) { DateTime dt = (DateTime)o; return DateUtils.roundDate(ref dt); } else { throw new XPathTypeMismatchException("converting to date"); } } public static Boolean boolNot(Object o) { Boolean b = toBoolean(o); return !b; } public static Boolean boolStr(Object o) { String s = ToString(o); if (s.Equals("true", StringComparison.CurrentCultureIgnoreCase) || s.Equals("1")) return true; else return false; } public static String dateStr(Object od, Object of) { od = toDate(od); if (od is DateTime) { DateTime dt = (DateTime)od; return DateUtils.format(ref dt, ToString(of)); } else { return ""; } } public static Object ifThenElse(Object o1, Object o2, Object o3) { Boolean b = toBoolean(o1); return (b ? o2 : o3); } /** * return whether a particular choice of a multi-select is selected * * @param o1 XML-serialized answer to multi-select question (i.e, space-delimited choice values) * @param o2 choice to look for * @return */ public static Boolean multiSelected(Object o1, Object o2) { String s1 = (String)unpack(o1); String s2 = ((String)unpack(o2)).Trim(); return (" " + s1 + " ").IndexOf(" " + s2 + " ") != -1; } /** * return the number of choices in a multi-select answer * * @param o XML-serialized answer to multi-select question (i.e, space-delimited choice values) * @return */ public static Double countSelected(Object o) { String s = (String)unpack(o); return DateUtils.split(s, " ", true).Count; } /** * count the number of nodes in a nodeset * * @param o * @return */ public static Double count(Object o) { if (o is XPathNodeset) { return ((XPathNodeset)o).size(); } else { throw new XPathTypeMismatchException("not a nodeset"); } } /** * sum the values in a nodeset; each element is coerced to a numeric value * * @param model * @param o * @return */ public static Double sum(Object[] argVals) { double sum = 0.0; for (int i = 0; i < argVals.Length; i++) { sum += toNumeric(argVals[i]); } return sum; } /** * concatenate an abritrary-length argument list of string values together * * @param argVals * @return */ public static String join(Object oSep, Object[] argVals) { String sep = ToString(oSep); StringBuilder sb = new StringBuilder(); for (int i = 0; i < argVals.Length; i++) { sb.Append(ToString(argVals[i])); if (i < argVals.Length - 1) sb.Append(sep); } return sb.ToString(); } public static String Substring(Object o1, Object o2, Object o3) { String s = ToString(o1); int start =(int) toInt(o2); int len = s.Length; int end = (o3 != null ? (int)toInt(o3) : len); if (start < 0) { start = len + start; } if (end < 0) { end = len + end; } start = Math.Min(Math.Max(0, start), end); end = Math.Min(Math.Max(0, end), end); return (start <= end ? s.Substring(start, end) : ""); } /** * perform a 'checklist' computation, enabling expressions like 'if there are at least 3 risk * factors active' * * @param argVals * the first argument is a numeric value expressing the minimum number of factors required. * if -1, no minimum is applicable * the second argument is a numeric value expressing the maximum number of allowed factors. * if -1, no maximum is applicalbe * arguments 3 through the end are the individual factors, each coerced to a Boolean value * @return true if the count of 'true' factors is between the applicable minimum and maximum, * inclusive */ public static Boolean checklist(Object oMin, Object oMax, Object[] factors) { int min = (int)toNumeric(oMin); int max = (int)toNumeric(oMax); int count = 0; for (int i = 0; i < factors.Length; i++) { if (toBoolean(factors[i])) count++; } return (min < 0 || count >= min) && (max < 0 || count <= max); } /** * very similar to checklist, only each factor is assigned a real-number 'weight'. * * the first and second args are again the minimum and maximum, but -1 no longer means * 'not applicable'. * * subsequent arguments come in pairs: first the Boolean value, then the floating-point * weight for that value * * the weights of all the 'true' factors are summed, and the function returns whether * this sum is between the min and max * * @param argVals * @return */ public static Boolean checklistWeighted(Object oMin, Object oMax, Object[] flags, Object[] weights) { double min = toNumeric(oMin); double max = toNumeric(oMax); double sum = 0.0; for (int i = 0; i < flags.Length; i++) { Boolean flag = toBoolean(flags[i]); double weight = toNumeric(weights[i]); if (flag) sum += weight; } return sum >= min && sum <= max; } /** * determine if a string matches a regular expression. * * @param o1 string being matched * @param o2 regular expression * @return */ public static Boolean regex(Object o1, Object o2) { String str = ToString(o1); String re = ToString(o2); Regex regexp = new Regex(re); Boolean result = (regexp.Match(str)!=null? true : false); return result; } private static Object[] subsetArgList(Object[] args, int start) { return subsetArgList(args, start, 1); } /** * return a subset of an argument list as a new arguments list * * @param args * @param start index to start at * @param skip sub-list will contain every nth argument, where n == skip (default: 1) * @return */ private static Object[] subsetArgList(Object[] args, int start, int skip) { if (start > args.Length || skip < 1) { throw new SystemException("error in subsetting arglist"); } Object[] subargs = new Object[(int)MathUtils.divLongNotSuck(args.Length - start - 1, skip) + 1]; for (int i = start, j = 0; i < args.Length; i += skip, j++) { subargs[j] = args[i]; } return subargs; } public static Object unpack(Object o) { if (o is XPathNodeset) { return ((XPathNodeset)o).unpack(); } else { return o; } } /** * */ public Object pivot(FormInstance model, EvaluationContext evalContext, List<Object> pivots, Object sentinal) { String name = this.id.ToString(); //for now we'll assume that all that functions do is return the composition of their components Object[] argVals = new Object[args.Length]; //Identify whether this function is an identity: IE: can reflect back the pivot sentinal with no modification String[] identities = new String[] { "string-length" }; Boolean id = false; foreach (String identity in identities) { if (identity.Equals(name)) { id = true; } } //get each argument's pivot for (int i = 0; i < args.Length; i++) { argVals[i] = args[i].pivot(model, evalContext, pivots, sentinal); } Boolean pivoted = false; //evaluate the pivots for (int i = 0; i < argVals.Length; ++i) { if (argVals[i] == null) { //one of our arguments contained pivots, pivoted = true; } else if (sentinal.Equals(argVals[i])) { //one of our arguments is the sentinal, return the sentinal if possible if (id) { return sentinal; } else { //This function modifies the sentinal in a way that makes it impossible to capture //the pivot. throw new UnpivotableExpressionException(); } } } if (pivoted) { if (id) { return null; } else { //This function modifies the sentinal in a way that makes it impossible to capture //the pivot. throw new UnpivotableExpressionException(); } } //TODO: Inner eval here with eval'd args to improve speed return eval(model, evalContext); } } }
// 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.ServiceFabric { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ClustersOperations operations. /// </summary> internal partial class ClustersOperations : IServiceOperations<ServiceFabricManagementClient>, IClustersOperations { /// <summary> /// Initializes a new instance of the ClustersOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ClustersOperations(ServiceFabricManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the ServiceFabricManagementClient /// </summary> public ServiceFabricManagementClient Client { get; private set; } /// <summary> /// Update cluster configuration /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to which the resource belongs or get created /// </param> /// <param name='clusterName'> /// The name of the cluster resource /// </param> /// <param name='clusterUpdateParameters'> /// The parameters which contains the property value and property name which /// used to update the cluster configuration /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<Cluster>> UpdateWithHttpMessagesAsync(string resourceGroupName, string clusterName, ClusterUpdateParameters clusterUpdateParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<Cluster> _response = await BeginUpdateWithHttpMessagesAsync(resourceGroupName, clusterName, clusterUpdateParameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get cluster resource /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to which the resource belongs or get created /// </param> /// <param name='clusterName'> /// The name of the cluster resource /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorModelException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Cluster>> GetWithHttpMessagesAsync(string resourceGroupName, string clusterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (clusterName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "clusterName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("clusterName", clusterName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters/{clusterName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{clusterName}", System.Uri.EscapeDataString(clusterName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorModelException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorModel _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorModel>(_responseContent, 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<Cluster>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Cluster>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create cluster resource /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to which the resource belongs or get created /// </param> /// <param name='clusterName'> /// The name of the cluster resource /// </param> /// <param name='clusterResource'> /// Put Request /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<Cluster>> CreateWithHttpMessagesAsync(string resourceGroupName, string clusterName, Cluster clusterResource, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<Cluster> _response = await BeginCreateWithHttpMessagesAsync(resourceGroupName, clusterName, clusterResource, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Delete cluster resource /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to which the resource belongs or get created /// </param> /// <param name='clusterName'> /// The name of the cluster resource /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorModelException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string clusterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (clusterName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "clusterName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("clusterName", clusterName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters/{clusterName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{clusterName}", System.Uri.EscapeDataString(clusterName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 204) { var ex = new ErrorModelException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorModel _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorModel>(_responseContent, 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; } /// <summary> /// List cluster resource by resource group /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to which the resource belongs or get created /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Cluster>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Cluster>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Cluster>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// List cluster resource /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Cluster>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.ServiceFabric/clusters").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Cluster>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Cluster>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Update cluster configuration /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to which the resource belongs or get created /// </param> /// <param name='clusterName'> /// The name of the cluster resource /// </param> /// <param name='clusterUpdateParameters'> /// The parameters which contains the property value and property name which /// used to update the cluster configuration /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorModelException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Cluster>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string clusterName, ClusterUpdateParameters clusterUpdateParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (clusterName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "clusterName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (clusterUpdateParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "clusterUpdateParameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("clusterName", clusterName); tracingParameters.Add("clusterUpdateParameters", clusterUpdateParameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters/{clusterName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{clusterName}", System.Uri.EscapeDataString(clusterName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(clusterUpdateParameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(clusterUpdateParameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new ErrorModelException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorModel _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorModel>(_responseContent, 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<Cluster>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Cluster>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create cluster resource /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to which the resource belongs or get created /// </param> /// <param name='clusterName'> /// The name of the cluster resource /// </param> /// <param name='clusterResource'> /// Put Request /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorModelException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Cluster>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string clusterName, Cluster clusterResource, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (clusterName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "clusterName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (clusterResource == null) { throw new ValidationException(ValidationRules.CannotBeNull, "clusterResource"); } if (clusterResource != null) { clusterResource.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("clusterName", clusterName); tracingParameters.Add("clusterResource", clusterResource); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters/{clusterName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{clusterName}", System.Uri.EscapeDataString(clusterName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(clusterResource != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(clusterResource, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new ErrorModelException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorModel _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorModel>(_responseContent, 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<Cluster>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Cluster>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// List cluster resource by resource group /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Cluster>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroupNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Cluster>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Cluster>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// List cluster resource /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Cluster>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Cluster>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Cluster>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Sockets; #if !NETCOREAPP using System.Runtime.Remoting.Messaging; #endif using System.Text; using System.Threading.Tasks; namespace Mono.Debugger.Soft { public class LaunchOptions { public string AgentArgs { get; set; } public bool Valgrind { get; set; } public ProcessLauncher CustomProcessLauncher { get; set; } public TargetProcessLauncher CustomTargetProcessLauncher { get; set; } public delegate Process ProcessLauncher (ProcessStartInfo info); public delegate ITargetProcess TargetProcessLauncher (ProcessStartInfo info); } public class VirtualMachineManager { private delegate VirtualMachine LaunchCallback (ITargetProcess p, ProcessStartInfo info, Socket socket); private delegate VirtualMachine ListenCallback (Socket dbg_sock, Socket con_sock); private delegate VirtualMachine ConnectCallback (Socket dbg_sock, Socket con_sock, IPEndPoint dbg_ep, IPEndPoint con_ep); internal VirtualMachineManager () { } public static VirtualMachine LaunchInternal (Process p, ProcessStartInfo info, Socket socket) { return LaunchInternal (new ProcessWrapper (p), info, socket); } public static VirtualMachine LaunchInternal (ITargetProcess p, ProcessStartInfo info, Socket socket) { return LaunchInternalAsync (p, info, socket).Result; } public static async Task<VirtualMachine> LaunchInternalAsync (ITargetProcess p, ProcessStartInfo info, Socket socket) { Socket accepted = null; try { accepted = await socket.AcceptAsync ().ConfigureAwait(false); } catch (Exception) { throw; } Connection conn = new TcpConnection (accepted); VirtualMachine vm = new VirtualMachine (p, conn); if (info.RedirectStandardOutput) vm.StandardOutput = p.StandardOutput; if (info.RedirectStandardError) vm.StandardError = p.StandardError; conn.EventHandler = new EventHandler (vm); vm.connect (); return vm; } public static IAsyncResult BeginLaunch (ProcessStartInfo info, AsyncCallback callback) { return BeginLaunch (info, callback, null); } public static IAsyncResult BeginLaunch (ProcessStartInfo info, AsyncCallback callback, LaunchOptions options) { if (info == null) throw new ArgumentNullException ("info"); Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Bind (new IPEndPoint (IPAddress.Loopback, 0)); socket.Listen (1000); IPEndPoint ep = (IPEndPoint) socket.LocalEndPoint; // We need to inject our arguments into the psi info.Arguments = string.Format ("{0} --debug --debugger-agent=transport=dt_socket,address={1}:{2}{3} {4}", options == null || !options.Valgrind ? "" : info.FileName, ep.Address, ep.Port, options == null || options.AgentArgs == null ? "" : "," + options.AgentArgs, info.Arguments); if (options != null && options.Valgrind) info.FileName = "valgrind"; info.UseShellExecute = false; if (info.RedirectStandardError) info.StandardErrorEncoding = Encoding.UTF8; if (info.RedirectStandardOutput) info.StandardOutputEncoding = Encoding.UTF8; ITargetProcess p; if (options != null && options.CustomProcessLauncher != null) p = new ProcessWrapper (options.CustomProcessLauncher (info)); else if (options != null && options.CustomTargetProcessLauncher != null) p = options.CustomTargetProcessLauncher (info); else p = new ProcessWrapper (Process.Start (info)); p.Exited += delegate (object sender, EventArgs eargs) { socket.Close (); }; var listenTask = LaunchInternalAsync (p, info, socket); listenTask.ContinueWith (t => callback (listenTask)); return listenTask; } public static VirtualMachine EndLaunch (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); var listenTask = (Task<VirtualMachine>)asyncResult; return listenTask.Result; } public static VirtualMachine Launch (ProcessStartInfo info) { return Launch (info, null); } public static VirtualMachine Launch (ProcessStartInfo info, LaunchOptions options) { return EndLaunch (BeginLaunch (info, null, options)); } public static VirtualMachine Launch (string[] args) { return Launch (args, null); } public static VirtualMachine Launch (string[] args, LaunchOptions options) { ProcessStartInfo pi = new ProcessStartInfo ("mono"); pi.Arguments = String.Join (" ", args); return Launch (pi, options); } public static VirtualMachine ListenInternal (Socket dbg_sock, Socket con_sock) { return ListenInternalAsync (dbg_sock, con_sock).Result; } static async Task<VirtualMachine> ListenInternalAsync (Socket dbg_sock, Socket con_sock) { Socket con_acc = null; Socket dbg_acc = null; if (con_sock != null) { try { con_acc = await con_sock.AcceptAsync ().ConfigureAwait (false); } catch (Exception) { try { dbg_sock.Close (); } catch { } throw; } } try { dbg_acc = await dbg_sock.AcceptAsync ().ConfigureAwait (false); } catch (Exception) { if (con_sock != null) { try { con_sock.Close (); con_acc.Close (); } catch { } } throw; } if (con_sock != null) { if (con_sock.Connected) con_sock.Disconnect (false); con_sock.Close (); } if (dbg_sock.Connected) dbg_sock.Disconnect (false); dbg_sock.Close (); Connection transport = new TcpConnection (dbg_acc); StreamReader console = con_acc != null ? new StreamReader (new NetworkStream (con_acc)) : null; return Connect (transport, console, null); } public static IAsyncResult BeginListen (IPEndPoint dbg_ep, AsyncCallback callback) { return BeginListen (dbg_ep, null, callback); } public static IAsyncResult BeginListen (IPEndPoint dbg_ep, IPEndPoint con_ep, AsyncCallback callback) { int dbg_port, con_port; return BeginListen (dbg_ep, con_ep, callback, out dbg_port, out con_port); } public static IAsyncResult BeginListen (IPEndPoint dbg_ep, IPEndPoint con_ep, AsyncCallback callback, out int dbg_port, out int con_port) { dbg_port = con_port = 0; Socket dbg_sock = null; Socket con_sock = null; dbg_sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); dbg_sock.Bind (dbg_ep); dbg_sock.Listen (1000); dbg_port = ((IPEndPoint) dbg_sock.LocalEndPoint).Port; if (con_ep != null) { con_sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); con_sock.Bind (con_ep); con_sock.Listen (1000); con_port = ((IPEndPoint) con_sock.LocalEndPoint).Port; } var listenTask = ListenInternalAsync (dbg_sock, con_sock); listenTask.ContinueWith (t => callback (listenTask)); return listenTask; } public static VirtualMachine EndListen (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); var listenTask = (Task<VirtualMachine>)asyncResult; return listenTask.Result; } public static VirtualMachine Listen (IPEndPoint dbg_ep) { return Listen (dbg_ep, null); } public static VirtualMachine Listen (IPEndPoint dbg_ep, IPEndPoint con_ep) { return EndListen (BeginListen (dbg_ep, con_ep, null)); } /* * Connect to a virtual machine listening at the specified address. */ public static VirtualMachine Connect (IPEndPoint endpoint) { return Connect (endpoint, null); } public static VirtualMachine Connect (IPEndPoint endpoint, IPEndPoint consoleEndpoint) { if (endpoint == null) throw new ArgumentNullException ("endpoint"); return EndConnect (BeginConnect (endpoint, consoleEndpoint, null)); } public static VirtualMachine ConnectInternal (Socket dbg_sock, Socket con_sock, IPEndPoint dbg_ep, IPEndPoint con_ep) { return ConnectInternalAsync (dbg_sock, con_sock, dbg_ep, con_ep).Result; } public static async Task<VirtualMachine> ConnectInternalAsync (Socket dbg_sock, Socket con_sock, IPEndPoint dbg_ep, IPEndPoint con_ep) { if (con_sock != null) { try { await con_sock.ConnectAsync(con_ep).ConfigureAwait (false); } catch (Exception) { try { dbg_sock.Close (); } catch { } throw; } } try { await dbg_sock.ConnectAsync(dbg_ep).ConfigureAwait(false); } catch (Exception) { if (con_sock != null) { try { con_sock.Close (); } catch { } } throw; } Connection transport = new TcpConnection (dbg_sock); StreamReader console = con_sock != null ? new StreamReader (new NetworkStream (con_sock)) : null; return Connect (transport, console, null); } public static IAsyncResult BeginConnect (IPEndPoint dbg_ep, AsyncCallback callback) { return BeginConnect (dbg_ep, null, callback); } public static IAsyncResult BeginConnect (IPEndPoint dbg_ep, IPEndPoint con_ep, AsyncCallback callback) { Socket dbg_sock = null; Socket con_sock = null; dbg_sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); if (con_ep != null) { con_sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } var connectTask = ConnectInternalAsync (dbg_sock, con_sock, dbg_ep, con_ep); connectTask.ContinueWith (t => callback (connectTask)); return connectTask; } public static VirtualMachine EndConnect (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); var connectTask = (Task<VirtualMachine>)asyncResult; return connectTask.Result; } public static void CancelConnection (IAsyncResult asyncResult) { ((Socket)asyncResult.AsyncState).Close (); } public static VirtualMachine Connect (Connection transport, StreamReader standardOutput, StreamReader standardError) { VirtualMachine vm = new VirtualMachine (null, transport); vm.StandardOutput = standardOutput; vm.StandardError = standardError; transport.EventHandler = new EventHandler (vm); vm.connect (); return vm; } } }
// 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: Culture-specific collection of resources. ** ** ===========================================================*/ using System.Collections; using System.IO; using System.Reflection; using System.Diagnostics.Contracts; namespace System.Resources { // A ResourceSet stores all the resources defined in one particular CultureInfo. // // The method used to load resources is straightforward - this class // enumerates over an IResourceReader, loading every name and value, and // stores them in a hash table. Custom IResourceReaders can be used. // public class ResourceSet : IDisposable, IEnumerable { protected IResourceReader Reader; internal Hashtable Table; private Hashtable _caseInsensitiveTable; // For case-insensitive lookups. protected ResourceSet() { // To not inconvenience people subclassing us, we should allocate a new // hashtable here just so that Table is set to something. CommonInit(); } // For RuntimeResourceSet, ignore the Table parameter - it's a wasted // allocation. internal ResourceSet(bool junk) { } // Creates a ResourceSet using the system default ResourceReader // implementation. Use this constructor to open & read from a file // on disk. // public ResourceSet(String fileName) { Reader = new ResourceReader(fileName); CommonInit(); ReadResources(); } // Creates a ResourceSet using the system default ResourceReader // implementation. Use this constructor to read from an open stream // of data. // public ResourceSet(Stream stream) { Reader = new ResourceReader(stream); CommonInit(); ReadResources(); } public ResourceSet(IResourceReader reader) { if (reader == null) throw new ArgumentNullException(nameof(reader)); Contract.EndContractBlock(); Reader = reader; CommonInit(); ReadResources(); } private void CommonInit() { Table = new Hashtable(); } // Closes and releases any resources used by this ResourceSet, if any. // All calls to methods on the ResourceSet after a call to close may // fail. Close is guaranteed to be safely callable multiple times on a // particular ResourceSet, and all subclasses must support these semantics. public virtual void Close() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { // Close the Reader in a thread-safe way. IResourceReader copyOfReader = Reader; Reader = null; if (copyOfReader != null) copyOfReader.Close(); } Reader = null; _caseInsensitiveTable = null; Table = null; } public void Dispose() { Dispose(true); } // Returns the preferred IResourceReader class for this kind of ResourceSet. // Subclasses of ResourceSet using their own Readers &; should override // GetDefaultReader and GetDefaultWriter. public virtual Type GetDefaultReader() { return typeof(ResourceReader); } // Returns the preferred IResourceWriter class for this kind of ResourceSet. // Subclasses of ResourceSet using their own Readers &; should override // GetDefaultReader and GetDefaultWriter. public virtual Type GetDefaultWriter() { Assembly resourceWriterAssembly = Assembly.Load("System.Resources.Writer, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); return resourceWriterAssembly.GetType("System.Resources.ResourceWriter", true); } public virtual IDictionaryEnumerator GetEnumerator() { return GetEnumeratorHelper(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumeratorHelper(); } private IDictionaryEnumerator GetEnumeratorHelper() { Hashtable copyOfTable = Table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); return copyOfTable.GetEnumerator(); } // Look up a string value for a resource given its name. // public virtual String GetString(String name) { Object obj = GetObjectInternal(name); try { return (String)obj; } catch (InvalidCastException) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Name, name)); } } public virtual String GetString(String name, bool ignoreCase) { Object obj; String s; // Case-sensitive lookup obj = GetObjectInternal(name); try { s = (String)obj; } catch (InvalidCastException) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Name, name)); } // case-sensitive lookup succeeded if (s != null || !ignoreCase) { return s; } // Try doing a case-insensitive lookup obj = GetCaseInsensitiveObjectInternal(name); try { return (String)obj; } catch (InvalidCastException) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Name, name)); } } // Look up an object value for a resource given its name. // public virtual Object GetObject(String name) { return GetObjectInternal(name); } public virtual Object GetObject(String name, bool ignoreCase) { Object obj = GetObjectInternal(name); if (obj != null || !ignoreCase) return obj; return GetCaseInsensitiveObjectInternal(name); } protected virtual void ReadResources() { IDictionaryEnumerator en = Reader.GetEnumerator(); while (en.MoveNext()) { Object value = en.Value; Table.Add(en.Key, value); } // While technically possible to close the Reader here, don't close it // to help with some WinRes lifetime issues. } private Object GetObjectInternal(String name) { if (name == null) throw new ArgumentNullException(nameof(name)); Contract.EndContractBlock(); Hashtable copyOfTable = Table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); return copyOfTable[name]; } private Object GetCaseInsensitiveObjectInternal(String name) { Hashtable copyOfTable = Table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); Hashtable caseTable = _caseInsensitiveTable; // Avoid a race condition with Close if (caseTable == null) { caseTable = new Hashtable(StringComparer.OrdinalIgnoreCase); IDictionaryEnumerator en = copyOfTable.GetEnumerator(); while (en.MoveNext()) { caseTable.Add(en.Key, en.Value); } _caseInsensitiveTable = caseTable; } return caseTable[name]; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Settings/Master/GymBattleSettings.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace POGOProtos.Settings.Master { /// <summary>Holder for reflection information generated from POGOProtos/Settings/Master/GymBattleSettings.proto</summary> public static partial class GymBattleSettingsReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Settings/Master/GymBattleSettings.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static GymBattleSettingsReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjJQT0dPUHJvdG9zL1NldHRpbmdzL01hc3Rlci9HeW1CYXR0bGVTZXR0aW5n", "cy5wcm90bxIaUE9HT1Byb3Rvcy5TZXR0aW5ncy5NYXN0ZXIi7gMKEUd5bUJh", "dHRsZVNldHRpbmdzEhYKDmVuZXJneV9wZXJfc2VjGAEgASgCEhkKEWRvZGdl", "X2VuZXJneV9jb3N0GAIgASgCEhgKEHJldGFyZ2V0X3NlY29uZHMYAyABKAIS", "HQoVZW5lbXlfYXR0YWNrX2ludGVydmFsGAQgASgCEh4KFmF0dGFja19zZXJ2", "ZXJfaW50ZXJ2YWwYBSABKAISHgoWcm91bmRfZHVyYXRpb25fc2Vjb25kcxgG", "IAEoAhIjChtib251c190aW1lX3Blcl9hbGx5X3NlY29uZHMYByABKAISJAoc", "bWF4aW11bV9hdHRhY2tlcnNfcGVyX2JhdHRsZRgIIAEoBRIpCiFzYW1lX3R5", "cGVfYXR0YWNrX2JvbnVzX211bHRpcGxpZXIYCSABKAISFgoObWF4aW11bV9l", "bmVyZ3kYCiABKAUSJAocZW5lcmd5X2RlbHRhX3Blcl9oZWFsdGhfbG9zdBgL", "IAEoAhIZChFkb2RnZV9kdXJhdGlvbl9tcxgMIAEoBRIcChRtaW5pbXVtX3Bs", "YXllcl9sZXZlbBgNIAEoBRIYChBzd2FwX2R1cmF0aW9uX21zGA4gASgFEiYK", "HmRvZGdlX2RhbWFnZV9yZWR1Y3Rpb25fcGVyY2VudBgPIAEoAmIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Settings.Master.GymBattleSettings), global::POGOProtos.Settings.Master.GymBattleSettings.Parser, new[]{ "EnergyPerSec", "DodgeEnergyCost", "RetargetSeconds", "EnemyAttackInterval", "AttackServerInterval", "RoundDurationSeconds", "BonusTimePerAllySeconds", "MaximumAttackersPerBattle", "SameTypeAttackBonusMultiplier", "MaximumEnergy", "EnergyDeltaPerHealthLost", "DodgeDurationMs", "MinimumPlayerLevel", "SwapDurationMs", "DodgeDamageReductionPercent" }, null, null, null) })); } #endregion } #region Messages public sealed partial class GymBattleSettings : pb::IMessage<GymBattleSettings> { private static readonly pb::MessageParser<GymBattleSettings> _parser = new pb::MessageParser<GymBattleSettings>(() => new GymBattleSettings()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GymBattleSettings> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Settings.Master.GymBattleSettingsReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GymBattleSettings() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GymBattleSettings(GymBattleSettings other) : this() { energyPerSec_ = other.energyPerSec_; dodgeEnergyCost_ = other.dodgeEnergyCost_; retargetSeconds_ = other.retargetSeconds_; enemyAttackInterval_ = other.enemyAttackInterval_; attackServerInterval_ = other.attackServerInterval_; roundDurationSeconds_ = other.roundDurationSeconds_; bonusTimePerAllySeconds_ = other.bonusTimePerAllySeconds_; maximumAttackersPerBattle_ = other.maximumAttackersPerBattle_; sameTypeAttackBonusMultiplier_ = other.sameTypeAttackBonusMultiplier_; maximumEnergy_ = other.maximumEnergy_; energyDeltaPerHealthLost_ = other.energyDeltaPerHealthLost_; dodgeDurationMs_ = other.dodgeDurationMs_; minimumPlayerLevel_ = other.minimumPlayerLevel_; swapDurationMs_ = other.swapDurationMs_; dodgeDamageReductionPercent_ = other.dodgeDamageReductionPercent_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GymBattleSettings Clone() { return new GymBattleSettings(this); } /// <summary>Field number for the "energy_per_sec" field.</summary> public const int EnergyPerSecFieldNumber = 1; private float energyPerSec_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float EnergyPerSec { get { return energyPerSec_; } set { energyPerSec_ = value; } } /// <summary>Field number for the "dodge_energy_cost" field.</summary> public const int DodgeEnergyCostFieldNumber = 2; private float dodgeEnergyCost_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float DodgeEnergyCost { get { return dodgeEnergyCost_; } set { dodgeEnergyCost_ = value; } } /// <summary>Field number for the "retarget_seconds" field.</summary> public const int RetargetSecondsFieldNumber = 3; private float retargetSeconds_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float RetargetSeconds { get { return retargetSeconds_; } set { retargetSeconds_ = value; } } /// <summary>Field number for the "enemy_attack_interval" field.</summary> public const int EnemyAttackIntervalFieldNumber = 4; private float enemyAttackInterval_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float EnemyAttackInterval { get { return enemyAttackInterval_; } set { enemyAttackInterval_ = value; } } /// <summary>Field number for the "attack_server_interval" field.</summary> public const int AttackServerIntervalFieldNumber = 5; private float attackServerInterval_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float AttackServerInterval { get { return attackServerInterval_; } set { attackServerInterval_ = value; } } /// <summary>Field number for the "round_duration_seconds" field.</summary> public const int RoundDurationSecondsFieldNumber = 6; private float roundDurationSeconds_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float RoundDurationSeconds { get { return roundDurationSeconds_; } set { roundDurationSeconds_ = value; } } /// <summary>Field number for the "bonus_time_per_ally_seconds" field.</summary> public const int BonusTimePerAllySecondsFieldNumber = 7; private float bonusTimePerAllySeconds_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float BonusTimePerAllySeconds { get { return bonusTimePerAllySeconds_; } set { bonusTimePerAllySeconds_ = value; } } /// <summary>Field number for the "maximum_attackers_per_battle" field.</summary> public const int MaximumAttackersPerBattleFieldNumber = 8; private int maximumAttackersPerBattle_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int MaximumAttackersPerBattle { get { return maximumAttackersPerBattle_; } set { maximumAttackersPerBattle_ = value; } } /// <summary>Field number for the "same_type_attack_bonus_multiplier" field.</summary> public const int SameTypeAttackBonusMultiplierFieldNumber = 9; private float sameTypeAttackBonusMultiplier_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float SameTypeAttackBonusMultiplier { get { return sameTypeAttackBonusMultiplier_; } set { sameTypeAttackBonusMultiplier_ = value; } } /// <summary>Field number for the "maximum_energy" field.</summary> public const int MaximumEnergyFieldNumber = 10; private int maximumEnergy_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int MaximumEnergy { get { return maximumEnergy_; } set { maximumEnergy_ = value; } } /// <summary>Field number for the "energy_delta_per_health_lost" field.</summary> public const int EnergyDeltaPerHealthLostFieldNumber = 11; private float energyDeltaPerHealthLost_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float EnergyDeltaPerHealthLost { get { return energyDeltaPerHealthLost_; } set { energyDeltaPerHealthLost_ = value; } } /// <summary>Field number for the "dodge_duration_ms" field.</summary> public const int DodgeDurationMsFieldNumber = 12; private int dodgeDurationMs_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int DodgeDurationMs { get { return dodgeDurationMs_; } set { dodgeDurationMs_ = value; } } /// <summary>Field number for the "minimum_player_level" field.</summary> public const int MinimumPlayerLevelFieldNumber = 13; private int minimumPlayerLevel_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int MinimumPlayerLevel { get { return minimumPlayerLevel_; } set { minimumPlayerLevel_ = value; } } /// <summary>Field number for the "swap_duration_ms" field.</summary> public const int SwapDurationMsFieldNumber = 14; private int swapDurationMs_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int SwapDurationMs { get { return swapDurationMs_; } set { swapDurationMs_ = value; } } /// <summary>Field number for the "dodge_damage_reduction_percent" field.</summary> public const int DodgeDamageReductionPercentFieldNumber = 15; private float dodgeDamageReductionPercent_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float DodgeDamageReductionPercent { get { return dodgeDamageReductionPercent_; } set { dodgeDamageReductionPercent_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GymBattleSettings); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GymBattleSettings other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (EnergyPerSec != other.EnergyPerSec) return false; if (DodgeEnergyCost != other.DodgeEnergyCost) return false; if (RetargetSeconds != other.RetargetSeconds) return false; if (EnemyAttackInterval != other.EnemyAttackInterval) return false; if (AttackServerInterval != other.AttackServerInterval) return false; if (RoundDurationSeconds != other.RoundDurationSeconds) return false; if (BonusTimePerAllySeconds != other.BonusTimePerAllySeconds) return false; if (MaximumAttackersPerBattle != other.MaximumAttackersPerBattle) return false; if (SameTypeAttackBonusMultiplier != other.SameTypeAttackBonusMultiplier) return false; if (MaximumEnergy != other.MaximumEnergy) return false; if (EnergyDeltaPerHealthLost != other.EnergyDeltaPerHealthLost) return false; if (DodgeDurationMs != other.DodgeDurationMs) return false; if (MinimumPlayerLevel != other.MinimumPlayerLevel) return false; if (SwapDurationMs != other.SwapDurationMs) return false; if (DodgeDamageReductionPercent != other.DodgeDamageReductionPercent) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (EnergyPerSec != 0F) hash ^= EnergyPerSec.GetHashCode(); if (DodgeEnergyCost != 0F) hash ^= DodgeEnergyCost.GetHashCode(); if (RetargetSeconds != 0F) hash ^= RetargetSeconds.GetHashCode(); if (EnemyAttackInterval != 0F) hash ^= EnemyAttackInterval.GetHashCode(); if (AttackServerInterval != 0F) hash ^= AttackServerInterval.GetHashCode(); if (RoundDurationSeconds != 0F) hash ^= RoundDurationSeconds.GetHashCode(); if (BonusTimePerAllySeconds != 0F) hash ^= BonusTimePerAllySeconds.GetHashCode(); if (MaximumAttackersPerBattle != 0) hash ^= MaximumAttackersPerBattle.GetHashCode(); if (SameTypeAttackBonusMultiplier != 0F) hash ^= SameTypeAttackBonusMultiplier.GetHashCode(); if (MaximumEnergy != 0) hash ^= MaximumEnergy.GetHashCode(); if (EnergyDeltaPerHealthLost != 0F) hash ^= EnergyDeltaPerHealthLost.GetHashCode(); if (DodgeDurationMs != 0) hash ^= DodgeDurationMs.GetHashCode(); if (MinimumPlayerLevel != 0) hash ^= MinimumPlayerLevel.GetHashCode(); if (SwapDurationMs != 0) hash ^= SwapDurationMs.GetHashCode(); if (DodgeDamageReductionPercent != 0F) hash ^= DodgeDamageReductionPercent.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (EnergyPerSec != 0F) { output.WriteRawTag(13); output.WriteFloat(EnergyPerSec); } if (DodgeEnergyCost != 0F) { output.WriteRawTag(21); output.WriteFloat(DodgeEnergyCost); } if (RetargetSeconds != 0F) { output.WriteRawTag(29); output.WriteFloat(RetargetSeconds); } if (EnemyAttackInterval != 0F) { output.WriteRawTag(37); output.WriteFloat(EnemyAttackInterval); } if (AttackServerInterval != 0F) { output.WriteRawTag(45); output.WriteFloat(AttackServerInterval); } if (RoundDurationSeconds != 0F) { output.WriteRawTag(53); output.WriteFloat(RoundDurationSeconds); } if (BonusTimePerAllySeconds != 0F) { output.WriteRawTag(61); output.WriteFloat(BonusTimePerAllySeconds); } if (MaximumAttackersPerBattle != 0) { output.WriteRawTag(64); output.WriteInt32(MaximumAttackersPerBattle); } if (SameTypeAttackBonusMultiplier != 0F) { output.WriteRawTag(77); output.WriteFloat(SameTypeAttackBonusMultiplier); } if (MaximumEnergy != 0) { output.WriteRawTag(80); output.WriteInt32(MaximumEnergy); } if (EnergyDeltaPerHealthLost != 0F) { output.WriteRawTag(93); output.WriteFloat(EnergyDeltaPerHealthLost); } if (DodgeDurationMs != 0) { output.WriteRawTag(96); output.WriteInt32(DodgeDurationMs); } if (MinimumPlayerLevel != 0) { output.WriteRawTag(104); output.WriteInt32(MinimumPlayerLevel); } if (SwapDurationMs != 0) { output.WriteRawTag(112); output.WriteInt32(SwapDurationMs); } if (DodgeDamageReductionPercent != 0F) { output.WriteRawTag(125); output.WriteFloat(DodgeDamageReductionPercent); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (EnergyPerSec != 0F) { size += 1 + 4; } if (DodgeEnergyCost != 0F) { size += 1 + 4; } if (RetargetSeconds != 0F) { size += 1 + 4; } if (EnemyAttackInterval != 0F) { size += 1 + 4; } if (AttackServerInterval != 0F) { size += 1 + 4; } if (RoundDurationSeconds != 0F) { size += 1 + 4; } if (BonusTimePerAllySeconds != 0F) { size += 1 + 4; } if (MaximumAttackersPerBattle != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(MaximumAttackersPerBattle); } if (SameTypeAttackBonusMultiplier != 0F) { size += 1 + 4; } if (MaximumEnergy != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(MaximumEnergy); } if (EnergyDeltaPerHealthLost != 0F) { size += 1 + 4; } if (DodgeDurationMs != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(DodgeDurationMs); } if (MinimumPlayerLevel != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(MinimumPlayerLevel); } if (SwapDurationMs != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(SwapDurationMs); } if (DodgeDamageReductionPercent != 0F) { size += 1 + 4; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GymBattleSettings other) { if (other == null) { return; } if (other.EnergyPerSec != 0F) { EnergyPerSec = other.EnergyPerSec; } if (other.DodgeEnergyCost != 0F) { DodgeEnergyCost = other.DodgeEnergyCost; } if (other.RetargetSeconds != 0F) { RetargetSeconds = other.RetargetSeconds; } if (other.EnemyAttackInterval != 0F) { EnemyAttackInterval = other.EnemyAttackInterval; } if (other.AttackServerInterval != 0F) { AttackServerInterval = other.AttackServerInterval; } if (other.RoundDurationSeconds != 0F) { RoundDurationSeconds = other.RoundDurationSeconds; } if (other.BonusTimePerAllySeconds != 0F) { BonusTimePerAllySeconds = other.BonusTimePerAllySeconds; } if (other.MaximumAttackersPerBattle != 0) { MaximumAttackersPerBattle = other.MaximumAttackersPerBattle; } if (other.SameTypeAttackBonusMultiplier != 0F) { SameTypeAttackBonusMultiplier = other.SameTypeAttackBonusMultiplier; } if (other.MaximumEnergy != 0) { MaximumEnergy = other.MaximumEnergy; } if (other.EnergyDeltaPerHealthLost != 0F) { EnergyDeltaPerHealthLost = other.EnergyDeltaPerHealthLost; } if (other.DodgeDurationMs != 0) { DodgeDurationMs = other.DodgeDurationMs; } if (other.MinimumPlayerLevel != 0) { MinimumPlayerLevel = other.MinimumPlayerLevel; } if (other.SwapDurationMs != 0) { SwapDurationMs = other.SwapDurationMs; } if (other.DodgeDamageReductionPercent != 0F) { DodgeDamageReductionPercent = other.DodgeDamageReductionPercent; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 13: { EnergyPerSec = input.ReadFloat(); break; } case 21: { DodgeEnergyCost = input.ReadFloat(); break; } case 29: { RetargetSeconds = input.ReadFloat(); break; } case 37: { EnemyAttackInterval = input.ReadFloat(); break; } case 45: { AttackServerInterval = input.ReadFloat(); break; } case 53: { RoundDurationSeconds = input.ReadFloat(); break; } case 61: { BonusTimePerAllySeconds = input.ReadFloat(); break; } case 64: { MaximumAttackersPerBattle = input.ReadInt32(); break; } case 77: { SameTypeAttackBonusMultiplier = input.ReadFloat(); break; } case 80: { MaximumEnergy = input.ReadInt32(); break; } case 93: { EnergyDeltaPerHealthLost = input.ReadFloat(); break; } case 96: { DodgeDurationMs = input.ReadInt32(); break; } case 104: { MinimumPlayerLevel = input.ReadInt32(); break; } case 112: { SwapDurationMs = input.ReadInt32(); break; } case 125: { DodgeDamageReductionPercent = input.ReadFloat(); break; } } } } } #endregion } #endregion Designer generated code
namespace Petstore { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// Extension methods for SwaggerPetstore. /// </summary> public static partial class SwaggerPetstoreExtensions { /// <summary> /// Fake endpoint to test byte array in body parameter for adding a new pet to /// the store /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object in the form of byte array /// </param> public static void AddPetUsingByteArray(this ISwaggerPetstore operations, string body = default(string)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).AddPetUsingByteArrayAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Fake endpoint to test byte array in body parameter for adding a new pet to /// the store /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object in the form of byte array /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task AddPetUsingByteArrayAsync(this ISwaggerPetstore operations, string body = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.AddPetUsingByteArrayWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Add a new pet to the store /// </summary> /// <remarks> /// Adds a new pet to the store. You may receive an HTTP invalid input if your /// pet is invalid. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> public static void AddPet(this ISwaggerPetstore operations, Pet body = default(Pet)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).AddPetAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Add a new pet to the store /// </summary> /// <remarks> /// Adds a new pet to the store. You may receive an HTTP invalid input if your /// pet is invalid. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task AddPetAsync(this ISwaggerPetstore operations, Pet body = default(Pet), CancellationToken cancellationToken = default(CancellationToken)) { await operations.AddPetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Update an existing pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> public static void UpdatePet(this ISwaggerPetstore operations, Pet body = default(Pet)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).UpdatePetAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update an existing pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdatePetAsync(this ISwaggerPetstore operations, Pet body = default(Pet), CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdatePetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Finds Pets by status /// </summary> /// <remarks> /// Multiple status values can be provided with comma seperated strings /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='status'> /// Status values that need to be considered for filter /// </param> public static IList<Pet> FindPetsByStatus(this ISwaggerPetstore operations, IList<string> status = default(IList<string>)) { return Task.Factory.StartNew(s => ((ISwaggerPetstore)s).FindPetsByStatusAsync(status), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by status /// </summary> /// <remarks> /// Multiple status values can be provided with comma seperated strings /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='status'> /// Status values that need to be considered for filter /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Pet>> FindPetsByStatusAsync(this ISwaggerPetstore operations, IList<string> status = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.FindPetsByStatusWithHttpMessagesAsync(status, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Finds Pets by tags /// </summary> /// <remarks> /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, /// tag3 for testing. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='tags'> /// Tags to filter by /// </param> public static IList<Pet> FindPetsByTags(this ISwaggerPetstore operations, IList<string> tags = default(IList<string>)) { return Task.Factory.StartNew(s => ((ISwaggerPetstore)s).FindPetsByTagsAsync(tags), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by tags /// </summary> /// <remarks> /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, /// tag3 for testing. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='tags'> /// Tags to filter by /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Pet>> FindPetsByTagsAsync(this ISwaggerPetstore operations, IList<string> tags = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.FindPetsByTagsWithHttpMessagesAsync(tags, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Fake endpoint to test byte array return by 'Find pet by ID' /// </summary> /// <remarks> /// Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate /// API error conditions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet that needs to be fetched /// </param> public static string FindPetsWithByteArray(this ISwaggerPetstore operations, long petId) { return Task.Factory.StartNew(s => ((ISwaggerPetstore)s).FindPetsWithByteArrayAsync(petId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Fake endpoint to test byte array return by 'Find pet by ID' /// </summary> /// <remarks> /// Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate /// API error conditions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet that needs to be fetched /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> FindPetsWithByteArrayAsync(this ISwaggerPetstore operations, long petId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.FindPetsWithByteArrayWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Find pet by ID /// </summary> /// <remarks> /// Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate /// API error conditions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet that needs to be fetched /// </param> public static Pet GetPetById(this ISwaggerPetstore operations, long petId) { return Task.Factory.StartNew(s => ((ISwaggerPetstore)s).GetPetByIdAsync(petId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Find pet by ID /// </summary> /// <remarks> /// Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate /// API error conditions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet that needs to be fetched /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Pet> GetPetByIdAsync(this ISwaggerPetstore operations, long petId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetPetByIdWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet that needs to be updated /// </param> /// <param name='name'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> public static void UpdatePetWithForm(this ISwaggerPetstore operations, string petId, string name = default(string), string status = default(string)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).UpdatePetWithFormAsync(petId, name, status), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet that needs to be updated /// </param> /// <param name='name'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdatePetWithFormAsync(this ISwaggerPetstore operations, string petId, string name = default(string), string status = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdatePetWithFormWithHttpMessagesAsync(petId, name, status, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> public static void DeletePet(this ISwaggerPetstore operations, long petId, string apiKey = default(string)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).DeletePetAsync(petId, apiKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeletePetAsync(this ISwaggerPetstore operations, long petId, string apiKey = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeletePetWithHttpMessagesAsync(petId, apiKey, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// uploads an image /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet to update /// </param> /// <param name='additionalMetadata'> /// Additional data to pass to server /// </param> /// <param name='file'> /// file to upload /// </param> public static void UploadFile(this ISwaggerPetstore operations, long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).UploadFileAsync(petId, additionalMetadata, file), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// uploads an image /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// ID of pet to update /// </param> /// <param name='additionalMetadata'> /// Additional data to pass to server /// </param> /// <param name='file'> /// file to upload /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UploadFileAsync(this ISwaggerPetstore operations, long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), CancellationToken cancellationToken = default(CancellationToken)) { await operations.UploadFileWithHttpMessagesAsync(petId, additionalMetadata, file, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Returns pet inventories by status /// </summary> /// <remarks> /// Returns a map of status codes to quantities /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IDictionary<string, int?> GetInventory(this ISwaggerPetstore operations) { return Task.Factory.StartNew(s => ((ISwaggerPetstore)s).GetInventoryAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns pet inventories by status /// </summary> /// <remarks> /// Returns a map of status codes to quantities /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IDictionary<string, int?>> GetInventoryAsync(this ISwaggerPetstore operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetInventoryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Place an order for a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// order placed for purchasing the pet /// </param> public static Order PlaceOrder(this ISwaggerPetstore operations, Order body = default(Order)) { return Task.Factory.StartNew(s => ((ISwaggerPetstore)s).PlaceOrderAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Place an order for a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// order placed for purchasing the pet /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Order> PlaceOrderAsync(this ISwaggerPetstore operations, Order body = default(Order), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PlaceOrderWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Find purchase order by ID /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other /// values will generated exceptions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// ID of pet that needs to be fetched /// </param> public static Order GetOrderById(this ISwaggerPetstore operations, string orderId) { return Task.Factory.StartNew(s => ((ISwaggerPetstore)s).GetOrderByIdAsync(orderId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Find purchase order by ID /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other /// values will generated exceptions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// ID of pet that needs to be fetched /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Order> GetOrderByIdAsync(this ISwaggerPetstore operations, string orderId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetOrderByIdWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete purchase order by ID /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt; 1000. Anything above /// 1000 or nonintegers will generate API errors /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// ID of the order that needs to be deleted /// </param> public static void DeleteOrder(this ISwaggerPetstore operations, string orderId) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).DeleteOrderAsync(orderId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete purchase order by ID /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt; 1000. Anything above /// 1000 or nonintegers will generate API errors /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// ID of the order that needs to be deleted /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteOrderAsync(this ISwaggerPetstore operations, string orderId, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteOrderWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Create user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Created user object /// </param> public static void CreateUser(this ISwaggerPetstore operations, User body = default(User)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).CreateUserAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Created user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateUserAsync(this ISwaggerPetstore operations, User body = default(User), CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUserWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> public static void CreateUsersWithArrayInput(this ISwaggerPetstore operations, IList<User> body = default(IList<User>)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).CreateUsersWithArrayInputAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateUsersWithArrayInputAsync(this ISwaggerPetstore operations, IList<User> body = default(IList<User>), CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> public static void CreateUsersWithListInput(this ISwaggerPetstore operations, IList<User> body = default(IList<User>)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).CreateUsersWithListInputAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateUsersWithListInputAsync(this ISwaggerPetstore operations, IList<User> body = default(IList<User>), CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUsersWithListInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Logs user into the system /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> public static string LoginUser(this ISwaggerPetstore operations, string username = default(string), string password = default(string)) { return Task.Factory.StartNew(s => ((ISwaggerPetstore)s).LoginUserAsync(username, password), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Logs user into the system /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> LoginUserAsync(this ISwaggerPetstore operations, string username = default(string), string password = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.LoginUserWithHttpMessagesAsync(username, password, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void LogoutUser(this ISwaggerPetstore operations) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).LogoutUserAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task LogoutUserAsync(this ISwaggerPetstore operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.LogoutUserWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get user by user name /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> public static User GetUserByName(this ISwaggerPetstore operations, string username) { return Task.Factory.StartNew(s => ((ISwaggerPetstore)s).GetUserByNameAsync(username), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get user by user name /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<User> GetUserByNameAsync(this ISwaggerPetstore operations, string username, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetUserByNameWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updated user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> public static void UpdateUser(this ISwaggerPetstore operations, string username, User body = default(User)) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).UpdateUserAsync(username, body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updated user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateUserAsync(this ISwaggerPetstore operations, string username, User body = default(User), CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdateUserWithHttpMessagesAsync(username, body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Delete user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be deleted /// </param> public static void DeleteUser(this ISwaggerPetstore operations, string username) { Task.Factory.StartNew(s => ((ISwaggerPetstore)s).DeleteUserAsync(username), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be deleted /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteUserAsync(this ISwaggerPetstore operations, string username, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteUserWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false); } } }
namespace System.IO.BACnet; public class BacnetPipeTransport : IBacnetSerialTransport { private PipeStream _conn; private IAsyncResult _currentRead; private IAsyncResult _currentConnect; private readonly bool _isServer; public string Name { get; } public int BytesToRead => PeekPipe(); public static string[] AvailablePorts { get { try { var listOfPipes = Directory.GetFiles(@"\\.\pipe\"); for (var i = 0; i < listOfPipes.Length; i++) listOfPipes[i] = listOfPipes[i].Replace(@"\\.\pipe\", ""); return listOfPipes; } catch (Exception ex) { var log = LogManager.GetLogger<BacnetPipeTransport>(); log.Warn("Exception in AvailablePorts", ex); return InteropAvailablePorts; } } } public BacnetPipeTransport(string name, bool isServer = false) { Name = name; _isServer = isServer; } /// <summary> /// Get the available byte count. (The .NET pipe interface has a few lackings. See also the "InteropAvailablePorts" function) /// </summary> [DllImport("kernel32.dll", EntryPoint = "PeekNamedPipe", SetLastError = true)] private static extern bool PeekNamedPipe(IntPtr handle, IntPtr buffer, uint nBufferSize, IntPtr bytesRead, ref uint bytesAvail, IntPtr bytesLeftThisMessage); public int PeekPipe() { uint bytesAvail = 0; return PeekNamedPipe(_conn.SafePipeHandle.DangerousGetHandle(), IntPtr.Zero, 0, IntPtr.Zero, ref bytesAvail, IntPtr.Zero) ? (int)bytesAvail : 0; } public override string ToString() { return Name; } public override int GetHashCode() { return Name.GetHashCode(); } public override bool Equals(object obj) { if (obj is not BacnetPipeTransport) return false; var a = (BacnetPipeTransport)obj; return Name.Equals(a.Name); } public void Open() { if (_conn != null) Close(); if (!_isServer) { _conn = new NamedPipeClientStream(".", Name, PipeDirection.InOut, PipeOptions.Asynchronous); ((NamedPipeClientStream)_conn).Connect(3000); } else { _conn = new NamedPipeServerStream(Name, PipeDirection.InOut, 20, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); } } public void Write(byte[] buffer, int offset, int length) { if (!_conn.IsConnected) return; try { //doing syncronous writes (to an Asynchronous pipe) seems to be a bad thing _conn.BeginWrite(buffer, offset, length, (r) => { _conn.EndWrite(r); }, null); } catch (IOException) { Disconnect(); } } private void Disconnect() { if (_conn is NamedPipeServerStream stream) { try { stream.Disconnect(); } catch { } _currentConnect = null; } _currentRead = null; } private bool WaitForConnection(int timeoutMs) { if (_conn.IsConnected) return true; if (_conn is not NamedPipeServerStream) return true; var server = (NamedPipeServerStream)_conn; if (_currentConnect == null) { try { _currentConnect = server.BeginWaitForConnection(null, null); } catch (IOException) { Disconnect(); _currentConnect = server.BeginWaitForConnection(null, null); } } if (_currentConnect.IsCompleted || _currentConnect.AsyncWaitHandle.WaitOne(timeoutMs)) { try { server.EndWaitForConnection(_currentConnect); } catch (IOException) { Disconnect(); } _currentConnect = null; } return _conn.IsConnected; } public int Read(byte[] buffer, int offset, int length, int timeoutMs) { if (!WaitForConnection(timeoutMs)) return -BacnetMstpProtocolTransport.ETIMEDOUT; if (_currentRead == null) { try { _currentRead = _conn.BeginRead(buffer, offset, length, null, null); } catch (Exception) { Disconnect(); return -1; } } if (!_currentRead.IsCompleted && !_currentRead.AsyncWaitHandle.WaitOne(timeoutMs)) return -BacnetMstpProtocolTransport.ETIMEDOUT; try { var rx = _conn.EndRead(_currentRead); _currentRead = null; return rx; } catch (Exception) { Disconnect(); return -1; } } public void Close() { if (_conn == null) return; _conn.Close(); _conn = null; } public void Dispose() { Close(); } #region " Interop Get Pipe Names " // ReSharper disable All [StructLayout(LayoutKind.Sequential)] private struct FILETIME { public uint dwLowDateTime; public uint dwHighDateTime; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private struct WIN32_FIND_DATA { public uint dwFileAttributes; public FILETIME ftCreationTime; public FILETIME ftLastAccessTime; public FILETIME ftLastWriteTime; public uint nFileSizeHigh; public uint nFileSizeLow; public uint dwReserved0; public uint dwReserved1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string cFileName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] public string cAlternateFileName; } [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern int FindNextFile(IntPtr hFindFile, out WIN32_FIND_DATA lpFindFileData); [DllImport("kernel32.dll")] private static extern bool FindClose(IntPtr hFindFile); /// <summary> /// The built-in functions for pipe enumeration isn't perfect, I'm afraid. Hence this messy interop. /// </summary> private static string[] InteropAvailablePorts { get { var ret = new List<string>(); var handle = FindFirstFile(@"\\.\pipe\*", out var data); if (handle == new IntPtr(-1)) return ret.ToArray(); do { ret.Add(data.cFileName); } while (FindNextFile(handle, out data) != 0); FindClose(handle); return ret.ToArray(); } } // ReSharper restore #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CSharp; using Microsoft.VisualBasic; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Runtime.Serialization; namespace System.CodeDom.Compiler { public abstract class CodeDomProvider : Component { private static readonly Dictionary<string, CompilerInfo> s_compilerLanguages = new Dictionary<string, CompilerInfo>(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary<string, CompilerInfo> s_compilerExtensions = new Dictionary<string, CompilerInfo>(StringComparer.OrdinalIgnoreCase); private static readonly List<CompilerInfo> s_allCompilerInfo = new List<CompilerInfo>(); static CodeDomProvider() { // C# AddCompilerInfo(new CompilerInfo(new CompilerParameters() { WarningLevel = 4 }, typeof(CSharpCodeProvider).FullName) { _compilerLanguages = new string[] { "c#", "cs", "csharp" }, _compilerExtensions = new string[] { ".cs", "cs" } }); // VB AddCompilerInfo(new CompilerInfo(new CompilerParameters() { WarningLevel = 4 }, typeof(VBCodeProvider).FullName) { _compilerLanguages = new string[] { "vb", "vbs", "visualbasic", "vbscript" }, _compilerExtensions = new string[] { ".vb", "vb" } }); } private static void AddCompilerInfo(CompilerInfo compilerInfo) { foreach (string language in compilerInfo._compilerLanguages) { s_compilerLanguages[language] = compilerInfo; } foreach (string extension in compilerInfo._compilerExtensions) { s_compilerExtensions[extension] = compilerInfo; } s_allCompilerInfo.Add(compilerInfo); } public static CodeDomProvider CreateProvider(string language, System.Collections.Generic.IDictionary<string, string> providerOptions) { CompilerInfo compilerInfo = GetCompilerInfo(language); return compilerInfo.CreateProvider(providerOptions); } public static CodeDomProvider CreateProvider(string language) { CompilerInfo compilerInfo = GetCompilerInfo(language); return compilerInfo.CreateProvider(); } public static string GetLanguageFromExtension(string extension) { CompilerInfo compilerInfo = GetCompilerInfoForExtensionNoThrow(extension); if (compilerInfo == null) { throw new ConfigurationErrorsException(SR.CodeDomProvider_NotDefined); } return compilerInfo._compilerLanguages[0]; } public static bool IsDefinedLanguage(string language) => GetCompilerInfoForLanguageNoThrow(language) != null; public static bool IsDefinedExtension(string extension) => GetCompilerInfoForExtensionNoThrow(extension) != null; public static CompilerInfo GetCompilerInfo(string language) { CompilerInfo compilerInfo = GetCompilerInfoForLanguageNoThrow(language); if (compilerInfo == null) { throw new ConfigurationErrorsException(SR.CodeDomProvider_NotDefined); } return compilerInfo; } private static CompilerInfo GetCompilerInfoForLanguageNoThrow(string language) { if (language == null) { throw new ArgumentNullException(nameof(language)); } CompilerInfo value; s_compilerLanguages.TryGetValue(language.Trim(), out value); return value; } private static CompilerInfo GetCompilerInfoForExtensionNoThrow(string extension) { if (extension == null) { throw new ArgumentNullException(nameof(extension)); } CompilerInfo value; s_compilerExtensions.TryGetValue(extension.Trim(), out value); return value; } public static CompilerInfo[] GetAllCompilerInfo() => s_allCompilerInfo.ToArray(); public virtual string FileExtension => string.Empty; public virtual LanguageOptions LanguageOptions => LanguageOptions.None; [Obsolete("Callers should not use the ICodeGenerator interface and should instead use the methods directly on the CodeDomProvider class. Those inheriting from CodeDomProvider must still implement this interface, and should exclude this warning or also obsolete this method.")] public abstract ICodeGenerator CreateGenerator(); #pragma warning disable 618 // obsolete public virtual ICodeGenerator CreateGenerator(TextWriter output) => CreateGenerator(); public virtual ICodeGenerator CreateGenerator(string fileName) => CreateGenerator(); #pragma warning restore 618 [Obsolete("Callers should not use the ICodeCompiler interface and should instead use the methods directly on the CodeDomProvider class. Those inheriting from CodeDomProvider must still implement this interface, and should exclude this warning or also obsolete this method.")] public abstract ICodeCompiler CreateCompiler(); [Obsolete("Callers should not use the ICodeParser interface and should instead use the methods directly on the CodeDomProvider class. Those inheriting from CodeDomProvider must still implement this interface, and should exclude this warning or also obsolete this method.")] public virtual ICodeParser CreateParser() => null; public virtual TypeConverter GetConverter(Type type) => TypeDescriptor.GetConverter(type); public virtual CompilerResults CompileAssemblyFromDom(CompilerParameters options, params CodeCompileUnit[] compilationUnits) => CreateCompilerHelper().CompileAssemblyFromDomBatch(options, compilationUnits); public virtual CompilerResults CompileAssemblyFromFile(CompilerParameters options, params string[] fileNames) => CreateCompilerHelper().CompileAssemblyFromFileBatch(options, fileNames); public virtual CompilerResults CompileAssemblyFromSource(CompilerParameters options, params string[] sources) => CreateCompilerHelper().CompileAssemblyFromSourceBatch(options, sources); public virtual bool IsValidIdentifier(string value) => CreateGeneratorHelper().IsValidIdentifier(value); public virtual string CreateEscapedIdentifier(string value) => CreateGeneratorHelper().CreateEscapedIdentifier(value); public virtual string CreateValidIdentifier(string value) => CreateGeneratorHelper().CreateValidIdentifier(value); public virtual string GetTypeOutput(CodeTypeReference type) => CreateGeneratorHelper().GetTypeOutput(type); public virtual bool Supports(GeneratorSupport generatorSupport) => CreateGeneratorHelper().Supports(generatorSupport); public virtual void GenerateCodeFromExpression(CodeExpression expression, TextWriter writer, CodeGeneratorOptions options) => CreateGeneratorHelper().GenerateCodeFromExpression(expression, writer, options); public virtual void GenerateCodeFromStatement(CodeStatement statement, TextWriter writer, CodeGeneratorOptions options) => CreateGeneratorHelper().GenerateCodeFromStatement(statement, writer, options); public virtual void GenerateCodeFromNamespace(CodeNamespace codeNamespace, TextWriter writer, CodeGeneratorOptions options) => CreateGeneratorHelper().GenerateCodeFromNamespace(codeNamespace, writer, options); public virtual void GenerateCodeFromCompileUnit(CodeCompileUnit compileUnit, TextWriter writer, CodeGeneratorOptions options) => CreateGeneratorHelper().GenerateCodeFromCompileUnit(compileUnit, writer, options); public virtual void GenerateCodeFromType(CodeTypeDeclaration codeType, TextWriter writer, CodeGeneratorOptions options) => CreateGeneratorHelper().GenerateCodeFromType(codeType, writer, options); public virtual void GenerateCodeFromMember(CodeTypeMember member, TextWriter writer, CodeGeneratorOptions options) { throw new NotImplementedException(SR.NotSupported_CodeDomAPI); } public virtual CodeCompileUnit Parse(TextReader codeStream) => CreateParserHelper().Parse(codeStream); #pragma warning disable 0618 // obsolete private ICodeCompiler CreateCompilerHelper() { ICodeCompiler compiler = CreateCompiler(); if (compiler == null) { throw new NotImplementedException(SR.NotSupported_CodeDomAPI); } return compiler; } private ICodeGenerator CreateGeneratorHelper() { ICodeGenerator generator = CreateGenerator(); if (generator == null) { throw new NotImplementedException(SR.NotSupported_CodeDomAPI); } return generator; } private ICodeParser CreateParserHelper() { ICodeParser parser = CreateParser(); if (parser == null) { throw new NotImplementedException(SR.NotSupported_CodeDomAPI); } return parser; } #pragma warning restore 618 private sealed class ConfigurationErrorsException : SystemException { public ConfigurationErrorsException(string message) : base(message) { } public ConfigurationErrorsException(SerializationInfo info, StreamingContext context) : base(info, context) { throw new PlatformNotSupportedException(); } } } }
using System; using System.Collections.Generic; using System.Linq; using Signum.Utilities; using System.ComponentModel; using Newtonsoft.Json; using Signum.Entities.Authorization; namespace Signum.Entities.Omnibox { public static class OmniboxUtils { public static bool IsPascalCasePattern(string ident) { if (string.IsNullOrEmpty(ident)) return false; for (int i = 0; i < ident.Length; i++) { if (!char.IsUpper(ident[i])) return false; } return true; } public static OmniboxMatch? SubsequencePascal(object value, string identifier, string pattern) { char[] mask = new string('_', identifier.Length).ToCharArray(); int j = 0; for (int i = 0; i < pattern.Length; i++) { var pc = pattern[i]; for (; j < identifier.Length; j++) { var ic = identifier[j]; if (char.IsUpper(ic)) { if (ic == pc) { mask[j] = '#'; break; } } } if (j == identifier.Length) return null; j++; } return new OmniboxMatch(value, remaining: identifier.Count(char.IsUpper) - pattern.Length, choosenString: identifier, boldMask: new string(mask)); } public static IEnumerable<OmniboxMatch> Matches<T>(Dictionary<string, T> values, Func<T, bool> filter, string pattern, bool isPascalCase) where T : notnull { pattern = pattern.RemoveDiacritics(); if (values.TryGetValue(pattern, out T val) && filter(val)) { yield return new OmniboxMatch(val!, 0, pattern, new string('#', pattern.Length)); } else { foreach (var kvp in values.Where(kvp => filter(kvp.Value))) { OmniboxMatch? result; if (isPascalCase) { result = SubsequencePascal(kvp.Value, kvp.Key, pattern); if (result != null) { yield return result; continue; } } result = Contains(kvp.Value, kvp.Key, pattern); if (result != null) { yield return result; continue; } } } } public static OmniboxMatch? Contains(object value, string identifier, string pattern) { var parts = pattern.SplitNoEmpty(' '); char[] mask = new string('_', identifier.Length).ToCharArray(); foreach (var p in parts) { int index = identifier.IndexOf(p, StringComparison.InvariantCultureIgnoreCase); if (index == -1) return null; for (int i = 0; i < p.Length; i++) mask[index + i] = '#'; } return new OmniboxMatch(value, remaining: identifier.Length - pattern.Length, choosenString: identifier, boldMask: new string(mask)); } public static string CleanCommas(string str) { return str.Trim('\'', '"'); } } public class OmniboxMatch { public OmniboxMatch(object value, int remaining, string choosenString, string boldMask) { if (choosenString.Length != boldMask.Length) throw new ArgumentException("choosenString '{0}' is {1} long but boldIndices is {2}".FormatWith(choosenString, choosenString.Length, boldMask.Length)); this.Value = value; this.Text = choosenString; this.BoldMask = boldMask; this.Distance = remaining; if (boldMask.Length > 0 && boldMask[0] == '#') this.Distance /= 2f; } [JsonIgnore] public object Value; public float Distance; public string Text; public string BoldMask; public IEnumerable<(string span, bool isBold)> BoldSpans() { return this.Text.ZipStrict(BoldMask) .GroupWhenChange(a => a.second == '#') .Select(gr => (span: new string(gr.Select(a => a.first).ToArray()), isBold: gr.Key)); } } public enum OmniboxMessage { [Description("no")] No, [Description("[Not found]")] NotFound, [Description("Searching between 'apostrophe' will make queries to the database")] Omnibox_DatabaseAccess, [Description("With [Tab] you disambiguate you query")] Omnibox_Disambiguate, [Description("Field")] Omnibox_Field, [Description("Help")] Omnibox_Help, [Description("Omnibox Syntax Guide:")] Omnibox_OmniboxSyntaxGuide, [Description("You can match results by (st)art, mid(dle) or (U)pper(C)ase")] Omnibox_MatchingOptions, [Description("Query")] Omnibox_Query, [Description("Type")] Omnibox_Type, [Description("UserChart")] Omnibox_UserChart, [Description("UserQuery")] Omnibox_UserQuery, [Description("Dashboard")] Omnibox_Dashboard, [Description("Value")] Omnibox_Value, Unknown, [Description("yes")] Yes, [Description(@"\b(the|of) ")] ComplementWordsRegex, [Description("Search...")] Search, } [AutoInit] public static class OmniboxPermission { public static PermissionSymbol ViewOmnibox; } }
// This file is provided under The MIT License as part of Steamworks.NET. // Copyright (c) 2013-2015 Riley Labrecque // Please see the included LICENSE.txt for additional information. // Changes to this file will be reverted when you update Steamworks.NET #if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 #error Unsupported Unity platform. Steamworks.NET requires Unity 4.6 or higher. #elif UNITY_4_6 || UNITY_5 #if UNITY_EDITOR_WIN || (UNITY_STANDALONE_WIN && !UNITY_EDITOR) #define WINDOWS_BUILD #endif #elif STEAMWORKS_WIN #define WINDOWS_BUILD #elif STEAMWORKS_LIN_OSX // So that we don't trigger the else. #else #error You need to define STEAMWORKS_WIN, or STEAMWORKS_LIN_OSX. Refer to the readme for more details. #endif // Unity 32bit Mono on Windows crashes with ThisCall/Cdecl for some reason, StdCall without the 'this' ptr is the only thing that works..? #if (UNITY_EDITOR_WIN && !UNITY_EDITOR_64) || (!UNITY_EDITOR && UNITY_STANDALONE_WIN && !UNITY_64) #define STDCALL #elif STEAMWORKS_WIN #define THISCALL #endif // Calling Conventions: // Unity x86 Windows - StdCall (No this pointer) // Unity x86 Linux - Cdecl // Unity x86 OSX - Cdecl // Unity x64 Windows - Cdecl // Unity x64 Linux - Cdecl // Unity x64 OSX - Cdecl // Microsoft x86 Windows - ThisCall // Microsoft x64 Windows - ThisCall // Mono x86 Linux - Cdecl // Mono x86 OSX - Cdecl // Mono x64 Linux - Cdecl // Mono x64 OSX - Cdecl // Mono on Windows is probably not supported. using System; using System.Runtime.InteropServices; namespace Steamworks { public static class CallbackDispatcher { // We catch exceptions inside callbacks and reroute them here. // For some reason throwing an exception causes RunCallbacks() to break otherwise. // If you have a custom ExceptionHandler in your engine you can register it here manually until we get something more elegant hooked up. public static void ExceptionHandler(Exception e) { #if UNITY_BUILD UnityEngine.Debug.LogException(e); #else Console.WriteLine(e.Message); #endif } } public sealed class Callback<T> { private CCallbackBaseVTable VTable; private IntPtr m_pVTable = IntPtr.Zero; private CCallbackBase m_CCallbackBase; private GCHandle m_pCCallbackBase; public delegate void DispatchDelegate(T param); private event DispatchDelegate m_Func; private bool m_bGameServer; private readonly int m_size = Marshal.SizeOf(typeof(T)); /// <summary> /// Creates a new Callback. You must be calling SteamAPI.RunCallbacks() to retrieve the callbacks. /// <para>Returns a handle to the Callback. This must be assigned to a member variable to prevent the GC from cleaning it up.</para> /// </summary> public static Callback<T> Create(DispatchDelegate func) { return new Callback<T>(func, bGameServer: false); } /// <summary> /// Creates a new GameServer Callback. You must be calling GameServer.RunCallbacks() to retrieve the callbacks. /// <para>Returns a handle to the Callback. This must be assigned to a member variable to prevent the GC from cleaning it up.</para> /// </summary> public static Callback<T> CreateGameServer(DispatchDelegate func) { return new Callback<T>(func, bGameServer: true); } public Callback(DispatchDelegate func, bool bGameServer = false) { m_bGameServer = bGameServer; BuildCCallbackBase(); Register(func); } ~Callback() { Unregister(); if (m_pVTable != IntPtr.Zero) { Marshal.FreeHGlobal(m_pVTable); } if (m_pCCallbackBase.IsAllocated) { m_pCCallbackBase.Free(); } } // Manual registration of the callback public void Register(DispatchDelegate func) { if (func == null) { throw new Exception("Callback function must not be null."); } if ((m_CCallbackBase.m_nCallbackFlags & CCallbackBase.k_ECallbackFlagsRegistered) == CCallbackBase.k_ECallbackFlagsRegistered) { Unregister(); } if (m_bGameServer) { SetGameserverFlag(); } m_Func = func; // k_ECallbackFlagsRegistered is set by SteamAPI_RegisterCallback. NativeMethods.SteamAPI_RegisterCallback(m_pCCallbackBase.AddrOfPinnedObject(), CallbackIdentities.GetCallbackIdentity(typeof(T))); } public void Unregister() { // k_ECallbackFlagsRegistered is removed by SteamAPI_UnregisterCallback. NativeMethods.SteamAPI_UnregisterCallback(m_pCCallbackBase.AddrOfPinnedObject()); } public void SetGameserverFlag() { m_CCallbackBase.m_nCallbackFlags |= CCallbackBase.k_ECallbackFlagsGameServer; } private void OnRunCallback( #if !STDCALL IntPtr thisptr, #endif IntPtr pvParam) { try { m_Func((T)Marshal.PtrToStructure(pvParam, typeof(T))); } catch (Exception e) { CallbackDispatcher.ExceptionHandler(e); } } // Shouldn't get ever get called here, but this is what C++ Steamworks does! private void OnRunCallResult( #if !STDCALL IntPtr thisptr, #endif IntPtr pvParam, bool bFailed, ulong hSteamAPICall) { try { m_Func((T)Marshal.PtrToStructure(pvParam, typeof(T))); } catch (Exception e) { CallbackDispatcher.ExceptionHandler(e); } } private int OnGetCallbackSizeBytes( #if !STDCALL IntPtr thisptr #endif ) { return m_size; } // Steamworks.NET Specific private void BuildCCallbackBase() { VTable = new CCallbackBaseVTable() { m_RunCallResult = OnRunCallResult, m_RunCallback = OnRunCallback, m_GetCallbackSizeBytes = OnGetCallbackSizeBytes }; m_pVTable = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(CCallbackBaseVTable))); Marshal.StructureToPtr(VTable, m_pVTable, false); m_CCallbackBase = new CCallbackBase() { m_vfptr = m_pVTable, m_nCallbackFlags = 0, m_iCallback = CallbackIdentities.GetCallbackIdentity(typeof(T)) }; m_pCCallbackBase = GCHandle.Alloc(m_CCallbackBase, GCHandleType.Pinned); } } public sealed class CallResult<T> { private CCallbackBaseVTable VTable; private IntPtr m_pVTable = IntPtr.Zero; private CCallbackBase m_CCallbackBase; private GCHandle m_pCCallbackBase; public delegate void APIDispatchDelegate(T param, bool bIOFailure); private event APIDispatchDelegate m_Func; private SteamAPICall_t m_hAPICall = SteamAPICall_t.Invalid; public SteamAPICall_t Handle { get { return m_hAPICall; } } private readonly int m_size = Marshal.SizeOf(typeof(T)); /// <summary> /// Creates a new async CallResult. You must be calling SteamAPI.RunCallbacks() to retrieve the callback. /// <para>Returns a handle to the CallResult. This must be assigned to a member variable to prevent the GC from cleaning it up.</para> /// </summary> public static CallResult<T> Create(APIDispatchDelegate func = null) { return new CallResult<T>(func); } public CallResult(APIDispatchDelegate func = null) { m_Func = func; BuildCCallbackBase(); } ~CallResult() { Cancel(); if (m_pVTable != IntPtr.Zero) { Marshal.FreeHGlobal(m_pVTable); } if (m_pCCallbackBase.IsAllocated) { m_pCCallbackBase.Free(); } } public void Set(SteamAPICall_t hAPICall, APIDispatchDelegate func = null) { // Unlike the official SDK we let the user assign a single function during creation, // and allow them to skip having to do so every time that they call .Set() if (func != null) { m_Func = func; } if (m_Func == null) { throw new Exception("CallResult function was null, you must either set it in the CallResult Constructor or in Set()"); } if (m_hAPICall != SteamAPICall_t.Invalid) { NativeMethods.SteamAPI_UnregisterCallResult(m_pCCallbackBase.AddrOfPinnedObject(), (ulong)m_hAPICall); } m_hAPICall = hAPICall; if (hAPICall != SteamAPICall_t.Invalid) { NativeMethods.SteamAPI_RegisterCallResult(m_pCCallbackBase.AddrOfPinnedObject(), (ulong)hAPICall); } } public bool IsActive() { return (m_hAPICall != SteamAPICall_t.Invalid); } public void Cancel() { if (m_hAPICall != SteamAPICall_t.Invalid) { NativeMethods.SteamAPI_UnregisterCallResult(m_pCCallbackBase.AddrOfPinnedObject(), (ulong)m_hAPICall); m_hAPICall = SteamAPICall_t.Invalid; } } public void SetGameserverFlag() { m_CCallbackBase.m_nCallbackFlags |= CCallbackBase.k_ECallbackFlagsGameServer; } // Shouldn't get ever get called here, but this is what C++ Steamworks does! private void OnRunCallback( #if !STDCALL IntPtr thisptr, #endif IntPtr pvParam) { m_hAPICall = SteamAPICall_t.Invalid; // Caller unregisters for us try { m_Func((T)Marshal.PtrToStructure(pvParam, typeof(T)), false); } catch (Exception e) { CallbackDispatcher.ExceptionHandler(e); } } private void OnRunCallResult( #if !STDCALL IntPtr thisptr, #endif IntPtr pvParam, bool bFailed, ulong hSteamAPICall) { SteamAPICall_t hAPICall = (SteamAPICall_t)hSteamAPICall; if (hAPICall == m_hAPICall) { try { m_Func((T)Marshal.PtrToStructure(pvParam, typeof(T)), bFailed); } catch (Exception e) { CallbackDispatcher.ExceptionHandler(e); } // The official SDK sets m_hAPICall to invalid before calling the callresult function, // this doesn't let us access .Handle from within the function though. if (hAPICall == m_hAPICall) { // Ensure that m_hAPICall has not been changed in m_Func m_hAPICall = SteamAPICall_t.Invalid; // Caller unregisters for us } } } private int OnGetCallbackSizeBytes( #if !STDCALL IntPtr thisptr #endif ) { return m_size; } // Steamworks.NET Specific private void BuildCCallbackBase() { VTable = new CCallbackBaseVTable() { m_RunCallback = OnRunCallback, m_RunCallResult = OnRunCallResult, m_GetCallbackSizeBytes = OnGetCallbackSizeBytes }; m_pVTable = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(CCallbackBaseVTable))); Marshal.StructureToPtr(VTable, m_pVTable, false); m_CCallbackBase = new CCallbackBase() { m_vfptr = m_pVTable, m_nCallbackFlags = 0, m_iCallback = CallbackIdentities.GetCallbackIdentity(typeof(T)) }; m_pCCallbackBase = GCHandle.Alloc(m_CCallbackBase, GCHandleType.Pinned); } } [StructLayout(LayoutKind.Sequential)] internal class CCallbackBase { public const byte k_ECallbackFlagsRegistered = 0x01; public const byte k_ECallbackFlagsGameServer = 0x02; public IntPtr m_vfptr; public byte m_nCallbackFlags; public int m_iCallback; }; [StructLayout(LayoutKind.Sequential)] internal class CCallbackBaseVTable { #if STDCALL private const CallingConvention cc = CallingConvention.StdCall; [UnmanagedFunctionPointer(cc)] public delegate void RunCBDel(IntPtr pvParam); [UnmanagedFunctionPointer(cc)] public delegate void RunCRDel(IntPtr pvParam, [MarshalAs(UnmanagedType.I1)] bool bIOFailure, ulong hSteamAPICall); [UnmanagedFunctionPointer(cc)] public delegate int GetCallbackSizeBytesDel(); #else #if THISCALL private const CallingConvention cc = CallingConvention.ThisCall; #else private const CallingConvention cc = CallingConvention.Cdecl; #endif [UnmanagedFunctionPointer(cc)] public delegate void RunCBDel(IntPtr thisptr, IntPtr pvParam); [UnmanagedFunctionPointer(cc)] public delegate void RunCRDel(IntPtr thisptr, IntPtr pvParam, [MarshalAs(UnmanagedType.I1)] bool bIOFailure, ulong hSteamAPICall); [UnmanagedFunctionPointer(cc)] public delegate int GetCallbackSizeBytesDel(IntPtr thisptr); #endif // RunCallback and RunCallResult are swapped in MSVC ABI #if WINDOWS_BUILD [NonSerialized] [MarshalAs(UnmanagedType.FunctionPtr)] public RunCRDel m_RunCallResult; #endif [NonSerialized] [MarshalAs(UnmanagedType.FunctionPtr)] public RunCBDel m_RunCallback; #if !WINDOWS_BUILD [NonSerialized] [MarshalAs(UnmanagedType.FunctionPtr)] public RunCRDel m_RunCallResult; #endif [NonSerialized] [MarshalAs(UnmanagedType.FunctionPtr)] public GetCallbackSizeBytesDel m_GetCallbackSizeBytes; } }
using System; namespace System.Threading.Tasks { // Task type used to implement: Task ContinueWith(Action<Task>,...>) internal sealed class ContinuationTaskFromTask : Task { private Task m_antecedant; public ContinuationTaskFromTask( Task antecedent, Delegate action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions) : base(action, state, cancellationToken, creationOptions, InternalTaskOptions.ContinuationTask) { } internal override void Invoke() { // Get and null out the antecedent. This is crucial to avoid a memory leak with long chains of continuations. Task antecedent = m_antecedant; m_antecedant = null; #if ENABLE_CONTRACTS Contract.Assert(antecedent != null, "No antecedent was set for the task continuation."); #endif // ENABLE_CONTRACTS var action = m_action as Action<Task>; if (action != null) { action(antecedent); return; } var actionWithState = m_action as Action<Task, object>; if (actionWithState != null) { actionWithState(antecedent, m_stateObject); return; } #if ENABLE_CONTRACTS Contract.Assert(false, "Invalid m_action in ContinuationTaskFromTask."); #endif // ENABLE_CONTRACTS } } // Task type used to implement: Task ContinueWith(Action<Task<TAntecedentResult>,...>) internal sealed class ContinuationTaskFromResultTask<TAntecedentResult> : Task { private Task<TAntecedentResult> m_antecedant; public ContinuationTaskFromResultTask( Task<TAntecedentResult> antecedent, Delegate action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions) : base(action, state, cancellationToken, creationOptions, InternalTaskOptions.ContinuationTask) { } internal override void Invoke() { // Get and null out the antecedent. This is crucial to avoid a memory leak with long chains of continuations. Task<TAntecedentResult> antecedent = m_antecedant; m_antecedant = null; #if ENABLE_CONTRACTS Contract.Assert(antecedent != null, "No antecedent was set for the task continuation."); #endif // ENABLE_CONTRACTS var action = m_action as Action<Task<TAntecedentResult>>; if (action != null) { action(antecedent); return; } var actionWithState = m_action as Action<Task<TAntecedentResult>, object>; if (actionWithState != null) { actionWithState(antecedent, m_stateObject); return; } #if ENABLE_CONTRACTS Contract.Assert(false, "Invalid m_action in ContinuationTaskFromResultTask"); #endif // ENABLE_CONTRACTS } } // Task type used to implement: Task<TResult> ContinueWith(Func<Task<TAntecedentResult>,...>) internal sealed class ContinuationResultTaskFromTask<TResult> : Task<TResult> { private Task m_antecedant; public ContinuationResultTaskFromTask( Task antecedent, Delegate function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions) : base(function, state, cancellationToken, creationOptions, InternalTaskOptions.ContinuationTask) { } internal override void Invoke() { // Get and null out the antecedent. This is crucial to avoid a memory leak with long chains of continuations. Task antecedent = m_antecedant; m_antecedant = null; #if ENABLE_CONTRACTS Contract.Assert(antecedent != null, "No antecedent was set for the task continuation."); #endif // ENABLE_CONTRACTS var func = m_action as Func<Task, TResult>; if (func != null) { m_result = func(antecedent); return; } var funcWithState = m_action as Func<Task, object, TResult>; if (funcWithState != null) { m_result = funcWithState(antecedent, m_stateObject); return; } #if ENABLE_CONTRACTS Contract.Assert(false, "Invalid m_action in ContinuationResultTaskFromResultTask"); #endif // ENABLE_CONTRACTS } } // Task type used to implement: Task<TResult> ContinueWith(Func<Task<TAntecedentResult>,...>) internal sealed class ContinuationResultTaskFromResultTask<TAntecedentResult, TResult> : Task<TResult> { private Task<TAntecedentResult> m_antecedant; public ContinuationResultTaskFromResultTask( Task<TAntecedentResult> antecedent, Delegate function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions) : base(function, state, cancellationToken, creationOptions, InternalTaskOptions.ContinuationTask) { } internal override void Invoke() { // Get and null out the antecedent. This is crucial to avoid a memory leak with long chains of continuations. Task<TAntecedentResult> antecedent = m_antecedant; m_antecedant = null; #if ENABLE_CONTRACTS Contract.Assert(antecedent != null, "No antecedent was set for the task continuation."); #endif // ENABLE_CONTRACTS var func = m_action as Func<Task<TAntecedentResult>, TResult>; if (func != null) { m_result = func(antecedent); return; } var funcWithState = m_action as Func<Task<TAntecedentResult>, object, TResult>; if (funcWithState != null) { m_result = funcWithState(antecedent, m_stateObject); return; } #if ENABLE_CONTRACTS Contract.Assert(false, "Invalid m_action in ContinuationResultTaskFromResultTask"); #endif // ENABLE_CONTRACTS } } /// <summary> /// Wrapper class to simplify invocation of continuation tasks. /// </summary> internal class TaskContinuation { private readonly Task m_task; private readonly TaskContinuationOptions m_continuationOptions; public TaskContinuation(Task continuationTask, TaskContinuationOptions continuationOptions) { m_task = continuationTask; m_continuationOptions = continuationOptions; } public void RunOrSchedule(Task antecedent) { TaskStatus status = antecedent.Status; switch (status) { case TaskStatus.RanToCompletion: if ((m_continuationOptions & TaskContinuationOptions.NotOnRanToCompletion) != 0) { m_task.InternalCancel(); return; } break; case TaskStatus.Canceled: if ((m_continuationOptions & TaskContinuationOptions.NotOnCanceled) != 0) { m_task.InternalCancel(); return; } break; case TaskStatus.Faulted: if ((m_continuationOptions & TaskContinuationOptions.NotOnFaulted) != 0) { m_task.InternalCancel(); return; } break; } bool runSynchronously = ((m_continuationOptions & TaskContinuationOptions.ExecuteSynchronously) != 0) && ((antecedent.CreationOptions & TaskCreationOptions.RunContinuationsAsynchronously) == 0); m_task.Start(runSynchronously); } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; namespace DotSpatial.Data { /// <summary> /// BinaryRasterProvider. /// </summary> public class BinaryRasterProvider : IRasterProvider { #region Fields #endregion #region Properties /// <summary> /// Gets a basic description that will fall next to your plugin in the Add Other Data dialog. /// This will only be shown if your plugin does not supply a DialogReadFilter. /// </summary> public virtual string Description => "This data provider uses a file format, and not the 'other data' methods."; /// <summary> /// Gets a dialog read filter that lists each of the file type descriptions and file extensions, delimeted /// by the | symbol. Each will appear in DotSpatial's open file dialog filter, preceeded by the name provided /// on this object. /// </summary> public virtual string DialogReadFilter => "Binary Files (*.bgd)|*.bgd"; /// <summary> /// Gets a dialog filter that lists each of the file type descriptions and extensions for a Save File Dialog. /// Each will appear in DotSpatial's open file dialog filter, preceeded by the name provided on this object. /// </summary> public virtual string DialogWriteFilter => "Binary Files (*.bgd)|*.bgd"; /// <summary> /// Gets a prefereably short name that identifies this data provider. Example might be GDAL. /// This will be prepended to each of the DialogReadFilter members from this plugin. /// </summary> public virtual string Name => "DotSpatial"; /// <summary> /// Gets or sets the control or method that should report on progress. /// </summary> public IProgressHandler ProgressHandler { get; set; } #endregion #region Methods /// <summary> /// Reads a binary header to determine the appropriate data type. /// </summary> /// <param name="fileName">File to read the header from.</param> /// <returns>The datatype that was found.</returns> public static RasterDataType GetDataType(string fileName) { using (var br = new BinaryReader(new FileStream(fileName, FileMode.Open))) { br.ReadInt32(); // NumColumns br.ReadInt32(); // NumRows br.ReadDouble(); // CellWidth br.ReadDouble(); // CellHeight br.ReadDouble(); // xllcenter br.ReadDouble(); // yllcenter return (RasterDataType)br.ReadInt32(); } } /// <summary> /// This create new method implies that this provider has the priority for creating a new file. /// An instance of the dataset should be created and then returned. By this time, the fileName /// will already be checked to see if it exists, and deleted if the user wants to overwrite it. /// </summary> /// <param name="name">The string fileName for the new instance.</param> /// <param name="driverCode">The string short name of the driver for creating the raster.</param> /// <param name="xSize">The number of columns in the raster.</param> /// <param name="ySize">The number of rows in the raster.</param> /// <param name="numBands">The number of bands to create in the raster.</param> /// <param name="dataType">The data type to use for the raster.</param> /// <param name="options">The options to be used.</param> /// <returns>An IRaster.</returns> public IRaster Create(string name, string driverCode, int xSize, int ySize, int numBands, Type dataType, string[] options) { if (dataType == typeof(byte)) return new BgdRaster<byte>(name, ySize, xSize); if (dataType == typeof(short)) return new BgdRaster<short>(name, ySize, xSize); if (dataType == typeof(int)) return new BgdRaster<int>(name, ySize, xSize); if (dataType == typeof(long)) return new BgdRaster<long>(name, ySize, xSize); if (dataType == typeof(float)) return new BgdRaster<float>(name, ySize, xSize); if (dataType == typeof(double)) return new BgdRaster<double>(name, ySize, xSize); if (dataType == typeof(sbyte)) return new BgdRaster<sbyte>(name, ySize, xSize); if (dataType == typeof(ushort)) return new BgdRaster<ushort>(name, ySize, xSize); if (dataType == typeof(uint)) return new BgdRaster<uint>(name, ySize, xSize); if (dataType == typeof(ulong)) return new BgdRaster<ulong>(name, ySize, xSize); if (dataType == typeof(bool)) return new BgdRaster<bool>(name, ySize, xSize); return null; } /// <summary> /// This open method is only called if this plugin has been given priority for one /// of the file extensions supported in the DialogReadFilter property supplied by /// this control. Failing to provide a DialogReadFilter will result in this plugin /// being added to the list of DataProviders being supplied under the Add Other Data /// option in the file menu. /// </summary> /// <param name="fileName">A string specifying the complete path and extension of the file to open.</param> /// <returns>An IDataSet to be added to the Map. These can also be groups of datasets.</returns> public virtual IRaster Open(string fileName) { RasterDataType fileDataType = GetDataType(fileName); Raster raster = null; switch (fileDataType) { case RasterDataType.BYTE: raster = new BgdRaster<byte> { ProgressHandler = ProgressHandler, Filename = fileName }; break; case RasterDataType.SHORT: raster = new BgdRaster<short> { ProgressHandler = ProgressHandler, Filename = fileName }; break; case RasterDataType.INTEGER: raster = new BgdRaster<int> { ProgressHandler = ProgressHandler, Filename = fileName }; break; case RasterDataType.LONG: raster = new BgdRaster<long> { ProgressHandler = ProgressHandler, Filename = fileName }; break; case RasterDataType.SINGLE: raster = new BgdRaster<float> { ProgressHandler = ProgressHandler, Filename = fileName }; break; case RasterDataType.DOUBLE: raster = new BgdRaster<double> { ProgressHandler = ProgressHandler, Filename = fileName }; break; case RasterDataType.SBYTE: raster = new BgdRaster<sbyte> { ProgressHandler = ProgressHandler, Filename = fileName }; break; case RasterDataType.USHORT: raster = new BgdRaster<ushort> { ProgressHandler = ProgressHandler, Filename = fileName }; break; case RasterDataType.UINTEGER: raster = new BgdRaster<uint> { ProgressHandler = ProgressHandler, Filename = fileName }; break; case RasterDataType.ULONG: raster = new BgdRaster<ulong> { ProgressHandler = ProgressHandler, Filename = fileName }; break; case RasterDataType.BOOL: raster = new BgdRaster<bool> { ProgressHandler = ProgressHandler, Filename = fileName }; break; } raster?.Open(); return raster; } /// <summary> /// A Non-File based open. If no DialogReadFilter is provided, DotSpatial will call /// this method when this plugin is selected from the Add Other Data option in the /// file menu. /// </summary> /// <returns>null.</returns> public virtual List<IDataSet> Open() { // This data provider uses a file format, and not the 'other data' methods. return null; } /// <summary> /// Opens the given file. /// </summary> /// <param name="fileName">File that should be opened.</param> /// <returns>An IDataSet with the files data.</returns> IDataSet IDataProvider.Open(string fileName) { return Open(fileName); } #endregion } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="InflateManager.cs" company="XamlNinja"> // 2011 Richard Griffin and Ollie Riches // </copyright> // <summary> // http://www.sharpgis.net/post/2011/08/28/GZIP-Compressed-Web-Requests-in-WP7-Take-2.aspx // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace WP7Contrib.Communications.Compression { internal sealed class InflateManager { private static byte[] mark = new byte[4] { (byte) 0, (byte) 0, byte.MaxValue, byte.MaxValue }; internal long[] was = new long[1]; private bool _handleRfc1950HeaderBytes = true; private const int PRESET_DICT = 32; private const int Z_DEFLATED = 8; private const int METHOD = 0; private const int FLAG = 1; private const int DICT4 = 2; private const int DICT3 = 3; private const int DICT2 = 4; private const int DICT1 = 5; private const int DICT0 = 6; private const int BLOCKS = 7; private const int CHECK4 = 8; private const int CHECK3 = 9; private const int CHECK2 = 10; private const int CHECK1 = 11; private const int DONE = 12; private const int BAD = 13; internal int mode; internal ZlibCodec _codec; internal int method; internal long need; internal int marker; internal int wbits; internal InflateBlocks blocks; internal bool HandleRfc1950HeaderBytes { get { return this._handleRfc1950HeaderBytes; } set { this._handleRfc1950HeaderBytes = value; } } static InflateManager() { } public InflateManager() { } public InflateManager(bool expectRfc1950HeaderBytes) { this._handleRfc1950HeaderBytes = expectRfc1950HeaderBytes; } internal int Reset() { this._codec.TotalBytesIn = this._codec.TotalBytesOut = 0L; this._codec.Message = (string)null; this.mode = this.HandleRfc1950HeaderBytes ? 0 : 7; this.blocks.Reset((long[])null); return 0; } internal int End() { if (this.blocks != null) this.blocks.Free(); this.blocks = (InflateBlocks)null; return 0; } internal int Initialize(ZlibCodec codec, int w) { this._codec = codec; this._codec.Message = (string)null; this.blocks = (InflateBlocks)null; if (w < 8 || w > 15) { this.End(); throw new ZlibException("Bad window size."); } else { this.wbits = w; this.blocks = new InflateBlocks(codec, this.HandleRfc1950HeaderBytes ? (object)this : (object)(InflateManager)null, 1 << w); this.Reset(); return 0; } } internal int Inflate(FlushType flush) { int num1 = (int)flush; if (this._codec.InputBuffer == null) throw new ZlibException("InputBuffer is null. "); int num2 = num1 == 4 ? -5 : 0; int r = -5; while (true) { switch (this.mode) { case 0: if (this._codec.AvailableBytesIn != 0) { r = num2; --this._codec.AvailableBytesIn; ++this._codec.TotalBytesIn; InflateManager inflateManager = this; byte[] numArray = this._codec.InputBuffer; int index = this._codec.NextIn++; int num3; int num4 = num3 = (int)numArray[index]; inflateManager.method = num3; if ((num4 & 15) != 8) { this.mode = 13; this._codec.Message = string.Format("unknown compression method (0x{0:X2})", (object)this.method); this.marker = 5; break; } else if ((this.method >> 4) + 8 > this.wbits) { this.mode = 13; this._codec.Message = string.Format("invalid window size ({0})", (object)((this.method >> 4) + 8)); this.marker = 5; break; } else { this.mode = 1; goto case 1; } } else goto label_4; case 1: if (this._codec.AvailableBytesIn != 0) { r = num2; --this._codec.AvailableBytesIn; ++this._codec.TotalBytesIn; int num3 = (int)this._codec.InputBuffer[this._codec.NextIn++] & (int)byte.MaxValue; if (((this.method << 8) + num3) % 31 != 0) { this.mode = 13; this._codec.Message = "incorrect header check"; this.marker = 5; break; } else if ((num3 & 32) == 0) { this.mode = 7; break; } else goto label_16; } else goto label_11; case 2: goto label_17; case 3: goto label_20; case 4: goto label_23; case 5: goto label_26; case 6: goto label_29; case 7: r = this.blocks.Process(r); if (r == -3) { this.mode = 13; this.marker = 0; break; } else { if (r == 0) r = num2; if (r == 1) { r = num2; this.blocks.Reset(this.was); if (!this.HandleRfc1950HeaderBytes) { this.mode = 12; break; } else { this.mode = 8; goto case 8; } } else goto label_35; } case 8: if (this._codec.AvailableBytesIn != 0) { r = num2; --this._codec.AvailableBytesIn; ++this._codec.TotalBytesIn; this.need = (long)(((int)this._codec.InputBuffer[this._codec.NextIn++] & (int)byte.MaxValue) << 24 & -16777216); this.mode = 9; goto case 9; } else goto label_40; case 9: if (this._codec.AvailableBytesIn != 0) { r = num2; --this._codec.AvailableBytesIn; ++this._codec.TotalBytesIn; this.need += (long)(((int)this._codec.InputBuffer[this._codec.NextIn++] & (int)byte.MaxValue) << 16) & 16711680L; this.mode = 10; goto case 10; } else goto label_43; case 10: if (this._codec.AvailableBytesIn != 0) { r = num2; --this._codec.AvailableBytesIn; ++this._codec.TotalBytesIn; this.need += (long)(((int)this._codec.InputBuffer[this._codec.NextIn++] & (int)byte.MaxValue) << 8) & 65280L; this.mode = 11; goto case 11; } else goto label_46; case 11: if (this._codec.AvailableBytesIn != 0) { r = num2; --this._codec.AvailableBytesIn; ++this._codec.TotalBytesIn; this.need += (long)this._codec.InputBuffer[this._codec.NextIn++] & (long)byte.MaxValue; if ((int)this.was[0] != (int)this.need) { this.mode = 13; this._codec.Message = "incorrect data check"; this.marker = 5; break; } else goto label_52; } else goto label_49; case 12: goto label_53; case 13: goto label_54; default: goto label_55; } } label_4: return r; label_11: return r; label_16: this.mode = 2; label_17: if (this._codec.AvailableBytesIn == 0) return r; r = num2; --this._codec.AvailableBytesIn; ++this._codec.TotalBytesIn; this.need = (long)(((int)this._codec.InputBuffer[this._codec.NextIn++] & (int)byte.MaxValue) << 24 & -16777216); this.mode = 3; label_20: if (this._codec.AvailableBytesIn == 0) return r; r = num2; --this._codec.AvailableBytesIn; ++this._codec.TotalBytesIn; this.need += (long)(((int)this._codec.InputBuffer[this._codec.NextIn++] & (int)byte.MaxValue) << 16) & 16711680L; this.mode = 4; label_23: if (this._codec.AvailableBytesIn == 0) return r; r = num2; --this._codec.AvailableBytesIn; ++this._codec.TotalBytesIn; this.need += (long)(((int)this._codec.InputBuffer[this._codec.NextIn++] & (int)byte.MaxValue) << 8) & 65280L; this.mode = 5; label_26: if (this._codec.AvailableBytesIn == 0) return r; --this._codec.AvailableBytesIn; ++this._codec.TotalBytesIn; this.need += (long)this._codec.InputBuffer[this._codec.NextIn++] & (long)byte.MaxValue; this._codec._Adler32 = this.need; this.mode = 6; return 2; label_29: this.mode = 13; this._codec.Message = "need dictionary"; this.marker = 0; return -2; label_35: return r; label_40: return r; label_43: return r; label_46: return r; label_49: return r; label_52: this.mode = 12; label_53: return 1; label_54: throw new ZlibException(string.Format("Bad state ({0})", (object)this._codec.Message)); label_55: throw new ZlibException("Stream error."); } internal int SetDictionary(byte[] dictionary) { int start = 0; int n = dictionary.Length; if (this.mode != 6) throw new ZlibException("Stream error."); if (Adler.Adler32(1L, dictionary, 0, dictionary.Length) != this._codec._Adler32) return -3; this._codec._Adler32 = Adler.Adler32(0L, (byte[])null, 0, 0); if (n >= 1 << this.wbits) { n = (1 << this.wbits) - 1; start = dictionary.Length - n; } this.blocks.SetDictionary(dictionary, start, n); this.mode = 7; return 0; } internal int Sync() { if (this.mode != 13) { this.mode = 13; this.marker = 0; } int num1; if ((num1 = this._codec.AvailableBytesIn) == 0) return -5; int index1 = this._codec.NextIn; int index2; for (index2 = this.marker; num1 != 0 && index2 < 4; --num1) { if ((int)this._codec.InputBuffer[index1] == (int)InflateManager.mark[index2]) ++index2; else index2 = (int)this._codec.InputBuffer[index1] == 0 ? 4 - index2 : 0; ++index1; } this._codec.TotalBytesIn += (long)(index1 - this._codec.NextIn); this._codec.NextIn = index1; this._codec.AvailableBytesIn = num1; this.marker = index2; if (index2 != 4) return -3; long num2 = this._codec.TotalBytesIn; long num3 = this._codec.TotalBytesOut; this.Reset(); this._codec.TotalBytesIn = num2; this._codec.TotalBytesOut = num3; this.mode = 7; return 0; } internal int SyncPoint(ZlibCodec z) { return this.blocks.SyncPoint(); } } }
/* MIT License Copyright (c) 2017 Saied Zarrinmehr 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.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Runtime.InteropServices; using System.Windows.Interop; using SpatialAnalysis.FieldUtility; using SpatialAnalysis.CellularEnvironment; using SpatialAnalysis.Miscellaneous; namespace SpatialAnalysis.Data.Visualization { /// <summary> /// Interaction logic for SelectDataForVisualization.xaml /// </summary> public partial class SelectDataFor2DVisualization : Window { #region Hiding the close button private const int GWL_STYLE = -16; private const int WS_SYSMENU = 0x80000; [DllImport("user32.dll", SetLastError = true)] private static extern int GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("user32.dll")] private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); void SelectDataForVisualization_Loaded(object sender, RoutedEventArgs e) { var hwnd = new WindowInteropHelper(this).Handle; SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU); } #endregion /// <summary> /// Gets or sets a value indicating whether to visualize cost /// </summary> /// <value><c>true</c> if cost visualized; otherwise, <c>false</c>.</value> public bool VisualizeCost { get; set; } /// <summary> /// Gets or sets the number. /// </summary> /// <value>The number.</value> public int Number { get; set; } /// <summary> /// Gets or sets the name of the data. /// </summary> /// <value>The name of the selected data.</value> public ISpatialData SelectedSpatialData { get; set; } private OSMDocument _host; /// <summary> /// Initializes a new instance of the <see cref="SelectDataFor2DVisualization"/> class. /// </summary> /// <param name="cellularFloor">The cellular floor.</param> /// <param name="allActivities">All activities.</param> /// <param name="allEvents">All events.</param> public SelectDataFor2DVisualization(OSMDocument host) { InitializeComponent(); this._host = host; this._colorStep.Text = this._host.ColorCode.Steps.ToString(); this.VisualizeCost = false; this.Loaded += new RoutedEventHandler(SelectDataForVisualization_Loaded); this.dataNames.SelectionMode = SelectionMode.Single; this._selectedItem.Text = string.Empty; var cellularDataNames = new TextBlock() { Text = "Spatial Data".ToUpper(), FontSize = 14, FontWeight= FontWeights.Bold, Foreground = new SolidColorBrush(Colors.DarkGray) }; this.dataNames.Items.Add(cellularDataNames); foreach (Function item in this._host.cellularFloor.AllSpatialDataFields.Values) { SpatialDataField data = item as SpatialDataField; if (data != null) { this.dataNames.Items.Add(data.Name); } } if (this._host.AllActivities.Count > 0) { var fieldNames = new TextBlock() { Text = "Activities".ToUpper(), FontSize = 14, FontWeight = FontWeights.Bold, Foreground = new SolidColorBrush(Colors.DarkGray) }; this.dataNames.Items.Add(fieldNames); foreach (var item in this._host.AllActivities.Values) { this.dataNames.Items.Add(item.Name); } } if (this._host.AllOccupancyEvent.Count > 0) { var eventNames = new TextBlock { Text = "Occupancy Events".ToUpper(), FontSize = 14, FontWeight = FontWeights.Bold, Foreground = new SolidColorBrush(Colors.DarkGray) }; this.dataNames.Items.Add(eventNames); foreach (var item in this._host.AllOccupancyEvent.Values) { this.dataNames.Items.Add(item.Name); } } if (this._host.AllSimulationResults.Count>0) { var simulationResults = new TextBlock { Text = "Simulation Results".ToUpper(), FontSize = 14, FontWeight = FontWeights.Bold, Foreground = new SolidColorBrush(Colors.DarkGray) }; this.dataNames.Items.Add(simulationResults); foreach (var item in this._host.AllSimulationResults.Values) { this.dataNames.Items.Add(item.Name); } } this.dataNames.SelectionChanged += dataNames_SelectionChanged; this.KeyDown += SelectDataFor2DVisualization_KeyDown; } void SelectDataFor2DVisualization_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { this.Okay(); } else if (e.Key == Key.Escape) { this.SelectedSpatialData = null; this.Close(); } } void dataNames_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (this.dataNames.SelectedIndex == -1) { return; } try { var obj = this.dataNames.SelectedItem; TextBlock selected = obj as TextBlock; if (selected != null) { this.dataNames.SelectedIndex = -1; this._selectedItem.Text = string.Empty; return; } else { string name = (string)this.dataNames.SelectedItem; if (this._host.ContainsSpatialData(name)) { this.SelectedSpatialData = this._host.GetSpatialData(name); this._selectedItem.Text = this.SelectedSpatialData.Name; } } this._useCost.IsChecked = false; if (this.SelectedSpatialData != null && this.SelectedSpatialData.Type != DataType.SpatialData) { this._useCost.IsEnabled = false; this._useCost.IsChecked = false; } else { this._useCost.IsChecked = false; this._useCost.IsEnabled = true; } } catch (Exception error) { MessageBox.Show(error.Report()); } } private void Okay_Click(object sender, RoutedEventArgs e) { this.Okay(); } private void Okay() { if (string.IsNullOrEmpty(this._selectedItem.Text)) { MessageBox.Show("Select a data field"); return; } double x = 0; if (!double.TryParse(this._colorStep.Text, out x)) { MessageBox.Show("Invalid input for 'Color Steps'"); return; } if (x<4) { MessageBox.Show("Enter a number larger than 3 for 'Color Steps'"); return; } this.Number = (int)x; if (this._host.ColorCode.Steps != this.Number) { this._host.ColorCode.SetSteps(this.Number); } if (this._useCost.IsChecked.Value) { this.VisualizeCost = true; } else { VisualizeCost = false; } this.Close(); } private void Cancel_Click(object sender, RoutedEventArgs e) { this.SelectedSpatialData = null; this.Close(); } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.8657 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // // This source code was auto-generated by wsdl, Version=2.0.50727.3038. // namespace WebsitePanel.Providers.HostedSolution { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; using WebsitePanel.Providers.SharePoint; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="HostedSharePointServerEntSoap", Namespace="http://smbsaas/websitepanel/server/")] [System.Xml.Serialization.XmlIncludeAttribute(typeof(ServiceProviderItem))] public partial class HostedSharePointServerEnt : Microsoft.Web.Services3.WebServicesClientProtocol { public ServiceProviderSettingsSoapHeader ServiceProviderSettingsSoapHeaderValue; private System.Threading.SendOrPostCallback Enterprise_GetSupportedLanguagesOperationCompleted; private System.Threading.SendOrPostCallback Enterprise_GetSiteCollectionsOperationCompleted; private System.Threading.SendOrPostCallback Enterprise_GetSiteCollectionOperationCompleted; private System.Threading.SendOrPostCallback Enterprise_CreateSiteCollectionOperationCompleted; private System.Threading.SendOrPostCallback Enterprise_UpdateQuotasOperationCompleted; private System.Threading.SendOrPostCallback Enterprise_CalculateSiteCollectionsDiskSpaceOperationCompleted; private System.Threading.SendOrPostCallback Enterprise_DeleteSiteCollectionOperationCompleted; private System.Threading.SendOrPostCallback Enterprise_BackupSiteCollectionOperationCompleted; private System.Threading.SendOrPostCallback Enterprise_RestoreSiteCollectionOperationCompleted; private System.Threading.SendOrPostCallback Enterprise_GetTempFileBinaryChunkOperationCompleted; private System.Threading.SendOrPostCallback Enterprise_AppendTempFileBinaryChunkOperationCompleted; private System.Threading.SendOrPostCallback Enterprise_GetSiteCollectionSizeOperationCompleted; private System.Threading.SendOrPostCallback Enterprise_SetPeoplePickerOuOperationCompleted; /// <remarks/> public HostedSharePointServerEnt() { this.Url = "http://localhost:9003/HostedSharePointServerEnt.asmx"; } /// <remarks/> public event Enterprise_GetSupportedLanguagesCompletedEventHandler Enterprise_GetSupportedLanguagesCompleted; /// <remarks/> public event Enterprise_GetSiteCollectionsCompletedEventHandler Enterprise_GetSiteCollectionsCompleted; /// <remarks/> public event Enterprise_GetSiteCollectionCompletedEventHandler Enterprise_GetSiteCollectionCompleted; /// <remarks/> public event Enterprise_CreateSiteCollectionCompletedEventHandler Enterprise_CreateSiteCollectionCompleted; /// <remarks/> public event Enterprise_UpdateQuotasCompletedEventHandler Enterprise_UpdateQuotasCompleted; /// <remarks/> public event Enterprise_CalculateSiteCollectionsDiskSpaceCompletedEventHandler Enterprise_CalculateSiteCollectionsDiskSpaceCompleted; /// <remarks/> public event Enterprise_DeleteSiteCollectionCompletedEventHandler Enterprise_DeleteSiteCollectionCompleted; /// <remarks/> public event Enterprise_BackupSiteCollectionCompletedEventHandler Enterprise_BackupSiteCollectionCompleted; /// <remarks/> public event Enterprise_RestoreSiteCollectionCompletedEventHandler Enterprise_RestoreSiteCollectionCompleted; /// <remarks/> public event Enterprise_GetTempFileBinaryChunkCompletedEventHandler Enterprise_GetTempFileBinaryChunkCompleted; /// <remarks/> public event Enterprise_AppendTempFileBinaryChunkCompletedEventHandler Enterprise_AppendTempFileBinaryChunkCompleted; /// <remarks/> public event Enterprise_GetSiteCollectionSizeCompletedEventHandler Enterprise_GetSiteCollectionSizeCompleted; /// <remarks/> public event Enterprise_SetPeoplePickerOuCompletedEventHandler Enterprise_SetPeoplePickerOuCompleted; /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/Enterprise_GetSupportedLanguages", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int[] Enterprise_GetSupportedLanguages() { object[] results = this.Invoke("Enterprise_GetSupportedLanguages", new object[0]); return ((int[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginEnterprise_GetSupportedLanguages(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("Enterprise_GetSupportedLanguages", new object[0], callback, asyncState); } /// <remarks/> public int[] EndEnterprise_GetSupportedLanguages(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int[])(results[0])); } /// <remarks/> public void Enterprise_GetSupportedLanguagesAsync() { this.Enterprise_GetSupportedLanguagesAsync(null); } /// <remarks/> public void Enterprise_GetSupportedLanguagesAsync(object userState) { if ((this.Enterprise_GetSupportedLanguagesOperationCompleted == null)) { this.Enterprise_GetSupportedLanguagesOperationCompleted = new System.Threading.SendOrPostCallback(this.OnEnterprise_GetSupportedLanguagesOperationCompleted); } this.InvokeAsync("Enterprise_GetSupportedLanguages", new object[0], this.Enterprise_GetSupportedLanguagesOperationCompleted, userState); } private void OnEnterprise_GetSupportedLanguagesOperationCompleted(object arg) { if ((this.Enterprise_GetSupportedLanguagesCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.Enterprise_GetSupportedLanguagesCompleted(this, new Enterprise_GetSupportedLanguagesCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/Enterprise_GetSiteCollections", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public SharePointEnterpriseSiteCollection[] Enterprise_GetSiteCollections() { object[] results = this.Invoke("Enterprise_GetSiteCollections", new object[0]); return ((SharePointEnterpriseSiteCollection[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginEnterprise_GetSiteCollections(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("Enterprise_GetSiteCollections", new object[0], callback, asyncState); } /// <remarks/> public SharePointEnterpriseSiteCollection[] EndEnterprise_GetSiteCollections(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((SharePointEnterpriseSiteCollection[])(results[0])); } /// <remarks/> public void Enterprise_GetSiteCollectionsAsync() { this.Enterprise_GetSiteCollectionsAsync(null); } /// <remarks/> public void Enterprise_GetSiteCollectionsAsync(object userState) { if ((this.Enterprise_GetSiteCollectionsOperationCompleted == null)) { this.Enterprise_GetSiteCollectionsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnEnterprise_GetSiteCollectionsOperationCompleted); } this.InvokeAsync("Enterprise_GetSiteCollections", new object[0], this.Enterprise_GetSiteCollectionsOperationCompleted, userState); } private void OnEnterprise_GetSiteCollectionsOperationCompleted(object arg) { if ((this.Enterprise_GetSiteCollectionsCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.Enterprise_GetSiteCollectionsCompleted(this, new Enterprise_GetSiteCollectionsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/Enterprise_GetSiteCollection", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public SharePointEnterpriseSiteCollection Enterprise_GetSiteCollection(string url) { object[] results = this.Invoke("Enterprise_GetSiteCollection", new object[] { url}); return ((SharePointEnterpriseSiteCollection)(results[0])); } /// <remarks/> public System.IAsyncResult BeginEnterprise_GetSiteCollection(string url, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("Enterprise_GetSiteCollection", new object[] { url}, callback, asyncState); } /// <remarks/> public SharePointEnterpriseSiteCollection EndEnterprise_GetSiteCollection(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((SharePointEnterpriseSiteCollection)(results[0])); } /// <remarks/> public void Enterprise_GetSiteCollectionAsync(string url) { this.Enterprise_GetSiteCollectionAsync(url, null); } /// <remarks/> public void Enterprise_GetSiteCollectionAsync(string url, object userState) { if ((this.Enterprise_GetSiteCollectionOperationCompleted == null)) { this.Enterprise_GetSiteCollectionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnEnterprise_GetSiteCollectionOperationCompleted); } this.InvokeAsync("Enterprise_GetSiteCollection", new object[] { url}, this.Enterprise_GetSiteCollectionOperationCompleted, userState); } private void OnEnterprise_GetSiteCollectionOperationCompleted(object arg) { if ((this.Enterprise_GetSiteCollectionCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.Enterprise_GetSiteCollectionCompleted(this, new Enterprise_GetSiteCollectionCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/Enterprise_CreateSiteCollection", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void Enterprise_CreateSiteCollection(SharePointEnterpriseSiteCollection siteCollection) { this.Invoke("Enterprise_CreateSiteCollection", new object[] { siteCollection}); } /// <remarks/> public System.IAsyncResult BeginEnterprise_CreateSiteCollection(SharePointEnterpriseSiteCollection siteCollection, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("Enterprise_CreateSiteCollection", new object[] { siteCollection}, callback, asyncState); } /// <remarks/> public void EndEnterprise_CreateSiteCollection(System.IAsyncResult asyncResult) { this.EndInvoke(asyncResult); } /// <remarks/> public void Enterprise_CreateSiteCollectionAsync(SharePointEnterpriseSiteCollection siteCollection) { this.Enterprise_CreateSiteCollectionAsync(siteCollection, null); } /// <remarks/> public void Enterprise_CreateSiteCollectionAsync(SharePointEnterpriseSiteCollection siteCollection, object userState) { if ((this.Enterprise_CreateSiteCollectionOperationCompleted == null)) { this.Enterprise_CreateSiteCollectionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnEnterprise_CreateSiteCollectionOperationCompleted); } this.InvokeAsync("Enterprise_CreateSiteCollection", new object[] { siteCollection}, this.Enterprise_CreateSiteCollectionOperationCompleted, userState); } private void OnEnterprise_CreateSiteCollectionOperationCompleted(object arg) { if ((this.Enterprise_CreateSiteCollectionCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.Enterprise_CreateSiteCollectionCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/Enterprise_UpdateQuotas", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void Enterprise_UpdateQuotas(string url, long maxSize, long warningSize) { this.Invoke("Enterprise_UpdateQuotas", new object[] { url, maxSize, warningSize}); } /// <remarks/> public System.IAsyncResult BeginEnterprise_UpdateQuotas(string url, long maxSize, long warningSize, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("Enterprise_UpdateQuotas", new object[] { url, maxSize, warningSize}, callback, asyncState); } /// <remarks/> public void EndEnterprise_UpdateQuotas(System.IAsyncResult asyncResult) { this.EndInvoke(asyncResult); } /// <remarks/> public void Enterprise_UpdateQuotasAsync(string url, long maxSize, long warningSize) { this.Enterprise_UpdateQuotasAsync(url, maxSize, warningSize, null); } /// <remarks/> public void Enterprise_UpdateQuotasAsync(string url, long maxSize, long warningSize, object userState) { if ((this.Enterprise_UpdateQuotasOperationCompleted == null)) { this.Enterprise_UpdateQuotasOperationCompleted = new System.Threading.SendOrPostCallback(this.OnEnterprise_UpdateQuotasOperationCompleted); } this.InvokeAsync("Enterprise_UpdateQuotas", new object[] { url, maxSize, warningSize}, this.Enterprise_UpdateQuotasOperationCompleted, userState); } private void OnEnterprise_UpdateQuotasOperationCompleted(object arg) { if ((this.Enterprise_UpdateQuotasCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.Enterprise_UpdateQuotasCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/Enterprise_CalculateSiteCollectionsDiskSpace", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public SharePointSiteDiskSpace[] Enterprise_CalculateSiteCollectionsDiskSpace(string[] urls) { object[] results = this.Invoke("Enterprise_CalculateSiteCollectionsDiskSpace", new object[] { urls}); return ((SharePointSiteDiskSpace[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginEnterprise_CalculateSiteCollectionsDiskSpace(string[] urls, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("Enterprise_CalculateSiteCollectionsDiskSpace", new object[] { urls}, callback, asyncState); } /// <remarks/> public SharePointSiteDiskSpace[] EndEnterprise_CalculateSiteCollectionsDiskSpace(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((SharePointSiteDiskSpace[])(results[0])); } /// <remarks/> public void Enterprise_CalculateSiteCollectionsDiskSpaceAsync(string[] urls) { this.Enterprise_CalculateSiteCollectionsDiskSpaceAsync(urls, null); } /// <remarks/> public void Enterprise_CalculateSiteCollectionsDiskSpaceAsync(string[] urls, object userState) { if ((this.Enterprise_CalculateSiteCollectionsDiskSpaceOperationCompleted == null)) { this.Enterprise_CalculateSiteCollectionsDiskSpaceOperationCompleted = new System.Threading.SendOrPostCallback(this.OnEnterprise_CalculateSiteCollectionsDiskSpaceOperationCompleted); } this.InvokeAsync("Enterprise_CalculateSiteCollectionsDiskSpace", new object[] { urls}, this.Enterprise_CalculateSiteCollectionsDiskSpaceOperationCompleted, userState); } private void OnEnterprise_CalculateSiteCollectionsDiskSpaceOperationCompleted(object arg) { if ((this.Enterprise_CalculateSiteCollectionsDiskSpaceCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.Enterprise_CalculateSiteCollectionsDiskSpaceCompleted(this, new Enterprise_CalculateSiteCollectionsDiskSpaceCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/Enterprise_DeleteSiteCollection", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void Enterprise_DeleteSiteCollection(SharePointEnterpriseSiteCollection siteCollection) { this.Invoke("Enterprise_DeleteSiteCollection", new object[] { siteCollection}); } /// <remarks/> public System.IAsyncResult BeginEnterprise_DeleteSiteCollection(SharePointEnterpriseSiteCollection siteCollection, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("Enterprise_DeleteSiteCollection", new object[] { siteCollection}, callback, asyncState); } /// <remarks/> public void EndEnterprise_DeleteSiteCollection(System.IAsyncResult asyncResult) { this.EndInvoke(asyncResult); } /// <remarks/> public void Enterprise_DeleteSiteCollectionAsync(SharePointEnterpriseSiteCollection siteCollection) { this.Enterprise_DeleteSiteCollectionAsync(siteCollection, null); } /// <remarks/> public void Enterprise_DeleteSiteCollectionAsync(SharePointEnterpriseSiteCollection siteCollection, object userState) { if ((this.Enterprise_DeleteSiteCollectionOperationCompleted == null)) { this.Enterprise_DeleteSiteCollectionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnEnterprise_DeleteSiteCollectionOperationCompleted); } this.InvokeAsync("Enterprise_DeleteSiteCollection", new object[] { siteCollection}, this.Enterprise_DeleteSiteCollectionOperationCompleted, userState); } private void OnEnterprise_DeleteSiteCollectionOperationCompleted(object arg) { if ((this.Enterprise_DeleteSiteCollectionCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.Enterprise_DeleteSiteCollectionCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/Enterprise_BackupSiteCollection", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public string Enterprise_BackupSiteCollection(string url, string filename, bool zip) { object[] results = this.Invoke("Enterprise_BackupSiteCollection", new object[] { url, filename, zip}); return ((string)(results[0])); } /// <remarks/> public System.IAsyncResult BeginEnterprise_BackupSiteCollection(string url, string filename, bool zip, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("Enterprise_BackupSiteCollection", new object[] { url, filename, zip}, callback, asyncState); } /// <remarks/> public string EndEnterprise_BackupSiteCollection(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } /// <remarks/> public void Enterprise_BackupSiteCollectionAsync(string url, string filename, bool zip) { this.Enterprise_BackupSiteCollectionAsync(url, filename, zip, null); } /// <remarks/> public void Enterprise_BackupSiteCollectionAsync(string url, string filename, bool zip, object userState) { if ((this.Enterprise_BackupSiteCollectionOperationCompleted == null)) { this.Enterprise_BackupSiteCollectionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnEnterprise_BackupSiteCollectionOperationCompleted); } this.InvokeAsync("Enterprise_BackupSiteCollection", new object[] { url, filename, zip}, this.Enterprise_BackupSiteCollectionOperationCompleted, userState); } private void OnEnterprise_BackupSiteCollectionOperationCompleted(object arg) { if ((this.Enterprise_BackupSiteCollectionCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.Enterprise_BackupSiteCollectionCompleted(this, new Enterprise_BackupSiteCollectionCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/Enterprise_RestoreSiteCollection", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void Enterprise_RestoreSiteCollection(SharePointEnterpriseSiteCollection siteCollection, string filename) { this.Invoke("Enterprise_RestoreSiteCollection", new object[] { siteCollection, filename}); } /// <remarks/> public System.IAsyncResult BeginEnterprise_RestoreSiteCollection(SharePointEnterpriseSiteCollection siteCollection, string filename, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("Enterprise_RestoreSiteCollection", new object[] { siteCollection, filename}, callback, asyncState); } /// <remarks/> public void EndEnterprise_RestoreSiteCollection(System.IAsyncResult asyncResult) { this.EndInvoke(asyncResult); } /// <remarks/> public void Enterprise_RestoreSiteCollectionAsync(SharePointEnterpriseSiteCollection siteCollection, string filename) { this.Enterprise_RestoreSiteCollectionAsync(siteCollection, filename, null); } /// <remarks/> public void Enterprise_RestoreSiteCollectionAsync(SharePointEnterpriseSiteCollection siteCollection, string filename, object userState) { if ((this.Enterprise_RestoreSiteCollectionOperationCompleted == null)) { this.Enterprise_RestoreSiteCollectionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnEnterprise_RestoreSiteCollectionOperationCompleted); } this.InvokeAsync("Enterprise_RestoreSiteCollection", new object[] { siteCollection, filename}, this.Enterprise_RestoreSiteCollectionOperationCompleted, userState); } private void OnEnterprise_RestoreSiteCollectionOperationCompleted(object arg) { if ((this.Enterprise_RestoreSiteCollectionCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.Enterprise_RestoreSiteCollectionCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/Enterprise_GetTempFileBinaryChunk", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] [return: System.Xml.Serialization.XmlElementAttribute(DataType="base64Binary")] public byte[] Enterprise_GetTempFileBinaryChunk(string path, int offset, int length) { object[] results = this.Invoke("Enterprise_GetTempFileBinaryChunk", new object[] { path, offset, length}); return ((byte[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginEnterprise_GetTempFileBinaryChunk(string path, int offset, int length, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("Enterprise_GetTempFileBinaryChunk", new object[] { path, offset, length}, callback, asyncState); } /// <remarks/> public byte[] EndEnterprise_GetTempFileBinaryChunk(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((byte[])(results[0])); } /// <remarks/> public void Enterprise_GetTempFileBinaryChunkAsync(string path, int offset, int length) { this.Enterprise_GetTempFileBinaryChunkAsync(path, offset, length, null); } /// <remarks/> public void Enterprise_GetTempFileBinaryChunkAsync(string path, int offset, int length, object userState) { if ((this.Enterprise_GetTempFileBinaryChunkOperationCompleted == null)) { this.Enterprise_GetTempFileBinaryChunkOperationCompleted = new System.Threading.SendOrPostCallback(this.OnEnterprise_GetTempFileBinaryChunkOperationCompleted); } this.InvokeAsync("Enterprise_GetTempFileBinaryChunk", new object[] { path, offset, length}, this.Enterprise_GetTempFileBinaryChunkOperationCompleted, userState); } private void OnEnterprise_GetTempFileBinaryChunkOperationCompleted(object arg) { if ((this.Enterprise_GetTempFileBinaryChunkCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.Enterprise_GetTempFileBinaryChunkCompleted(this, new Enterprise_GetTempFileBinaryChunkCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/Enterprise_AppendTempFileBinaryChunk", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public string Enterprise_AppendTempFileBinaryChunk(string fileName, string path, [System.Xml.Serialization.XmlElementAttribute(DataType="base64Binary")] byte[] chunk) { object[] results = this.Invoke("Enterprise_AppendTempFileBinaryChunk", new object[] { fileName, path, chunk}); return ((string)(results[0])); } /// <remarks/> public System.IAsyncResult BeginEnterprise_AppendTempFileBinaryChunk(string fileName, string path, byte[] chunk, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("Enterprise_AppendTempFileBinaryChunk", new object[] { fileName, path, chunk}, callback, asyncState); } /// <remarks/> public string EndEnterprise_AppendTempFileBinaryChunk(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } /// <remarks/> public void Enterprise_AppendTempFileBinaryChunkAsync(string fileName, string path, byte[] chunk) { this.Enterprise_AppendTempFileBinaryChunkAsync(fileName, path, chunk, null); } /// <remarks/> public void Enterprise_AppendTempFileBinaryChunkAsync(string fileName, string path, byte[] chunk, object userState) { if ((this.Enterprise_AppendTempFileBinaryChunkOperationCompleted == null)) { this.Enterprise_AppendTempFileBinaryChunkOperationCompleted = new System.Threading.SendOrPostCallback(this.OnEnterprise_AppendTempFileBinaryChunkOperationCompleted); } this.InvokeAsync("Enterprise_AppendTempFileBinaryChunk", new object[] { fileName, path, chunk}, this.Enterprise_AppendTempFileBinaryChunkOperationCompleted, userState); } private void OnEnterprise_AppendTempFileBinaryChunkOperationCompleted(object arg) { if ((this.Enterprise_AppendTempFileBinaryChunkCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.Enterprise_AppendTempFileBinaryChunkCompleted(this, new Enterprise_AppendTempFileBinaryChunkCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/Enterprise_GetSiteCollectionSize", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public long Enterprise_GetSiteCollectionSize(string url) { object[] results = this.Invoke("Enterprise_GetSiteCollectionSize", new object[] { url}); return ((long)(results[0])); } /// <remarks/> public System.IAsyncResult BeginEnterprise_GetSiteCollectionSize(string url, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("Enterprise_GetSiteCollectionSize", new object[] { url}, callback, asyncState); } /// <remarks/> public long EndEnterprise_GetSiteCollectionSize(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((long)(results[0])); } /// <remarks/> public void Enterprise_GetSiteCollectionSizeAsync(string url) { this.Enterprise_GetSiteCollectionSizeAsync(url, null); } /// <remarks/> public void Enterprise_GetSiteCollectionSizeAsync(string url, object userState) { if ((this.Enterprise_GetSiteCollectionSizeOperationCompleted == null)) { this.Enterprise_GetSiteCollectionSizeOperationCompleted = new System.Threading.SendOrPostCallback(this.OnEnterprise_GetSiteCollectionSizeOperationCompleted); } this.InvokeAsync("Enterprise_GetSiteCollectionSize", new object[] { url}, this.Enterprise_GetSiteCollectionSizeOperationCompleted, userState); } private void OnEnterprise_GetSiteCollectionSizeOperationCompleted(object arg) { if ((this.Enterprise_GetSiteCollectionSizeCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.Enterprise_GetSiteCollectionSizeCompleted(this, new Enterprise_GetSiteCollectionSizeCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/Enterprise_SetPeoplePickerOu", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void Enterprise_SetPeoplePickerOu(string site, string ou) { this.Invoke("Enterprise_SetPeoplePickerOu", new object[] { site, ou}); } /// <remarks/> public System.IAsyncResult BeginEnterprise_SetPeoplePickerOu(string site, string ou, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("Enterprise_SetPeoplePickerOu", new object[] { site, ou}, callback, asyncState); } /// <remarks/> public void EndEnterprise_SetPeoplePickerOu(System.IAsyncResult asyncResult) { this.EndInvoke(asyncResult); } /// <remarks/> public void Enterprise_SetPeoplePickerOuAsync(string site, string ou) { this.Enterprise_SetPeoplePickerOuAsync(site, ou, null); } /// <remarks/> public void Enterprise_SetPeoplePickerOuAsync(string site, string ou, object userState) { if ((this.Enterprise_SetPeoplePickerOuOperationCompleted == null)) { this.Enterprise_SetPeoplePickerOuOperationCompleted = new System.Threading.SendOrPostCallback(this.OnEnterprise_SetPeoplePickerOuOperationCompleted); } this.InvokeAsync("Enterprise_SetPeoplePickerOu", new object[] { site, ou}, this.Enterprise_SetPeoplePickerOuOperationCompleted, userState); } private void OnEnterprise_SetPeoplePickerOuOperationCompleted(object arg) { if ((this.Enterprise_SetPeoplePickerOuCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.Enterprise_SetPeoplePickerOuCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> public new void CancelAsync(object userState) { base.CancelAsync(userState); } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void Enterprise_GetSupportedLanguagesCompletedEventHandler(object sender, Enterprise_GetSupportedLanguagesCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class Enterprise_GetSupportedLanguagesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal Enterprise_GetSupportedLanguagesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int[] Result { get { this.RaiseExceptionIfNecessary(); return ((int[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void Enterprise_GetSiteCollectionsCompletedEventHandler(object sender, Enterprise_GetSiteCollectionsCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class Enterprise_GetSiteCollectionsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal Enterprise_GetSiteCollectionsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public SharePointEnterpriseSiteCollection[] Result { get { this.RaiseExceptionIfNecessary(); return ((SharePointEnterpriseSiteCollection[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void Enterprise_GetSiteCollectionCompletedEventHandler(object sender, Enterprise_GetSiteCollectionCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class Enterprise_GetSiteCollectionCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal Enterprise_GetSiteCollectionCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public SharePointEnterpriseSiteCollection Result { get { this.RaiseExceptionIfNecessary(); return ((SharePointEnterpriseSiteCollection)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void Enterprise_CreateSiteCollectionCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void Enterprise_UpdateQuotasCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void Enterprise_CalculateSiteCollectionsDiskSpaceCompletedEventHandler(object sender, Enterprise_CalculateSiteCollectionsDiskSpaceCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class Enterprise_CalculateSiteCollectionsDiskSpaceCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal Enterprise_CalculateSiteCollectionsDiskSpaceCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public SharePointSiteDiskSpace[] Result { get { this.RaiseExceptionIfNecessary(); return ((SharePointSiteDiskSpace[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void Enterprise_DeleteSiteCollectionCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void Enterprise_BackupSiteCollectionCompletedEventHandler(object sender, Enterprise_BackupSiteCollectionCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class Enterprise_BackupSiteCollectionCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal Enterprise_BackupSiteCollectionCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public string Result { get { this.RaiseExceptionIfNecessary(); return ((string)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void Enterprise_RestoreSiteCollectionCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void Enterprise_GetTempFileBinaryChunkCompletedEventHandler(object sender, Enterprise_GetTempFileBinaryChunkCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class Enterprise_GetTempFileBinaryChunkCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal Enterprise_GetTempFileBinaryChunkCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public byte[] Result { get { this.RaiseExceptionIfNecessary(); return ((byte[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void Enterprise_AppendTempFileBinaryChunkCompletedEventHandler(object sender, Enterprise_AppendTempFileBinaryChunkCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class Enterprise_AppendTempFileBinaryChunkCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal Enterprise_AppendTempFileBinaryChunkCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public string Result { get { this.RaiseExceptionIfNecessary(); return ((string)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void Enterprise_GetSiteCollectionSizeCompletedEventHandler(object sender, Enterprise_GetSiteCollectionSizeCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class Enterprise_GetSiteCollectionSizeCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal Enterprise_GetSiteCollectionSizeCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public long Result { get { this.RaiseExceptionIfNecessary(); return ((long)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void Enterprise_SetPeoplePickerOuCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); }
// 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.Immutable; using System.Diagnostics; using System.IO; using System.Reflection.Internal; using System.Reflection.Metadata; using System.Threading; namespace System.Reflection.PortableExecutable { /// <summary> /// Portable Executable format reader. /// </summary> /// <remarks> /// The implementation is thread-safe, that is multiple threads can read data from the reader in parallel. /// Disposal of the reader is not thread-safe (see <see cref="Dispose"/>). /// </remarks> public sealed class PEReader : IDisposable { // May be null in the event that the entire image is not // deemed necessary and we have been instructed to read // the image contents without being lazy. private MemoryBlockProvider _peImage; // If we read the data from the image lazily (peImage != null) we defer reading the PE headers. private PEHeaders _lazyPEHeaders; private AbstractMemoryBlock _lazyMetadataBlock; private AbstractMemoryBlock _lazyImageBlock; private AbstractMemoryBlock[] _lazyPESectionBlocks; /// <summary> /// Creates a Portable Executable reader over a PE image stored in memory. /// </summary> /// <param name="peImage">Pointer to the start of the PE image.</param> /// <param name="size">The size of the PE image.</param> /// <exception cref="ArgumentNullException"><paramref name="peImage"/> is <see cref="IntPtr.Zero"/>.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="size"/> is negative.</exception> /// <remarks> /// The memory is owned by the caller and not released on disposal of the <see cref="PEReader"/>. /// The caller is responsible for keeping the memory alive and unmodified throughout the lifetime of the <see cref="PEReader"/>. /// The content of the image is not read during the construction of the <see cref="PEReader"/> /// </remarks> public unsafe PEReader(byte* peImage, int size) { if (peImage == null) { throw new ArgumentNullException(nameof(peImage)); } if (size < 0) { throw new ArgumentOutOfRangeException(nameof(size)); } _peImage = new ExternalMemoryBlockProvider(peImage, size); } /// <summary> /// Creates a Portable Executable reader over a PE image stored in a stream. /// </summary> /// <param name="peStream">PE image stream.</param> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="BadImageFormatException"> /// <see cref="PEStreamOptions.PrefetchMetadata"/> is specified and the PE headers of the image are invalid. /// </exception> /// <remarks> /// Ownership of the stream is transferred to the <see cref="PEReader"/> upon successful validation of constructor arguments. It will be /// disposed by the <see cref="PEReader"/> and the caller must not manipulate it. /// </remarks> public PEReader(Stream peStream) : this(peStream, PEStreamOptions.Default) { } /// <summary> /// Creates a Portable Executable reader over a PE image stored in a stream beginning at its current position and ending at the end of the stream. /// </summary> /// <param name="peStream">PE image stream.</param> /// <param name="options"> /// Options specifying how sections of the PE image are read from the stream. /// /// Unless <see cref="PEStreamOptions.LeaveOpen"/> is specified, ownership of the stream is transferred to the <see cref="PEReader"/> /// upon successful argument validation. It will be disposed by the <see cref="PEReader"/> and the caller must not manipulate it. /// /// Unless <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/> is specified no data /// is read from the stream during the construction of the <see cref="PEReader"/>. Furthermore, the stream must not be manipulated /// by caller while the <see cref="PEReader"/> is alive and undisposed. /// /// If <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/>, the <see cref="PEReader"/> /// will have read all of the data requested during construction. As such, if <see cref="PEStreamOptions.LeaveOpen"/> is also /// specified, the caller retains full ownership of the stream and is assured that it will not be manipulated by the <see cref="PEReader"/> /// after construction. /// </param> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="options"/> has an invalid value.</exception> /// <exception cref="BadImageFormatException"> /// <see cref="PEStreamOptions.PrefetchMetadata"/> is specified and the PE headers of the image are invalid. /// </exception> public PEReader(Stream peStream, PEStreamOptions options) : this(peStream, options, (int?)null) { } /// <summary> /// Creates a Portable Executable reader over a PE image of the given size beginning at the stream's current position. /// </summary> /// <param name="peStream">PE image stream.</param> /// <param name="size">PE image size.</param> /// <param name="options"> /// Options specifying how sections of the PE image are read from the stream. /// /// Unless <see cref="PEStreamOptions.LeaveOpen"/> is specified, ownership of the stream is transferred to the <see cref="PEReader"/> /// upon successful argument validation. It will be disposed by the <see cref="PEReader"/> and the caller must not manipulate it. /// /// Unless <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/> is specified no data /// is read from the stream during the construction of the <see cref="PEReader"/>. Furthermore, the stream must not be manipulated /// by caller while the <see cref="PEReader"/> is alive and undisposed. /// /// If <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/>, the <see cref="PEReader"/> /// will have read all of the data requested during construction. As such, if <see cref="PEStreamOptions.LeaveOpen"/> is also /// specified, the caller retains full ownership of the stream and is assured that it will not be manipulated by the <see cref="PEReader"/> /// after construction. /// </param> /// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</exception> public PEReader(Stream peStream, PEStreamOptions options, int size) : this(peStream, options, (int?)size) { } private unsafe PEReader(Stream peStream, PEStreamOptions options, int? sizeOpt) { if (peStream == null) { throw new ArgumentNullException(nameof(peStream)); } if (!peStream.CanRead || !peStream.CanSeek) { throw new ArgumentException(SR.StreamMustSupportReadAndSeek, nameof(peStream)); } if (!options.IsValid()) { throw new ArgumentOutOfRangeException(nameof(options)); } long start = peStream.Position; int size = PEBinaryReader.GetAndValidateSize(peStream, sizeOpt); bool closeStream = true; try { bool isFileStream = FileStreamReadLightUp.IsFileStream(peStream); if ((options & (PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage)) == 0) { _peImage = new StreamMemoryBlockProvider(peStream, start, size, isFileStream, (options & PEStreamOptions.LeaveOpen) != 0); closeStream = false; } else { // Read in the entire image or metadata blob: if ((options & PEStreamOptions.PrefetchEntireImage) != 0) { var imageBlock = StreamMemoryBlockProvider.ReadMemoryBlockNoLock(peStream, isFileStream, 0, (int)Math.Min(peStream.Length, int.MaxValue)); _lazyImageBlock = imageBlock; _peImage = new ExternalMemoryBlockProvider(imageBlock.Pointer, imageBlock.Size); // if the caller asked for metadata initialize the PE headers (calculates metadata offset): if ((options & PEStreamOptions.PrefetchMetadata) != 0) { InitializePEHeaders(); } } else { // The peImage is left null, but the lazyMetadataBlock is initialized up front. _lazyPEHeaders = new PEHeaders(peStream); _lazyMetadataBlock = StreamMemoryBlockProvider.ReadMemoryBlockNoLock(peStream, isFileStream, _lazyPEHeaders.MetadataStartOffset, _lazyPEHeaders.MetadataSize); } // We read all we need, the stream is going to be closed. } } finally { if (closeStream && (options & PEStreamOptions.LeaveOpen) == 0) { peStream.Dispose(); } } } /// <summary> /// Creates a Portable Executable reader over a PE image stored in a byte array. /// </summary> /// <param name="peImage">PE image.</param> /// <remarks> /// The content of the image is not read during the construction of the <see cref="PEReader"/> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="peImage"/> is null.</exception> public PEReader(ImmutableArray<byte> peImage) { if (peImage.IsDefault) { throw new ArgumentNullException(nameof(peImage)); } _peImage = new ByteArrayMemoryProvider(peImage); } /// <summary> /// Disposes all memory allocated by the reader. /// </summary> /// <remarks> /// <see cref="Dispose"/> can be called multiple times (but not in parallel). /// It is not safe to call <see cref="Dispose"/> in parallel with any other operation on the <see cref="PEReader"/> /// or reading from <see cref="PEMemoryBlock"/>s retrieved from the reader. /// </remarks> public void Dispose() { var image = _peImage; if (image != null) { image.Dispose(); _peImage = null; } var imageBlock = _lazyImageBlock; if (imageBlock != null) { imageBlock.Dispose(); _lazyImageBlock = null; } var metadataBlock = _lazyMetadataBlock; if (metadataBlock != null) { metadataBlock.Dispose(); _lazyMetadataBlock = null; } var peSectionBlocks = _lazyPESectionBlocks; if (peSectionBlocks != null) { foreach (var block in peSectionBlocks) { if (block != null) { block.Dispose(); } } _lazyPESectionBlocks = null; } } /// <summary> /// Gets the PE headers. /// </summary> /// <exception cref="BadImageFormatException">The headers contain invalid data.</exception> public PEHeaders PEHeaders { get { if (_lazyPEHeaders == null) { InitializePEHeaders(); } return _lazyPEHeaders; } } private void InitializePEHeaders() { Debug.Assert(_peImage != null); StreamConstraints constraints; Stream stream = _peImage.GetStream(out constraints); PEHeaders headers; if (constraints.GuardOpt != null) { lock (constraints.GuardOpt) { headers = ReadPEHeadersNoLock(stream, constraints.ImageStart, constraints.ImageSize); } } else { headers = ReadPEHeadersNoLock(stream, constraints.ImageStart, constraints.ImageSize); } Interlocked.CompareExchange(ref _lazyPEHeaders, headers, null); } private static PEHeaders ReadPEHeadersNoLock(Stream stream, long imageStartPosition, int imageSize) { Debug.Assert(imageStartPosition >= 0 && imageStartPosition <= stream.Length); stream.Seek(imageStartPosition, SeekOrigin.Begin); return new PEHeaders(stream, imageSize); } /// <summary> /// Returns a view of the entire image as a pointer and length. /// </summary> /// <exception cref="InvalidOperationException">PE image not available.</exception> private AbstractMemoryBlock GetEntireImageBlock() { if (_lazyImageBlock == null) { if (_peImage == null) { throw new InvalidOperationException(SR.PEImageNotAvailable); } var newBlock = _peImage.GetMemoryBlock(); if (Interlocked.CompareExchange(ref _lazyImageBlock, newBlock, null) != null) { // another thread created the block already, we need to dispose ours: newBlock.Dispose(); } } return _lazyImageBlock; } private AbstractMemoryBlock GetMetadataBlock() { if (!HasMetadata) { throw new InvalidOperationException(SR.PEImageDoesNotHaveMetadata); } if (_lazyMetadataBlock == null) { Debug.Assert(_peImage != null, "We always have metadata if peImage is not available."); var newBlock = _peImage.GetMemoryBlock(PEHeaders.MetadataStartOffset, PEHeaders.MetadataSize); if (Interlocked.CompareExchange(ref _lazyMetadataBlock, newBlock, null) != null) { // another thread created the block already, we need to dispose ours: newBlock.Dispose(); } } return _lazyMetadataBlock; } private AbstractMemoryBlock GetPESectionBlock(int index) { Debug.Assert(index >= 0 && index < PEHeaders.SectionHeaders.Length); Debug.Assert(_peImage != null); if (_lazyPESectionBlocks == null) { Interlocked.CompareExchange(ref _lazyPESectionBlocks, new AbstractMemoryBlock[PEHeaders.SectionHeaders.Length], null); } var newBlock = _peImage.GetMemoryBlock( PEHeaders.SectionHeaders[index].PointerToRawData, PEHeaders.SectionHeaders[index].SizeOfRawData); if (Interlocked.CompareExchange(ref _lazyPESectionBlocks[index], newBlock, null) != null) { // another thread created the block already, we need to dispose ours: newBlock.Dispose(); } return _lazyPESectionBlocks[index]; } /// <summary> /// Return true if the reader can access the entire PE image. /// </summary> /// <remarks> /// Returns false if the <see cref="PEReader"/> is constructed from a stream and only part of it is prefetched into memory. /// </remarks> public bool IsEntireImageAvailable { get { return _lazyImageBlock != null || _peImage != null; } } /// <summary> /// Gets a pointer to and size of the PE image if available (<see cref="IsEntireImageAvailable"/>). /// </summary> /// <exception cref="InvalidOperationException">The entire PE image is not available.</exception> public PEMemoryBlock GetEntireImage() { return new PEMemoryBlock(GetEntireImageBlock()); } /// <summary> /// Returns true if the PE image contains CLI metadata. /// </summary> /// <exception cref="BadImageFormatException">The PE headers contain invalid data.</exception> public bool HasMetadata { get { return PEHeaders.MetadataSize > 0; } } /// <summary> /// Loads PE section that contains CLI metadata. /// </summary> /// <exception cref="InvalidOperationException">The PE image doesn't contain metadata (<see cref="HasMetadata"/> returns false).</exception> /// <exception cref="BadImageFormatException">The PE headers contain invalid data.</exception> public PEMemoryBlock GetMetadata() { return new PEMemoryBlock(GetMetadataBlock()); } /// <summary> /// Loads PE section that contains the specified <paramref name="relativeVirtualAddress"/> into memory /// and returns a memory block that starts at <paramref name="relativeVirtualAddress"/> and ends at the end of the containing section. /// </summary> /// <param name="relativeVirtualAddress">Relative Virtual Address of the data to read.</param> /// <returns> /// An empty block if <paramref name="relativeVirtualAddress"/> doesn't represent a location in any of the PE sections of this PE image. /// </returns> /// <exception cref="BadImageFormatException">The PE headers contain invalid data.</exception> public PEMemoryBlock GetSectionData(int relativeVirtualAddress) { var sectionIndex = PEHeaders.GetContainingSectionIndex(relativeVirtualAddress); if (sectionIndex < 0) { return default(PEMemoryBlock); } int relativeOffset = relativeVirtualAddress - PEHeaders.SectionHeaders[sectionIndex].VirtualAddress; int size = PEHeaders.SectionHeaders[sectionIndex].VirtualSize - relativeOffset; AbstractMemoryBlock block; if (_peImage != null) { block = GetPESectionBlock(sectionIndex); } else { block = GetEntireImageBlock(); relativeOffset += PEHeaders.SectionHeaders[sectionIndex].PointerToRawData; } return new PEMemoryBlock(block, relativeOffset); } /// <summary> /// Reads all Debug Directory table entries. /// </summary> /// <exception cref="BadImageFormatException">Bad format of the entry.</exception> public unsafe ImmutableArray<DebugDirectoryEntry> ReadDebugDirectory() { var debugDirectory = PEHeaders.PEHeader.DebugTableDirectory; if (debugDirectory.Size == 0) { return ImmutableArray<DebugDirectoryEntry>.Empty; } int position; if (!PEHeaders.TryGetDirectoryOffset(debugDirectory, out position)) { throw new BadImageFormatException(SR.InvalidDirectoryRVA); } const int entrySize = 0x1c; if (debugDirectory.Size % entrySize != 0) { throw new BadImageFormatException(SR.InvalidDirectorySize); } using (AbstractMemoryBlock block = _peImage.GetMemoryBlock(position, debugDirectory.Size)) { var reader = new BlobReader(block.Pointer, block.Size); int entryCount = debugDirectory.Size / entrySize; var builder = ImmutableArray.CreateBuilder<DebugDirectoryEntry>(entryCount); for (int i = 0; i < entryCount; i++) { // Reserved, must be zero. int characteristics = reader.ReadInt32(); if (characteristics != 0) { throw new BadImageFormatException(SR.InvalidDebugDirectoryEntryCharacteristics); } uint stamp = reader.ReadUInt32(); ushort majorVersion = reader.ReadUInt16(); ushort minorVersion = reader.ReadUInt16(); var type = (DebugDirectoryEntryType)reader.ReadInt32(); int dataSize = reader.ReadInt32(); int dataRva = reader.ReadInt32(); int dataPointer = reader.ReadInt32(); builder.Add(new DebugDirectoryEntry(stamp, majorVersion, minorVersion, type, dataSize, dataRva, dataPointer)); } return builder.MoveToImmutable(); } } /// <summary> /// Reads the data pointed to by the specifed Debug Directory entry and interprets them as CodeView. /// </summary> /// <exception cref="ArgumentException"><paramref name="entry"/> is not a CodeView entry.</exception> /// <exception cref="BadImageFormatException">Bad format of the data.</exception> public unsafe CodeViewDebugDirectoryData ReadCodeViewDebugDirectoryData(DebugDirectoryEntry entry) { if (entry.Type != DebugDirectoryEntryType.CodeView) { throw new ArgumentException(nameof(entry)); } using (AbstractMemoryBlock block = _peImage.GetMemoryBlock(entry.DataPointer, entry.DataSize)) { var reader = new BlobReader(block.Pointer, block.Size); if (reader.ReadByte() != (byte)'R' || reader.ReadByte() != (byte)'S' || reader.ReadByte() != (byte)'D' || reader.ReadByte() != (byte)'S') { throw new BadImageFormatException(SR.UnexpectedCodeViewDataSignature); } Guid guid = reader.ReadGuid(); int age = reader.ReadInt32(); string path = reader.ReadUtf8NullTerminated(); // path may be padded with NULs while (reader.RemainingBytes > 0) { if (reader.ReadByte() != 0) { throw new BadImageFormatException(SR.InvalidPathPadding); } } return new CodeViewDebugDirectoryData(guid, age, path); } } } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace HostMe.Sdk.Model { /// <summary> /// /// </summary> [DataContract] public partial class PanelConfirmation : IEquatable<PanelConfirmation> { /// <summary> /// Gets or Sets CustomerName /// </summary> [DataMember(Name="customerName", EmitDefaultValue=true)] public string CustomerName { get; set; } /// <summary> /// Gets or Sets PhoneNumber /// </summary> [DataMember(Name="phoneNumber", EmitDefaultValue=true)] public string PhoneNumber { get; set; } /// <summary> /// Gets or Sets ConfirmationMethod /// </summary> [DataMember(Name="confirmationMethod", EmitDefaultValue=true)] public string ConfirmationMethod { get; set; } /// <summary> /// Gets or Sets GroupSize /// </summary> [DataMember(Name="groupSize", EmitDefaultValue=true)] public int? GroupSize { get; set; } /// <summary> /// Gets or Sets Areas /// </summary> [DataMember(Name="areas", EmitDefaultValue=true)] public string Areas { get; set; } /// <summary> /// Gets or Sets Note /// </summary> [DataMember(Name="note", EmitDefaultValue=true)] public string Note { get; set; } /// <summary> /// Gets or Sets HighChair /// </summary> [DataMember(Name="highChair", EmitDefaultValue=true)] public bool? HighChair { get; set; } /// <summary> /// Gets or Sets Stroller /// </summary> [DataMember(Name="stroller", EmitDefaultValue=true)] public bool? Stroller { get; set; } /// <summary> /// Gets or Sets Party /// </summary> [DataMember(Name="party", EmitDefaultValue=true)] public bool? Party { get; set; } /// <summary> /// Gets or Sets CustomerProfile /// </summary> [DataMember(Name="customerProfile", EmitDefaultValue=true)] public Profile CustomerProfile { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class PanelConfirmation {\n"); sb.Append(" CustomerName: ").Append(CustomerName).Append("\n"); sb.Append(" PhoneNumber: ").Append(PhoneNumber).Append("\n"); sb.Append(" ConfirmationMethod: ").Append(ConfirmationMethod).Append("\n"); sb.Append(" GroupSize: ").Append(GroupSize).Append("\n"); sb.Append(" Areas: ").Append(Areas).Append("\n"); sb.Append(" Note: ").Append(Note).Append("\n"); sb.Append(" HighChair: ").Append(HighChair).Append("\n"); sb.Append(" Stroller: ").Append(Stroller).Append("\n"); sb.Append(" Party: ").Append(Party).Append("\n"); sb.Append(" CustomerProfile: ").Append(CustomerProfile).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as PanelConfirmation); } /// <summary> /// Returns true if PanelConfirmation instances are equal /// </summary> /// <param name="other">Instance of PanelConfirmation to be compared</param> /// <returns>Boolean</returns> public bool Equals(PanelConfirmation other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.CustomerName == other.CustomerName || this.CustomerName != null && this.CustomerName.Equals(other.CustomerName) ) && ( this.PhoneNumber == other.PhoneNumber || this.PhoneNumber != null && this.PhoneNumber.Equals(other.PhoneNumber) ) && ( this.ConfirmationMethod == other.ConfirmationMethod || this.ConfirmationMethod != null && this.ConfirmationMethod.Equals(other.ConfirmationMethod) ) && ( this.GroupSize == other.GroupSize || this.GroupSize != null && this.GroupSize.Equals(other.GroupSize) ) && ( this.Areas == other.Areas || this.Areas != null && this.Areas.Equals(other.Areas) ) && ( this.Note == other.Note || this.Note != null && this.Note.Equals(other.Note) ) && ( this.HighChair == other.HighChair || this.HighChair != null && this.HighChair.Equals(other.HighChair) ) && ( this.Stroller == other.Stroller || this.Stroller != null && this.Stroller.Equals(other.Stroller) ) && ( this.Party == other.Party || this.Party != null && this.Party.Equals(other.Party) ) && ( this.CustomerProfile == other.CustomerProfile || this.CustomerProfile != null && this.CustomerProfile.Equals(other.CustomerProfile) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.CustomerName != null) hash = hash * 59 + this.CustomerName.GetHashCode(); if (this.PhoneNumber != null) hash = hash * 59 + this.PhoneNumber.GetHashCode(); if (this.ConfirmationMethod != null) hash = hash * 59 + this.ConfirmationMethod.GetHashCode(); if (this.GroupSize != null) hash = hash * 59 + this.GroupSize.GetHashCode(); if (this.Areas != null) hash = hash * 59 + this.Areas.GetHashCode(); if (this.Note != null) hash = hash * 59 + this.Note.GetHashCode(); if (this.HighChair != null) hash = hash * 59 + this.HighChair.GetHashCode(); if (this.Stroller != null) hash = hash * 59 + this.Stroller.GetHashCode(); if (this.Party != null) hash = hash * 59 + this.Party.GetHashCode(); if (this.CustomerProfile != null) hash = hash * 59 + this.CustomerProfile.GetHashCode(); return hash; } } } }
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ // This code is auto-generated, do not modify using Ds3.Models; using System; using System.Net; namespace Ds3.Calls { public class PairBackRegisteredDs3TargetSpectraS3Request : Ds3Request { public string Ds3Target { get; private set; } private Ds3TargetAccessControlReplication? _accessControlReplication; public Ds3TargetAccessControlReplication? AccessControlReplication { get { return _accessControlReplication; } set { WithAccessControlReplication(value); } } private string _adminAuthId; public string AdminAuthId { get { return _adminAuthId; } set { WithAdminAuthId(value); } } private string _adminSecretKey; public string AdminSecretKey { get { return _adminSecretKey; } set { WithAdminSecretKey(value); } } private string _dataPathEndPoint; public string DataPathEndPoint { get { return _dataPathEndPoint; } set { WithDataPathEndPoint(value); } } private bool? _dataPathHttps; public bool? DataPathHttps { get { return _dataPathHttps; } set { WithDataPathHttps(value); } } private int? _dataPathPort; public int? DataPathPort { get { return _dataPathPort; } set { WithDataPathPort(value); } } private string _dataPathProxy; public string DataPathProxy { get { return _dataPathProxy; } set { WithDataPathProxy(value); } } private bool? _dataPathVerifyCertificate; public bool? DataPathVerifyCertificate { get { return _dataPathVerifyCertificate; } set { WithDataPathVerifyCertificate(value); } } private TargetReadPreferenceType? _defaultReadPreference; public TargetReadPreferenceType? DefaultReadPreference { get { return _defaultReadPreference; } set { WithDefaultReadPreference(value); } } private string _name; public string Name { get { return _name; } set { WithName(value); } } private bool? _permitGoingOutOfSync; public bool? PermitGoingOutOfSync { get { return _permitGoingOutOfSync; } set { WithPermitGoingOutOfSync(value); } } private string _replicatedUserDefaultDataPolicy; public string ReplicatedUserDefaultDataPolicy { get { return _replicatedUserDefaultDataPolicy; } set { WithReplicatedUserDefaultDataPolicy(value); } } public PairBackRegisteredDs3TargetSpectraS3Request WithAccessControlReplication(Ds3TargetAccessControlReplication? accessControlReplication) { this._accessControlReplication = accessControlReplication; if (accessControlReplication != null) { this.QueryParams.Add("access_control_replication", accessControlReplication.ToString()); } else { this.QueryParams.Remove("access_control_replication"); } return this; } public PairBackRegisteredDs3TargetSpectraS3Request WithAdminAuthId(string adminAuthId) { this._adminAuthId = adminAuthId; if (adminAuthId != null) { this.QueryParams.Add("admin_auth_id", adminAuthId); } else { this.QueryParams.Remove("admin_auth_id"); } return this; } public PairBackRegisteredDs3TargetSpectraS3Request WithAdminSecretKey(string adminSecretKey) { this._adminSecretKey = adminSecretKey; if (adminSecretKey != null) { this.QueryParams.Add("admin_secret_key", adminSecretKey); } else { this.QueryParams.Remove("admin_secret_key"); } return this; } public PairBackRegisteredDs3TargetSpectraS3Request WithDataPathEndPoint(string dataPathEndPoint) { this._dataPathEndPoint = dataPathEndPoint; if (dataPathEndPoint != null) { this.QueryParams.Add("data_path_end_point", dataPathEndPoint); } else { this.QueryParams.Remove("data_path_end_point"); } return this; } public PairBackRegisteredDs3TargetSpectraS3Request WithDataPathHttps(bool? dataPathHttps) { this._dataPathHttps = dataPathHttps; if (dataPathHttps != null) { this.QueryParams.Add("data_path_https", dataPathHttps.ToString()); } else { this.QueryParams.Remove("data_path_https"); } return this; } public PairBackRegisteredDs3TargetSpectraS3Request WithDataPathPort(int? dataPathPort) { this._dataPathPort = dataPathPort; if (dataPathPort != null) { this.QueryParams.Add("data_path_port", dataPathPort.ToString()); } else { this.QueryParams.Remove("data_path_port"); } return this; } public PairBackRegisteredDs3TargetSpectraS3Request WithDataPathProxy(string dataPathProxy) { this._dataPathProxy = dataPathProxy; if (dataPathProxy != null) { this.QueryParams.Add("data_path_proxy", dataPathProxy); } else { this.QueryParams.Remove("data_path_proxy"); } return this; } public PairBackRegisteredDs3TargetSpectraS3Request WithDataPathVerifyCertificate(bool? dataPathVerifyCertificate) { this._dataPathVerifyCertificate = dataPathVerifyCertificate; if (dataPathVerifyCertificate != null) { this.QueryParams.Add("data_path_verify_certificate", dataPathVerifyCertificate.ToString()); } else { this.QueryParams.Remove("data_path_verify_certificate"); } return this; } public PairBackRegisteredDs3TargetSpectraS3Request WithDefaultReadPreference(TargetReadPreferenceType? defaultReadPreference) { this._defaultReadPreference = defaultReadPreference; if (defaultReadPreference != null) { this.QueryParams.Add("default_read_preference", defaultReadPreference.ToString()); } else { this.QueryParams.Remove("default_read_preference"); } return this; } public PairBackRegisteredDs3TargetSpectraS3Request WithName(string name) { this._name = name; if (name != null) { this.QueryParams.Add("name", name); } else { this.QueryParams.Remove("name"); } return this; } public PairBackRegisteredDs3TargetSpectraS3Request WithPermitGoingOutOfSync(bool? permitGoingOutOfSync) { this._permitGoingOutOfSync = permitGoingOutOfSync; if (permitGoingOutOfSync != null) { this.QueryParams.Add("permit_going_out_of_sync", permitGoingOutOfSync.ToString()); } else { this.QueryParams.Remove("permit_going_out_of_sync"); } return this; } public PairBackRegisteredDs3TargetSpectraS3Request WithReplicatedUserDefaultDataPolicy(string replicatedUserDefaultDataPolicy) { this._replicatedUserDefaultDataPolicy = replicatedUserDefaultDataPolicy; if (replicatedUserDefaultDataPolicy != null) { this.QueryParams.Add("replicated_user_default_data_policy", replicatedUserDefaultDataPolicy); } else { this.QueryParams.Remove("replicated_user_default_data_policy"); } return this; } public PairBackRegisteredDs3TargetSpectraS3Request(string ds3Target) { this.Ds3Target = ds3Target; this.QueryParams.Add("operation", "pair_back"); } internal override HttpVerb Verb { get { return HttpVerb.PUT; } } internal override string Path { get { return "/_rest_/ds3_target/" + Ds3Target; } } } }
using System.Diagnostics; namespace Lucene.Net.Codecs.Lucene41 { /* * 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 IOUtils = Lucene.Net.Util.IOUtils; using SegmentReadState = Lucene.Net.Index.SegmentReadState; using SegmentWriteState = Lucene.Net.Index.SegmentWriteState; /// <summary> /// Lucene 4.1 postings format, which encodes postings in packed integer blocks /// for fast decode. /// /// <para><b>NOTE</b>: this format is still experimental and /// subject to change without backwards compatibility. /// /// <para> /// Basic idea: /// <list type="bullet"> /// <item><description> /// <b>Packed Blocks and VInt Blocks</b>: /// <para>In packed blocks, integers are encoded with the same bit width packed format (<see cref="Util.Packed.PackedInt32s"/>): /// the block size (i.e. number of integers inside block) is fixed (currently 128). Additionally blocks /// that are all the same value are encoded in an optimized way.</para> /// <para>In VInt blocks, integers are encoded as VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>): /// the block size is variable.</para> /// </description></item> /// /// <item><description> /// <b>Block structure</b>: /// <para>When the postings are long enough, Lucene41PostingsFormat will try to encode most integer data /// as a packed block.</para> /// <para>Take a term with 259 documents as an example, the first 256 document ids are encoded as two packed /// blocks, while the remaining 3 are encoded as one VInt block. </para> /// <para>Different kinds of data are always encoded separately into different packed blocks, but may /// possibly be interleaved into the same VInt block. </para> /// <para>This strategy is applied to pairs: /// &lt;document number, frequency&gt;, /// &lt;position, payload length&gt;, /// &lt;position, offset start, offset length&gt;, and /// &lt;position, payload length, offsetstart, offset length&gt;.</para> /// </description></item> /// /// <item><description> /// <b>Skipdata settings</b>: /// <para>The structure of skip table is quite similar to previous version of Lucene. Skip interval is the /// same as block size, and each skip entry points to the beginning of each block. However, for /// the first block, skip data is omitted.</para> /// </description></item> /// /// <item><description> /// <b>Positions, Payloads, and Offsets</b>: /// <para>A position is an integer indicating where the term occurs within one document. /// A payload is a blob of metadata associated with current position. /// An offset is a pair of integers indicating the tokenized start/end offsets for given term /// in current position: it is essentially a specialized payload. </para> /// <para>When payloads and offsets are not omitted, numPositions==numPayloads==numOffsets (assuming a /// null payload contributes one count). As mentioned in block structure, it is possible to encode /// these three either combined or separately.</para> /// <para>In all cases, payloads and offsets are stored together. When encoded as a packed block, /// position data is separated out as .pos, while payloads and offsets are encoded in .pay (payload /// metadata will also be stored directly in .pay). When encoded as VInt blocks, all these three are /// stored interleaved into the .pos (so is payload metadata).</para> /// <para>With this strategy, the majority of payload and offset data will be outside .pos file. /// So for queries that require only position data, running on a full index with payloads and offsets, /// this reduces disk pre-fetches.</para> /// </description></item> /// </list> /// </para> /// /// <para> /// Files and detailed format: /// <list type="bullet"> /// <item><description><c>.tim</c>: <a href="#Termdictionary">Term Dictionary</a></description></item> /// <item><description><c>.tip</c>: <a href="#Termindex">Term Index</a></description></item> /// <item><description><c>.doc</c>: <a href="#Frequencies">Frequencies and Skip Data</a></description></item> /// <item><description><c>.pos</c>: <a href="#Positions">Positions</a></description></item> /// <item><description><c>.pay</c>: <a href="#Payloads">Payloads and Offsets</a></description></item> /// </list> /// </para> /// /// <a name="Termdictionary" id="Termdictionary"></a> /// <dl> /// <dd> /// <b>Term Dictionary</b> /// /// <para>The .tim file contains the list of terms in each /// field along with per-term statistics (such as docfreq) /// and pointers to the frequencies, positions, payload and /// skip data in the .doc, .pos, and .pay files. /// See <see cref="BlockTreeTermsWriter"/> for more details on the format. /// </para> /// /// <para>NOTE: The term dictionary can plug into different postings implementations: /// the postings writer/reader are actually responsible for encoding /// and decoding the PostingsHeader and TermMetadata sections described here:</para> /// /// <list type="bullet"> /// <item><description>PostingsHeader --&gt; Header, PackedBlockSize</description></item> /// <item><description>TermMetadata --&gt; (DocFPDelta|SingletonDocID), PosFPDelta?, PosVIntBlockFPDelta?, PayFPDelta?, /// SkipFPDelta?</description></item> /// <item><description>Header, --&gt; CodecHeader (<see cref="CodecUtil.WriteHeader(Store.DataOutput, string, int)"/>) </description></item> /// <item><description>PackedBlockSize, SingletonDocID --&gt; VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) </description></item> /// <item><description>DocFPDelta, PosFPDelta, PayFPDelta, PosVIntBlockFPDelta, SkipFPDelta --&gt; VLong (<see cref="Store.DataOutput.WriteVInt64(long)"/>) </description></item> /// <item><description>Footer --&gt; CodecFooter (<see cref="CodecUtil.WriteFooter(Store.IndexOutput)"/>) </description></item> /// </list> /// <para>Notes:</para> /// <list type="bullet"> /// <item><description>Header is a CodecHeader (<see cref="CodecUtil.WriteHeader(Store.DataOutput, string, int)"/>) storing the version information /// for the postings.</description></item> /// <item><description>PackedBlockSize is the fixed block size for packed blocks. In packed block, bit width is /// determined by the largest integer. Smaller block size result in smaller variance among width /// of integers hence smaller indexes. Larger block size result in more efficient bulk i/o hence /// better acceleration. This value should always be a multiple of 64, currently fixed as 128 as /// a tradeoff. It is also the skip interval used to accelerate <see cref="Search.DocIdSetIterator.Advance(int)"/>.</description></item> /// <item><description>DocFPDelta determines the position of this term's TermFreqs within the .doc file. /// In particular, it is the difference of file offset between this term's /// data and previous term's data (or zero, for the first term in the block).On disk it is /// stored as the difference from previous value in sequence. </description></item> /// <item><description>PosFPDelta determines the position of this term's TermPositions within the .pos file. /// While PayFPDelta determines the position of this term's &lt;TermPayloads, TermOffsets?&gt; within /// the .pay file. Similar to DocFPDelta, it is the difference between two file positions (or /// neglected, for fields that omit payloads and offsets).</description></item> /// <item><description>PosVIntBlockFPDelta determines the position of this term's last TermPosition in last pos packed /// block within the .pos file. It is synonym for PayVIntBlockFPDelta or OffsetVIntBlockFPDelta. /// This is actually used to indicate whether it is necessary to load following /// payloads and offsets from .pos instead of .pay. Every time a new block of positions are to be /// loaded, the PostingsReader will use this value to check whether current block is packed format /// or VInt. When packed format, payloads and offsets are fetched from .pay, otherwise from .pos. /// (this value is neglected when total number of positions i.e. totalTermFreq is less or equal /// to PackedBlockSize).</description></item> /// <item><description>SkipFPDelta determines the position of this term's SkipData within the .doc /// file. In particular, it is the length of the TermFreq data. /// SkipDelta is only stored if DocFreq is not smaller than SkipMinimum /// (i.e. 128 in Lucene41PostingsFormat).</description></item> /// <item><description>SingletonDocID is an optimization when a term only appears in one document. In this case, instead /// of writing a file pointer to the .doc file (DocFPDelta), and then a VIntBlock at that location, the /// single document ID is written to the term dictionary.</description></item> /// </list> /// </dd> /// </dl> /// /// <a name="Termindex" id="Termindex"></a> /// <dl> /// <dd> /// <b>Term Index</b> /// <para>The .tip file contains an index into the term dictionary, so that it can be /// accessed randomly. See <see cref="BlockTreeTermsWriter"/> for more details on the format.</para> /// </dd> /// </dl> /// /// /// <a name="Frequencies" id="Frequencies"></a> /// <dl> /// <dd> /// <b>Frequencies and Skip Data</b> /// /// <para>The .doc file contains the lists of documents which contain each term, along /// with the frequency of the term in that document (except when frequencies are /// omitted: <see cref="Index.IndexOptions.DOCS_ONLY"/>). It also saves skip data to the beginning of /// each packed or VInt block, when the length of document list is larger than packed block size.</para> /// /// <list type="bullet"> /// <item><description>docFile(.doc) --&gt; Header, &lt;TermFreqs, SkipData?&gt;<sup>TermCount</sup>, Footer</description></item> /// <item><description>Header --&gt; CodecHeader (<see cref="CodecUtil.WriteHeader(Store.DataOutput, string, int)"/>)</description></item> /// <item><description>TermFreqs --&gt; &lt;PackedBlock&gt; <sup>PackedDocBlockNum</sup>, /// VIntBlock? </description></item> /// <item><description>PackedBlock --&gt; PackedDocDeltaBlock, PackedFreqBlock?</description></item> /// <item><description>VIntBlock --&gt; &lt;DocDelta[, Freq?]&gt;<sup>DocFreq-PackedBlockSize*PackedDocBlockNum</sup></description></item> /// <item><description>SkipData --&gt; &lt;&lt;SkipLevelLength, SkipLevel&gt; /// <sup>NumSkipLevels-1</sup>, SkipLevel&gt;, SkipDatum?</description></item> /// <item><description>SkipLevel --&gt; &lt;SkipDatum&gt; <sup>TrimmedDocFreq/(PackedBlockSize^(Level + 1))</sup></description></item> /// <item><description>SkipDatum --&gt; DocSkip, DocFPSkip, &lt;PosFPSkip, PosBlockOffset, PayLength?, /// PayFPSkip?&gt;?, SkipChildLevelPointer?</description></item> /// <item><description>PackedDocDeltaBlock, PackedFreqBlock --&gt; PackedInts (<see cref="Util.Packed.PackedInt32s"/>) </description></item> /// <item><description>DocDelta, Freq, DocSkip, DocFPSkip, PosFPSkip, PosBlockOffset, PayByteUpto, PayFPSkip /// --&gt; /// VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) </description></item> /// <item><description>SkipChildLevelPointer --&gt; VLong (<see cref="Store.DataOutput.WriteVInt64(long)"/>) </description></item> /// <item><description>Footer --&gt; CodecFooter (<see cref="CodecUtil.WriteFooter(Store.IndexOutput)"/>) </description></item> /// </list> /// <para>Notes:</para> /// <list type="bullet"> /// <item><description>PackedDocDeltaBlock is theoretically generated from two steps: /// <list type="number"> /// <item><description>Calculate the difference between each document number and previous one, /// and get a d-gaps list (for the first document, use absolute value); </description></item> /// <item><description>For those d-gaps from first one to PackedDocBlockNum*PackedBlockSize<sup>th</sup>, /// separately encode as packed blocks.</description></item> /// </list> /// If frequencies are not omitted, PackedFreqBlock will be generated without d-gap step. /// </description></item> /// <item><description>VIntBlock stores remaining d-gaps (along with frequencies when possible) with a format /// that encodes DocDelta and Freq: /// <para>DocDelta: if frequencies are indexed, this determines both the document /// number and the frequency. In particular, DocDelta/2 is the difference between /// this document number and the previous document number (or zero when this is the /// first document in a TermFreqs). When DocDelta is odd, the frequency is one. /// When DocDelta is even, the frequency is read as another VInt. If frequencies /// are omitted, DocDelta contains the gap (not multiplied by 2) between document /// numbers and no frequency information is stored.</para> /// <para>For example, the TermFreqs for a term which occurs once in document seven /// and three times in document eleven, with frequencies indexed, would be the /// following sequence of VInts:</para> /// <para>15, 8, 3</para> /// <para>If frequencies were omitted (<see cref="Index.IndexOptions.DOCS_ONLY"/>) it would be this /// sequence of VInts instead:</para> /// <para>7,4</para> /// </description></item> /// <item><description>PackedDocBlockNum is the number of packed blocks for current term's docids or frequencies. /// In particular, PackedDocBlockNum = floor(DocFreq/PackedBlockSize) </description></item> /// <item><description>TrimmedDocFreq = DocFreq % PackedBlockSize == 0 ? DocFreq - 1 : DocFreq. /// We use this trick since the definition of skip entry is a little different from base interface. /// In <see cref="MultiLevelSkipListWriter"/>, skip data is assumed to be saved for /// skipInterval<sup>th</sup>, 2*skipInterval<sup>th</sup> ... posting in the list. However, /// in Lucene41PostingsFormat, the skip data is saved for skipInterval+1<sup>th</sup>, /// 2*skipInterval+1<sup>th</sup> ... posting (skipInterval==PackedBlockSize in this case). /// When DocFreq is multiple of PackedBlockSize, MultiLevelSkipListWriter will expect one /// more skip data than Lucene41SkipWriter. </description></item> /// <item><description>SkipDatum is the metadata of one skip entry. /// For the first block (no matter packed or VInt), it is omitted.</description></item> /// <item><description>DocSkip records the document number of every PackedBlockSize<sup>th</sup> document number in /// the postings (i.e. last document number in each packed block). On disk it is stored as the /// difference from previous value in the sequence. </description></item> /// <item><description>DocFPSkip records the file offsets of each block (excluding )posting at /// PackedBlockSize+1<sup>th</sup>, 2*PackedBlockSize+1<sup>th</sup> ... , in DocFile. /// The file offsets are relative to the start of current term's TermFreqs. /// On disk it is also stored as the difference from previous SkipDatum in the sequence.</description></item> /// <item><description>Since positions and payloads are also block encoded, the skip should skip to related block first, /// then fetch the values according to in-block offset. PosFPSkip and PayFPSkip record the file /// offsets of related block in .pos and .pay, respectively. While PosBlockOffset indicates /// which value to fetch inside the related block (PayBlockOffset is unnecessary since it is always /// equal to PosBlockOffset). Same as DocFPSkip, the file offsets are relative to the start of /// current term's TermFreqs, and stored as a difference sequence.</description></item> /// <item><description>PayByteUpto indicates the start offset of the current payload. It is equivalent to /// the sum of the payload lengths in the current block up to PosBlockOffset</description></item> /// </list> /// </dd> /// </dl> /// /// <a name="Positions" id="Positions"></a> /// <dl> /// <dd> /// <b>Positions</b> /// <para>The .pos file contains the lists of positions that each term occurs at within documents. It also /// sometimes stores part of payloads and offsets for speedup.</para> /// <list type="bullet"> /// <item><description>PosFile(.pos) --&gt; Header, &lt;TermPositions&gt; <sup>TermCount</sup>, Footer</description></item> /// <item><description>Header --&gt; CodecHeader (<see cref="CodecUtil.WriteHeader(Store.DataOutput, string, int)"/>) </description></item> /// <item><description>TermPositions --&gt; &lt;PackedPosDeltaBlock&gt; <sup>PackedPosBlockNum</sup>, /// VIntBlock? </description></item> /// <item><description>VIntBlock --&gt; &lt;PositionDelta[, PayloadLength?], PayloadData?, /// OffsetDelta?, OffsetLength?&gt;<sup>PosVIntCount</sup></description></item> /// <item><description>PackedPosDeltaBlock --&gt; PackedInts (<see cref="Util.Packed.PackedInt32s"/>)</description></item> /// <item><description>PositionDelta, OffsetDelta, OffsetLength --&gt; /// VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) </description></item> /// <item><description>PayloadData --&gt; byte (<see cref="Store.DataOutput.WriteByte(byte)"/>)<sup>PayLength</sup></description></item> /// <item><description>Footer --&gt; CodecFooter (<see cref="CodecUtil.WriteFooter(Store.IndexOutput)"/>) </description></item> /// </list> /// <para>Notes:</para> /// <list type="bullet"> /// <item><description>TermPositions are order by term (terms are implicit, from the term dictionary), and position /// values for each term document pair are incremental, and ordered by document number.</description></item> /// <item><description>PackedPosBlockNum is the number of packed blocks for current term's positions, payloads or offsets. /// In particular, PackedPosBlockNum = floor(totalTermFreq/PackedBlockSize) </description></item> /// <item><description>PosVIntCount is the number of positions encoded as VInt format. In particular, /// PosVIntCount = totalTermFreq - PackedPosBlockNum*PackedBlockSize</description></item> /// <item><description>The procedure how PackedPosDeltaBlock is generated is the same as PackedDocDeltaBlock /// in chapter <a href="#Frequencies">Frequencies and Skip Data</a>.</description></item> /// <item><description>PositionDelta is, if payloads are disabled for the term's field, the /// difference between the position of the current occurrence in the document and /// the previous occurrence (or zero, if this is the first occurrence in this /// document). If payloads are enabled for the term's field, then PositionDelta/2 /// is the difference between the current and the previous position. If payloads /// are enabled and PositionDelta is odd, then PayloadLength is stored, indicating /// the length of the payload at the current term position.</description></item> /// <item><description>For example, the TermPositions for a term which occurs as the fourth term in /// one document, and as the fifth and ninth term in a subsequent document, would /// be the following sequence of VInts (payloads disabled): /// <para>4, 5, 4</para></description></item> /// <item><description>PayloadData is metadata associated with the current term position. If /// PayloadLength is stored at the current position, then it indicates the length /// of this payload. If PayloadLength is not stored, then this payload has the same /// length as the payload at the previous position.</description></item> /// <item><description>OffsetDelta/2 is the difference between this position's startOffset from the /// previous occurrence (or zero, if this is the first occurrence in this document). /// If OffsetDelta is odd, then the length (endOffset-startOffset) differs from the /// previous occurrence and an OffsetLength follows. Offset data is only written for /// <see cref="Index.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS"/>.</description></item> /// </list> /// </dd> /// </dl> /// /// <a name="Payloads" id="Payloads"></a> /// <dl> /// <dd> /// <b>Payloads and Offsets</b> /// <para>The .pay file will store payloads and offsets associated with certain term-document positions. /// Some payloads and offsets will be separated out into .pos file, for performance reasons.</para> /// <list type="bullet"> /// <item><description>PayFile(.pay): --&gt; Header, &lt;TermPayloads, TermOffsets?&gt; <sup>TermCount</sup>, Footer</description></item> /// <item><description>Header --&gt; CodecHeader (<see cref="CodecUtil.WriteHeader(Store.DataOutput, string, int)"/>) </description></item> /// <item><description>TermPayloads --&gt; &lt;PackedPayLengthBlock, SumPayLength, PayData&gt; <sup>PackedPayBlockNum</sup></description></item> /// <item><description>TermOffsets --&gt; &lt;PackedOffsetStartDeltaBlock, PackedOffsetLengthBlock&gt; <sup>PackedPayBlockNum</sup></description></item> /// <item><description>PackedPayLengthBlock, PackedOffsetStartDeltaBlock, PackedOffsetLengthBlock --&gt; PackedInts (<see cref="Util.Packed.PackedInt32s"/>) </description></item> /// <item><description>SumPayLength --&gt; VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) </description></item> /// <item><description>PayData --&gt; byte (<see cref="Store.DataOutput.WriteByte(byte)"/>) <sup>SumPayLength</sup></description></item> /// <item><description>Footer --&gt; CodecFooter (<see cref="CodecUtil.WriteFooter(Store.IndexOutput)"/>) </description></item> /// </list> /// <para>Notes:</para> /// <list type="bullet"> /// <item><description>The order of TermPayloads/TermOffsets will be the same as TermPositions, note that part of /// payload/offsets are stored in .pos.</description></item> /// <item><description>The procedure how PackedPayLengthBlock and PackedOffsetLengthBlock are generated is the /// same as PackedFreqBlock in chapter <a href="#Frequencies">Frequencies and Skip Data</a>. /// While PackedStartDeltaBlock follows a same procedure as PackedDocDeltaBlock.</description></item> /// <item><description>PackedPayBlockNum is always equal to PackedPosBlockNum, for the same term. It is also synonym /// for PackedOffsetBlockNum.</description></item> /// <item><description>SumPayLength is the total length of payloads written within one block, should be the sum /// of PayLengths in one packed block.</description></item> /// <item><description>PayLength in PackedPayLengthBlock is the length of each payload associated with the current /// position.</description></item> /// </list> /// </dd> /// </dl> /// </para> /// /// @lucene.experimental /// </summary> [PostingsFormatName("Lucene41")] // LUCENENET specific - using PostingsFormatName attribute to ensure the default name passed from subclasses is the same as this class name public sealed class Lucene41PostingsFormat : PostingsFormat { /// <summary> /// Filename extension for document number, frequencies, and skip data. /// See chapter: <a href="#Frequencies">Frequencies and Skip Data</a> /// </summary> public const string DOC_EXTENSION = "doc"; /// <summary> /// Filename extension for positions. /// See chapter: <a href="#Positions">Positions</a> /// </summary> public const string POS_EXTENSION = "pos"; /// <summary> /// Filename extension for payloads and offsets. /// See chapter: <a href="#Payloads">Payloads and Offsets</a> /// </summary> public const string PAY_EXTENSION = "pay"; private readonly int minTermBlockSize; private readonly int maxTermBlockSize; /// <summary> /// Fixed packed block size, number of integers encoded in /// a single packed block. /// </summary> // NOTE: must be multiple of 64 because of PackedInts long-aligned encoding/decoding public static int BLOCK_SIZE = 128; /// <summary> /// Creates <see cref="Lucene41PostingsFormat"/> with default /// settings. /// </summary> public Lucene41PostingsFormat() : this(BlockTreeTermsWriter.DEFAULT_MIN_BLOCK_SIZE, BlockTreeTermsWriter.DEFAULT_MAX_BLOCK_SIZE) { } /// <summary> /// Creates <see cref="Lucene41PostingsFormat"/> with custom /// values for <paramref name="minTermBlockSize"/> and /// <paramref name="maxTermBlockSize"/> passed to block terms dictionary. </summary> /// <seealso cref="BlockTreeTermsWriter.BlockTreeTermsWriter(SegmentWriteState,PostingsWriterBase,int,int)"/> public Lucene41PostingsFormat(int minTermBlockSize, int maxTermBlockSize) : base() { this.minTermBlockSize = minTermBlockSize; Debug.Assert(minTermBlockSize > 1); this.maxTermBlockSize = maxTermBlockSize; Debug.Assert(minTermBlockSize <= maxTermBlockSize); } public override string ToString() { return Name + "(blocksize=" + BLOCK_SIZE + ")"; } public override FieldsConsumer FieldsConsumer(SegmentWriteState state) { PostingsWriterBase postingsWriter = new Lucene41PostingsWriter(state); bool success = false; try { FieldsConsumer ret = new BlockTreeTermsWriter(state, postingsWriter, minTermBlockSize, maxTermBlockSize); success = true; return ret; } finally { if (!success) { IOUtils.DisposeWhileHandlingException(postingsWriter); } } } public override FieldsProducer FieldsProducer(SegmentReadState state) { PostingsReaderBase postingsReader = new Lucene41PostingsReader(state.Directory, state.FieldInfos, state.SegmentInfo, state.Context, state.SegmentSuffix); bool success = false; try { FieldsProducer ret = new BlockTreeTermsReader(state.Directory, state.FieldInfos, state.SegmentInfo, postingsReader, state.Context, state.SegmentSuffix, state.TermsIndexDivisor); success = true; return ret; } finally { if (!success) { IOUtils.DisposeWhileHandlingException(postingsReader); } } } } }
// 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.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.CustomerInsights.Models { using Azure; using Management; using CustomerInsights; using Rest; using Rest.Serialization; using Newtonsoft.Json; using System.Linq; /// <summary> /// The c onnector mapping resource format. /// </summary> [JsonTransformation] public partial class ConnectorMappingResourceFormat : ProxyResource { /// <summary> /// Initializes a new instance of the ConnectorMappingResourceFormat /// class. /// </summary> public ConnectorMappingResourceFormat() { MappingProperties = new ConnectorMappingProperties(); } /// <summary> /// Initializes a new instance of the ConnectorMappingResourceFormat /// class. /// </summary> /// <param name="entityType">Defines which entity type the file should /// map to. Possible values include: 'None', 'Profile', 'Interaction', /// 'Relationship'</param> /// <param name="entityTypeName">The mapping entity name.</param> /// <param name="mappingProperties">The properties of the /// mapping.</param> /// <param name="id">Resource ID.</param> /// <param name="name">Resource name.</param> /// <param name="type">Resource type.</param> /// <param name="connectorName">The connector name.</param> /// <param name="connectorType">Type of connector. Possible values /// include: 'CRM', 'AzureBlob', 'Salesforce'</param> /// <param name="created">The created time.</param> /// <param name="lastModified">The last monified time.</param> /// <param name="connectorMappingName">The connector mapping /// name</param> /// <param name="displayName">Display name for the connector /// mapping.</param> /// <param name="description">The description of the connector /// mapping.</param> /// <param name="dataFormatId">The DataFormat ID.</param> /// <param name="nextRunTime">The next run time based on customer's /// settings.</param> /// <param name="runId">The RunId.</param> /// <param name="state">State of connector mapping. Possible values /// include: 'Creating', 'Created', 'Failed', 'Ready', 'Running', /// 'Stopped', 'Expiring'</param> /// <param name="tenantId">The hub name.</param> public ConnectorMappingResourceFormat(EntityTypes entityType, string entityTypeName, ConnectorMappingProperties mappingProperties, string id = default(string), string name = default(string), string type = default(string), string connectorName = default(string), ConnectorTypes? connectorType = default(ConnectorTypes?), System.DateTime? created = default(System.DateTime?), System.DateTime? lastModified = default(System.DateTime?), string connectorMappingName = default(string), string displayName = default(string), string description = default(string), string dataFormatId = default(string), System.DateTime? nextRunTime = default(System.DateTime?), string runId = default(string), ConnectorMappingStates? state = default(ConnectorMappingStates?), string tenantId = default(string)) : base(id, name, type) { MappingProperties = new ConnectorMappingProperties(); ConnectorName = connectorName; ConnectorType = connectorType; Created = created; LastModified = lastModified; EntityType = entityType; EntityTypeName = entityTypeName; ConnectorMappingName = connectorMappingName; DisplayName = displayName; Description = description; DataFormatId = dataFormatId; MappingProperties = mappingProperties; NextRunTime = nextRunTime; RunId = runId; State = state; TenantId = tenantId; } /// <summary> /// Gets the connector name. /// </summary> [JsonProperty(PropertyName = "properties.connectorName")] public string ConnectorName { get; protected set; } /// <summary> /// Gets or sets type of connector. Possible values include: 'CRM', /// 'AzureBlob', 'Salesforce' /// </summary> [JsonProperty(PropertyName = "properties.connectorType")] public ConnectorTypes? ConnectorType { get; set; } /// <summary> /// Gets the created time. /// </summary> [JsonProperty(PropertyName = "properties.created")] public System.DateTime? Created { get; protected set; } /// <summary> /// Gets the last monified time. /// </summary> [JsonProperty(PropertyName = "properties.lastModified")] public System.DateTime? LastModified { get; protected set; } /// <summary> /// Gets or sets defines which entity type the file should map to. /// Possible values include: 'None', 'Profile', 'Interaction', /// 'Relationship' /// </summary> [JsonProperty(PropertyName = "properties.entityType")] public EntityTypes EntityType { get; set; } /// <summary> /// Gets or sets the mapping entity name. /// </summary> [JsonProperty(PropertyName = "properties.entityTypeName")] public string EntityTypeName { get; set; } /// <summary> /// Gets the connector mapping name /// </summary> [JsonProperty(PropertyName = "properties.connectorMappingName")] public string ConnectorMappingName { get; protected set; } /// <summary> /// Gets or sets display name for the connector mapping. /// </summary> [JsonProperty(PropertyName = "properties.displayName")] public string DisplayName { get; set; } /// <summary> /// Gets or sets the description of the connector mapping. /// </summary> [JsonProperty(PropertyName = "properties.description")] public string Description { get; set; } /// <summary> /// Gets the DataFormat ID. /// </summary> [JsonProperty(PropertyName = "properties.dataFormatId")] public string DataFormatId { get; protected set; } /// <summary> /// Gets or sets the properties of the mapping. /// </summary> [JsonProperty(PropertyName = "properties.mappingProperties")] public ConnectorMappingProperties MappingProperties { get; set; } /// <summary> /// Gets the next run time based on customer's settings. /// </summary> [JsonProperty(PropertyName = "properties.nextRunTime")] public System.DateTime? NextRunTime { get; protected set; } /// <summary> /// Gets the RunId. /// </summary> [JsonProperty(PropertyName = "properties.runId")] public string RunId { get; protected set; } /// <summary> /// Gets state of connector mapping. Possible values include: /// 'Creating', 'Created', 'Failed', 'Ready', 'Running', 'Stopped', /// 'Expiring' /// </summary> [JsonProperty(PropertyName = "properties.state")] public ConnectorMappingStates? State { get; protected set; } /// <summary> /// Gets the hub name. /// </summary> [JsonProperty(PropertyName = "properties.tenantId")] public string TenantId { get; protected set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (EntityTypeName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "EntityTypeName"); } if (MappingProperties == null) { throw new ValidationException(ValidationRules.CannotBeNull, "MappingProperties"); } if (MappingProperties != null) { MappingProperties.Validate(); } } } }
using System.Diagnostics; using System; using System.Management; using System.Collections; using Microsoft.VisualBasic; using System.Data.SqlClient; using System.Web.UI.Design; using System.Data; using System.Collections.Generic; using System.Linq; using System.Web; using System.Net.Mail; using System.Web.UI; using System.IO; using System.Web.UI.WebControls; namespace ACSGhana.Web.Framework { public struct WorkflowMailRecipient { public WorkflowMailRecipient(string FirstName, string Email) { this.FirstName = FirstName; this.Email = Email; } public string FirstName; public string Email; } public struct RecipientEmails { public string @To; public string Cc; public string Bcc; public RecipientEmails(string toAddress, string ccAddress, string bccAddress) { @To = toAddress; @Cc = ccAddress; @Bcc = bccAddress; } public RecipientEmails(string[] addressArray) { @To = addressArray[0]; @Cc = addressArray[1]; @Bcc = addressArray[2]; } } public partial class ReportMail { public ReportMail(WorkflowMailRecipient Recipient, string ReportName, string ReportFile, string MailBody, MailPriority Priority) { this._RecipientEmail = Recipient; this._ReportName = ReportName; if (! string.IsNullOrEmpty(ReportFile)) { this._AttachedReport = new Attachment(ReportFile); } this._MailBody = MailBody; this._Priority = Priority; } private Guid _MailGuid; public Guid MailGuid { get { if (_MailGuid == Guid.Empty) { _MailGuid = Guid.NewGuid(); } return _MailGuid; } } private WorkflowMailRecipient _RecipientEmail; public WorkflowMailRecipient RecipientEmail { get { return _RecipientEmail; } } private Attachment _AttachedReport = null; public Attachment AttachedReport { get { return _AttachedReport; } } private string _ReportName = null; public string ReportName { get { return _ReportName; } } private string _MailBody = null; public string MailBody { get { return _MailBody; } } private MailPriority _Priority = MailPriority.Normal; public MailPriority Priority { get { return _Priority; } } } public class EmailServices { public static void AddEmptyItem(DropDownList ddl) { ListItem li = new ListItem("[None]", "-1"); ddl.Items.Insert(0, li); } public static void SendSuggestion(string Sender, RecipientEmails RecipientList, string Subject, string BodyText) { SendNotification(Sender, RecipientList, "Suggestion: " + Subject, BodyText, MailPriority.High); } public static void SendComplaint(string Sender, RecipientEmails RecipientList, string Subject, string BodyText) { SendNotification(Sender, RecipientList, "Complaint: " + Subject, BodyText, MailPriority.High); } public static void SendQuestion(string Sender, RecipientEmails RecipientList, string Subject, string BodyText) { SendNotification(Sender, RecipientList, "Question: " + Subject, BodyText, MailPriority.High); } public static string GetStringEmailList(WorkflowMailRecipient[] emailList) { List<string> targetString = new List<string>(); foreach (WorkflowMailRecipient emailItem in emailList) { targetString.Add(emailItem.Email); } string target = string.Join(", ", targetString.ToArray()); return target; } public static void SendNotification(string Sender, RecipientEmails RecipientList, string Subject, string BodyText) { SendNotification(Sender, RecipientList, Subject, BodyText, MailPriority.Normal); } public static void SendNotification(string Sender, RecipientEmails RecipientList, string Subject, string BodyText, MailPriority Priority) { SendNotification(Sender, RecipientList, Subject, BodyText, MailPriority.Normal, null); } public static void SendNotification(string Sender, RecipientEmails RecipientList, string Subject, string BodyText, MailPriority Priority, List<Attachment> Attachments) { try { //(1) Create the MailMessage instance using (MailMessage mm = new MailMessage(Sender, RecipientList.To)) { string strBody = "<div style=\'color:#4B6C8B; font-size:1.0em; font-family:Century Gothic,Verdana,Arial,Helvetica,sans-serif;\'>"; strBody += BodyText + " </div>"; //(2) Assign the MailMessage's properties mm.Subject = Subject; mm.Body = strBody; mm.IsBodyHtml = true; mm.Priority = Priority; if (RecipientList.Cc != string.Empty) { mm.CC.Add(RecipientList.Cc); } if (RecipientList.Bcc != string.Empty) { mm.Bcc.Add(RecipientList.Bcc); } if (Attachments != null) { foreach (Attachment attach in Attachments) { mm.Attachments.Add(attach); } } //(3) Create the SmtpClient object SmtpClient smtp = new SmtpClient(); bool RetrySend = true; while (RetrySend) { try { smtp.Send(mm); } catch (SmtpFailedRecipientException ex) { switch (ex.StatusCode) { case SmtpStatusCode.MailboxBusy: case SmtpStatusCode.TransactionFailed: continue; default: break; } } catch (SmtpException ex) { switch (ex.StatusCode) { case SmtpStatusCode.MailboxBusy: case SmtpStatusCode.TransactionFailed: continue; default: break; } } catch (System.Exception) { } } } } catch (System.Exception) { } } public static void SendMailReport(string Sender, ReportMail Report) { try { //(1) Create the MailMessage instance using (MailMessage mm = new MailMessage(Sender, Report.RecipientEmail.Email)) { string strBody = "<div style=\'color:#4B6C8B; font-size:1.0em; font-family:Century Gothic,Verdana,Arial,Helvetica,sans-serif;\'>"; strBody += Report.MailBody + " </div>"; //(2) Assign the MailMessage's properties mm.Subject = "G.C.P Report Mail: " + Report.ReportName; mm.Body = strBody; mm.IsBodyHtml = true; mm.Priority = Report.Priority; if (Report.AttachedReport != null) { mm.Attachments.Add(Report.AttachedReport); } //(3) Create the SmtpClient object SmtpClient smtp = new SmtpClient(); bool RetrySend = true; while (RetrySend) { try { smtp.Send(mm); } catch (SmtpFailedRecipientException ex) { switch (ex.StatusCode) { case SmtpStatusCode.MailboxBusy: case SmtpStatusCode.TransactionFailed: continue; default: break; } } catch (SmtpException ex) { switch (ex.StatusCode) { case SmtpStatusCode.MailboxBusy: case SmtpStatusCode.TransactionFailed: continue; default: break; } } catch (System.Exception) { } break; } } } catch (System.Exception) { } } public static IAsyncResult SendNotificationAsync(string Sender, RecipientEmails RecipientList, string Subject, string BodyText, MailPriority Priority) { try { //(1) Create the MailMessage instance using (MailMessage mm = new MailMessage(Sender, RecipientList.To)) { string strBody = "<div style=\'color:#4B6C8B; font-size:1.0em; font-family:Century Gothic,Verdana,Arial,Helvetica,sans-serif;\'>"; strBody += BodyText + " </div>"; //(2) Assign the MailMessage's properties mm.Subject = Subject; mm.Body = strBody; mm.IsBodyHtml = true; mm.Priority = Priority; if (RecipientList.Cc != string.Empty) { mm.CC.Add(RecipientList.Cc); } if (RecipientList.Bcc != string.Empty) { mm.Bcc.Add(RecipientList.Bcc); } //(3) Create the SmtpClient object SmtpClient smtp = new SmtpClient(); bool RetrySend = true; while (RetrySend) { try { smtp.Send(mm); } catch (SmtpFailedRecipientException ex) { switch (ex.StatusCode) { case SmtpStatusCode.MailboxBusy: case SmtpStatusCode.TransactionFailed: continue; default: break; } } catch (SmtpException ex) { switch (ex.StatusCode) { case SmtpStatusCode.MailboxBusy: case SmtpStatusCode.TransactionFailed: continue; default: break; } } catch (System.Exception) { } break; } } } catch (System.Exception) { } return new MailNotificationResult(); } } public class MailNotificationResult : IAsyncResult { private object _AsyncState; public object AsyncState { get { return _AsyncState; } } public System.Threading.WaitHandle AsyncWaitHandle { get { return null; } } public bool CompletedSynchronously { get { return false; } } public bool IsCompleted { get { return true; } } } }
using AxoCover.Common.Extensions; using AxoCover.Common.Models; using AxoCover.Common.Runner; using AxoCover.Common.Settings; using AxoCover.Models.Editor; using AxoCover.Models.Extensions; using AxoCover.Models.Storage; using AxoCover.Models.Telemetry; using AxoCover.Models.Testing.Adapters; using AxoCover.Models.Testing.Data; using AxoCover.Models.Toolkit; using EnvDTE; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace AxoCover.Models.Testing.Discovery { public class TestProvider : ITestProvider { public event EventHandler ScanningStarted; public event EventHandler ScanningFinished; private readonly IOptions _options; private readonly IEditorContext _editorContext; private readonly ITestAdapterRepository _testAdapterRepository; private readonly IEqualityComparer<TestCase> _testCaseEqualityComparer = new DelegateEqualityComparer<TestCase>((a, b) => a.Id == b.Id, p => p.Id.GetHashCode()); private readonly ITelemetryManager _telemetryManager; private int _sessionCount = 0; public bool IsActive { get { return _sessionCount > 0; } } public TestProvider(IEditorContext editorContext, ITestAdapterRepository testAdapterRepository, IOptions options, ITelemetryManager telemetryManager) { _editorContext = editorContext; _testAdapterRepository = testAdapterRepository; _options = options; _telemetryManager = telemetryManager; } public async Task<TestSolution> GetTestSolutionAsync(Solution solution, string testSettings) { try { Interlocked.Increment(ref _sessionCount); ScanningStarted?.Invoke(this, EventArgs.Empty); var testSolution = new TestSolution(solution.Properties.Item("Name").Value as string, solution.FileName); var testAdapters = new HashSet<ITestAdapter>(); var testAdapterModes = new HashSet<TestAdapterMode>(); var projects = solution.GetProjects(); foreach (Project project in projects) { var assemblyName = project.GetAssemblyName(); if (string.IsNullOrWhiteSpace(assemblyName)) continue; var isTestSource = false; var testAdapterNames = new List<string>(); foreach (var testAdapter in _testAdapterRepository.Adapters.Values) { if (testAdapter.IsTestSource(project)) { testAdapters.Add(testAdapter); testAdapterModes.Add(testAdapter.Mode); testAdapterNames.Add(testAdapter.Name); isTestSource = true; } } if (isTestSource) { var outputFilePath = project.GetOutputDllPath(); var testProject = new TestProject(testSolution, project.Name, outputFilePath, testAdapterNames.ToArray()); testSolution.TestAssemblies.Add(assemblyName); } else { testSolution.CodeAssemblies.Add(assemblyName); } } if (testAdapterModes.Count == 1) { _options.TestAdapterMode = testAdapterModes.First(); } foreach (var testAdapter in testAdapters.ToArray()) { if(testAdapter.Mode != _options.TestAdapterMode) { testAdapters.Remove(testAdapter); } } await Task.Run(() => { try { var testDiscoveryTasks = testAdapters .Select(p => new TestDiscoveryTask() { TestAssemblyPaths = testSolution.Children .OfType<TestProject>() .Where(q => q.TestAdapters.Contains(p.Name)) .Select(q => q.OutputFilePath) .ToArray(), TestAdapterOptions = p .GetLoadingOptions() .Do(q => q.IsRedirectingAssemblies = _options.IsRedirectingFrameworkAssemblies) }) .ToArray(); using (var discoveryProcess = DiscoveryProcess.Create(AdapterExtensions.GetTestPlatformAssemblyPaths(_options.TestAdapterMode), _options)) { _editorContext.WriteToLog(Resources.TestDiscoveryStarted); discoveryProcess.MessageReceived += (o, e) => _editorContext.WriteToLog(e.Value); discoveryProcess.OutputReceived += (o, e) => _editorContext.WriteToLog(e.Value); var discoveryResults = discoveryProcess.DiscoverTests(testDiscoveryTasks, testSettings); var testCasesByAssembly = discoveryResults .Distinct(_testCaseEqualityComparer) .GroupBy(p => p.Source) .ToDictionary(p => p.Key, p => p.ToArray(), StringComparer.OrdinalIgnoreCase); foreach (TestProject testProject in testSolution.Children.ToArray()) { var testCases = testCasesByAssembly.TryGetValue(testProject.OutputFilePath); if (testCases != null) { LoadTests(testProject, testCases); } var isEmpty = !testProject .Flatten<TestItem>(p => p.Children, false) .Any(p => p.Kind == CodeItemKind.Method); if (isEmpty) { testProject.Remove(); } } _editorContext.WriteToLog(Resources.TestDiscoveryFinished); } } catch (RemoteException exception) when (exception.RemoteReason != null) { _editorContext.WriteToLog(Resources.TestDiscoveryFailed); _telemetryManager.UploadExceptionAsync(exception.RemoteReason); } catch (Exception exception) { _editorContext.WriteToLog(Resources.TestDiscoveryFailed); _telemetryManager.UploadExceptionAsync(exception); } }); ScanningFinished?.Invoke(this, EventArgs.Empty); return testSolution; } finally { Interlocked.Decrement(ref _sessionCount); } } private void LoadTests(TestProject testProject, TestCase[] testCases) { var testItems = new Dictionary<string, TestItem>() { { "", testProject } }; var testCaseProcessors = testProject.TestAdapters .Select(p => _testAdapterRepository.Adapters[p]) .ToDictionary(p => p.ExecutorUri, StringComparer.OrdinalIgnoreCase); foreach (var testCase in testCases) { try { if (!testCaseProcessors.TryGetValue(testCase.ExecutorUri.ToString().TrimEnd('/'), out var testAdapter)) { throw new Exception("Cannot find adapter for executor URI: " + testCase.ExecutorUri); } var testItemKind = CodeItemKind.Method; var testItemPath = testCase.FullyQualifiedName; var displayName = null as string; foreach (var testCaseProcessor in testCaseProcessors.Values) { if (testCaseProcessor.CanProcessCase(testCase)) { testCaseProcessor.ProcessCase(testCase, ref testItemKind, ref testItemPath, ref displayName); break; } } AddTestItem(testItems, testItemKind, testItemPath, testCase, displayName, testAdapter.Name); } catch (Exception e) { _editorContext.WriteToLog($"Could not register test case {testCase.FullyQualifiedName}. Reason: {e.GetDescription()}"); } } } private static TestItem AddTestItem(Dictionary<string, TestItem> items, CodeItemKind itemKind, string itemPath, TestCase testCase = null, string displayName = null, string testAdapterName = null) { var nameParts = itemPath.SplitPath(); var parentName = string.Join(string.Empty, nameParts.Take(nameParts.Length - 1)); var itemName = nameParts[nameParts.Length - 1]; TestItem parent; if (!items.TryGetValue(parentName, out parent)) { switch (itemKind) { case CodeItemKind.Data: parent = AddTestItem(items, CodeItemKind.Method, parentName); break; case CodeItemKind.Class: if (itemName.StartsWith("+")) { parent = AddTestItem(items, CodeItemKind.Class, parentName); } else { parent = AddTestItem(items, CodeItemKind.Namespace, parentName); } break; case CodeItemKind.Method: parent = AddTestItem(items, CodeItemKind.Class, parentName); break; default: parent = AddTestItem(items, CodeItemKind.Namespace, parentName); break; } } var name = itemName.TrimStart('.', '+'); TestItem item = null; switch (itemKind) { case CodeItemKind.Namespace: item = new TestNamespace(parent as TestNamespace, name); break; case CodeItemKind.Class: if (parent is TestClass) { item = new TestClass(parent as TestClass, name); } else { item = new TestClass(parent as TestNamespace, name); } break; case CodeItemKind.Method: item = new TestMethod(parent as TestClass, name, testCase, testAdapterName); break; case CodeItemKind.Data: item = new TestMethod(parent as TestMethod, name, displayName, testCase, testAdapterName); break; default: throw new NotImplementedException(); } items.Add(itemPath, item); return item; } } }
// 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 Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class IOperationTests : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_ContainingMethodParameterReference() { string source = @" class C { public void M(int x) { /*<bind>*/int Local(int p1) { return x++; }/*</bind>*/ Local(0); } } "; string expectedOperationTree = @" ILocalFunctionStatement (Symbol: System.Int32 Local(System.Int32 p1)) (OperationKind.LocalFunctionStatement) (Syntax: 'int Local(i ... }') IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }') IReturnStatement (OperationKind.ReturnStatement) (Syntax: 'return x++;') ReturnedValue: IIncrementOrDecrementExpression (Postfix) (OperationKind.IncrementExpression, Type: System.Int32) (Syntax: 'x++') Target: IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_ContainingMethodParameterReference_ExpressionBodied() { string source = @" class C { public void M(int x) { /*<bind>*/int Local(int p1) => x++;/*</bind>*/ Local(0); } } "; string expectedOperationTree = @" ILocalFunctionStatement (Symbol: System.Int32 Local(System.Int32 p1)) (OperationKind.LocalFunctionStatement) (Syntax: 'int Local(i ... p1) => x++;') IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '=> x++') IReturnStatement (OperationKind.ReturnStatement, IsImplicit) (Syntax: 'x++') ReturnedValue: IIncrementOrDecrementExpression (Postfix) (OperationKind.IncrementExpression, Type: System.Int32) (Syntax: 'x++') Target: IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_LocalFunctionParameterReference() { string source = @" class C { public void M() { /*<bind>*/int Local(int x) => x++;/*</bind>*/ Local(0); } } "; string expectedOperationTree = @" ILocalFunctionStatement (Symbol: System.Int32 Local(System.Int32 x)) (OperationKind.LocalFunctionStatement) (Syntax: 'int Local(int x) => x++;') IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '=> x++') IReturnStatement (OperationKind.ReturnStatement, IsImplicit) (Syntax: 'x++') ReturnedValue: IIncrementOrDecrementExpression (Postfix) (OperationKind.IncrementExpression, Type: System.Int32) (Syntax: 'x++') Target: IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_ContainingLocalFunctionParameterReference() { string source = @" class C { public void M() { int LocalOuter (int x) { /*<bind>*/int Local(int y) => x + y;/*</bind>*/ return Local(x); } LocalOuter(0); } } "; string expectedOperationTree = @" ILocalFunctionStatement (Symbol: System.Int32 Local(System.Int32 y)) (OperationKind.LocalFunctionStatement) (Syntax: 'int Local(i ... ) => x + y;') IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '=> x + y') IReturnStatement (OperationKind.ReturnStatement, IsImplicit) (Syntax: 'x + y') ReturnedValue: IBinaryOperatorExpression (BinaryOperatorKind.Add) (OperationKind.BinaryOperatorExpression, Type: System.Int32) (Syntax: 'x + y') Left: IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'x') Right: IParameterReferenceExpression: y (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'y') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_LocalFunctionReference() { string source = @" class C { public void M() { int x; int Local(int p1) => x++; int Local2(int p1) => Local(p1); /*<bind>*/int Local3(int p1) => x + Local2(p1);/*</bind>*/ Local3(x = 0); } } "; string expectedOperationTree = @" ILocalFunctionStatement (Symbol: System.Int32 Local3(System.Int32 p1)) (OperationKind.LocalFunctionStatement) (Syntax: 'int Local3( ... Local2(p1);') IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '=> x + Local2(p1)') IReturnStatement (OperationKind.ReturnStatement, IsImplicit) (Syntax: 'x + Local2(p1)') ReturnedValue: IBinaryOperatorExpression (BinaryOperatorKind.Add) (OperationKind.BinaryOperatorExpression, Type: System.Int32) (Syntax: 'x + Local2(p1)') Left: ILocalReferenceExpression: x (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'x') Right: IInvocationExpression (System.Int32 Local2(System.Int32 p1)) (OperationKind.InvocationExpression, Type: System.Int32) (Syntax: 'Local2(p1)') Instance Receiver: null Arguments(1): IArgument (ArgumentKind.Explicit, Matching Parameter: p1) (OperationKind.Argument) (Syntax: 'p1') IParameterReferenceExpression: p1 (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'p1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_Recursion() { string source = @" class C { public void M(int x) { /*<bind>*/int Local(int p1) => Local(x + p1);/*</bind>*/ } } "; string expectedOperationTree = @" ILocalFunctionStatement (Symbol: System.Int32 Local(System.Int32 p1)) (OperationKind.LocalFunctionStatement) (Syntax: 'int Local(i ... al(x + p1);') IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '=> Local(x + p1)') IReturnStatement (OperationKind.ReturnStatement, IsImplicit) (Syntax: 'Local(x + p1)') ReturnedValue: IInvocationExpression (System.Int32 Local(System.Int32 p1)) (OperationKind.InvocationExpression, Type: System.Int32) (Syntax: 'Local(x + p1)') Instance Receiver: null Arguments(1): IArgument (ArgumentKind.Explicit, Matching Parameter: p1) (OperationKind.Argument) (Syntax: 'x + p1') IBinaryOperatorExpression (BinaryOperatorKind.Add) (OperationKind.BinaryOperatorExpression, Type: System.Int32) (Syntax: 'x + p1') Left: IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'x') Right: IParameterReferenceExpression: p1 (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'p1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_Async() { string source = @" using System.Threading.Tasks; class C { public void M(int x) { /*<bind>*/async Task<int> LocalAsync(int p1) { await Task.Delay(0); return x + p1; }/*</bind>*/ LocalAsync(0).Wait(); } } "; string expectedOperationTree = @" ILocalFunctionStatement (Symbol: System.Threading.Tasks.Task<System.Int32> LocalAsync(System.Int32 p1)) (OperationKind.LocalFunctionStatement) (Syntax: 'async Task< ... }') IBlockStatement (2 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }') IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'await Task.Delay(0);') Expression: IAwaitExpression (OperationKind.AwaitExpression, Type: System.Void) (Syntax: 'await Task.Delay(0)') Expression: IInvocationExpression (System.Threading.Tasks.Task System.Threading.Tasks.Task.Delay(System.Int32 millisecondsDelay)) (OperationKind.InvocationExpression, Type: System.Threading.Tasks.Task) (Syntax: 'Task.Delay(0)') Instance Receiver: null Arguments(1): IArgument (ArgumentKind.Explicit, Matching Parameter: millisecondsDelay) (OperationKind.Argument) (Syntax: '0') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 0) (Syntax: '0') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IReturnStatement (OperationKind.ReturnStatement) (Syntax: 'return x + p1;') ReturnedValue: IBinaryOperatorExpression (BinaryOperatorKind.Add) (OperationKind.BinaryOperatorExpression, Type: System.Int32) (Syntax: 'x + p1') Left: IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'x') Right: IParameterReferenceExpression: p1 (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'p1') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics, useLatestFrameworkReferences: true); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_CaptureForEachVar() { string source = @" class C { public void M(int[] array) { foreach (var x in array) { /*<bind>*/int Local() => x;/*</bind>*/ Local(); } } } "; string expectedOperationTree = @" ILocalFunctionStatement (Symbol: System.Int32 Local()) (OperationKind.LocalFunctionStatement) (Syntax: 'int Local() => x;') IBlockStatement (1 statements) (OperationKind.BlockStatement) (Syntax: '=> x') IReturnStatement (OperationKind.ReturnStatement, IsImplicit) (Syntax: 'x') ReturnedValue: ILocalReferenceExpression: x (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_UseOfUnusedVar() { string source = @" class C { void M() { F(); int x = 0; /*<bind>*/void F() => x++;/*</bind>*/ } } "; string expectedOperationTree = @" ILocalFunctionStatement (Symbol: void F()) (OperationKind.LocalFunctionStatement) (Syntax: 'void F() => x++;') IBlockStatement (2 statements) (OperationKind.BlockStatement) (Syntax: '=> x++') IExpressionStatement (OperationKind.ExpressionStatement, IsImplicit) (Syntax: 'x++') Expression: IIncrementOrDecrementExpression (Postfix) (OperationKind.IncrementExpression, Type: System.Int32) (Syntax: 'x++') Target: ILocalReferenceExpression: x (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'x') IReturnStatement (OperationKind.ReturnStatement, IsImplicit) (Syntax: '=> x++') ReturnedValue: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0165: Use of unassigned local variable 'x' // F(); Diagnostic(ErrorCode.ERR_UseDefViolation, "F()").WithArguments("x").WithLocation(6, 9) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_OutVar() { string source = @" class C { void M(int p) { int x; /*<bind>*/void F(out int y) => y = p;/*</bind>*/ F(out x); } } "; string expectedOperationTree = @" ILocalFunctionStatement (Symbol: void F(out System.Int32 y)) (OperationKind.LocalFunctionStatement) (Syntax: 'void F(out ... ) => y = p;') IBlockStatement (2 statements) (OperationKind.BlockStatement) (Syntax: '=> y = p') IExpressionStatement (OperationKind.ExpressionStatement, IsImplicit) (Syntax: 'y = p') Expression: ISimpleAssignmentExpression (OperationKind.SimpleAssignmentExpression, Type: System.Int32) (Syntax: 'y = p') Left: IParameterReferenceExpression: y (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'y') Right: IParameterReferenceExpression: p (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'p') IReturnStatement (OperationKind.ReturnStatement, IsImplicit) (Syntax: '=> y = p') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestInvalidLocalFunction_MissingBody() { string source = @" class C { void M(int p) { /*<bind>*/void F(out int y) => ;/*</bind>*/ } } "; string expectedOperationTree = @" ILocalFunctionStatement (Symbol: void F(out System.Int32 y)) (OperationKind.LocalFunctionStatement, IsInvalid) (Syntax: 'void F(out int y) => ;') IBlockStatement (2 statements) (OperationKind.BlockStatement, IsInvalid) (Syntax: '=> ') IExpressionStatement (OperationKind.ExpressionStatement, IsInvalid, IsImplicit) (Syntax: '') Expression: IInvalidExpression (OperationKind.InvalidExpression, Type: null, IsInvalid) (Syntax: '') Children(0) IReturnStatement (OperationKind.ReturnStatement, IsInvalid, IsImplicit) (Syntax: '=> ') ReturnedValue: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,40): error CS1525: Invalid expression term ';' // /*<bind>*/void F(out int y) => ;/*</bind>*/ Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 40), // file.cs(6,24): error CS0177: The out parameter 'y' must be assigned to before control leaves the current method // /*<bind>*/void F(out int y) => ;/*</bind>*/ Diagnostic(ErrorCode.ERR_ParamUnassigned, "F").WithArguments("y").WithLocation(6, 24), // file.cs(6,24): warning CS8321: The local function 'F' is declared but never used // /*<bind>*/void F(out int y) => ;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "F").WithArguments("F").WithLocation(6, 24) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestInvalidLocalFunction_MissingParameters() { string source = @" class C { void M(int p) { /*<bind>*/void F( { }/*</bind>*/; } } "; string expectedOperationTree = @" ILocalFunctionStatement (Symbol: void F()) (OperationKind.LocalFunctionStatement, IsInvalid) (Syntax: 'void F( { }') IBlockStatement (1 statements) (OperationKind.BlockStatement, IsInvalid) (Syntax: '{ }') IReturnStatement (OperationKind.ReturnStatement, IsInvalid, IsImplicit) (Syntax: '{ }') ReturnedValue: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS1026: ) expected // /*<bind>*/void F( { }/*</bind>*/; Diagnostic(ErrorCode.ERR_CloseParenExpected, "{").WithLocation(6, 27), // file.cs(6,24): warning CS8321: The local function 'F' is declared but never used // /*<bind>*/void F( { }/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "F").WithArguments("F").WithLocation(6, 24) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestInvalidLocalFunction_InvalidReturnType() { string source = @" class C { void M(int p) { /*<bind>*/X F() { }/*</bind>*/; } } "; string expectedOperationTree = @" ILocalFunctionStatement (Symbol: X F()) (OperationKind.LocalFunctionStatement, IsInvalid) (Syntax: 'X F() { }') IBlockStatement (0 statements) (OperationKind.BlockStatement) (Syntax: '{ }') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0161: 'F()': not all code paths return a value // /*<bind>*/X F() { }/*</bind>*/; Diagnostic(ErrorCode.ERR_ReturnExpected, "F").WithArguments("F()").WithLocation(6, 21), // CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // /*<bind>*/X F() { }/*</bind>*/; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(6, 19), // CS8321: The local function 'F' is declared but never used // /*<bind>*/X F() { }/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "F").WithArguments("F").WithLocation(6, 21) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using Microsoft.Practices.Prism.Interactivity.DefaultPopupWindows; using Microsoft.Practices.Prism.Interactivity.InteractionRequest; using System; using System.Windows; using System.Windows.Interactivity; namespace Microsoft.Practices.Prism.Interactivity { /// <summary> /// Shows a popup window in response to an <see cref="InteractionRequest"/> being raised. /// </summary> public class PopupWindowAction : TriggerAction<FrameworkElement> { /// <summary> /// The content of the child window to display as part of the popup. /// </summary> public static readonly DependencyProperty WindowContentProperty = DependencyProperty.Register( "WindowContent", typeof(FrameworkElement), typeof(PopupWindowAction), new PropertyMetadata(null)); /// <summary> /// Determines if the content should be shown in a modal window or not. /// </summary> public static readonly DependencyProperty IsModalProperty = DependencyProperty.Register( "IsModal", typeof(bool), typeof(PopupWindowAction), new PropertyMetadata(null)); /// <summary> /// Determines if the content should be initially shown centered over the view that raised the interaction request or not. /// </summary> public static readonly DependencyProperty CenterOverAssociatedObjectProperty = DependencyProperty.Register( "CenterOverAssociatedObject", typeof(bool), typeof(PopupWindowAction), new PropertyMetadata(null)); /// <summary> /// Gets or sets the content of the window. /// </summary> public FrameworkElement WindowContent { get { return (FrameworkElement)GetValue(WindowContentProperty); } set { SetValue(WindowContentProperty, value); } } /// <summary> /// Gets or sets if the window will be modal or not. /// </summary> public bool IsModal { get { return (bool)GetValue(IsModalProperty); } set { SetValue(IsModalProperty, value); } } /// <summary> /// Gets or sets if the window will be initially shown centered over the view that raised the interaction request or not. /// </summary> public bool CenterOverAssociatedObject { get { return (bool)GetValue(CenterOverAssociatedObjectProperty); } set { SetValue(CenterOverAssociatedObjectProperty, value); } } /// <summary> /// Displays the child window and collects results for <see cref="IInteractionRequest"/>. /// </summary> /// <param name="parameter">The parameter to the action. If the action does not require a parameter, the parameter may be set to a null reference.</param> protected override void Invoke(object parameter) { var args = parameter as InteractionRequestedEventArgs; if (args == null) { return; } // If the WindowContent shouldn't be part of another visual tree. if (this.WindowContent != null && this.WindowContent.Parent != null) { return; } Window wrapperWindow = this.GetWindow(args.Context); wrapperWindow.SizeToContent = SizeToContent.WidthAndHeight; // We invoke the callback when the interaction's window is closed. var callback = args.Callback; EventHandler handler = null; handler = (o, e) => { wrapperWindow.Closed -= handler; wrapperWindow.Content = null; if(callback != null) callback(); }; wrapperWindow.Closed += handler; if (this.CenterOverAssociatedObject && this.AssociatedObject != null) { // If we should center the popup over the parent window we subscribe to the SizeChanged event // so we can change its position after the dimensions are set. SizeChangedEventHandler sizeHandler = null; sizeHandler = (o, e) => { wrapperWindow.SizeChanged -= sizeHandler; FrameworkElement view = this.AssociatedObject; Point position = view.PointToScreen(new Point(0, 0)); wrapperWindow.Top = position.Y + ((view.ActualHeight - wrapperWindow.ActualHeight) / 2); wrapperWindow.Left = position.X + ((view.ActualWidth - wrapperWindow.ActualWidth) / 2); }; wrapperWindow.SizeChanged += sizeHandler; } if (this.IsModal) { wrapperWindow.ShowDialog(); } else { wrapperWindow.Show(); } } /// <summary> /// Returns the window to display as part of the trigger action. /// </summary> /// <param name="notification">The notification to be set as a DataContext in the window.</param> /// <returns></returns> protected virtual Window GetWindow(INotification notification) { Window wrapperWindow; if (this.WindowContent != null) { wrapperWindow = new Window(); // If the WindowContent does not have its own DataContext, it will inherit this one. wrapperWindow.DataContext = notification; wrapperWindow.Title = notification.Title; this.PrepareContentForWindow(notification, wrapperWindow); } else { wrapperWindow = this.CreateDefaultWindow(notification); } return wrapperWindow; } /// <summary> /// Checks if the WindowContent or its DataContext implements <see cref="IInteractionRequestAware"/>. /// If so, it sets the corresponding value. /// Also, if WindowContent does not have a RegionManager attached, it creates a new scoped RegionManager for it. /// </summary> /// <param name="notification">The notification to be set as a DataContext in the HostWindow.</param> /// <param name="wrapperWindow">The HostWindow</param> protected virtual void PrepareContentForWindow(INotification notification, Window wrapperWindow) { if (this.WindowContent == null) { return; } // We set the WindowContent as the content of the window. wrapperWindow.Content = this.WindowContent; IInteractionRequestAware interactionAware; // If the WindowContent implements IInteractionRequestAware we set the corresponding properties. interactionAware = this.WindowContent as IInteractionRequestAware; if (interactionAware != null) { interactionAware.Notification = notification; interactionAware.FinishInteraction = () => wrapperWindow.Close(); } // If the WindowContent's DataContext implements IInteractionRequestAware we set the corresponding properties. interactionAware = this.WindowContent.DataContext as IInteractionRequestAware; if (interactionAware != null) { interactionAware.Notification = notification; interactionAware.FinishInteraction = () => wrapperWindow.Close(); } } /// <summary> /// When no WindowContent is sent this method is used to create a default basic window to show /// the corresponding <see cref="INotification"/> or <see cref="IConfirmation"/>. /// </summary> /// <param name="notification">The INotification or IConfirmation parameter to show.</param> /// <returns></returns> protected Window CreateDefaultWindow(INotification notification) { Window window = null; if (notification is IConfirmation) { window = new DefaultConfirmationWindow() { Confirmation = (IConfirmation)notification }; } else { window = new DefaultNotificationWindow() { Notification = notification }; } return window; } } }
// // System.Xml.Serialization.SoapSchemaExporterTests // // Author: // Gert Driesen (drieseng@users.sourceforge.net) // // (C) 2005 Novell // #if !MOBILE using System; using System.Collections; using System.Globalization; using System.IO; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using NUnit.Framework; using MonoTests.System.Xml.TestClasses; namespace MonoTests.System.XmlSerialization { [TestFixture] public class SoapSchemaExporterTests { private XmlSchemas Export (Type type) { return Export (type, string.Empty); } private XmlSchemas Export (Type type, string defaultNamespace) { SoapReflectionImporter ri = new SoapReflectionImporter (defaultNamespace); XmlSchemas schemas = new XmlSchemas (); SoapSchemaExporter sx = new SoapSchemaExporter (schemas); XmlTypeMapping tm = ri.ImportTypeMapping (type); sx.ExportTypeMapping (tm); return schemas; } private XmlSchemas Export (Type type, SoapAttributeOverrides overrides) { return Export (type, overrides, string.Empty); } private XmlSchemas Export (Type type, SoapAttributeOverrides overrides, string defaultNamespace) { SoapReflectionImporter ri = new SoapReflectionImporter (overrides, defaultNamespace); XmlSchemas schemas = new XmlSchemas (); SoapSchemaExporter sx = new SoapSchemaExporter (schemas); XmlTypeMapping tm = ri.ImportTypeMapping (type); sx.ExportTypeMapping (tm); return schemas; } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportStruct () { XmlSchemas schemas = Export (typeof (TimeSpan), "NSTimeSpan"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSTimeSpan\" elementFormDefault=\"qualified\" targetNamespace=\"NSTimeSpan\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSTimeSpan\" targetNamespace=\"NSTimeSpan\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:complexType name=\"TimeSpan\" />{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); schemas = Export (typeof (TimeSpan)); Assert.AreEqual (1, schemas.Count, "#3"); sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema elementFormDefault=\"qualified\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:complexType name=\"TimeSpan\" />{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#4"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn /* #if NET_2_0 [Category ("NotWorking")] // minOccurs is 1 on Mono #endif */ public void ExportClass_SimpleClass () { SoapAttributeOverrides overrides = new SoapAttributeOverrides (); SoapAttributes attr = new SoapAttributes (); SoapElementAttribute element = new SoapElementAttribute (); element.ElementName = "saying"; element.IsNullable = true; attr.SoapElement = element; overrides.Add (typeof (SimpleClass), "something", attr); XmlSchemas schemas = Export (typeof (SimpleClass), overrides, "NSSimpleClass"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSSimpleClass\" elementFormDefault=\"qualified\" targetNamespace=\"NSSimpleClass\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSSimpleClass\" targetNamespace=\"NSSimpleClass\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:complexType name=\"SimpleClass\">{0}" + " <xs:sequence>{0}" + #if NET_2_0 " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"saying\" nillable=\"true\" type=\"xs:string\" />{0}" + #else " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"saying\" type=\"xs:string\" />{0}" + #endif " </xs:sequence>{0}" + " </xs:complexType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportClass_StringCollection () { XmlSchemas schemas = Export (typeof (StringCollection), "NSStringCollection"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSStringCollection\" elementFormDefault=\"qualified\" targetNamespace=\"NSStringCollection\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSStringCollection\" targetNamespace=\"NSStringCollection\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:import namespace=\"http://schemas.xmlsoap.org/soap/encoding/\" />{0}" + " <xs:import namespace=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " <xs:complexType name=\"ArrayOfString\">{0}" + " <xs:complexContent mixed=\"false\">{0}" + " <xs:restriction xmlns:q1=\"http://schemas.xmlsoap.org/soap/encoding/\" base=\"q1:Array\">{0}" + " <xs:attribute d5p1:arrayType=\"xs:string[]\" ref=\"q1:arrayType\" xmlns:d5p1=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " </xs:restriction>{0}" + " </xs:complexContent>{0}" + " </xs:complexType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportClass_StringCollectionContainer () { XmlSchemas schemas = Export (typeof (StringCollectionContainer), "NSStringCollectionContainer"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSStringCollectionContainer\" elementFormDefault=\"qualified\" targetNamespace=\"NSStringCollectionContainer\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSStringCollectionContainer\" targetNamespace=\"NSStringCollectionContainer\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:import namespace=\"http://schemas.xmlsoap.org/soap/encoding/\" />{0}" + " <xs:import namespace=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " <xs:complexType name=\"StringCollectionContainer\">{0}" + " <xs:sequence>{0}" + #if NET_2_0 " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"Messages\" type=\"tns:ArrayOfString\" />{0}" + #else " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"Messages\" type=\"tns:ArrayOfString\" />{0}" + #endif " </xs:sequence>{0}" + " </xs:complexType>{0}" + " <xs:complexType name=\"ArrayOfString\">{0}" + " <xs:complexContent mixed=\"false\">{0}" + " <xs:restriction xmlns:q1=\"http://schemas.xmlsoap.org/soap/encoding/\" base=\"q1:Array\">{0}" + " <xs:attribute d5p1:arrayType=\"xs:string[]\" ref=\"q1:arrayType\" xmlns:d5p1=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " </xs:restriction>{0}" + " </xs:complexContent>{0}" + " </xs:complexType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportClass_ArrayContainer () { XmlSchemas schemas = Export (typeof (ArrayContainer), "NSArrayContainer"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSArrayContainer\" elementFormDefault=\"qualified\" targetNamespace=\"NSArrayContainer\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSArrayContainer\" targetNamespace=\"NSArrayContainer\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:import namespace=\"http://schemas.xmlsoap.org/soap/encoding/\" />{0}" + " <xs:import namespace=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " <xs:complexType name=\"ArrayContainer\">{0}" + " <xs:sequence>{0}" + #if NET_2_0 " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"items\" type=\"tns:ArrayOfAnyType\" />{0}" + #else " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"items\" type=\"tns:ArrayOfAnyType\" />{0}" + #endif " </xs:sequence>{0}" + " </xs:complexType>{0}" + " <xs:complexType name=\"ArrayOfAnyType\">{0}" + " <xs:complexContent mixed=\"false\">{0}" + " <xs:restriction xmlns:q1=\"http://schemas.xmlsoap.org/soap/encoding/\" base=\"q1:Array\">{0}" + " <xs:attribute d5p1:arrayType=\"xs:anyType[]\" ref=\"q1:arrayType\" xmlns:d5p1=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " </xs:restriction>{0}" + " </xs:complexContent>{0}" + " </xs:complexType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportClass_ClassArrayContainer () { XmlSchemas schemas = Export (typeof (ClassArrayContainer), "NSClassArrayContainer"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSClassArrayContainer\" elementFormDefault=\"qualified\" targetNamespace=\"NSClassArrayContainer\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSClassArrayContainer\" targetNamespace=\"NSClassArrayContainer\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:import namespace=\"http://schemas.xmlsoap.org/soap/encoding/\" />{0}" + " <xs:import namespace=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " <xs:complexType name=\"ClassArrayContainer\">{0}" + " <xs:sequence>{0}" + #if NET_2_0 " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"items\" type=\"tns:ArrayOfSimpleClass\" />{0}" + #else " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"items\" type=\"tns:ArrayOfSimpleClass\" />{0}" + #endif " </xs:sequence>{0}" + " </xs:complexType>{0}" + " <xs:complexType name=\"ArrayOfSimpleClass\">{0}" + " <xs:complexContent mixed=\"false\">{0}" + " <xs:restriction xmlns:q1=\"http://schemas.xmlsoap.org/soap/encoding/\" base=\"q1:Array\">{0}" + " <xs:attribute d5p1:arrayType=\"tns:SimpleClass[]\" ref=\"q1:arrayType\" xmlns:d5p1=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " </xs:restriction>{0}" + " </xs:complexContent>{0}" + " </xs:complexType>{0}" + " <xs:complexType name=\"SimpleClass\">{0}" + " <xs:sequence>{0}" + #if NET_2_0 " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"something\" type=\"xs:string\" />{0}" + #else " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"something\" type=\"xs:string\" />{0}" + #endif " </xs:sequence>{0}" + " </xs:complexType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportClass_SimpleClassWithXmlAttributes () { XmlSchemas schemas = Export (typeof (SimpleClassWithXmlAttributes), "NSSimpleClassWithXmlAttributes"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSSimpleClassWithXmlAttributes\" elementFormDefault=\"qualified\" targetNamespace=\"NSSimpleClassWithXmlAttributes\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSSimpleClassWithXmlAttributes\" targetNamespace=\"NSSimpleClassWithXmlAttributes\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:complexType name=\"SimpleClassWithXmlAttributes\">{0}" + " <xs:sequence>{0}" + #if NET_2_0 " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"something\" type=\"xs:string\" />{0}" + #else " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"something\" type=\"xs:string\" />{0}" + #endif " </xs:sequence>{0}" + " </xs:complexType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportClass_Field () { XmlSchemas schemas = Export (typeof (Field), "NSField"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSField\" elementFormDefault=\"qualified\" targetNamespace=\"NSField\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSField\" targetNamespace=\"NSField\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:import namespace=\"http://schemas.xmlsoap.org/soap/encoding/\" />{0}" + " <xs:import namespace=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " <xs:complexType name=\"Field\">{0}" + " <xs:sequence>{0}" + #if NET_2_0 " <xs:element minOccurs=\"1\" maxOccurs=\"1\" form=\"unqualified\" name=\"Flags1\" type=\"tns:FlagEnum\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" form=\"unqualified\" name=\"Flags2\" type=\"tns:FlagEnum\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" form=\"unqualified\" name=\"Flags3\" type=\"tns:FlagEnum\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" form=\"unqualified\" name=\"Flags4\" type=\"tns:FlagEnum\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" form=\"unqualified\" name=\"Modifiers\" type=\"tns:MapModifiers\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" form=\"unqualified\" name=\"Modifiers2\" type=\"tns:MapModifiers\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" form=\"unqualified\" name=\"Modifiers3\" type=\"tns:MapModifiers\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" form=\"unqualified\" name=\"Modifiers4\" type=\"tns:MapModifiers\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" form=\"unqualified\" name=\"Modifiers5\" type=\"tns:MapModifiers\" />{0}" + " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"Names\" type=\"tns:ArrayOfString\" />{0}" + " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"Street\" type=\"xs:string\" />{0}" + #else " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"Flags1\" type=\"tns:FlagEnum\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"Flags2\" type=\"tns:FlagEnum\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"Flags3\" type=\"tns:FlagEnum\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"Flags4\" type=\"tns:FlagEnum\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"Modifiers\" type=\"tns:MapModifiers\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"Modifiers2\" type=\"tns:MapModifiers\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"Modifiers3\" type=\"tns:MapModifiers\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"Modifiers4\" type=\"tns:MapModifiers\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"Modifiers5\" type=\"tns:MapModifiers\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"Names\" type=\"tns:ArrayOfString\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"Street\" type=\"xs:string\" />{0}" + #endif " </xs:sequence>{0}" + " </xs:complexType>{0}" + " <xs:simpleType name=\"FlagEnum\">{0}" + " <xs:list>{0}" + " <xs:simpleType>{0}" + " <xs:restriction base=\"xs:string\">{0}" + " <xs:enumeration value=\"e1\" />{0}" + " <xs:enumeration value=\"e2\" />{0}" + " <xs:enumeration value=\"e4\" />{0}" + " </xs:restriction>{0}" + " </xs:simpleType>{0}" + " </xs:list>{0}" + " </xs:simpleType>{0}" + " <xs:simpleType name=\"MapModifiers\">{0}" + " <xs:list>{0}" + " <xs:simpleType>{0}" + " <xs:restriction base=\"xs:string\">{0}" + " <xs:enumeration value=\"Public\" />{0}" + " <xs:enumeration value=\"Protected\" />{0}" + " </xs:restriction>{0}" + " </xs:simpleType>{0}" + " </xs:list>{0}" + " </xs:simpleType>{0}" + " <xs:complexType name=\"ArrayOfString\">{0}" + " <xs:complexContent mixed=\"false\">{0}" + " <xs:restriction xmlns:q1=\"http://schemas.xmlsoap.org/soap/encoding/\" base=\"q1:Array\">{0}" + " <xs:attribute d5p1:arrayType=\"xs:string[]\" ref=\"q1:arrayType\" xmlns:d5p1=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " </xs:restriction>{0}" + " </xs:complexContent>{0}" + " </xs:complexType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportClass_MyList () { XmlSchemas schemas = Export (typeof (MyList), "NSMyList"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSMyList\" elementFormDefault=\"qualified\" targetNamespace=\"NSMyList\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSMyList\" targetNamespace=\"NSMyList\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:import namespace=\"http://schemas.xmlsoap.org/soap/encoding/\" />{0}" + " <xs:import namespace=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " <xs:complexType name=\"ArrayOfAnyType\">{0}" + " <xs:complexContent mixed=\"false\">{0}" + " <xs:restriction xmlns:q1=\"http://schemas.xmlsoap.org/soap/encoding/\" base=\"q1:Array\">{0}" + " <xs:attribute d5p1:arrayType=\"xs:anyType[]\" ref=\"q1:arrayType\" xmlns:d5p1=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " </xs:restriction>{0}" + " </xs:complexContent>{0}" + " </xs:complexType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportClass_Container () { XmlSchemas schemas = Export (typeof (Container), "NSContainer"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSContainer\" elementFormDefault=\"qualified\" targetNamespace=\"NSContainer\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSContainer\" targetNamespace=\"NSContainer\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:import namespace=\"http://schemas.xmlsoap.org/soap/encoding/\" />{0}" + " <xs:import namespace=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " <xs:complexType name=\"Container\">{0}" + " <xs:sequence>{0}" + #if NET_2_0 " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"Items\" type=\"tns:ArrayOfAnyType\" />{0}" + #else " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"Items\" type=\"tns:ArrayOfAnyType\" />{0}" + #endif " </xs:sequence>{0}" + " </xs:complexType>{0}" + " <xs:complexType name=\"ArrayOfAnyType\">{0}" + " <xs:complexContent mixed=\"false\">{0}" + " <xs:restriction xmlns:q1=\"http://schemas.xmlsoap.org/soap/encoding/\" base=\"q1:Array\">{0}" + " <xs:attribute d5p1:arrayType=\"xs:anyType[]\" ref=\"q1:arrayType\" xmlns:d5p1=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " </xs:restriction>{0}" + " </xs:complexContent>{0}" + " </xs:complexType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportClass_Container2 () { XmlSchemas schemas = Export (typeof (Container2), "NSContainer2"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSContainer2\" elementFormDefault=\"qualified\" targetNamespace=\"NSContainer2\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSContainer2\" targetNamespace=\"NSContainer2\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:import namespace=\"http://schemas.xmlsoap.org/soap/encoding/\" />{0}" + " <xs:import namespace=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " <xs:complexType name=\"Container2\">{0}" + " <xs:sequence>{0}" + #if NET_2_0 " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"Items\" type=\"tns:ArrayOfAnyType\" />{0}" + #else " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"Items\" type=\"tns:ArrayOfAnyType\" />{0}" + #endif " </xs:sequence>{0}" + " </xs:complexType>{0}" + " <xs:complexType name=\"ArrayOfAnyType\">{0}" + " <xs:complexContent mixed=\"false\">{0}" + " <xs:restriction xmlns:q1=\"http://schemas.xmlsoap.org/soap/encoding/\" base=\"q1:Array\">{0}" + " <xs:attribute d5p1:arrayType=\"xs:anyType[]\" ref=\"q1:arrayType\" xmlns:d5p1=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " </xs:restriction>{0}" + " </xs:complexContent>{0}" + " </xs:complexType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } [Test] [ExpectedException (typeof (NotSupportedException))] public void ExportClass_MyElem () { Export (typeof (MyElem), "NSMyElem"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn [ExpectedException (typeof (NotSupportedException))] // The type System.Xml.XmlCDataSection may not be serialized with SOAP-encoded messages. public void ExportClass_CDataContainer () { Export (typeof (CDataContainer), "NSCDataContainer"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn [ExpectedException (typeof (NotSupportedException))] // The type System.Xml.XmlCDataSection may not be serialized with SOAP-encoded messages. public void ExportClass_NodeContainer () { Export (typeof (NodeContainer), "NSNodeContainer"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportClass_Choices () { XmlSchemas schemas = Export (typeof (Choices), "NSChoices"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSChoices\" elementFormDefault=\"qualified\" targetNamespace=\"NSChoices\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSChoices\" targetNamespace=\"NSChoices\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:complexType name=\"Choices\">{0}" + " <xs:sequence>{0}" + #if NET_2_0 " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"MyChoice\" type=\"xs:string\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" form=\"unqualified\" name=\"ItemType\" type=\"tns:ItemChoiceType\" />{0}" + #else " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"MyChoice\" type=\"xs:string\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"ItemType\" type=\"tns:ItemChoiceType\" />{0}" + #endif " </xs:sequence>{0}" + " </xs:complexType>{0}" + " <xs:simpleType name=\"ItemChoiceType\">{0}" + " <xs:restriction base=\"xs:string\">{0}" + " <xs:enumeration value=\"ChoiceZero\" />{0}" + " <xs:enumeration value=\"StrangeOne\" />{0}" + " <xs:enumeration value=\"ChoiceTwo\" />{0}" + " </xs:restriction>{0}" + " </xs:simpleType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportClass_WrongChoices () { XmlSchemas schemas = Export (typeof (WrongChoices), "NSWrongChoices"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSWrongChoices\" elementFormDefault=\"qualified\" targetNamespace=\"NSWrongChoices\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSWrongChoices\" targetNamespace=\"NSWrongChoices\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:complexType name=\"WrongChoices\">{0}" + " <xs:sequence>{0}" + #if NET_2_0 " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"MyChoice\" type=\"xs:string\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" form=\"unqualified\" name=\"ItemType\" type=\"tns:ItemChoiceType\" />{0}" + #else " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"MyChoice\" type=\"xs:string\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"ItemType\" type=\"tns:ItemChoiceType\" />{0}" + #endif " </xs:sequence>{0}" + " </xs:complexType>{0}" + " <xs:simpleType name=\"ItemChoiceType\">{0}" + " <xs:restriction base=\"xs:string\">{0}" + " <xs:enumeration value=\"ChoiceZero\" />{0}" + " <xs:enumeration value=\"StrangeOne\" />{0}" + " <xs:enumeration value=\"ChoiceTwo\" />{0}" + " </xs:restriction>{0}" + " </xs:simpleType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportClass_TestSpace () { XmlSchemas schemas = Export (typeof (TestSpace), "NSTestSpace"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSTestSpace\" elementFormDefault=\"qualified\" targetNamespace=\"NSTestSpace\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSTestSpace\" targetNamespace=\"NSTestSpace\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:complexType name=\"TestSpace\">{0}" + " <xs:sequence>{0}" + #if NET_2_0 " <xs:element minOccurs=\"1\" maxOccurs=\"1\" form=\"unqualified\" name=\"elem\" type=\"xs:int\" />{0}" + #else " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"elem\" type=\"xs:int\" />{0}" + #endif #if NET_2_0 " <xs:element minOccurs=\"1\" maxOccurs=\"1\" form=\"unqualified\" name=\"attr\" type=\"xs:int\" />{0}" + #else " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"attr\" type=\"xs:int\" />{0}" + #endif " </xs:sequence>{0}" + " </xs:complexType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportClass_ReadOnlyProperties () { XmlSchemas schemas = Export (typeof (ReadOnlyProperties), "NSReadOnlyProperties"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSReadOnlyProperties\" elementFormDefault=\"qualified\" targetNamespace=\"NSReadOnlyProperties\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSReadOnlyProperties\" targetNamespace=\"NSReadOnlyProperties\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:complexType name=\"ReadOnlyProperties\" />{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportClass_ListDefaults () { XmlSchemas schemas = Export (typeof (ListDefaults), "NSListDefaults"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSListDefaults\" elementFormDefault=\"qualified\" targetNamespace=\"NSListDefaults\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSListDefaults\" targetNamespace=\"NSListDefaults\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:import namespace=\"http://schemas.xmlsoap.org/soap/encoding/\" />{0}" + " <xs:import namespace=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " <xs:complexType name=\"ListDefaults\">{0}" + " <xs:sequence>{0}" + #if NET_2_0 " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"list2\" type=\"tns:ArrayOfAnyType\" />{0}" + " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"list3\" type=\"tns:ArrayOfAnyType\" />{0}" + " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"list4\" type=\"tns:ArrayOfString\" />{0}" + " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"list5\" type=\"tns:ArrayOfAnyType\" />{0}" + " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"ed\" type=\"tns:SimpleClass\" />{0}" + " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"str\" type=\"xs:string\" />{0}" + #else " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"list2\" type=\"tns:ArrayOfAnyType\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"list3\" type=\"tns:ArrayOfAnyType\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"list4\" type=\"tns:ArrayOfString\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"list5\" type=\"tns:ArrayOfAnyType\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"ed\" type=\"tns:SimpleClass\" />{0}" + " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"str\" type=\"xs:string\" />{0}" + #endif " </xs:sequence>{0}" + " </xs:complexType>{0}" + " <xs:complexType name=\"ArrayOfAnyType\">{0}" + " <xs:complexContent mixed=\"false\">{0}" + " <xs:restriction xmlns:q1=\"http://schemas.xmlsoap.org/soap/encoding/\" base=\"q1:Array\">{0}" + " <xs:attribute d5p1:arrayType=\"xs:anyType[]\" ref=\"q1:arrayType\" xmlns:d5p1=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " </xs:restriction>{0}" + " </xs:complexContent>{0}" + " </xs:complexType>{0}" + " <xs:complexType name=\"SimpleClass\">{0}" + " <xs:sequence>{0}" + #if NET_2_0 " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"something\" type=\"xs:string\" />{0}" + #else " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"something\" type=\"xs:string\" />{0}" + #endif " </xs:sequence>{0}" + " </xs:complexType>{0}" + " <xs:complexType name=\"ArrayOfString\">{0}" + " <xs:complexContent mixed=\"false\">{0}" + " <xs:restriction xmlns:q2=\"http://schemas.xmlsoap.org/soap/encoding/\" base=\"q2:Array\">{0}" + " <xs:attribute d5p1:arrayType=\"xs:string[]\" ref=\"q2:arrayType\" xmlns:d5p1=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " </xs:restriction>{0}" + " </xs:complexContent>{0}" + " </xs:complexType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportClass_ClsPerson () { XmlSchemas schemas = Export (typeof (clsPerson), "NSClsPerson"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSClsPerson\" elementFormDefault=\"qualified\" targetNamespace=\"NSClsPerson\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSClsPerson\" targetNamespace=\"NSClsPerson\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:import namespace=\"http://schemas.xmlsoap.org/soap/encoding/\" />{0}" + " <xs:import namespace=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " <xs:complexType name=\"clsPerson\">{0}" + " <xs:sequence>{0}" + #if NET_2_0 " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"EmailAccounts\" type=\"tns:ArrayOfAnyType\" />{0}" + #else " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"EmailAccounts\" type=\"tns:ArrayOfAnyType\" />{0}" + #endif " </xs:sequence>{0}" + " </xs:complexType>{0}" + " <xs:complexType name=\"ArrayOfAnyType\">{0}" + " <xs:complexContent mixed=\"false\">{0}" + " <xs:restriction xmlns:q1=\"http://schemas.xmlsoap.org/soap/encoding/\" base=\"q1:Array\">{0}" + " <xs:attribute d5p1:arrayType=\"xs:anyType[]\" ref=\"q1:arrayType\" xmlns:d5p1=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " </xs:restriction>{0}" + " </xs:complexContent>{0}" + " </xs:complexType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportClass_ArrayClass () { XmlSchemas schemas = Export (typeof (ArrayClass), "NSArrayClass"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSArrayClass\" elementFormDefault=\"qualified\" targetNamespace=\"NSArrayClass\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSArrayClass\" targetNamespace=\"NSArrayClass\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:complexType name=\"ArrayClass\">{0}" + " <xs:sequence>{0}" + #if NET_2_0 " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"names\" type=\"xs:anyType\" />{0}" + #else " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"names\" type=\"xs:anyType\" />{0}" + #endif " </xs:sequence>{0}" + " </xs:complexType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#4"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportClass_StructContainer () { XmlSchemas schemas = Export (typeof (StructContainer), "NSStructContainer"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSStructContainer\" elementFormDefault=\"qualified\" targetNamespace=\"NSStructContainer\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSStructContainer\" targetNamespace=\"NSStructContainer\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:complexType name=\"StructContainer\">{0}" + " <xs:sequence>{0}" + #if NET_2_0 " <xs:element minOccurs=\"1\" maxOccurs=\"1\" form=\"unqualified\" name=\"Value\" type=\"tns:EnumDefaultValue\" />{0}" + #else " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"Value\" type=\"tns:EnumDefaultValue\" />{0}" + #endif " </xs:sequence>{0}" + " </xs:complexType>{0}" + " <xs:simpleType name=\"EnumDefaultValue\">{0}" + " <xs:list>{0}" + " <xs:simpleType>{0}" + " <xs:restriction base=\"xs:string\">{0}" + " <xs:enumeration value=\"e1\" />{0}" + " <xs:enumeration value=\"e2\" />{0}" + " <xs:enumeration value=\"e3\" />{0}" + " </xs:restriction>{0}" + " </xs:simpleType>{0}" + " </xs:list>{0}" + " </xs:simpleType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn /* #if NET_2_0 [Category ("NotWorking")] // minOccurs is 1 on Mono #endif */ public void ExportClass_SimpleClass_Array () { SoapAttributeOverrides overrides = new SoapAttributeOverrides (); SoapAttributes attr = new SoapAttributes (); SoapElementAttribute element = new SoapElementAttribute (); element.ElementName = "saying"; element.IsNullable = true; attr.SoapElement = element; overrides.Add (typeof (SimpleClass), "something", attr); SoapReflectionImporter ri = new SoapReflectionImporter (overrides, "NSSimpleClassArray"); XmlSchemas schemas = new XmlSchemas (); SoapSchemaExporter sx = new SoapSchemaExporter (schemas); XmlTypeMapping tm = ri.ImportTypeMapping (typeof (SimpleClass[])); sx.ExportTypeMapping (tm); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSSimpleClassArray\" elementFormDefault=\"qualified\" targetNamespace=\"NSSimpleClassArray\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSSimpleClassArray\" targetNamespace=\"NSSimpleClassArray\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:import namespace=\"http://schemas.xmlsoap.org/soap/encoding/\" />{0}" + " <xs:import namespace=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " <xs:complexType name=\"ArrayOfSimpleClass\">{0}" + " <xs:complexContent mixed=\"false\">{0}" + " <xs:restriction xmlns:q1=\"http://schemas.xmlsoap.org/soap/encoding/\" base=\"q1:Array\">{0}" + " <xs:attribute d5p1:arrayType=\"tns:SimpleClass[]\" ref=\"q1:arrayType\" xmlns:d5p1=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " </xs:restriction>{0}" + " </xs:complexContent>{0}" + " </xs:complexType>{0}" + " <xs:complexType name=\"SimpleClass\">{0}" + " <xs:sequence>{0}" + #if NET_2_0 " <xs:element minOccurs=\"0\" maxOccurs=\"1\" form=\"unqualified\" name=\"saying\" nillable=\"true\" type=\"xs:string\" />{0}" + #else " <xs:element minOccurs=\"1\" maxOccurs=\"1\" name=\"saying\" type=\"xs:string\" />{0}" + #endif " </xs:sequence>{0}" + " </xs:complexType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportEnum () { XmlSchemas schemas = Export (typeof (EnumDefaultValue), "NSEnumDefaultValue"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSEnumDefaultValue\" elementFormDefault=\"qualified\" targetNamespace=\"NSEnumDefaultValue\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSEnumDefaultValue\" targetNamespace=\"NSEnumDefaultValue\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:simpleType name=\"EnumDefaultValue\">{0}" + " <xs:list>{0}" + " <xs:simpleType>{0}" + " <xs:restriction base=\"xs:string\">{0}" + " <xs:enumeration value=\"e1\" />{0}" + " <xs:enumeration value=\"e2\" />{0}" + " <xs:enumeration value=\"e3\" />{0}" + " </xs:restriction>{0}" + " </xs:simpleType>{0}" + " </xs:list>{0}" + " </xs:simpleType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); schemas = Export (typeof (EnumDefaultValueNF), "NSEnumDefaultValueNF"); Assert.AreEqual (1, schemas.Count, "#3"); sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"NSEnumDefaultValueNF\" elementFormDefault=\"qualified\" targetNamespace=\"NSEnumDefaultValueNF\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"NSEnumDefaultValueNF\" targetNamespace=\"NSEnumDefaultValueNF\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:simpleType name=\"EnumDefaultValueNF\">{0}" + " <xs:restriction base=\"xs:string\">{0}" + " <xs:enumeration value=\"e1\" />{0}" + " <xs:enumeration value=\"e2\" />{0}" + " <xs:enumeration value=\"e3\" />{0}" + " </xs:restriction>{0}" + " </xs:simpleType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#4"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportXsdPrimitive () { ArrayList types = new ArrayList (); types.Add (new TypeDescription (typeof (object), true, "anyType", "Object")); types.Add (new TypeDescription (typeof (byte), true, "unsignedByte", "Byte")); types.Add (new TypeDescription (typeof (sbyte), true, "byte", "Byte")); types.Add (new TypeDescription (typeof (bool), true, "boolean", "Boolean")); types.Add (new TypeDescription (typeof (short), true, "short", "Short")); types.Add (new TypeDescription (typeof (int), true, "int", "Int")); types.Add (new TypeDescription (typeof (long), true, "long", "Long")); types.Add (new TypeDescription (typeof (float), true, "float", "Float")); types.Add (new TypeDescription (typeof (double), true, "double", "Double")); types.Add (new TypeDescription (typeof (decimal), true, "decimal", "Decimal")); types.Add (new TypeDescription (typeof (ushort), true, "unsignedShort", "UnsignedShort")); types.Add (new TypeDescription (typeof (uint), true, "unsignedInt", "UnsignedInt")); types.Add (new TypeDescription (typeof (ulong), true, "unsignedLong", "UnsignedLong")); types.Add (new TypeDescription (typeof (DateTime), true, "dateTime", "DateTime")); #if NET_2_0 types.Add (new TypeDescription (typeof (XmlQualifiedName), true, "QName", "QName", true)); #else types.Add (new TypeDescription (typeof (XmlQualifiedName), true, "QName", "QName")); #endif types.Add (new TypeDescription (typeof (string), true, "string", "String", true)); foreach (TypeDescription typeDesc in types) { XmlSchemas schemas = Export (typeDesc.Type, typeDesc.Type.Name); Assert.AreEqual (0, schemas.Count, typeDesc.Type.FullName + "#1"); } } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportXsdPrimitive_ByteArray () { XmlSchemas schemas = Export (typeof (byte[]), "ByteArray"); Assert.AreEqual (0, schemas.Count, "#1"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportXsdPrimitive_Arrays () { ArrayList types = new ArrayList (); types.Add (new TypeDescription (typeof (object[]), true, "anyType", "AnyType")); types.Add (new TypeDescription (typeof (sbyte[]), true, "byte", "Byte")); types.Add (new TypeDescription (typeof (bool[]), true, "boolean", "Boolean")); types.Add (new TypeDescription (typeof (short[]), true, "short", "Short")); types.Add (new TypeDescription (typeof (int[]), true, "int", "Int")); types.Add (new TypeDescription (typeof (long[]), true, "long", "Long")); types.Add (new TypeDescription (typeof (float[]), true, "float", "Float")); types.Add (new TypeDescription (typeof (double[]), true, "double", "Double")); types.Add (new TypeDescription (typeof (decimal[]), true, "decimal", "Decimal")); types.Add (new TypeDescription (typeof (ushort[]), true, "unsignedShort", "UnsignedShort")); types.Add (new TypeDescription (typeof (uint[]), true, "unsignedInt", "UnsignedInt")); types.Add (new TypeDescription (typeof (ulong[]), true, "unsignedLong", "UnsignedLong")); types.Add (new TypeDescription (typeof (DateTime[]), true, "dateTime", "DateTime")); #if NET_2_0 types.Add (new TypeDescription (typeof (XmlQualifiedName[]), true, "QName", "QName", true)); #else types.Add (new TypeDescription (typeof (XmlQualifiedName[]), true, "QName", "QName")); #endif types.Add (new TypeDescription (typeof (string[]), true, "string", "String", true)); foreach (TypeDescription typeDesc in types) { XmlSchemas schemas = Export (typeDesc.Type, typeDesc.Type.Name); Assert.AreEqual (1, schemas.Count, typeDesc.Type.FullName + "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"{1}\" elementFormDefault=\"qualified\" targetNamespace=\"{1}\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"{1}\" targetNamespace=\"{1}\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:import namespace=\"http://schemas.xmlsoap.org/soap/encoding/\" />{0}" + " <xs:import namespace=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " <xs:complexType name=\"ArrayOf{2}\">{0}" + " <xs:complexContent mixed=\"false\">{0}" + " <xs:restriction xmlns:q1=\"http://schemas.xmlsoap.org/soap/encoding/\" base=\"q1:Array\">{0}" + " <xs:attribute d5p1:arrayType=\"xs:{3}[]\" ref=\"q1:arrayType\" xmlns:d5p1=\"http://schemas.xmlsoap.org/wsdl/\" />{0}" + " </xs:restriction>{0}" + " </xs:complexContent>{0}" + " </xs:complexType>{0}" + "</xs:schema>", Environment.NewLine, typeDesc.Type.Name, typeDesc.ArrayType, typeDesc.XmlType, typeDesc.XsdType ? "xs" : "tns", typeDesc.IsNillable ? "nillable=\"true\" " : ""), sw.ToString (), typeDesc.Type.FullName + "#2"); } } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportNonXsdPrimitive_Guid () { XmlSchemas schemas = Export (typeof (Guid), "NSPrimGuid"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"http://microsoft.com/wsdl/types/\" elementFormDefault=\"qualified\" targetNamespace=\"http://microsoft.com/wsdl/types/\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"http://microsoft.com/wsdl/types/\" targetNamespace=\"http://microsoft.com/wsdl/types/\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:simpleType name=\"guid\">{0}" + " <xs:restriction base=\"xs:string\">{0}" + " <xs:pattern value=\"[0-9a-fA-F]{{8}}-[0-9a-fA-F]{{4}}-[0-9a-fA-F]{{4}}-[0-9a-fA-F]{{4}}-[0-9a-fA-F]{{12}}\" />{0}" + " </xs:restriction>{0}" + " </xs:simpleType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } [Test] [Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ExportNonXsdPrimitive_Char () { XmlSchemas schemas = Export (typeof (Char), "NSPrimChar"); Assert.AreEqual (1, schemas.Count, "#1"); StringWriter sw = new StringWriter (); schemas[0].Write (sw); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + #if NET_2_0 "<xs:schema xmlns:tns=\"http://microsoft.com/wsdl/types/\" elementFormDefault=\"qualified\" targetNamespace=\"http://microsoft.com/wsdl/types/\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #else "<xs:schema xmlns:tns=\"http://microsoft.com/wsdl/types/\" targetNamespace=\"http://microsoft.com/wsdl/types/\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #endif " <xs:simpleType name=\"char\">{0}" + " <xs:restriction base=\"xs:unsignedShort\" />{0}" + " </xs:simpleType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); } public class Employee : IXmlSerializable { private string _firstName; private string _lastName; private string _address; public XmlSchema GetSchema () { return null; } public void WriteXml (XmlWriter writer) { writer.WriteStartElement ("employee", "urn:devx-com"); writer.WriteAttributeString ("firstName", _firstName); writer.WriteAttributeString ("lastName", _lastName); writer.WriteAttributeString ("address", _address); writer.WriteEndElement (); } public void ReadXml (XmlReader reader) { XmlNodeType type = reader.MoveToContent (); if (type == XmlNodeType.Element && reader.LocalName == "employee") { _firstName = reader["firstName"]; _lastName = reader["lastName"]; _address = reader["address"]; } } } public class StructContainer { public EnumDefaultValue Value; } private class TypeDescription { public TypeDescription (Type type, bool xsdType, string xmlType, string arrayType) : this (type, xsdType, xmlType, arrayType, false) { } public TypeDescription (Type type, bool xsdType, string xmlType, string arrayType, bool isNillable) { _type = type; _xsdType = xsdType; _xmlType = xmlType; _arrayType = arrayType; _isNillable = isNillable; } public Type Type { get { return _type; } } public string XmlType { get { return _xmlType; } } public string ArrayType { get { return _arrayType; } } public bool XsdType { get { return _xsdType; } } public bool IsNillable { get { return _isNillable; } } private Type _type; private bool _xsdType; private string _xmlType; private string _arrayType; private bool _isNillable; } } } #endif
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using LSLInteger = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase { public partial class ScriptBaseClass { // LSL CONSTANTS public static readonly LSLInteger TRUE = new LSLInteger(1); public static readonly LSLInteger FALSE = new LSLInteger(0); public const int STATUS_PHYSICS = 1; public const int STATUS_ROTATE_X = 2; public const int STATUS_ROTATE_Y = 4; public const int STATUS_ROTATE_Z = 8; public const int STATUS_PHANTOM = 16; public const int STATUS_SANDBOX = 32; public const int STATUS_BLOCK_GRAB = 64; public const int STATUS_DIE_AT_EDGE = 128; public const int STATUS_RETURN_AT_EDGE = 256; public const int STATUS_CAST_SHADOWS = 512; public const int AGENT = 1; public const int ACTIVE = 2; public const int PASSIVE = 4; public const int SCRIPTED = 8; public const int CONTROL_FWD = 1; public const int CONTROL_BACK = 2; public const int CONTROL_LEFT = 4; public const int CONTROL_RIGHT = 8; public const int CONTROL_UP = 16; public const int CONTROL_DOWN = 32; public const int CONTROL_ROT_LEFT = 256; public const int CONTROL_ROT_RIGHT = 512; public const int CONTROL_LBUTTON = 268435456; public const int CONTROL_ML_LBUTTON = 1073741824; //Permissions public const int PERMISSION_DEBIT = 2; public const int PERMISSION_TAKE_CONTROLS = 4; public const int PERMISSION_REMAP_CONTROLS = 8; public const int PERMISSION_TRIGGER_ANIMATION = 16; public const int PERMISSION_ATTACH = 32; public const int PERMISSION_RELEASE_OWNERSHIP = 64; public const int PERMISSION_CHANGE_LINKS = 128; public const int PERMISSION_CHANGE_JOINTS = 256; public const int PERMISSION_CHANGE_PERMISSIONS = 512; public const int PERMISSION_TRACK_CAMERA = 1024; public const int PERMISSION_CONTROL_CAMERA = 2048; public const int AGENT_FLYING = 1; public const int AGENT_ATTACHMENTS = 2; public const int AGENT_SCRIPTED = 4; public const int AGENT_MOUSELOOK = 8; public const int AGENT_SITTING = 16; public const int AGENT_ON_OBJECT = 32; public const int AGENT_AWAY = 64; public const int AGENT_WALKING = 128; public const int AGENT_IN_AIR = 256; public const int AGENT_TYPING = 512; public const int AGENT_CROUCHING = 1024; public const int AGENT_BUSY = 2048; public const int AGENT_ALWAYS_RUN = 4096; //Particle Systems public const int PSYS_PART_INTERP_COLOR_MASK = 1; public const int PSYS_PART_INTERP_SCALE_MASK = 2; public const int PSYS_PART_BOUNCE_MASK = 4; public const int PSYS_PART_WIND_MASK = 8; public const int PSYS_PART_FOLLOW_SRC_MASK = 16; public const int PSYS_PART_FOLLOW_VELOCITY_MASK = 32; public const int PSYS_PART_TARGET_POS_MASK = 64; public const int PSYS_PART_TARGET_LINEAR_MASK = 128; public const int PSYS_PART_EMISSIVE_MASK = 256; public const int PSYS_PART_FLAGS = 0; public const int PSYS_PART_START_COLOR = 1; public const int PSYS_PART_START_ALPHA = 2; public const int PSYS_PART_END_COLOR = 3; public const int PSYS_PART_END_ALPHA = 4; public const int PSYS_PART_START_SCALE = 5; public const int PSYS_PART_END_SCALE = 6; public const int PSYS_PART_MAX_AGE = 7; public const int PSYS_SRC_ACCEL = 8; public const int PSYS_SRC_PATTERN = 9; public const int PSYS_SRC_INNERANGLE = 10; public const int PSYS_SRC_OUTERANGLE = 11; public const int PSYS_SRC_TEXTURE = 12; public const int PSYS_SRC_BURST_RATE = 13; public const int PSYS_SRC_BURST_PART_COUNT = 15; public const int PSYS_SRC_BURST_RADIUS = 16; public const int PSYS_SRC_BURST_SPEED_MIN = 17; public const int PSYS_SRC_BURST_SPEED_MAX = 18; public const int PSYS_SRC_MAX_AGE = 19; public const int PSYS_SRC_TARGET_KEY = 20; public const int PSYS_SRC_OMEGA = 21; public const int PSYS_SRC_ANGLE_BEGIN = 22; public const int PSYS_SRC_ANGLE_END = 23; public const int PSYS_SRC_PATTERN_DROP = 1; public const int PSYS_SRC_PATTERN_EXPLODE = 2; public const int PSYS_SRC_PATTERN_ANGLE = 4; public const int PSYS_SRC_PATTERN_ANGLE_CONE = 8; public const int PSYS_SRC_PATTERN_ANGLE_CONE_EMPTY = 16; public const int VEHICLE_TYPE_NONE = 0; public const int VEHICLE_TYPE_SLED = 1; public const int VEHICLE_TYPE_CAR = 2; public const int VEHICLE_TYPE_BOAT = 3; public const int VEHICLE_TYPE_AIRPLANE = 4; public const int VEHICLE_TYPE_BALLOON = 5; public const int VEHICLE_LINEAR_FRICTION_TIMESCALE = 16; public const int VEHICLE_ANGULAR_FRICTION_TIMESCALE = 17; public const int VEHICLE_LINEAR_MOTOR_DIRECTION = 18; public const int VEHICLE_LINEAR_MOTOR_OFFSET = 20; public const int VEHICLE_ANGULAR_MOTOR_DIRECTION = 19; public const int VEHICLE_HOVER_HEIGHT = 24; public const int VEHICLE_HOVER_EFFICIENCY = 25; public const int VEHICLE_HOVER_TIMESCALE = 26; public const int VEHICLE_BUOYANCY = 27; public const int VEHICLE_LINEAR_DEFLECTION_EFFICIENCY = 28; public const int VEHICLE_LINEAR_DEFLECTION_TIMESCALE = 29; public const int VEHICLE_LINEAR_MOTOR_TIMESCALE = 30; public const int VEHICLE_LINEAR_MOTOR_DECAY_TIMESCALE = 31; public const int VEHICLE_ANGULAR_DEFLECTION_EFFICIENCY = 32; public const int VEHICLE_ANGULAR_DEFLECTION_TIMESCALE = 33; public const int VEHICLE_ANGULAR_MOTOR_TIMESCALE = 34; public const int VEHICLE_ANGULAR_MOTOR_DECAY_TIMESCALE = 35; public const int VEHICLE_VERTICAL_ATTRACTION_EFFICIENCY = 36; public const int VEHICLE_VERTICAL_ATTRACTION_TIMESCALE = 37; public const int VEHICLE_BANKING_EFFICIENCY = 38; public const int VEHICLE_BANKING_MIX = 39; public const int VEHICLE_BANKING_TIMESCALE = 40; public const int VEHICLE_REFERENCE_FRAME = 44; public const int VEHICLE_FLAG_NO_DEFLECTION_UP = 1; public const int VEHICLE_FLAG_LIMIT_ROLL_ONLY = 2; public const int VEHICLE_FLAG_HOVER_WATER_ONLY = 4; public const int VEHICLE_FLAG_HOVER_TERRAIN_ONLY = 8; public const int VEHICLE_FLAG_HOVER_GLOBAL_HEIGHT = 16; public const int VEHICLE_FLAG_HOVER_UP_ONLY = 32; public const int VEHICLE_FLAG_LIMIT_MOTOR_UP = 64; public const int VEHICLE_FLAG_MOUSELOOK_STEER = 128; public const int VEHICLE_FLAG_MOUSELOOK_BANK = 256; public const int VEHICLE_FLAG_CAMERA_DECOUPLED = 512; public const int INVENTORY_ALL = -1; public const int INVENTORY_NONE = -1; public const int INVENTORY_TEXTURE = 0; public const int INVENTORY_SOUND = 1; public const int INVENTORY_LANDMARK = 3; public const int INVENTORY_CLOTHING = 5; public const int INVENTORY_OBJECT = 6; public const int INVENTORY_NOTECARD = 7; public const int INVENTORY_SCRIPT = 10; public const int INVENTORY_BODYPART = 13; public const int INVENTORY_ANIMATION = 20; public const int INVENTORY_GESTURE = 21; public const int ATTACH_CHEST = 1; public const int ATTACH_HEAD = 2; public const int ATTACH_LSHOULDER = 3; public const int ATTACH_RSHOULDER = 4; public const int ATTACH_LHAND = 5; public const int ATTACH_RHAND = 6; public const int ATTACH_LFOOT = 7; public const int ATTACH_RFOOT = 8; public const int ATTACH_BACK = 9; public const int ATTACH_PELVIS = 10; public const int ATTACH_MOUTH = 11; public const int ATTACH_CHIN = 12; public const int ATTACH_LEAR = 13; public const int ATTACH_REAR = 14; public const int ATTACH_LEYE = 15; public const int ATTACH_REYE = 16; public const int ATTACH_NOSE = 17; public const int ATTACH_RUARM = 18; public const int ATTACH_RLARM = 19; public const int ATTACH_LUARM = 20; public const int ATTACH_LLARM = 21; public const int ATTACH_RHIP = 22; public const int ATTACH_RULEG = 23; public const int ATTACH_RLLEG = 24; public const int ATTACH_LHIP = 25; public const int ATTACH_LULEG = 26; public const int ATTACH_LLLEG = 27; public const int ATTACH_BELLY = 28; public const int ATTACH_RPEC = 29; public const int ATTACH_LPEC = 30; public const int ATTACH_HUD_CENTER_2 = 31; public const int ATTACH_HUD_TOP_RIGHT = 32; public const int ATTACH_HUD_TOP_CENTER = 33; public const int ATTACH_HUD_TOP_LEFT = 34; public const int ATTACH_HUD_CENTER_1 = 35; public const int ATTACH_HUD_BOTTOM_LEFT = 36; public const int ATTACH_HUD_BOTTOM = 37; public const int ATTACH_HUD_BOTTOM_RIGHT = 38; public const int LAND_LEVEL = 0; public const int LAND_RAISE = 1; public const int LAND_LOWER = 2; public const int LAND_SMOOTH = 3; public const int LAND_NOISE = 4; public const int LAND_REVERT = 5; public const int LAND_SMALL_BRUSH = 1; public const int LAND_MEDIUM_BRUSH = 2; public const int LAND_LARGE_BRUSH = 3; //Agent Dataserver public const int DATA_ONLINE = 1; public const int DATA_NAME = 2; public const int DATA_BORN = 3; public const int DATA_RATING = 4; public const int DATA_SIM_POS = 5; public const int DATA_SIM_STATUS = 6; public const int DATA_SIM_RATING = 7; public const int DATA_PAYINFO = 8; public const int DATA_SIM_RELEASE = 128; public const int ANIM_ON = 1; public const int LOOP = 2; public const int REVERSE = 4; public const int PING_PONG = 8; public const int SMOOTH = 16; public const int ROTATE = 32; public const int SCALE = 64; public const int ALL_SIDES = -1; public const int LINK_SET = -1; public const int LINK_ROOT = 1; public const int LINK_ALL_OTHERS = -2; public const int LINK_ALL_CHILDREN = -3; public const int LINK_THIS = -4; public const int CHANGED_INVENTORY = 1; public const int CHANGED_COLOR = 2; public const int CHANGED_SHAPE = 4; public const int CHANGED_SCALE = 8; public const int CHANGED_TEXTURE = 16; public const int CHANGED_LINK = 32; public const int CHANGED_ALLOWED_DROP = 64; public const int CHANGED_OWNER = 128; public const int CHANGED_REGION_RESTART = 256; public const int CHANGED_REGION = 512; public const int CHANGED_TELEPORT = 1024; public const int CHANGED_ANIMATION = 16384; public const int TYPE_INVALID = 0; public const int TYPE_INTEGER = 1; public const int TYPE_FLOAT = 2; public const int TYPE_STRING = 3; public const int TYPE_KEY = 4; public const int TYPE_VECTOR = 5; public const int TYPE_ROTATION = 6; //XML RPC Remote Data Channel public const int REMOTE_DATA_CHANNEL = 1; public const int REMOTE_DATA_REQUEST = 2; public const int REMOTE_DATA_REPLY = 3; //llHTTPRequest public const int HTTP_METHOD = 0; public const int HTTP_MIMETYPE = 1; public const int HTTP_BODY_MAXLENGTH = 2; public const int HTTP_VERIFY_CERT = 3; public const int PRIM_MATERIAL = 2; public const int PRIM_PHYSICS = 3; public const int PRIM_TEMP_ON_REZ = 4; public const int PRIM_PHANTOM = 5; public const int PRIM_POSITION = 6; public const int PRIM_SIZE = 7; public const int PRIM_ROTATION = 8; public const int PRIM_TYPE = 9; public const int PRIM_TEXTURE = 17; public const int PRIM_COLOR = 18; public const int PRIM_BUMP_SHINY = 19; public const int PRIM_FULLBRIGHT = 20; public const int PRIM_FLEXIBLE = 21; public const int PRIM_TEXGEN = 22; public const int PRIM_CAST_SHADOWS = 24; // Not implemented, here for completeness sake public const int PRIM_POINT_LIGHT = 23; // Huh? public const int PRIM_GLOW = 25; public const int PRIM_TEXGEN_DEFAULT = 0; public const int PRIM_TEXGEN_PLANAR = 1; public const int PRIM_TYPE_BOX = 0; public const int PRIM_TYPE_CYLINDER = 1; public const int PRIM_TYPE_PRISM = 2; public const int PRIM_TYPE_SPHERE = 3; public const int PRIM_TYPE_TORUS = 4; public const int PRIM_TYPE_TUBE = 5; public const int PRIM_TYPE_RING = 6; public const int PRIM_TYPE_SCULPT = 7; public const int PRIM_HOLE_DEFAULT = 0; public const int PRIM_HOLE_CIRCLE = 16; public const int PRIM_HOLE_SQUARE = 32; public const int PRIM_HOLE_TRIANGLE = 48; public const int PRIM_MATERIAL_STONE = 0; public const int PRIM_MATERIAL_METAL = 1; public const int PRIM_MATERIAL_GLASS = 2; public const int PRIM_MATERIAL_WOOD = 3; public const int PRIM_MATERIAL_FLESH = 4; public const int PRIM_MATERIAL_PLASTIC = 5; public const int PRIM_MATERIAL_RUBBER = 6; public const int PRIM_MATERIAL_LIGHT = 7; public const int PRIM_SHINY_NONE = 0; public const int PRIM_SHINY_LOW = 1; public const int PRIM_SHINY_MEDIUM = 2; public const int PRIM_SHINY_HIGH = 3; public const int PRIM_BUMP_NONE = 0; public const int PRIM_BUMP_BRIGHT = 1; public const int PRIM_BUMP_DARK = 2; public const int PRIM_BUMP_WOOD = 3; public const int PRIM_BUMP_BARK = 4; public const int PRIM_BUMP_BRICKS = 5; public const int PRIM_BUMP_CHECKER = 6; public const int PRIM_BUMP_CONCRETE = 7; public const int PRIM_BUMP_TILE = 8; public const int PRIM_BUMP_STONE = 9; public const int PRIM_BUMP_DISKS = 10; public const int PRIM_BUMP_GRAVEL = 11; public const int PRIM_BUMP_BLOBS = 12; public const int PRIM_BUMP_SIDING = 13; public const int PRIM_BUMP_LARGETILE = 14; public const int PRIM_BUMP_STUCCO = 15; public const int PRIM_BUMP_SUCTION = 16; public const int PRIM_BUMP_WEAVE = 17; public const int PRIM_SCULPT_TYPE_SPHERE = 1; public const int PRIM_SCULPT_TYPE_TORUS = 2; public const int PRIM_SCULPT_TYPE_PLANE = 3; public const int PRIM_SCULPT_TYPE_CYLINDER = 4; public const int MASK_BASE = 0; public const int MASK_OWNER = 1; public const int MASK_GROUP = 2; public const int MASK_EVERYONE = 3; public const int MASK_NEXT = 4; public const int PERM_TRANSFER = 8192; public const int PERM_MODIFY = 16384; public const int PERM_COPY = 32768; public const int PERM_MOVE = 524288; public const int PERM_ALL = 2147483647; public const int PARCEL_MEDIA_COMMAND_STOP = 0; public const int PARCEL_MEDIA_COMMAND_PAUSE = 1; public const int PARCEL_MEDIA_COMMAND_PLAY = 2; public const int PARCEL_MEDIA_COMMAND_LOOP = 3; public const int PARCEL_MEDIA_COMMAND_TEXTURE = 4; public const int PARCEL_MEDIA_COMMAND_URL = 5; public const int PARCEL_MEDIA_COMMAND_TIME = 6; public const int PARCEL_MEDIA_COMMAND_AGENT = 7; public const int PARCEL_MEDIA_COMMAND_UNLOAD = 8; public const int PARCEL_MEDIA_COMMAND_AUTO_ALIGN = 9; public const int PARCEL_MEDIA_COMMAND_TYPE = 10; public const int PARCEL_MEDIA_COMMAND_SIZE = 11; public const int PARCEL_MEDIA_COMMAND_DESC = 12; public const int PARCEL_FLAG_ALLOW_FLY = 0x1; // parcel allows flying public const int PARCEL_FLAG_ALLOW_SCRIPTS = 0x2; // parcel allows outside scripts public const int PARCEL_FLAG_ALLOW_LANDMARK = 0x8; // parcel allows landmarks to be created public const int PARCEL_FLAG_ALLOW_TERRAFORM = 0x10; // parcel allows anyone to terraform the land public const int PARCEL_FLAG_ALLOW_DAMAGE = 0x20; // parcel allows damage public const int PARCEL_FLAG_ALLOW_CREATE_OBJECTS = 0x40; // parcel allows anyone to create objects public const int PARCEL_FLAG_USE_ACCESS_GROUP = 0x100; // parcel limits access to a group public const int PARCEL_FLAG_USE_ACCESS_LIST = 0x200; // parcel limits access to a list of residents public const int PARCEL_FLAG_USE_BAN_LIST = 0x400; // parcel uses a ban list, including restricting access based on payment info public const int PARCEL_FLAG_USE_LAND_PASS_LIST = 0x800; // parcel allows passes to be purchased public const int PARCEL_FLAG_LOCAL_SOUND_ONLY = 0x8000; // parcel restricts spatialized sound to the parcel public const int PARCEL_FLAG_RESTRICT_PUSHOBJECT = 0x200000; // parcel restricts llPushObject public const int PARCEL_FLAG_ALLOW_GROUP_SCRIPTS = 0x2000000; // parcel allows scripts owned by group public const int PARCEL_FLAG_ALLOW_CREATE_GROUP_OBJECTS = 0x4000000; // parcel allows group object creation public const int PARCEL_FLAG_ALLOW_ALL_OBJECT_ENTRY = 0x8000000; // parcel allows objects owned by any user to enter public const int PARCEL_FLAG_ALLOW_GROUP_OBJECT_ENTRY = 0x10000000; // parcel allows with the same group to enter public const int REGION_FLAG_ALLOW_DAMAGE = 0x1; // region is entirely damage enabled public const int REGION_FLAG_FIXED_SUN = 0x10; // region has a fixed sun position public const int REGION_FLAG_BLOCK_TERRAFORM = 0x40; // region terraforming disabled public const int REGION_FLAG_SANDBOX = 0x100; // region is a sandbox public const int REGION_FLAG_DISABLE_COLLISIONS = 0x1000; // region has disabled collisions public const int REGION_FLAG_DISABLE_PHYSICS = 0x4000; // region has disabled physics public const int REGION_FLAG_BLOCK_FLY = 0x80000; // region blocks flying public const int REGION_FLAG_ALLOW_DIRECT_TELEPORT = 0x100000; // region allows direct teleports public const int REGION_FLAG_RESTRICT_PUSHOBJECT = 0x400000; // region restricts llPushObject public static readonly LSLInteger PAY_HIDE = new LSLInteger(-1); public static readonly LSLInteger PAY_DEFAULT = new LSLInteger(-2); public const string NULL_KEY = "00000000-0000-0000-0000-000000000000"; public const string EOF = "\n\n\n"; public const double PI = 3.14159274f; public const double TWO_PI = 6.28318548f; public const double PI_BY_TWO = 1.57079637f; public const double DEG_TO_RAD = 0.01745329238f; public const double RAD_TO_DEG = 57.29578f; public const double SQRT2 = 1.414213538f; public const int STRING_TRIM_HEAD = 1; public const int STRING_TRIM_TAIL = 2; public const int STRING_TRIM = 3; public const int LIST_STAT_RANGE = 0; public const int LIST_STAT_MIN = 1; public const int LIST_STAT_MAX = 2; public const int LIST_STAT_MEAN = 3; public const int LIST_STAT_MEDIAN = 4; public const int LIST_STAT_STD_DEV = 5; public const int LIST_STAT_SUM = 6; public const int LIST_STAT_SUM_SQUARES = 7; public const int LIST_STAT_NUM_COUNT = 8; public const int LIST_STAT_GEOMETRIC_MEAN = 9; public const int LIST_STAT_HARMONIC_MEAN = 100; //ParcelPrim Categories public const int PARCEL_COUNT_TOTAL = 0; public const int PARCEL_COUNT_OWNER = 1; public const int PARCEL_COUNT_GROUP = 2; public const int PARCEL_COUNT_OTHER = 3; public const int PARCEL_COUNT_SELECTED = 4; public const int PARCEL_COUNT_TEMP = 5; public const int DEBUG_CHANNEL = 0x7FFFFFFF; public const int PUBLIC_CHANNEL = 0x00000000; public const int OBJECT_NAME = 1; public const int OBJECT_DESC = 2; public const int OBJECT_POS = 3; public const int OBJECT_ROT = 4; public const int OBJECT_VELOCITY = 5; public const int OBJECT_OWNER = 6; public const int OBJECT_GROUP = 7; public const int OBJECT_CREATOR = 8; // Can not be public const? public static readonly vector ZERO_VECTOR = new vector(0.0, 0.0, 0.0); public static readonly rotation ZERO_ROTATION = new rotation(0.0, 0.0, 0.0, 1.0); // constants for llSetCameraParams public const int CAMERA_PITCH = 0; public const int CAMERA_FOCUS_OFFSET = 1; public const int CAMERA_FOCUS_OFFSET_X = 2; public const int CAMERA_FOCUS_OFFSET_Y = 3; public const int CAMERA_FOCUS_OFFSET_Z = 4; public const int CAMERA_POSITION_LAG = 5; public const int CAMERA_FOCUS_LAG = 6; public const int CAMERA_DISTANCE = 7; public const int CAMERA_BEHINDNESS_ANGLE = 8; public const int CAMERA_BEHINDNESS_LAG = 9; public const int CAMERA_POSITION_THRESHOLD = 10; public const int CAMERA_FOCUS_THRESHOLD = 11; public const int CAMERA_ACTIVE = 12; public const int CAMERA_POSITION = 13; public const int CAMERA_POSITION_X = 14; public const int CAMERA_POSITION_Y = 15; public const int CAMERA_POSITION_Z = 16; public const int CAMERA_FOCUS = 17; public const int CAMERA_FOCUS_X = 18; public const int CAMERA_FOCUS_Y = 19; public const int CAMERA_FOCUS_Z = 20; public const int CAMERA_POSITION_LOCKED = 21; public const int CAMERA_FOCUS_LOCKED = 22; // constants for llGetParcelDetails public const int PARCEL_DETAILS_NAME = 0; public const int PARCEL_DETAILS_DESC = 1; public const int PARCEL_DETAILS_OWNER = 2; public const int PARCEL_DETAILS_GROUP = 3; public const int PARCEL_DETAILS_AREA = 4; // constants for llSetClickAction public const int CLICK_ACTION_NONE = 0; public const int CLICK_ACTION_TOUCH = 0; public const int CLICK_ACTION_SIT = 1; public const int CLICK_ACTION_BUY = 2; public const int CLICK_ACTION_PAY = 3; public const int CLICK_ACTION_OPEN = 4; public const int CLICK_ACTION_PLAY = 5; public const int CLICK_ACTION_OPEN_MEDIA = 6; // constants for the llDetectedTouch* functions public const int TOUCH_INVALID_FACE = -1; public static readonly vector TOUCH_INVALID_TEXCOORD = new vector(-1.0, -1.0, 0.0); public static readonly vector TOUCH_INVALID_VECTOR = ZERO_VECTOR; // Constants for default textures public const string TEXTURE_BLANK = "5748decc-f629-461c-9a36-a35a221fe21f"; public const string TEXTURE_DEFAULT = "89556747-24cb-43ed-920b-47caed15465f"; public const string TEXTURE_PLYWOOD = "89556747-24cb-43ed-920b-47caed15465f"; public const string TEXTURE_TRANSPARENT = "8dcd4a48-2d37-4909-9f78-f7a9eb4ef903"; public const string TEXTURE_MEDIA = "8b5fec65-8d8d-9dc5-cda8-8fdf2716e361"; } }
#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.Threading.Async { /// <summary> /// AsyncResultWrapper /// </summary> #if COREINTERNAL internal #else public #endif static class AsyncResultWrapper { public static IAsyncResult Begin(AsyncCallback callback, object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate) { return Begin<AsyncVoid>(callback, state, beginDelegate, MakeVoidDelegate(endDelegate), null); } public static IAsyncResult Begin(AsyncCallback callback, object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, object tag) { return Begin<AsyncVoid>(callback, state, beginDelegate, MakeVoidDelegate(endDelegate), tag, -1); } public static IAsyncResult Begin(AsyncCallback callback, object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, object tag, int timeout) { return Begin<AsyncVoid>(callback, state, beginDelegate, MakeVoidDelegate(endDelegate), tag, timeout); } public static IAsyncResult Begin<TResult>(AsyncCallback callback, object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate<TResult> endDelegate) { return Begin<TResult>(callback, state, beginDelegate, endDelegate, null); } public static IAsyncResult Begin<TResult>(AsyncCallback callback, object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate<TResult> endDelegate, object tag) { return Begin<TResult>(callback, state, beginDelegate, endDelegate, tag, -1); } public static IAsyncResult Begin<TResult>(AsyncCallback callback, object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate<TResult> endDelegate, object tag, int timeout) { WrappedAsyncResult<TResult> result = new WrappedAsyncResult<TResult>(beginDelegate, endDelegate, tag); result.Begin(callback, state, timeout); return result; } public static IAsyncResult BeginSynchronous(AsyncCallback callback, object state, Action action) { return BeginSynchronous<AsyncVoid>(callback, state, MakeVoidDelegate(action), null); } public static IAsyncResult BeginSynchronous(AsyncCallback callback, object state, Action action, object tag) { return BeginSynchronous<AsyncVoid>(callback, state, MakeVoidDelegate(action), tag); } public static IAsyncResult BeginSynchronous<TResult>(AsyncCallback callback, object state, Func<TResult> func) { return BeginSynchronous<TResult>(callback, state, func, null); } public static IAsyncResult BeginSynchronous<TResult>(AsyncCallback callback, object state, Func<TResult> func, object tag) { BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) { var result2 = new SimpleAsyncResult(asyncState); result2.MarkCompleted(true, asyncCallback); return result2; }; EndInvokeDelegate<TResult> endDelegate = (_ => func()); var result = new WrappedAsyncResult<TResult>(beginDelegate, endDelegate, tag); result.Begin(callback, state, -1); return result; } public static TResult End<TResult>(IAsyncResult asyncResult) { return End<TResult>(asyncResult, null); } public static void End(IAsyncResult asyncResult) { End<AsyncVoid>(asyncResult, null); } public static void End(IAsyncResult asyncResult, object tag) { End<AsyncVoid>(asyncResult, tag); } public static TResult End<TResult>(IAsyncResult asyncResult, object tag) { return WrappedAsyncResult<TResult>.Cast(asyncResult, tag).End(); } private static Func<AsyncVoid> MakeVoidDelegate(Action action) { return () => { action(); return new AsyncVoid(); }; } private static EndInvokeDelegate<AsyncVoid> MakeVoidDelegate(EndInvokeDelegate endDelegate) { return (IAsyncResult ar) => { endDelegate(ar); return new AsyncVoid(); }; } /// <summary> /// WrappedAsyncResult /// </summary> private sealed class WrappedAsyncResult<TResult> : IAsyncResult { private readonly BeginInvokeDelegate _beginDelegate; private readonly object _beginDelegateLockObj; private readonly EndInvokeDelegate<TResult> _endDelegate; private readonly SingleEntryGate _endExecutedGate; private readonly SingleEntryGate _handleCallbackGate; private IAsyncResult _innerAsyncResult; private AsyncCallback _originalCallback; private readonly object _tag; private volatile bool _timedOut; private Timer _timer; public WrappedAsyncResult(BeginInvokeDelegate beginDelegate, EndInvokeDelegate<TResult> endDelegate, object tag) { _beginDelegateLockObj = new object(); _endExecutedGate = new SingleEntryGate(); _handleCallbackGate = new SingleEntryGate(); _beginDelegate = beginDelegate; _endDelegate = endDelegate; _tag = tag; } public void Begin(AsyncCallback callback, object state, int timeout) { bool completedSynchronously; _originalCallback = callback; lock (_beginDelegateLockObj) { _innerAsyncResult = _beginDelegate(new AsyncCallback(HandleAsynchronousCompletion), state); completedSynchronously = _innerAsyncResult.CompletedSynchronously; if (!completedSynchronously && (timeout > -1)) CreateTimer(timeout); } if (completedSynchronously && (callback != null)) callback(this); } public static AsyncResultWrapper.WrappedAsyncResult<TResult> Cast(IAsyncResult asyncResult, object tag) { if (asyncResult == null) throw new ArgumentNullException("asyncResult"); var result = (asyncResult as AsyncResultWrapper.WrappedAsyncResult<TResult>); if ((result == null) || !object.Equals(result._tag, tag)) throw new InvalidOperationException(); // Error.AsyncCommon_InvalidAsyncResult("asyncResult"); return result; } private void CreateTimer(int timeout) { _timer = new Timer(new TimerCallback(HandleTimeout), null, timeout, -1); } public TResult End() { if (!_endExecutedGate.TryEnter()) throw new InvalidOperationException(); // Error.AsyncCommon_AsyncResultAlreadyConsumed(); if (_timedOut) throw new TimeoutException(); WaitForBeginToCompleteAndDestroyTimer(); return _endDelegate(this._innerAsyncResult); } private void ExecuteAsynchronousCallback(bool timedOut) { WaitForBeginToCompleteAndDestroyTimer(); if (_handleCallbackGate.TryEnter()) { _timedOut = timedOut; if (_originalCallback != null) _originalCallback(this); } } private void HandleAsynchronousCompletion(IAsyncResult asyncResult) { if (!asyncResult.CompletedSynchronously) ExecuteAsynchronousCallback(false); } private void HandleTimeout(object state) { ExecuteAsynchronousCallback(true); } private void WaitForBeginToCompleteAndDestroyTimer() { lock (_beginDelegateLockObj) { if (_timer != null) _timer.Dispose(); _timer = null; } } public object AsyncState { get { return _innerAsyncResult.AsyncState; } } public WaitHandle AsyncWaitHandle { get { return _innerAsyncResult.AsyncWaitHandle; } } public bool CompletedSynchronously { get { return _innerAsyncResult.CompletedSynchronously; } } public bool IsCompleted { get { return _innerAsyncResult.IsCompleted; } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace CustomerManager.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ // @Generated by gentest/gentest.rb from gentest/fixtures/YGMinMaxDimensionTest.html using System; using NUnit.Framework; namespace Facebook.Yoga { [TestFixture] public class YGMinMaxDimensionTest { [Test] public void Test_max_width() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.MaxWidth = 50; root_child0.Height = 10; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); } [Test] public void Test_max_height() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 10; root_child0.MaxHeight = 50; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(90f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); } [Test] public void Test_min_height() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.FlexGrow = 1; root_child0.MinHeight = 60; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.FlexGrow = 1; root.Insert(1, root_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(80f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(80f, root_child1.LayoutY); Assert.AreEqual(100f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(80f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(80f, root_child1.LayoutY); Assert.AreEqual(100f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); } [Test] public void Test_min_width() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.FlexGrow = 1; root_child0.MinWidth = 60; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.FlexGrow = 1; root.Insert(1, root_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(80f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(80f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(20f, root_child1.LayoutWidth); Assert.AreEqual(100f, root_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(20f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(80f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(20f, root_child1.LayoutWidth); Assert.AreEqual(100f, root_child1.LayoutHeight); } [Test] public void Test_justify_content_min_max() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.Width = 100; root.MinHeight = 100; root.MaxHeight = 200; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 60; root_child0.Height = 60; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(20f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(60f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(40f, root_child0.LayoutX); Assert.AreEqual(20f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(60f, root_child0.LayoutHeight); } [Test] public void Test_align_items_min_max() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignItems = YogaAlign.Center; root.MinWidth = 100; root.MaxWidth = 200; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 60; root_child0.Height = 60; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(20f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(60f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(20f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(60f, root_child0.LayoutHeight); } [Test] public void Test_justify_content_overflow_min_max() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.MinHeight = 100; root.MaxHeight = 110; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 50; root_child1.Height = 50; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 50; root_child2.Height = 50; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(50f, root.LayoutWidth); Assert.AreEqual(110f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(-20f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(30f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(80f, root_child2.LayoutY); Assert.AreEqual(50f, root_child2.LayoutWidth); Assert.AreEqual(50f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(50f, root.LayoutWidth); Assert.AreEqual(110f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(-20f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(30f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(80f, root_child2.LayoutY); Assert.AreEqual(50f, root_child2.LayoutWidth); Assert.AreEqual(50f, root_child2.LayoutHeight); } [Test] public void Test_flex_grow_to_min() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 100; root.MinHeight = 100; root.MaxHeight = 500; YogaNode root_child0 = new YogaNode(config); root_child0.FlexGrow = 1; root_child0.FlexShrink = 1; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Height = 50; root.Insert(1, root_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(100f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(100f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); } [Test] public void Test_flex_grow_in_at_most_container() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.FlexStart; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.FlexDirection = YogaFlexDirection.Row; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.FlexGrow = 1; root_child0_child0.FlexBasis = 0; root_child0.Insert(0, root_child0_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(0f, root_child0.LayoutWidth); Assert.AreEqual(0f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(0f, root_child0_child0.LayoutWidth); Assert.AreEqual(0f, root_child0_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(100f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(0f, root_child0.LayoutWidth); Assert.AreEqual(0f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(0f, root_child0_child0.LayoutWidth); Assert.AreEqual(0f, root_child0_child0.LayoutHeight); } [Test] public void Test_flex_grow_child() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; YogaNode root_child0 = new YogaNode(config); root_child0.FlexGrow = 1; root_child0.FlexBasis = 0; root_child0.Height = 100; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(0f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(0f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(0f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(0f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); } [Test] public void Test_flex_grow_within_constrained_min_max_column() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.MinHeight = 100; root.MaxHeight = 200; YogaNode root_child0 = new YogaNode(config); root_child0.FlexGrow = 1; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Height = 50; root.Insert(1, root_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(0f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(0f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(0f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(0f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(0f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(0f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); } [Test] public void Test_flex_grow_within_max_width() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 200; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.FlexDirection = YogaFlexDirection.Row; root_child0.MaxWidth = 100; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.FlexGrow = 1; root_child0_child0.Height = 20; root_child0.Insert(0, root_child0_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(20f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(100f, root_child0_child0.LayoutWidth); Assert.AreEqual(20f, root_child0_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(100f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(20f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(100f, root_child0_child0.LayoutWidth); Assert.AreEqual(20f, root_child0_child0.LayoutHeight); } [Test] public void Test_flex_grow_within_constrained_max_width() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 200; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.FlexDirection = YogaFlexDirection.Row; root_child0.MaxWidth = 300; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.FlexGrow = 1; root_child0_child0.Height = 20; root_child0.Insert(0, root_child0_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(200f, root_child0.LayoutWidth); Assert.AreEqual(20f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(200f, root_child0_child0.LayoutWidth); Assert.AreEqual(20f, root_child0_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(200f, root_child0.LayoutWidth); Assert.AreEqual(20f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(200f, root_child0_child0.LayoutWidth); Assert.AreEqual(20f, root_child0_child0.LayoutHeight); } [Test] public void Test_flex_grow_within_constrained_min_row() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.MinWidth = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.FlexGrow = 1; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 50; root.Insert(1, root_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(100f, root_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(100f, root_child1.LayoutHeight); } [Test] public void Test_flex_grow_within_constrained_min_column() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.MinHeight = 100; YogaNode root_child0 = new YogaNode(config); root_child0.FlexGrow = 1; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Height = 50; root.Insert(1, root_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(0f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(0f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(0f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(0f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(0f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(0f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); } [Test] public void Test_flex_grow_within_constrained_max_row() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 200; YogaNode root_child0 = new YogaNode(config); root_child0.FlexDirection = YogaFlexDirection.Row; root_child0.MaxWidth = 100; root_child0.Height = 100; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.FlexShrink = 1; root_child0_child0.FlexBasis = 100; root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child1 = new YogaNode(config); root_child0_child1.Width = 50; root_child0.Insert(1, root_child0_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(50f, root_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0.LayoutHeight); Assert.AreEqual(50f, root_child0_child1.LayoutX); Assert.AreEqual(0f, root_child0_child1.LayoutY); Assert.AreEqual(50f, root_child0_child1.LayoutWidth); Assert.AreEqual(100f, root_child0_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(100f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(50f, root_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child1.LayoutX); Assert.AreEqual(0f, root_child0_child1.LayoutY); Assert.AreEqual(50f, root_child0_child1.LayoutWidth); Assert.AreEqual(100f, root_child0_child1.LayoutHeight); } [Test] public void Test_flex_grow_within_constrained_max_column() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 100; root.MaxHeight = 100; YogaNode root_child0 = new YogaNode(config); root_child0.FlexShrink = 1; root_child0.FlexBasis = 100; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Height = 50; root.Insert(1, root_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(100f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(100f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); } [Test] public void Test_child_min_max_width_flexing() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.Width = 120; root.Height = 50; YogaNode root_child0 = new YogaNode(config); root_child0.FlexGrow = 1; root_child0.FlexBasis = 0; root_child0.MinWidth = 60; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.FlexGrow = 1; root_child1.FlexBasis = 50.Percent(); root_child1.MaxWidth = 20; root.Insert(1, root_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(120f, root.LayoutWidth); Assert.AreEqual(50f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(100f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(20f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(120f, root.LayoutWidth); Assert.AreEqual(50f, root.LayoutHeight); Assert.AreEqual(20f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(20f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); } [Test] public void Test_min_width_overrides_width() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 50; root.MinWidth = 100; root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(0f, root.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(0f, root.LayoutHeight); } [Test] public void Test_max_width_overrides_width() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 200; root.MaxWidth = 100; root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(0f, root.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(0f, root.LayoutHeight); } [Test] public void Test_min_height_overrides_height() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Height = 50; root.MinHeight = 100; root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(0f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(0f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); } [Test] public void Test_max_height_overrides_height() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Height = 200; root.MaxHeight = 100; root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(0f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(0f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); } [Test] public void Test_min_max_percent_no_width_height() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignItems = YogaAlign.FlexStart; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.MinWidth = 10.Percent(); root_child0.MaxWidth = 10.Percent(); root_child0.MinHeight = 10.Percent(); root_child0.MaxHeight = 10.Percent(); root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(90f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); } } }
using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using Orleans.Runtime.Configuration; namespace Orleans.Runtime { internal class SocketManager { private readonly LRU<IPEndPoint, Socket> cache; private const int MAX_SOCKETS = 200; internal SocketManager(IMessagingConfiguration config) { cache = new LRU<IPEndPoint, Socket>(MAX_SOCKETS, config.MaxSocketAge, SendingSocketCreator); cache.RaiseFlushEvent += FlushHandler; } /// <summary> /// Creates a socket bound to an address for use accepting connections. /// This is for use by client gateways and other acceptors. /// </summary> /// <param name="address">The address to bind to.</param> /// <returns>The new socket, appropriately bound.</returns> internal static Socket GetAcceptingSocketForEndpoint(IPEndPoint address) { var s = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { // Prep the socket so it will reset on close s.LingerState = new LingerOption(true, 0); s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); // And bind it to the address s.Bind(address); } catch (Exception) { CloseSocket(s); throw; } return s; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal bool CheckSendingSocket(IPEndPoint target) { return cache.ContainsKey(target); } internal Socket GetSendingSocket(IPEndPoint target) { return cache.Get(target); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private Socket SendingSocketCreator(IPEndPoint target) { var s = new Socket(target.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { s.Connect(target); // Prep the socket so it will reset on close and won't Nagle s.LingerState = new LingerOption(true, 0); s.NoDelay = true; WriteConnectionPreemble(s, Constants.SiloDirectConnectionId); // Identifies this client as a direct silo-to-silo socket // Start an asynch receive off of the socket to detect closure var receiveAsyncEventArgs = new SocketAsyncEventArgs { BufferList = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[4]) }, UserToken = new Tuple<Socket, IPEndPoint, SocketManager>(s, target, this) }; receiveAsyncEventArgs.Completed += ReceiveCallback; bool receiveCompleted = s.ReceiveAsync(receiveAsyncEventArgs); NetworkingStatisticsGroup.OnOpenedSendingSocket(); if (!receiveCompleted) { ReceiveCallback(this, receiveAsyncEventArgs); } } catch (Exception) { try { s.Dispose(); } catch (Exception) { // ignore } throw; } return s; } internal static void WriteConnectionPreemble(Socket socket, GrainId grainId) { int size = 0; byte[] grainIdByteArray = null; if (grainId != null) { grainIdByteArray = grainId.ToByteArray(); size += grainIdByteArray.Length; } ByteArrayBuilder sizeArray = new ByteArrayBuilder(); sizeArray.Append(size); socket.Send(sizeArray.ToBytes()); // The size of the data that is coming next. //socket.Send(guid.ToByteArray()); // The guid of client/silo id if (grainId != null) { // No need to send in a loop. // From MSDN: If you are using a connection-oriented protocol, Send will block until all of the bytes in the buffer are sent, // unless a time-out was set by using Socket.SendTimeout. // If the time-out value was exceeded, the Send call will throw a SocketException. socket.Send(grainIdByteArray); // The grainId of the client } } // We start an asynch receive, with this callback, off of every send socket. // Since we should never see data coming in on these sockets, having the receive complete means that // the socket is in an unknown state and we should close it and try again. private static void ReceiveCallback(object sender, SocketAsyncEventArgs socketAsyncEventArgs) { var t = socketAsyncEventArgs.UserToken as Tuple<Socket, IPEndPoint, SocketManager>; try { t?.Item3.InvalidateEntry(t.Item2); } catch (Exception ex) { LogManager.GetLogger("SocketManager", LoggerType.Runtime).Error(ErrorCode.Messaging_Socket_ReceiveError, $"ReceiveCallback: {t?.Item2}", ex); } finally { socketAsyncEventArgs.Dispose(); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "s")] internal void ReturnSendingSocket(Socket s) { // Do nothing -- the socket will get cleaned up when it gets flushed from the cache } private static void FlushHandler(Object sender, LRU<IPEndPoint, Socket>.FlushEventArgs args) { if (args.Value == null) return; CloseSocket(args.Value); NetworkingStatisticsGroup.OnClosedSendingSocket(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] internal void InvalidateEntry(IPEndPoint target) { Socket socket; if (!cache.RemoveKey(target, out socket)) return; CloseSocket(socket); NetworkingStatisticsGroup.OnClosedSendingSocket(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] // Note that this method assumes that there are no other threads accessing this object while this method runs. // Since this is true for the MessageCenter's use of this object, we don't lock around all calls to avoid the overhead. internal void Stop() { // Clear() on an LRU<> calls the flush handler on every item, so no need to manually close the sockets. cache.Clear(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] internal static void CloseSocket(Socket s) { if (s == null) { return; } try { s.Shutdown(SocketShutdown.Both); } catch (ObjectDisposedException) { // Socket is already closed -- we're done here return; } catch (Exception) { // Ignore } try { s.Disconnect(false); } catch (Exception) { // Ignore } try { s.Dispose(); } catch (Exception) { // Ignore } } } }
using System; using System.Linq; using System.Reflection; using FluentNHibernate.Conventions.Instances; using FluentNHibernate.MappingModel; using FluentNHibernate.MappingModel.ClassBased; using FluentNHibernate.MappingModel.Identity; namespace FluentNHibernate.Conventions.Inspections { public class ClassInspector : IClassInspector { private readonly ClassMapping mapping; private readonly InspectorModelMapper<IClassInspector, ClassMapping> propertyMappings = new InspectorModelMapper<IClassInspector, ClassMapping>(); public ClassInspector(ClassMapping mapping) { this.mapping = mapping; propertyMappings.Map(x => x.LazyLoad, x => x.Lazy); propertyMappings.Map(x => x.ReadOnly, x => x.Mutable); propertyMappings.Map(x => x.EntityType, x => x.Type); } public Type EntityType { get { return mapping.Type; } } public string StringIdentifierForModel { get { return mapping.Name; } } public bool LazyLoad { get { return mapping.Lazy; } } public bool ReadOnly { get { return !mapping.Mutable; } } public string TableName { get { return mapping.TableName; } } ICacheInspector IClassInspector.Cache { get { return Cache; } } public ICacheInstance Cache { get { if (mapping.Cache == null) // conventions are hitting it, user must want a cache mapping.Cache = new CacheMapping(); return new CacheInstance(mapping.Cache); } } public OptimisticLock OptimisticLock { get { return OptimisticLock.FromString(mapping.OptimisticLock); } } public SchemaAction SchemaAction { get { return SchemaAction.FromString(mapping.SchemaAction); } } public string Schema { get { return mapping.Schema; } } public bool DynamicUpdate { get { return mapping.DynamicUpdate; } } public bool DynamicInsert { get { return mapping.DynamicInsert; } } public int BatchSize { get { return mapping.BatchSize; } } public bool Abstract { get { return mapping.Abstract; } } public IVersionInspector Version { get { if (mapping.Version == null) return new VersionInspector(new VersionMapping()); return new VersionInspector(mapping.Version); } } public IDefaultableEnumerable<IAnyInspector> Anys { get { return mapping.Anys .Select(x => new AnyInspector(x)) .Cast<IAnyInspector>() .ToDefaultableList(); } } public string Check { get { return mapping.Check; } } public IDefaultableEnumerable<ICollectionInspector> Collections { get { return mapping.Collections .Select(x => new CollectionInspector(x)) .Cast<ICollectionInspector>() .ToDefaultableList(); } } public IDefaultableEnumerable<IComponentBaseInspector> Components { get { return mapping.Components .Select(x => { if (x is ComponentMapping) return (IComponentBaseInspector)new ComponentInspector((ComponentMapping)x); return (IComponentBaseInspector)new DynamicComponentInspector((DynamicComponentMapping)x); }) .ToDefaultableList(); } } public IDefaultableEnumerable<IJoinInspector> Joins { get { return mapping.Joins .Select(x => new JoinInspector(x)) .Cast<IJoinInspector>() .ToDefaultableList(); } } public IDefaultableEnumerable<IOneToOneInspector> OneToOnes { get { return mapping.OneToOnes .Select(x => new OneToOneInspector(x)) .Cast<IOneToOneInspector>() .ToDefaultableList(); } } public IDefaultableEnumerable<IPropertyInspector> Properties { get { return mapping.Properties .Select(x => new PropertyInspector(x)) .Cast<IPropertyInspector>() .ToDefaultableList(); } } public IDefaultableEnumerable<IManyToOneInspector> References { get { return mapping.References .Select(x => new ManyToOneInspector(x)) .Cast<IManyToOneInspector>() .ToDefaultableList(); } } public IDefaultableEnumerable<ISubclassInspectorBase> Subclasses { get { return mapping.Subclasses .Where(x => x is SubclassMapping) .Select(x => { if (x is SubclassMapping) return (ISubclassInspectorBase)new SubclassInspector((SubclassMapping)x); return (ISubclassInspectorBase)new JoinedSubclassInspector((JoinedSubclassMapping)x); }) .Cast<ISubclassInspectorBase>() .ToDefaultableList(); } } public IDiscriminatorInspector Discriminator { get { if (mapping.Discriminator == null) // deliberately empty so nothing evaluates to true return new DiscriminatorInspector(new DiscriminatorMapping()); return new DiscriminatorInspector(mapping.Discriminator); } } public object DiscriminatorValue { get { return mapping.DiscriminatorValue; } } public string Name { get { return mapping.Name; } } public string Persister { get { return mapping.Persister; } } public Polymorphism Polymorphism { get { return Polymorphism.FromString(mapping.Polymorphism); } } public string Proxy { get { return mapping.Proxy; } } public string Where { get { return mapping.Where; } } public string Subselect { get { return mapping.Subselect; } } public bool SelectBeforeUpdate { get { return mapping.SelectBeforeUpdate; } } public IIdentityInspectorBase Id { get { if (mapping.Id == null) return new IdentityInspector(new IdMapping()); if (mapping.Id is CompositeIdMapping) return new CompositeIdentityInspector((CompositeIdMapping)mapping.Id); return new IdentityInspector((IdMapping)mapping.Id); } } public bool IsSet(PropertyInfo property) { return mapping.IsSpecified(propertyMappings.Get(property)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: This is the value class representing a Unicode character ** Char methods until we create this functionality. ** ** ===========================================================*/ using System; using System.Globalization; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Diagnostics.Contracts; namespace System { [System.Runtime.InteropServices.ComVisible(true)] [StructLayout(LayoutKind.Sequential)] public struct Char : IComparable, IComparable<Char>, IEquatable<Char>, IConvertible { // // Member Variables // internal char m_value; // // Public Constants // // The maximum character value. public const char MaxValue = (char)0xFFFF; // The minimum character value. public const char MinValue = (char)0x00; internal const char HIGH_SURROGATE_START_CHAR = '\ud800'; internal const char HIGH_SURROGATE_END_CHAR = '\udbff'; internal const char LOW_SURROGATE_START_CHAR = '\udc00'; internal const char LOW_SURROGATE_END_CHAR = '\udfff'; // Unicode category values from Unicode U+0000 ~ U+00FF. Store them in byte[] array to save space. private readonly static byte[] s_categoryForLatin1 = { (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0000 - 0007 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0008 - 000F (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0010 - 0017 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0018 - 001F (byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0020 - 0027 (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0028 - 002F (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, // 0030 - 0037 (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, // 0038 - 003F (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0040 - 0047 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0048 - 004F (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0050 - 0057 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.ConnectorPunctuation, // 0058 - 005F (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0060 - 0067 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0068 - 006F (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0070 - 0077 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.Control, // 0078 - 007F (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0080 - 0087 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0088 - 008F (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0090 - 0097 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0098 - 009F (byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherSymbol, // 00A0 - 00A7 (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.InitialQuotePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.ModifierSymbol, // 00A8 - 00AF (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherPunctuation, // 00B0 - 00B7 (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.FinalQuotePunctuation, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherPunctuation, // 00B8 - 00BF (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C0 - 00C7 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C8 - 00CF (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00D0 - 00D7 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00D8 - 00DF (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E0 - 00E7 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E8 - 00EF (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00F0 - 00F7 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00F8 - 00FF }; // Return true for all characters below or equal U+00ff, which is ASCII + Latin-1 Supplement. private static bool IsLatin1(char ch) { return (ch <= '\x00ff'); } // Return true for all characters below or equal U+007f, which is ASCII. private static bool IsAscii(char ch) { return (ch <= '\x007f'); } // Return the Unicode category for Unicode character <= 0x00ff. private static UnicodeCategory GetLatin1UnicodeCategory(char ch) { Contract.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f"); return (UnicodeCategory)(s_categoryForLatin1[(int)ch]); } // // Private Constants // // // Overriden Instance Methods // // Calculate a hashcode for a 2 byte Unicode character. public override int GetHashCode() { return (int)m_value | ((int)m_value << 16); } // Used for comparing two boxed Char objects. // public override bool Equals(Object obj) { if (!(obj is Char)) { return false; } return (m_value == ((Char)obj).m_value); } public bool Equals(Char obj) { return m_value == obj; } // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Char, this method throws an ArgumentException. // [Pure] int IComparable.CompareTo(Object value) { if (value == null) { return 1; } if (!(value is Char)) { throw new ArgumentException(SR.Arg_MustBeChar); } return (m_value - ((Char)value).m_value); } [Pure] public int CompareTo(Char value) { return (m_value - value); } // Overrides System.Object.ToString. [Pure] public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Char.ToString(m_value); } [Pure] String IConvertible.ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Char.ToString(m_value); } // // Formatting Methods // /*===================================ToString=================================== **This static methods takes a character and returns the String representation of it. ==============================================================================*/ // Provides a string representation of a character. [Pure] public static string ToString(char c) => string.CreateFromChar(c); public static char Parse(String s) { if (s == null) { throw new ArgumentNullException("s"); } Contract.EndContractBlock(); if (s.Length != 1) { throw new FormatException(SR.Format_NeedSingleChar); } return s[0]; } public static bool TryParse(String s, out Char result) { result = '\0'; if (s == null) { return false; } if (s.Length != 1) { return false; } result = s[0]; return true; } // // Static Methods // /*=================================ISDIGIT====================================== **A wrapper for Char. Returns a boolean indicating whether ** **character c is considered to be a digit. ** ==============================================================================*/ // Determines whether a character is a digit. [Pure] public static bool IsDigit(char c) { if (IsLatin1(c)) { return (c >= '0' && c <= '9'); } return (FormatProvider.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber); } /*=================================CheckLetter===================================== ** Check if the specified UnicodeCategory belongs to the letter categories. ==============================================================================*/ internal static bool CheckLetter(UnicodeCategory uc) { switch (uc) { case (UnicodeCategory.UppercaseLetter): case (UnicodeCategory.LowercaseLetter): case (UnicodeCategory.TitlecaseLetter): case (UnicodeCategory.ModifierLetter): case (UnicodeCategory.OtherLetter): return (true); } return (false); } /*=================================ISLETTER===================================== **A wrapper for Char. Returns a boolean indicating whether ** **character c is considered to be a letter. ** ==============================================================================*/ // Determines whether a character is a letter. [Pure] public static bool IsLetter(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { c |= (char)0x20; return ((c >= 'a' && c <= 'z')); } return (CheckLetter(GetLatin1UnicodeCategory(c))); } return (CheckLetter(FormatProvider.GetUnicodeCategory(c))); } private static bool IsWhiteSpaceLatin1(char c) { // There are characters which belong to UnicodeCategory.Control but are considered as white spaces. // We use code point comparisons for these characters here as a temporary fix. // U+0009 = <control> HORIZONTAL TAB // U+000a = <control> LINE FEED // U+000b = <control> VERTICAL TAB // U+000c = <contorl> FORM FEED // U+000d = <control> CARRIAGE RETURN // U+0085 = <control> NEXT LINE // U+00a0 = NO-BREAK SPACE if ((c == ' ') || (c >= '\x0009' && c <= '\x000d') || c == '\x00a0' || c == '\x0085') { return (true); } return (false); } internal static bool IsUnicodeWhiteSpace(char c) { UnicodeCategory uc = FormatProvider.GetUnicodeCategory(c); // In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator". // And U+2029 is th eonly character which is under the category "ParagraphSeparator". switch (uc) { case (UnicodeCategory.SpaceSeparator): case (UnicodeCategory.LineSeparator): case (UnicodeCategory.ParagraphSeparator): return (true); } return (false); } /*===============================ISWHITESPACE=================================== **A wrapper for Char. Returns a boolean indicating whether ** **character c is considered to be a whitespace character. ** ==============================================================================*/ // Determines whether a character is whitespace. [Pure] public static bool IsWhiteSpace(char c) { if (IsLatin1(c)) { return (IsWhiteSpaceLatin1(c)); } return IsUnicodeWhiteSpace(c); } /*===================================IsUpper==================================== **Arguments: c -- the characater to be checked. **Returns: True if c is an uppercase character. ==============================================================================*/ // Determines whether a character is upper-case. [Pure] public static bool IsUpper(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= 'A' && c <= 'Z'); } return (GetLatin1UnicodeCategory(c) == UnicodeCategory.UppercaseLetter); } return (FormatProvider.GetUnicodeCategory(c) == UnicodeCategory.UppercaseLetter); } /*===================================IsLower==================================== **Arguments: c -- the characater to be checked. **Returns: True if c is an lowercase character. ==============================================================================*/ // Determines whether a character is lower-case. [Pure] public static bool IsLower(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= 'a' && c <= 'z'); } return (GetLatin1UnicodeCategory(c) == UnicodeCategory.LowercaseLetter); } return (FormatProvider.GetUnicodeCategory(c) == UnicodeCategory.LowercaseLetter); } internal static bool CheckPunctuation(UnicodeCategory uc) { switch (uc) { case UnicodeCategory.ConnectorPunctuation: case UnicodeCategory.DashPunctuation: case UnicodeCategory.OpenPunctuation: case UnicodeCategory.ClosePunctuation: case UnicodeCategory.InitialQuotePunctuation: case UnicodeCategory.FinalQuotePunctuation: case UnicodeCategory.OtherPunctuation: return (true); } return (false); } /*================================IsPunctuation================================= **Arguments: c -- the characater to be checked. **Returns: True if c is an punctuation mark ==============================================================================*/ // Determines whether a character is a punctuation mark. [Pure] public static bool IsPunctuation(char c) { if (IsLatin1(c)) { return (CheckPunctuation(GetLatin1UnicodeCategory(c))); } return (CheckPunctuation(FormatProvider.GetUnicodeCategory(c))); } /*=================================CheckLetterOrDigit===================================== ** Check if the specified UnicodeCategory belongs to the letter or digit categories. ==============================================================================*/ internal static bool CheckLetterOrDigit(UnicodeCategory uc) { switch (uc) { case UnicodeCategory.UppercaseLetter: case UnicodeCategory.LowercaseLetter: case UnicodeCategory.TitlecaseLetter: case UnicodeCategory.ModifierLetter: case UnicodeCategory.OtherLetter: case UnicodeCategory.DecimalDigitNumber: return (true); } return (false); } // Determines whether a character is a letter or a digit. [Pure] public static bool IsLetterOrDigit(char c) { if (IsLatin1(c)) { return (CheckLetterOrDigit(GetLatin1UnicodeCategory(c))); } return (CheckLetterOrDigit(FormatProvider.GetUnicodeCategory(c))); } /*=================================TOUPPER====================================== **A wrapper for Char.toUpperCase. Converts character c to its ** **uppercase equivalent. If c is already an uppercase character or is not an ** **alphabetic, nothing happens. ** ==============================================================================*/ // Converts a character to upper-case for the default culture. // public static char ToUpper(char c) { return FormatProvider.ToUpper(c); } // Converts a character to upper-case for invariant culture. public static char ToUpperInvariant(char c) { return FormatProvider.ToUpperInvariant(c); } /*=================================TOLOWER====================================== **A wrapper for Char.toLowerCase. Converts character c to its ** **lowercase equivalent. If c is already a lowercase character or is not an ** **alphabetic, nothing happens. ** ==============================================================================*/ // Converts a character to lower-case for the default culture. public static char ToLower(char c) { return FormatProvider.ToLower(c); } // Converts a character to lower-case for invariant culture. public static char ToLowerInvariant(char c) { return FormatProvider.ToLowerInvariant(c); } // // IConvertible implementation // [Pure] TypeCode IConvertible.GetTypeCode() { return TypeCode.Char; } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Char", "Boolean")); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { return m_value; } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Char", "Single")); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Char", "Double")); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Char", "Decimal")); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Char", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } public static bool IsControl(char c) { if (IsLatin1(c)) { return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control); } return (FormatProvider.GetUnicodeCategory(c) == UnicodeCategory.Control); } public static bool IsControl(String s, int index) { if (s == null) throw new ArgumentNullException("s"); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException("index"); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control); } return (FormatProvider.GetUnicodeCategory(s, index) == UnicodeCategory.Control); } public static bool IsDigit(String s, int index) { if (s == null) throw new ArgumentNullException("s"); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException("index"); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { return (c >= '0' && c <= '9'); } return (FormatProvider.GetUnicodeCategory(s, index) == UnicodeCategory.DecimalDigitNumber); } public static bool IsLetter(String s, int index) { if (s == null) throw new ArgumentNullException("s"); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException("index"); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { c |= (char)0x20; return ((c >= 'a' && c <= 'z')); } return (CheckLetter(GetLatin1UnicodeCategory(c))); } return (CheckLetter(FormatProvider.GetUnicodeCategory(s, index))); } public static bool IsLetterOrDigit(String s, int index) { if (s == null) throw new ArgumentNullException("s"); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException("index"); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { return CheckLetterOrDigit(GetLatin1UnicodeCategory(c)); } return CheckLetterOrDigit(FormatProvider.GetUnicodeCategory(s, index)); } public static bool IsLower(String s, int index) { if (s == null) throw new ArgumentNullException("s"); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException("index"); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= 'a' && c <= 'z'); } return (GetLatin1UnicodeCategory(c) == UnicodeCategory.LowercaseLetter); } return (FormatProvider.GetUnicodeCategory(s, index) == UnicodeCategory.LowercaseLetter); } /*=================================CheckNumber===================================== ** Check if the specified UnicodeCategory belongs to the number categories. ==============================================================================*/ internal static bool CheckNumber(UnicodeCategory uc) { switch (uc) { case (UnicodeCategory.DecimalDigitNumber): case (UnicodeCategory.LetterNumber): case (UnicodeCategory.OtherNumber): return (true); } return (false); } public static bool IsNumber(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= '0' && c <= '9'); } return (CheckNumber(GetLatin1UnicodeCategory(c))); } return (CheckNumber(FormatProvider.GetUnicodeCategory(c))); } public static bool IsNumber(String s, int index) { if (s == null) throw new ArgumentNullException("s"); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException("index"); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= '0' && c <= '9'); } return (CheckNumber(GetLatin1UnicodeCategory(c))); } return (CheckNumber(FormatProvider.GetUnicodeCategory(s, index))); } //////////////////////////////////////////////////////////////////////// // // IsPunctuation // // Determines if the given character is a punctuation character. // //////////////////////////////////////////////////////////////////////// public static bool IsPunctuation(String s, int index) { if (s == null) throw new ArgumentNullException("s"); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException("index"); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { return (CheckPunctuation(GetLatin1UnicodeCategory(c))); } return (CheckPunctuation(FormatProvider.GetUnicodeCategory(s, index))); } /*================================= CheckSeparator ============================ ** Check if the specified UnicodeCategory belongs to the seprator categories. ==============================================================================*/ internal static bool CheckSeparator(UnicodeCategory uc) { switch (uc) { case UnicodeCategory.SpaceSeparator: case UnicodeCategory.LineSeparator: case UnicodeCategory.ParagraphSeparator: return (true); } return (false); } private static bool IsSeparatorLatin1(char c) { // U+00a0 = NO-BREAK SPACE // There is no LineSeparator or ParagraphSeparator in Latin 1 range. return (c == '\x0020' || c == '\x00a0'); } public static bool IsSeparator(char c) { if (IsLatin1(c)) { return (IsSeparatorLatin1(c)); } return (CheckSeparator(FormatProvider.GetUnicodeCategory(c))); } public static bool IsSeparator(String s, int index) { if (s == null) throw new ArgumentNullException("s"); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException("index"); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { return (IsSeparatorLatin1(c)); } return (CheckSeparator(FormatProvider.GetUnicodeCategory(s, index))); } [Pure] public static bool IsSurrogate(char c) { return (c >= HIGH_SURROGATE_START && c <= LOW_SURROGATE_END); } [Pure] public static bool IsSurrogate(String s, int index) { if (s == null) { throw new ArgumentNullException("s"); } if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException("index"); } Contract.EndContractBlock(); return (IsSurrogate(s[index])); } /*================================= CheckSymbol ============================ ** Check if the specified UnicodeCategory belongs to the symbol categories. ==============================================================================*/ internal static bool CheckSymbol(UnicodeCategory uc) { switch (uc) { case (UnicodeCategory.MathSymbol): case (UnicodeCategory.CurrencySymbol): case (UnicodeCategory.ModifierSymbol): case (UnicodeCategory.OtherSymbol): return (true); } return (false); } public static bool IsSymbol(char c) { if (IsLatin1(c)) { return (CheckSymbol(GetLatin1UnicodeCategory(c))); } return (CheckSymbol(FormatProvider.GetUnicodeCategory(c))); } public static bool IsSymbol(String s, int index) { if (s == null) throw new ArgumentNullException("s"); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException("index"); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { return (CheckSymbol(GetLatin1UnicodeCategory(c))); } return (CheckSymbol(FormatProvider.GetUnicodeCategory(s, index))); } public static bool IsUpper(String s, int index) { if (s == null) throw new ArgumentNullException("s"); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException("index"); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= 'A' && c <= 'Z'); } return (GetLatin1UnicodeCategory(c) == UnicodeCategory.UppercaseLetter); } return (FormatProvider.GetUnicodeCategory(s, index) == UnicodeCategory.UppercaseLetter); } internal static bool IsUnicodeWhiteSpace(String s, int index) { Contract.Assert(s != null, "s!=null"); Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); UnicodeCategory uc = FormatProvider.GetUnicodeCategory(s, index); // In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator". // And U+2029 is th eonly character which is under the category "ParagraphSeparator". switch (uc) { case (UnicodeCategory.SpaceSeparator): case (UnicodeCategory.LineSeparator): case (UnicodeCategory.ParagraphSeparator): return (true); } return (false); } public static bool IsWhiteSpace(String s, int index) { if (s == null) throw new ArgumentNullException("s"); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException("index"); } Contract.EndContractBlock(); if (IsLatin1(s[index])) { return IsWhiteSpaceLatin1(s[index]); } return IsUnicodeWhiteSpace(s, index); } //public static UnicodeCategory GetUnicodeCategory(char c) //{ // if (IsLatin1(c)) { // return (GetLatin1UnicodeCategory(c)); // } // return FormatProvider.InternalGetUnicodeCategory(c); //} //public static UnicodeCategory GetUnicodeCategory(String s, int index) //{ // if (s==null) // throw new ArgumentNullException("s"); // if (((uint)index)>=((uint)s.Length)) { // throw new ArgumentOutOfRangeException("index"); // } // Contract.EndContractBlock(); // if (IsLatin1(s[index])) { // return (GetLatin1UnicodeCategory(s[index])); // } // return FormatProvider.InternalGetUnicodeCategory(s, index); //} public static double GetNumericValue(char c) { return FormatProvider.GetNumericValue(c); } public static double GetNumericValue(String s, int index) { if (s == null) throw new ArgumentNullException("s"); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException("index"); } Contract.EndContractBlock(); return FormatProvider.GetNumericValue(s, index); } /*================================= IsHighSurrogate ============================ ** Check if a char is a high surrogate. ==============================================================================*/ [Pure] public static bool IsHighSurrogate(char c) { return ((c >= HIGH_SURROGATE_START_CHAR) && (c <= HIGH_SURROGATE_END_CHAR)); } [Pure] public static bool IsHighSurrogate(String s, int index) { if (s == null) { throw new ArgumentNullException("s"); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException("index"); } Contract.EndContractBlock(); return (IsHighSurrogate(s[index])); } /*================================= IsLowSurrogate ============================ ** Check if a char is a low surrogate. ==============================================================================*/ [Pure] public static bool IsLowSurrogate(char c) { return ((c >= LOW_SURROGATE_START_CHAR) && (c <= LOW_SURROGATE_END_CHAR)); } [Pure] public static bool IsLowSurrogate(String s, int index) { if (s == null) { throw new ArgumentNullException("s"); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException("index"); } Contract.EndContractBlock(); return (IsLowSurrogate(s[index])); } /*================================= IsSurrogatePair ============================ ** Check if the string specified by the index starts with a surrogate pair. ==============================================================================*/ [Pure] public static bool IsSurrogatePair(String s, int index) { if (s == null) { throw new ArgumentNullException("s"); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException("index"); } Contract.EndContractBlock(); if (index + 1 < s.Length) { return (IsSurrogatePair(s[index], s[index + 1])); } return (false); } [Pure] public static bool IsSurrogatePair(char highSurrogate, char lowSurrogate) { return ((highSurrogate >= Char.HIGH_SURROGATE_START_CHAR && highSurrogate <= Char.HIGH_SURROGATE_END_CHAR) && (lowSurrogate >= Char.LOW_SURROGATE_START_CHAR && lowSurrogate <= Char.LOW_SURROGATE_END_CHAR)); } internal const int UNICODE_PLANE00_END = 0x00ffff; // The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff. internal const int UNICODE_PLANE01_START = 0x10000; // The end codepoint for Unicode plane 16. This is the maximum code point value allowed for Unicode. // Plane 16 contains 0x100000 ~ 0x10ffff. internal const int UNICODE_PLANE16_END = 0x10ffff; internal const int HIGH_SURROGATE_START = 0x00d800; internal const int LOW_SURROGATE_END = 0x00dfff; /*================================= ConvertFromUtf32 ============================ ** Convert an UTF32 value into a surrogate pair. ==============================================================================*/ public static String ConvertFromUtf32(int utf32) { // For UTF32 values from U+00D800 ~ U+00DFFF, we should throw. They // are considered as irregular code unit sequence, but they are not illegal. if ((utf32 < 0 || utf32 > UNICODE_PLANE16_END) || (utf32 >= HIGH_SURROGATE_START && utf32 <= LOW_SURROGATE_END)) { throw new ArgumentOutOfRangeException("utf32", SR.ArgumentOutOfRange_InvalidUTF32); } Contract.EndContractBlock(); if (utf32 < UNICODE_PLANE01_START) { // This is a BMP character. return (Char.ToString((char)utf32)); } unsafe { // This is a supplementary character. Convert it to a surrogate pair in UTF-16. utf32 -= UNICODE_PLANE01_START; uint surrogate = 0; // allocate 2 chars worth of stack space char* address = (char*)&surrogate; address[0] = (char)((utf32 / 0x400) + (int)CharUnicodeInfo.HIGH_SURROGATE_START); address[1] = (char)((utf32 % 0x400) + (int)CharUnicodeInfo.LOW_SURROGATE_START); return new string(address, 0, 2); } } /*=============================ConvertToUtf32=================================== ** Convert a surrogate pair to UTF32 value ==============================================================================*/ public static int ConvertToUtf32(char highSurrogate, char lowSurrogate) { if (!IsHighSurrogate(highSurrogate)) { throw new ArgumentOutOfRangeException("highSurrogate", SR.ArgumentOutOfRange_InvalidHighSurrogate); } if (!IsLowSurrogate(lowSurrogate)) { throw new ArgumentOutOfRangeException("lowSurrogate", SR.ArgumentOutOfRange_InvalidLowSurrogate); } Contract.EndContractBlock(); return (((highSurrogate - Char.HIGH_SURROGATE_START_CHAR) * 0x400) + (lowSurrogate - Char.LOW_SURROGATE_START_CHAR) + UNICODE_PLANE01_START); } /*=============================ConvertToUtf32=================================== ** Convert a character or a surrogate pair starting at index of the specified string ** to UTF32 value. ** The char pointed by index should be a surrogate pair or a BMP character. ** This method throws if a high-surrogate is not followed by a low surrogate. ** This method throws if a low surrogate is seen without preceding a high-surrogate. ==============================================================================*/ public static int ConvertToUtf32(String s, int index) { if (s == null) { throw new ArgumentNullException("s"); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } Contract.EndContractBlock(); // Check if the character at index is a high surrogate. int temp1 = (int)s[index] - Char.HIGH_SURROGATE_START_CHAR; if (temp1 >= 0 && temp1 <= 0x7ff) { // Found a surrogate char. if (temp1 <= 0x3ff) { // Found a high surrogate. if (index < s.Length - 1) { int temp2 = (int)s[index + 1] - Char.LOW_SURROGATE_START_CHAR; if (temp2 >= 0 && temp2 <= 0x3ff) { // Found a low surrogate. return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START); } else { throw new ArgumentException(SR.Format(SR.Argument_InvalidHighSurrogate, index), "s"); } } else { // Found a high surrogate at the end of the string. throw new ArgumentException(SR.Format(SR.Argument_InvalidHighSurrogate, index), "s"); } } else { // Find a low surrogate at the character pointed by index. throw new ArgumentException(SR.Format(SR.Argument_InvalidLowSurrogate, index), "s"); } } // Not a high-surrogate or low-surrogate. Genereate the UTF32 value for the BMP characters. return ((int)s[index]); } } }
#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.ComponentModel; using Spring.Util; using System.Reflection; #endregion namespace Spring.Core.TypeConversion { /// <summary> /// Utility methods that are used to convert objects from one type into another. /// </summary> /// <author>Aleksandar Seovic</author> public class TypeConversionUtils { /// <summary> /// Convert the value to the required <see cref="System.Type"/> (if necessary from a string). /// </summary> /// <param name="newValue">The proposed change value.</param> /// <param name="requiredType"> /// The <see cref="System.Type"/> we must convert to. /// </param> /// <param name="propertyName">Property name, used for error reporting purposes...</param> /// <exception cref="Spring.Objects.ObjectsException"> /// If there is an internal error. /// </exception> /// <returns>The new value, possibly the result of type conversion.</returns> public static object ConvertValueIfNecessary(Type requiredType, object newValue, string propertyName) { if (newValue != null) { // if it is assignable, return the value right away if (IsAssignableFrom(newValue, requiredType)) { return newValue; } // if required type is an array, convert all the elements if (requiredType != null && requiredType.IsArray) { // convert individual elements to array elements Type componentType = requiredType.GetElementType(); if (newValue is ICollection) { ICollection elements = (ICollection)newValue; return ToArrayWithTypeConversion(componentType, elements, propertyName); } else if (newValue is string) { if (requiredType.Equals(typeof(char[]))) { return ((string)newValue).ToCharArray(); } else { string[] elements = StringUtils.CommaDelimitedListToStringArray((string)newValue); return ToArrayWithTypeConversion(componentType, elements, propertyName); } } else if (!newValue.GetType().IsArray) { // A plain value: convert it to an array with a single component. Array result = Array.CreateInstance(componentType, 1); object val = ConvertValueIfNecessary(componentType, newValue, propertyName); result.SetValue(val, 0); return result; } } // if required type is some ISet<T>, convert all the elements if (requiredType != null && requiredType.IsGenericType && TypeImplementsGenericInterface(requiredType, typeof(Spring.Collections.Generic.ISet<>))) { // convert individual elements to array elements Type componentType = requiredType.GetGenericArguments()[0]; if (newValue is ICollection) { ICollection elements = (ICollection)newValue; return ToTypedCollectionWithTypeConversion(typeof(Spring.Collections.Generic.HashedSet<>), componentType, elements, propertyName); } } // if required type is some IList<T>, convert all the elements if (requiredType != null && requiredType.IsGenericType && TypeImplementsGenericInterface(requiredType, typeof(IList<>))) { // convert individual elements to array elements Type componentType = requiredType.GetGenericArguments()[0]; if (newValue is ICollection) { ICollection elements = (ICollection)newValue; return ToTypedCollectionWithTypeConversion(typeof(List<>), componentType, elements, propertyName); } } // if required type is some IDictionary<K,V>, convert all the elements if (requiredType != null && requiredType.IsGenericType && TypeImplementsGenericInterface(requiredType, typeof(IDictionary<,>))) { Type[] typeParameters = requiredType.GetGenericArguments(); Type keyType = typeParameters[0]; Type valueType = typeParameters[1]; if (newValue is IDictionary) { IDictionary elements = (IDictionary)newValue; Type targetCollectionType = typeof(Dictionary<,>); Type collectionType = targetCollectionType.MakeGenericType(new Type[] { keyType, valueType }); object typedCollection = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add", new Type[] { keyType, valueType }); int i = 0; foreach (DictionaryEntry entry in elements) { string propertyExpr = BuildIndexedPropertyName(propertyName, i); object key = ConvertValueIfNecessary(keyType, entry.Key, propertyExpr + ".Key"); object value = ConvertValueIfNecessary(valueType, entry.Value, propertyExpr + ".Value"); addMethod.Invoke(typedCollection, new object[] { key, value }); i++; } return typedCollection; } } // if required type is some IEnumerable<T>, convert all the elements if (requiredType != null && requiredType.IsGenericType && TypeImplementsGenericInterface(requiredType, typeof(IEnumerable<>))) { // convert individual elements to array elements Type componentType = requiredType.GetGenericArguments()[0]; if (newValue is ICollection) { ICollection elements = (ICollection)newValue; return ToTypedCollectionWithTypeConversion(typeof(List<>), componentType, elements, propertyName); } } // try to convert using type converter try { TypeConverter typeConverter = TypeConverterRegistry.GetConverter(requiredType); if (typeConverter != null && typeConverter.CanConvertFrom(newValue.GetType())) { try { newValue = typeConverter.ConvertFrom(newValue); } catch { if (newValue is string) { newValue = typeConverter.ConvertFromInvariantString((string)newValue); } } } else { typeConverter = TypeConverterRegistry.GetConverter(newValue.GetType()); if (typeConverter != null && typeConverter.CanConvertTo(requiredType)) { newValue = typeConverter.ConvertTo(newValue, requiredType); } else { // look if it's an enum if (requiredType != null && requiredType.IsEnum && (!(newValue is float) && (!(newValue is double)))) { // convert numeric value into enum's underlying type Type numericType = Enum.GetUnderlyingType(requiredType); newValue = Convert.ChangeType(newValue, numericType); if (Enum.IsDefined(requiredType, newValue)) { newValue = Enum.ToObject(requiredType, newValue); } else { throw new TypeMismatchException( CreatePropertyChangeEventArgs(propertyName, null, newValue), requiredType); } } else if (newValue is IConvertible) { // last resort - try ChangeType newValue = Convert.ChangeType(newValue, requiredType); } else { throw new TypeMismatchException( CreatePropertyChangeEventArgs(propertyName, null, newValue), requiredType); } } } } catch (Exception ex) { throw new TypeMismatchException( CreatePropertyChangeEventArgs(propertyName, null, newValue), requiredType, ex); } if (newValue == null && (requiredType == null || !Type.GetType("System.Nullable`1").Equals(requiredType.GetGenericTypeDefinition()))) { throw new TypeMismatchException( CreatePropertyChangeEventArgs(propertyName, null, newValue), requiredType); } } return newValue; } private static object ToArrayWithTypeConversion(Type componentType, ICollection elements, string propertyName) { Array destination = Array.CreateInstance(componentType, elements.Count); int i = 0; foreach (object element in elements) { object value = ConvertValueIfNecessary(componentType, element, BuildIndexedPropertyName(propertyName, i)); destination.SetValue(value, i); i++; } return destination; } private static object ToTypedCollectionWithTypeConversion(Type targetCollectionType, Type componentType, ICollection elements, string propertyName) { if (!TypeImplementsGenericInterface(targetCollectionType, typeof(ICollection<>))) { throw new ArgumentException("argument must be a type that derives from ICollection<T>", "targetCollectionType"); } Type collectionType = targetCollectionType.MakeGenericType(new Type[] { componentType }); object typedCollection = Activator.CreateInstance(collectionType); int i = 0; foreach (object element in elements) { object value = ConvertValueIfNecessary(componentType, element, BuildIndexedPropertyName(propertyName, i)); collectionType.GetMethod("Add").Invoke(typedCollection, new object[] { value }); i++; } return typedCollection; } private static string BuildIndexedPropertyName(string propertyName, int index) { return (propertyName != null ? propertyName + "[" + index + "]" : null); } private static bool IsAssignableFrom(object newValue, Type requiredType) { if (newValue is MarshalByRefObject) { //TODO see what type of type checking can be done. May need to //preserve information when proxy was created by SaoServiceExporter. return true; } if (requiredType == null) { return false; } return requiredType.IsAssignableFrom(newValue.GetType()); } /// <summary> /// Utility method to create a property change event. /// </summary> /// <param name="fullPropertyName"> /// The full name of the property that has changed. /// </param> /// <param name="oldValue">The property old value</param> /// <param name="newValue">The property new value</param> /// <returns> /// A new <see cref="Spring.Core.PropertyChangeEventArgs"/>. /// </returns> private static PropertyChangeEventArgs CreatePropertyChangeEventArgs(string fullPropertyName, object oldValue, object newValue) { return new PropertyChangeEventArgs(fullPropertyName, oldValue, newValue); } /// <summary> /// Determines if a Type implements a specific generic interface. /// </summary> /// <param name="candidateType">Candidate <see lang="Type"/> to evaluate.</param> /// <param name="matchingInterface">The <see lang="interface"/> to test for in the Candidate <see lang="Type"/>.</param> /// <returns><see lang="true" /> if a match, else <see lang="false"/></returns> private static bool TypeImplementsGenericInterface(Type candidateType, Type matchingInterface) { if (!matchingInterface.IsInterface) { throw new ArgumentException("matchingInterface Type must be an Interface Type", "matchingInterface"); } if (candidateType.IsInterface && IsMatchingGenericInterface(candidateType, matchingInterface)) { return true; } bool match = false; Type[] implementedInterfaces = candidateType.GetInterfaces(); foreach (Type interfaceType in implementedInterfaces) { if (IsMatchingGenericInterface(interfaceType, matchingInterface)) { match = true; break; } } return match; } private static bool IsMatchingGenericInterface(Type candidateInterfaceType, Type matchingGenericInterface) { return candidateInterfaceType.IsGenericType && candidateInterfaceType.GetGenericTypeDefinition() == matchingGenericInterface; } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Web; using ASC.Core; using ASC.Data.Storage.Configuration; using ASC.Security.Cryptography; namespace ASC.Data.Storage { public abstract class BaseStorage : IDataStore { #region IDataStore Members internal string _modulename; internal DataList _dataList; internal string _tenant; internal Dictionary<string, TimeSpan> _domainsExpires = new Dictionary<string, TimeSpan>(); public IQuotaController QuotaController { get; set; } public TimeSpan GetExpire(string domain) { return _domainsExpires.ContainsKey(domain) ? _domainsExpires[domain] : _domainsExpires[string.Empty]; } public Uri GetUri(string path) { return GetUri(string.Empty, path); } public Uri GetUri(string domain, string path) { return GetPreSignedUri(domain, path, TimeSpan.MaxValue, null); } public Uri GetPreSignedUri(string domain, string path, TimeSpan expire, IEnumerable<string> headers) { if (path == null) { throw new ArgumentNullException("path"); } if (string.IsNullOrEmpty(_tenant) && IsSupportInternalUri) { return GetInternalUri(domain, path, expire, headers); } var headerAttr = string.Empty; if (headers != null) { headerAttr = string.Join("&", headers.Select(HttpUtility.UrlEncode)); } if (expire == TimeSpan.Zero || expire == TimeSpan.MinValue || expire == TimeSpan.MaxValue) { expire = GetExpire(domain); } var query = string.Empty; if (expire != TimeSpan.Zero && expire != TimeSpan.MinValue && expire != TimeSpan.MaxValue) { var expireString = expire.TotalMinutes.ToString(CultureInfo.InvariantCulture); int currentTenantId; var currentTenant = CoreContext.TenantManager.GetCurrentTenant(false); if (currentTenant != null) { currentTenantId = currentTenant.TenantId; } else if (!TenantPath.TryGetTenant(_tenant, out currentTenantId)) { currentTenantId = 0; } var auth = EmailValidationKeyProvider.GetEmailKey(currentTenantId, path.Replace('/', Path.DirectorySeparatorChar).Replace('\\', Path.DirectorySeparatorChar) + "." + headerAttr + "." + expireString); query = string.Format("{0}{1}={2}&{3}={4}", path.Contains("?") ? "&" : "?", Constants.QUERY_EXPIRE, expireString, Constants.QUERY_AUTH, auth); } if (!string.IsNullOrEmpty(headerAttr)) { query += string.Format("{0}{1}={2}", query.Contains("?") ? "&" : "?", Constants.QUERY_HEADER, HttpUtility.UrlEncode(headerAttr)); } var tenant = _tenant.Trim('/'); var vpath = PathUtils.ResolveVirtualPath(_modulename, domain); vpath = PathUtils.ResolveVirtualPath(vpath, false); vpath = string.Format(vpath, tenant); var virtualPath = new Uri(vpath + "/", UriKind.RelativeOrAbsolute); var uri = virtualPath.IsAbsoluteUri ? new MonoUri(virtualPath, virtualPath.LocalPath.TrimEnd('/') + EnsureLeadingSlash(path.Replace('\\', '/')) + query) : new MonoUri(virtualPath.ToString().TrimEnd('/') + EnsureLeadingSlash(path.Replace('\\', '/')) + query, UriKind.Relative); return uri; } public virtual bool IsSupportInternalUri { get { return true; } } public virtual Uri GetInternalUri(string domain, string path, TimeSpan expire, IEnumerable<string> headers) { return null; } public abstract Stream GetReadStream(string domain, string path); public abstract Stream GetReadStream(string domain, string path, int offset); public abstract Task<Stream> GetReadStreamAsync(string domain, string path, int offset); public abstract Uri Save(string domain, string path, Stream stream); public abstract Uri Save(string domain, string path, Stream stream, ACL acl); public Uri Save(string domain, string path, Stream stream, string attachmentFileName) { if (!string.IsNullOrEmpty(attachmentFileName)) { return SaveWithAutoAttachment(domain, path, stream, attachmentFileName); } return Save(domain, path, stream); } protected abstract Uri SaveWithAutoAttachment(string domain, string path, Stream stream, string attachmentFileName); public abstract Uri Save(string domain, string path, Stream stream, string contentType, string contentDisposition); public abstract Uri Save(string domain, string path, Stream stream, string contentEncoding, int cacheDays); public virtual bool IsSupportedPreSignedUri { get { return true; } } #region chunking public virtual string InitiateChunkedUpload(string domain, string path) { throw new NotImplementedException(); } public virtual string UploadChunk(string domain, string path, string uploadId, Stream stream, long defaultChunkSize, int chunkNumber, long chunkLength) { throw new NotImplementedException(); } public virtual Uri FinalizeChunkedUpload(string domain, string path, string uploadId, Dictionary<int, string> eTags) { throw new NotImplementedException(); } public virtual void AbortChunkedUpload(string domain, string path, string uploadId) { throw new NotImplementedException(); } public virtual bool IsSupportChunking { get { return false; } } #endregion public abstract void Delete(string domain, string path); public abstract void DeleteFiles(string domain, string folderPath, string pattern, bool recursive); public abstract void DeleteFiles(string domain, List<string> paths); public abstract void DeleteFiles(string domain, string folderPath, DateTime fromDate, DateTime toDate); public abstract void MoveDirectory(string srcdomain, string srcdir, string newdomain, string newdir); public abstract Uri Move(string srcdomain, string srcpath, string newdomain, string newpath, bool quotaCheckFileSize = true); public abstract Uri SaveTemp(string domain, out string assignedPath, Stream stream); public abstract string[] ListDirectoriesRelative(string domain, string path, bool recursive); public abstract string[] ListFilesRelative(string domain, string path, string pattern, bool recursive); public abstract bool IsFile(string domain, string path); public abstract Task<bool> IsFileAsync(string domain, string path); public abstract bool IsDirectory(string domain, string path); public abstract void DeleteDirectory(string domain, string path); public abstract long GetFileSize(string domain, string path); public abstract Task<long> GetFileSizeAsync(string domain, string path); public abstract long GetDirectorySize(string domain, string path); public abstract long ResetQuota(string domain); public abstract long GetUsedQuota(string domain); public abstract Uri Copy(string srcdomain, string path, string newdomain, string newpath); public abstract void CopyDirectory(string srcdomain, string dir, string newdomain, string newdir); public Stream GetReadStream(string path) { return GetReadStream(string.Empty, path); } public Uri Save(string path, Stream stream, string attachmentFileName) { return Save(string.Empty, path, stream, attachmentFileName); } public Uri Save(string path, Stream stream) { return Save(string.Empty, path, stream); } public void Delete(string path) { Delete(string.Empty, path); } public void DeleteFiles(string folderPath, string pattern, bool recursive) { DeleteFiles(string.Empty, folderPath, pattern, recursive); } public Uri Move(string srcpath, string newdomain, string newpath) { return Move(string.Empty, srcpath, newdomain, newpath); } public Uri SaveTemp(out string assignedPath, Stream stream) { return SaveTemp(string.Empty, out assignedPath, stream); } public string[] ListDirectoriesRelative(string path, bool recursive) { return ListDirectoriesRelative(string.Empty, path, recursive); } public Uri[] ListFiles(string path, string pattern, bool recursive) { return ListFiles(string.Empty, path, pattern, recursive); } public Uri[] ListFiles(string domain, string path, string pattern, bool recursive) { var filePaths = ListFilesRelative(domain, path, pattern, recursive); return Array.ConvertAll( filePaths, x => GetUri(domain, Path.Combine(PathUtils.Normalize(path), x))); } public bool IsFile(string path) { return IsFile(string.Empty, path); } public bool IsDirectory(string path) { return IsDirectory(string.Empty, path); } public void DeleteDirectory(string path) { DeleteDirectory(string.Empty, path); } public long GetFileSize(string path) { return GetFileSize(string.Empty, path); } public long GetDirectorySize(string path) { return GetDirectorySize(string.Empty, path); } public Uri Copy(string path, string newdomain, string newpath) { return Copy(string.Empty, path, newdomain, newpath); } public void CopyDirectory(string dir, string newdomain, string newdir) { CopyDirectory(string.Empty, dir, newdomain, newdir); } public virtual IDataStore Configure(IDictionary<string, string> props) { return this; } public IDataStore SetQuotaController(IQuotaController controller) { QuotaController = controller; return this; } public abstract string SavePrivate(string domain, string path, Stream stream, DateTime expires); public abstract void DeleteExpired(string domain, string path, TimeSpan oldThreshold); public abstract string GetUploadForm(string domain, string directoryPath, string redirectTo, long maxUploadSize, string contentType, string contentDisposition, string submitLabel); public abstract string GetUploadedUrl(string domain, string directoryPath); public abstract string GetUploadUrl(); public abstract string GetPostParams(string domain, string directoryPath, long maxUploadSize, string contentType, string contentDisposition); #endregion internal void QuotaUsedAdd(string domain, long size, bool quotaCheckFileSize = true) { if (QuotaController != null) { QuotaController.QuotaUsedAdd(_modulename, domain, _dataList.GetData(domain), size, quotaCheckFileSize); } } internal void QuotaUsedDelete(string domain, long size) { if (QuotaController != null) { QuotaController.QuotaUsedDelete(_modulename, domain, _dataList.GetData(domain), size); } } internal static string EnsureLeadingSlash(string str) { return "/" + str.TrimStart('/'); } internal class MonoUri : Uri { public MonoUri(Uri baseUri, string relativeUri) : base(baseUri, relativeUri) { } public MonoUri(string uriString, UriKind uriKind) : base(uriString, uriKind) { } public override string ToString() { var s = base.ToString(); if (WorkContext.IsMono && s.StartsWith(UriSchemeFile + SchemeDelimiter)) { return s.Substring(7); } return s; } } } }
namespace Gu.State { using System; using System.ComponentModel; using System.Reflection; using System.Text; /// <summary> /// Methods for checking if tracking dirty will work. /// </summary> public static partial class Track { /// <summary> /// Check if the properties of <typeparamref name="T"/> can be tracked. /// This method will throw an exception if copy cannot be performed for <typeparamref name="T"/> /// Read the exception message for detailed instructions about what is wrong. /// Use this to fail fast or in unit tests. /// </summary> /// <typeparam name="T">The type to get ignore properties for settings for.</typeparam> /// <param name="referenceHandling"> /// If Structural is used property values for sub properties are copied for the entire graph. /// Activator.CreateInstance is sued to new up references so a default constructor is required, can be private. /// </param> /// <param name="bindingFlags"> /// The binding flags to use when getting properties /// Default is BindingFlags.Instance | BindingFlags.Public. /// </param> public static void VerifyCanTrackIsDirty<T>( ReferenceHandling referenceHandling = ReferenceHandling.Structural, BindingFlags bindingFlags = Constants.DefaultPropertyBindingFlags) where T : class, INotifyPropertyChanged { var settings = PropertiesSettings.GetOrCreate(referenceHandling, bindingFlags); VerifyCanTrackIsDirty<T>(settings); } /// <summary> /// Check if the properties of <typeparamref name="T"/> can be tracked. /// This method will throw an exception if copy cannot be performed for <typeparamref name="T"/> /// Read the exception message for detailed instructions about what is wrong. /// Use this to fail fast or in unit tests. /// </summary> /// <typeparam name="T">The type to track.</typeparam> /// <param name="settings">Contains configuration for how tracking is performed.</param> public static void VerifyCanTrackIsDirty<T>(PropertiesSettings settings) where T : class, INotifyPropertyChanged { VerifyCanTrackIsDirty(typeof(T), settings); } /// <summary> /// Check if the properties of <paramref name="type"/> can be tracked. /// This method will throw an exception if copy cannot be performed for <paramref name="type"/> /// Read the exception message for detailed instructions about what is wrong. /// Use this to fail fast or in unit tests. /// </summary> /// <param name="type">The type to track.</param> /// <param name="settings">Contains configuration for how tracking is performed.</param> public static void VerifyCanTrackIsDirty(Type type, PropertiesSettings settings) { VerifyCanTrackIsDirty(type, settings, typeof(Track).Name, nameof(VerifyCanTrackIsDirty)); } /// <summary> /// Check if the properties of <typeparamref name="T"/> can be tracked. /// This method will throw an exception if synchronization cannot be performed for <typeparamref name="T"/> /// Read the exception message for detailed instructions about what is wrong. /// Use this to fail fast or in unit tests. /// </summary> /// <typeparam name="T">The type to check.</typeparam> /// <param name="referenceHandling"> /// If Structural is used property values for sub properties are copied for the entire graph. /// Activator.CreateInstance is used to new up references so a default constructor is required, can be private. /// </param> /// <param name="bindingFlags">The binding flags to use when getting properties.</param> public static void VerifyCanTrackChanges<T>( ReferenceHandling referenceHandling = ReferenceHandling.Structural, BindingFlags bindingFlags = Constants.DefaultPropertyBindingFlags) { var settings = PropertiesSettings.GetOrCreate(referenceHandling, bindingFlags); VerifyCanTrackChanges<T>(settings); } /// <summary> /// Check if the properties of <typeparamref name="T"/> can be tracked. /// This method will throw an exception if synchronization cannot be performed for <typeparamref name="T"/> /// Read the exception message for detailed instructions about what is wrong. /// Use this to fail fast or in unit tests. /// </summary> /// <typeparam name="T">The type to check.</typeparam> /// <param name="settings">Contains configuration for how tracking will be performed.</param> public static void VerifyCanTrackChanges<T>(PropertiesSettings settings) { VerifyCanTrackChanges(typeof(T), settings); } /// <summary> /// Check if the properties of <paramref name="type"/> can be tracked. /// This method will throw an exception if trackling cannot be performed for <paramref name="type"/> /// Read the exception message for detailed instructions about what is wrong. /// Use this to fail fast or in unit tests. /// </summary> /// <param name="type">The type to check.</param> /// <param name="settings">Contains configuration for how tracking will be performed.</param> public static void VerifyCanTrackChanges(Type type, PropertiesSettings settings) { VerifyCanTrackChanges(type, settings, typeof(Track).Name, nameof(VerifyCanTrackChanges)); } internal static void VerifyCanTrackChanges(Type type, PropertiesSettings settings, string className, string methodName) { Verify.CanTrackType(type, settings, className, methodName); } internal static void VerifyCanTrackIsDirty(Type type, PropertiesSettings settings, string className, string methodName) { EqualBy.VerifyCanEqualByMemberValues(type, settings, className, methodName); VerifyCanTrackChanges(type, settings, className, methodName); } private static bool HasErrors(this TypeErrors errors) { if (errors is null) { return false; } if (errors.Errors.Count == 1 && ReferenceEquals(errors.Errors[0], RequiresReferenceHandling.Default)) { return false; } return true; } /// <summary> /// This class is used for failing fast and throwing with nice exception messages. /// </summary> internal static class Verify { internal static void CanTrackValue(object value, PropertiesSettings settings) { var errors = GetOrCreateErrors(value.GetType(), settings); if (errors != null) { var typeErrors = new TypeErrors(null, errors); Throw.IfHasErrors(typeErrors, settings, typeof(Track).Name, nameof(Track.Changes)); } } internal static void CanTrackType(Type type, PropertiesSettings settings, string className = null, string methodName = null) { var errors = GetOrCreateErrors(type, settings); if (errors != null) { Throw.IfHasErrors(errors, settings, className ?? typeof(Track).Name, methodName ?? nameof(Track.Changes)); } } private static TypeErrors GetOrCreateErrors(Type type, MemberSettings settings, MemberPath path = null) { return ((PropertiesSettings)settings).TrackableErrors.GetOrAdd(type, t => CreateErrors(t, settings, path)); } private static TypeErrors CreateErrors(Type type, MemberSettings settings, MemberPath path) { if (settings.IsImmutable(type)) { return null; } var errors = ErrorBuilder.Start() .CheckRequiresReferenceHandling(type, settings, x => !settings.IsImmutable(x)) .CheckIndexers(type, settings) .CheckNotifies(type, settings) .VerifyRecursive(type, settings, path, GetNodeErrors) .Finnish(); return errors; } private static TypeErrors GetNodeErrors(MemberSettings settings, MemberPath path) { if (settings.ReferenceHandling == ReferenceHandling.References) { return null; } var type = path.LastNodeType; return GetOrCreateErrors(type, settings, path); } } private static class Throw { // ReSharper disable once UnusedParameter.Local internal static void IfHasErrors(TypeErrors errors, MemberSettings settings, string className, string methodName) { if (errors.HasErrors()) { var message = GetErrorText(errors, settings, className, methodName); throw new NotSupportedException(message); } } // ReSharper disable once UnusedParameter.Local private static string GetErrorText(TypeErrors errors, MemberSettings settings, string className, string methodName) { var errorBuilder = new StringBuilder(); errorBuilder.AppendLine($"{className}.{methodName}(x, y) failed.") .AppendNotSupported(errors) .AppendSolveTheProblemBy() .AppendSuggestNotify(errors) .AppendSuggestImmutable(errors) .AppendSuggestResizableCollection(errors) .AppendSuggestDefaultCtor(errors) .AppendLine($"* Use {settings?.GetType().Name} and specify how change tracking is performed:") .AppendLine($" - {typeof(ReferenceHandling).Name}.{nameof(ReferenceHandling.Structural)} means that a the entire graph is tracked.") .AppendLine($" - {typeof(ReferenceHandling).Name}.{nameof(ReferenceHandling.References)} means that only the root level changes are tracked.") .AppendSuggestExclude(errors); var message = errorBuilder.ToString(); return message; } } } }
#region License /* * 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. */ #endregion using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Gremlin.Net.Driver.Messages; using Gremlin.Net.Process; namespace Gremlin.Net.Driver { internal interface IResponseHandlerForSingleRequestMessage { void HandleReceived(ResponseMessage<List<object>> received); void Finalize(Dictionary<string, object> statusAttributes); void HandleFailure(Exception objException); } internal class Connection : IConnection { private readonly IMessageSerializer _messageSerializer; private readonly Uri _uri; private readonly WebSocketConnection _webSocketConnection; private readonly string _username; private readonly string _password; private readonly string _sessionId; private readonly bool _sessionEnabled; private readonly ConcurrentQueue<RequestMessage> _writeQueue = new ConcurrentQueue<RequestMessage>(); private readonly ConcurrentDictionary<Guid, IResponseHandlerForSingleRequestMessage> _callbackByRequestId = new ConcurrentDictionary<Guid, IResponseHandlerForSingleRequestMessage>(); private int _connectionState = 0; private int _writeInProgress = 0; private const int Closed = 1; public Connection(Uri uri, string username, string password, IMessageSerializer messageSerializer, Action<ClientWebSocketOptions> webSocketConfiguration, string sessionId) { _uri = uri; _username = username; _password = password; _sessionId = sessionId; if (!string.IsNullOrEmpty(sessionId)) { _sessionEnabled = true; } _messageSerializer = messageSerializer; _webSocketConnection = new WebSocketConnection(webSocketConfiguration); } public async Task ConnectAsync(CancellationToken cancellationToken) { await _webSocketConnection.ConnectAsync(_uri, cancellationToken).ConfigureAwait(false); BeginReceiving(); } public int NrRequestsInFlight => _callbackByRequestId.Count; public bool IsOpen => _webSocketConnection.IsOpen && Volatile.Read(ref _connectionState) != Closed; public Task<ResultSet<T>> SubmitAsync<T>(RequestMessage requestMessage) { var receiver = new ResponseHandlerForSingleRequestMessage<T>(); _callbackByRequestId.GetOrAdd(requestMessage.RequestId, receiver); _writeQueue.Enqueue(requestMessage); BeginSendingMessages(); return receiver.Result; } private void BeginReceiving() { var state = Volatile.Read(ref _connectionState); if (state == Closed) return; ReceiveMessagesAsync().Forget(); } private async Task ReceiveMessagesAsync() { while (true) { try { var received = await _webSocketConnection.ReceiveMessageAsync().ConfigureAwait(false); await HandleReceivedAsync(received).ConfigureAwait(false); } catch (Exception e) { await CloseConnectionBecauseOfFailureAsync(e).ConfigureAwait(false); break; } } } private async Task HandleReceivedAsync(byte[] received) { var receivedMsg = await _messageSerializer.DeserializeMessageAsync(received).ConfigureAwait(false); if (receivedMsg == null) { ThrowMessageDeserializedNull(); } try { HandleReceivedMessage(receivedMsg); } catch (Exception e) { if (receivedMsg.RequestId != null && _callbackByRequestId.TryRemove(receivedMsg.RequestId.Value, out var responseHandler)) { responseHandler?.HandleFailure(e); } } } private static void ThrowMessageDeserializedNull() => throw new InvalidOperationException("Received data deserialized into null object message. Cannot operate on it."); private void HandleReceivedMessage(ResponseMessage<List<object>> receivedMsg) { var status = receivedMsg.Status; status.ThrowIfStatusIndicatesError(); if (status.Code == ResponseStatusCode.Authenticate) { Authenticate(); return; } if (receivedMsg.RequestId == null) return; if (status.Code != ResponseStatusCode.NoContent) _callbackByRequestId[receivedMsg.RequestId.Value].HandleReceived(receivedMsg); if (status.Code == ResponseStatusCode.Success || status.Code == ResponseStatusCode.NoContent) { _callbackByRequestId[receivedMsg.RequestId.Value].Finalize(status.Attributes); _callbackByRequestId.TryRemove(receivedMsg.RequestId.Value, out _); } } private void Authenticate() { if (string.IsNullOrEmpty(_username) || string.IsNullOrEmpty(_password)) throw new InvalidOperationException( $"The Gremlin Server requires authentication, but no credentials are specified - username: {_username}, password: {_password}."); var message = RequestMessage.Build(Tokens.OpsAuthentication).Processor(Tokens.ProcessorTraversal) .AddArgument(Tokens.ArgsSasl, SaslArgument()).Create(); _writeQueue.Enqueue(message); BeginSendingMessages(); } private string SaslArgument() { var auth = $"\0{_username}\0{_password}"; var authBytes = Encoding.UTF8.GetBytes(auth); return Convert.ToBase64String(authBytes); } private void BeginSendingMessages() { if (Interlocked.CompareExchange(ref _writeInProgress, 1, 0) != 0) return; SendMessagesFromQueueAsync().Forget(); } private async Task SendMessagesFromQueueAsync() { while (_writeQueue.TryDequeue(out var msg)) { try { await SendMessageAsync(msg).ConfigureAwait(false); } catch (Exception e) { await CloseConnectionBecauseOfFailureAsync(e).ConfigureAwait(false); break; } } Interlocked.CompareExchange(ref _writeInProgress, 0, 1); // Since the loop ended and the write in progress was set to 0 // a new item could have been added, write queue can contain items at this time if (!_writeQueue.IsEmpty && Interlocked.CompareExchange(ref _writeInProgress, 1, 0) == 0) { await SendMessagesFromQueueAsync().ConfigureAwait(false); } } private async Task CloseConnectionBecauseOfFailureAsync(Exception exception) { EmptyWriteQueue(); await CloseAsync().ConfigureAwait(false); NotifyAboutConnectionFailure(exception); } private void EmptyWriteQueue() { while (_writeQueue.TryDequeue(out _)) { } } private void NotifyAboutConnectionFailure(Exception exception) { foreach (var cb in _callbackByRequestId.Values) { cb.HandleFailure(exception); } _callbackByRequestId.Clear(); } private async Task SendMessageAsync(RequestMessage message) { if (_sessionEnabled) { message = RebuildSessionMessage(message); } var serializedMsg = await _messageSerializer.SerializeMessageAsync(message).ConfigureAwait(false); await _webSocketConnection.SendMessageAsync(serializedMsg).ConfigureAwait(false); } private RequestMessage RebuildSessionMessage(RequestMessage message) { if (message.Processor == Tokens.OpsAuthentication) { return message; } var msgBuilder = RequestMessage.Build(message.Operation) .OverrideRequestId(message.RequestId).Processor(Tokens.ProcessorSession); foreach(var kv in message.Arguments) { msgBuilder.AddArgument(kv.Key, kv.Value); } msgBuilder.AddArgument(Tokens.ArgsSession, _sessionId); return msgBuilder.Create(); } public async Task CloseAsync() { Interlocked.Exchange(ref _connectionState, Closed); if (_sessionEnabled) { await CloseSession().ConfigureAwait(false); } await _webSocketConnection.CloseAsync().ConfigureAwait(false); } private async Task CloseSession() { // build a request to close this session var msg = RequestMessage.Build(Tokens.OpsClose).Processor(Tokens.ProcessorSession).Create(); await SendMessageAsync(msg).ConfigureAwait(false); } #region IDisposable Support private bool _disposed; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) _webSocketConnection?.Dispose(); _disposed = true; } } #endregion } }
//! \file ImageAP.cs //! \date Mon Jun 01 09:22:41 2015 //! \brief KaGuYa script engine bitmap format. // // Copyright (C) 2015 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System.ComponentModel.Composition; using System.IO; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; namespace GameRes.Formats.Kaguya { [Export(typeof(ImageFormat))] public class ApFormat : ImageFormat { public override string Tag { get { return "AP"; } } public override string Description { get { return "KaGuYa script engine image format"; } } public override uint Signature { get { return 0; } } public override bool CanWrite { get { return true; } } public ApFormat () { Extensions = new string[] { "bg_", "cg_", "cgw", "sp_", "aps", "alp", "prs" }; } public override ImageMetaData ReadMetaData (IBinaryStream stream) { int A = stream.ReadByte(); int P = stream.ReadByte(); if ('A' != A || 'P' != P) return null; var info = new ImageMetaData(); info.Width = stream.ReadUInt32(); info.Height = stream.ReadUInt32(); info.BPP = stream.ReadInt16(); if (info.Width > 0x8000 || info.Height > 0x8000 || !(32 == info.BPP || 24 == info.BPP)) return null; return info; } public override ImageData Read (IBinaryStream stream, ImageMetaData info) { stream.Position = 12; return ReadBitmapData (stream, info); } protected ImageData ReadBitmapData (IBinaryStream stream, ImageMetaData info) { int stride = (int)info.Width*4; var pixels = new byte[stride*info.Height]; for (int row = (int)info.Height-1; row >= 0; --row) { if (stride != stream.Read (pixels, row*stride, stride)) throw new InvalidFormatException(); } PixelFormat format = PixelFormats.Bgra32; return ImageData.Create (info, format, null, pixels); } public override void Write (Stream file, ImageData image) { using (var output = new BinaryWriter (file, Encoding.ASCII, true)) { output.Write ((byte)'A'); output.Write ((byte)'P'); output.Write (image.Width); output.Write (image.Height); output.Write ((short)24); WriteBitmapData (file, image); } } protected void WriteBitmapData (Stream file, ImageData image) { var bitmap = image.Bitmap; if (bitmap.Format != PixelFormats.Bgra32) { bitmap = new FormatConvertedBitmap (bitmap, PixelFormats.Bgra32, null, 0); } int stride = (int)image.Width * 4; byte[] row_data = new byte[stride]; Int32Rect rect = new Int32Rect (0, (int)image.Height, (int)image.Width, 1); for (uint row = 0; row < image.Height; ++row) { --rect.Y; bitmap.CopyPixels (rect, row_data, stride, 0); file.Write (row_data, 0, row_data.Length); } } } [Export(typeof(ImageFormat))] public class Ap0Format : ImageFormat { public override string Tag { get { return "AP-0"; } } public override string Description { get { return "KaGuYa script engine grayscale image format"; } } public override uint Signature { get { return 0x302D5041; } } // 'AP-0' public Ap0Format () { Extensions = new string[] { "alp" }; } public override ImageMetaData ReadMetaData (IBinaryStream stream) { var header = stream.ReadHeader (12); var info = new ImageMetaData { Width = header.ToUInt32 (4), Height = header.ToUInt32 (8), BPP = 8, }; if (info.Width > 0x8000 || info.Height > 0x8000) return null; return info; } public override ImageData Read (IBinaryStream stream, ImageMetaData info) { stream.Position = 0xC; var pixels = new byte[info.Width*info.Height]; if (pixels.Length != stream.Read (pixels, 0, pixels.Length)) throw new EndOfStreamException(); return ImageData.CreateFlipped (info, PixelFormats.Gray8, null, pixels, (int)info.Width); } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("Ap0Format.Write not implemented"); } } [Export(typeof(ImageFormat))] public class Ap2Format : ImageFormat { public override string Tag { get { return "AP-2"; } } public override string Description { get { return "KaGuYa script engine image format"; } } public override uint Signature { get { return 0x322D5041; } } // 'AP-2' public Ap2Format () { Extensions = new string[] { "alp" }; } public override ImageMetaData ReadMetaData (IBinaryStream stream) { stream.Position = 4; var info = new ImageMetaData(); info.OffsetX = stream.ReadInt32(); info.OffsetY = stream.ReadInt32(); info.Width = stream.ReadUInt32(); info.Height = stream.ReadUInt32(); info.BPP = 32; if (info.Width > 0x8000 || info.Height > 0x8000) return null; return info; } public override ImageData Read (IBinaryStream stream, ImageMetaData info) { stream.Position = 0x18; var pixels = new byte[4*info.Width*info.Height]; if (pixels.Length != stream.Read (pixels, 0, pixels.Length)) throw new EndOfStreamException(); return ImageData.CreateFlipped (info, PixelFormats.Bgra32, null, pixels, 4*(int)info.Width); } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("Ap2Format.Write not implemented"); } } [Export(typeof(ImageFormat))] public class Ap3Format : ImageFormat { public override string Tag { get { return "AP-3"; } } public override string Description { get { return "KaGuYa script engine image format"; } } public override uint Signature { get { return 0x332D5041; } } // 'AP-3' public Ap3Format () { Extensions = new string[] { "alp" }; } public override ImageMetaData ReadMetaData (IBinaryStream stream) { stream.Position = 4; var info = new ImageMetaData(); info.OffsetX = stream.ReadInt32(); info.OffsetY = stream.ReadInt32(); info.Width = stream.ReadUInt32(); info.Height = stream.ReadUInt32(); if (info.Width > 0x8000 || info.Height > 0x8000) return null; info.BPP = stream.ReadInt32(); if (info.BPP != 8 && info.BPP != 24 && info.BPP != 32) return null; return info; } public override ImageData Read (IBinaryStream stream, ImageMetaData info) { stream.Position = 0x18; int stride = info.BPP/8 * (int)info.Width; var pixels = new byte[stride * (int)info.Height]; if (pixels.Length != stream.Read (pixels, 0, pixels.Length)) throw new EndOfStreamException(); PixelFormat format = 24 == info.BPP ? PixelFormats.Bgr24 : 32 == info.BPP ? PixelFormats.Bgra32 : PixelFormats.Gray8; return ImageData.CreateFlipped (info, format, null, pixels, stride); } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("Ap3Format.Write not implemented"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.EcDsaOpenSsl.Tests { public static class EcDsaOpenSslTests { // TODO: Issue #4337. Temporary workaround for tests to pass on CentOS // where secp224r1 appears to be disabled. private static bool ECDsa224Available { get { try { using (ECDsaOpenSsl e = new ECDsaOpenSsl(224)) e.Exercise(); return true; } catch (Exception exc) { return !exc.Message.Contains("unknown group"); } } } [Fact] public static void DefaultCtor() { using (ECDsaOpenSsl e = new ECDsaOpenSsl()) { int keySize = e.KeySize; Assert.Equal(521, keySize); e.Exercise(); } } [ConditionalFact("ECDsa224Available")] // Issue #4337 public static void Ctor224() { int expectedKeySize = 224; using (ECDsaOpenSsl e = new ECDsaOpenSsl(expectedKeySize)) { int keySize = e.KeySize; Assert.Equal(expectedKeySize, keySize); e.Exercise(); } } [Fact] public static void Ctor384() { int expectedKeySize = 384; using (ECDsaOpenSsl e = new ECDsaOpenSsl(expectedKeySize)) { int keySize = e.KeySize; Assert.Equal(expectedKeySize, keySize); e.Exercise(); } } [Fact] public static void Ctor521() { int expectedKeySize = 521; using (ECDsaOpenSsl e = new ECDsaOpenSsl(expectedKeySize)) { int keySize = e.KeySize; Assert.Equal(expectedKeySize, keySize); e.Exercise(); } } [ConditionalFact("ECDsa224Available")] // Issue #4337 public static void CtorHandle224() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByCurveName(NID_secp224r1); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey)) { int keySize = e.KeySize; Assert.Equal(224, keySize); e.Exercise(); } Interop.Crypto.EcKeyDestroy(ecKey); } [Fact] public static void CtorHandle384() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByCurveName(NID_secp384r1); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey)) { int keySize = e.KeySize; Assert.Equal(384, keySize); e.Exercise(); } Interop.Crypto.EcKeyDestroy(ecKey); } [Fact] public static void CtorHandle521() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByCurveName(NID_secp521r1); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey)) { int keySize = e.KeySize; Assert.Equal(521, keySize); e.Exercise(); } Interop.Crypto.EcKeyDestroy(ecKey); } [Fact] public static void CtorHandleDuplicate() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByCurveName(NID_secp521r1); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey)) { // Make sure ECDsaOpenSsl did his own ref-count bump. Interop.Crypto.EcKeyDestroy(ecKey); int keySize = e.KeySize; Assert.Equal(521, keySize); e.Exercise(); } } [ConditionalFact("ECDsa224Available")] // Issue #4337 public static void KeySizeProp() { using (ECDsaOpenSsl e = new ECDsaOpenSsl()) { e.KeySize = 384; Assert.Equal(384, e.KeySize); e.Exercise(); e.KeySize = 224; Assert.Equal(224, e.KeySize); e.Exercise(); } } [Fact] public static void VerifyDuplicateKey_ValidHandle() { byte[] data = ByteUtils.RepeatByte(0x71, 11); using (ECDsaOpenSsl first = new ECDsaOpenSsl()) using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle()) { using (ECDsa second = new ECDsaOpenSsl(firstHandle)) { byte[] signed = second.SignData(data, HashAlgorithmName.SHA512); Assert.True(first.VerifyData(data, signed, HashAlgorithmName.SHA512)); } } } [Fact] public static void VerifyDuplicateKey_DistinctHandles() { using (ECDsaOpenSsl first = new ECDsaOpenSsl()) using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle()) using (SafeEvpPKeyHandle firstHandle2 = first.DuplicateKeyHandle()) { Assert.NotSame(firstHandle, firstHandle2); } } [Fact] public static void VerifyDuplicateKey_RefCounts() { byte[] data = ByteUtils.RepeatByte(0x74, 11); byte[] signature; ECDsa second; using (ECDsaOpenSsl first = new ECDsaOpenSsl()) using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle()) { signature = first.SignData(data, HashAlgorithmName.SHA384); second = new ECDsaOpenSsl(firstHandle); } // Now show that second still works, despite first and firstHandle being Disposed. using (second) { Assert.True(second.VerifyData(data, signature, HashAlgorithmName.SHA384)); } } [Fact] public static void VerifyDuplicateKey_NullHandle() { SafeEvpPKeyHandle pkey = null; Assert.Throws<ArgumentNullException>(() => new RSAOpenSsl(pkey)); } [Fact] public static void VerifyDuplicateKey_InvalidHandle() { using (ECDsaOpenSsl ecdsa = new ECDsaOpenSsl()) { SafeEvpPKeyHandle pkey = ecdsa.DuplicateKeyHandle(); using (pkey) { } Assert.Throws<ArgumentException>(() => new ECDsaOpenSsl(pkey)); } } [Fact] public static void VerifyDuplicateKey_NeverValidHandle() { using (SafeEvpPKeyHandle pkey = new SafeEvpPKeyHandle(IntPtr.Zero, false)) { Assert.Throws<ArgumentException>(() => new ECDsaOpenSsl(pkey)); } } [Fact] public static void VerifyDuplicateKey_RsaHandle() { using (RSAOpenSsl rsa = new RSAOpenSsl()) using (SafeEvpPKeyHandle pkey = rsa.DuplicateKeyHandle()) { Assert.ThrowsAny<CryptographicException>(() => new ECDsaOpenSsl(pkey)); } } private static void Exercise(this ECDsaOpenSsl e) { // Make a few calls on this to ensure we aren't broken due to bad/prematurely released handles. int keySize = e.KeySize; byte[] data = new byte[0x10]; byte[] sig = e.SignData(data, 0, data.Length, HashAlgorithmName.SHA1); bool verified = e.VerifyData(data, sig, HashAlgorithmName.SHA1); Assert.True(verified); sig[sig.Length - 1]++; verified = e.VerifyData(data, sig, HashAlgorithmName.SHA1); Assert.False(verified); } private const int NID_secp224r1 = 713; private const int NID_secp384r1 = 715; private const int NID_secp521r1 = 716; } } internal static partial class Interop { internal static class Crypto { [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyCreateByCurveName")] internal static extern IntPtr EcKeyCreateByCurveName(int nid); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyGenerateKey")] internal static extern int EcKeyGenerateKey(IntPtr ecKey); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyDestroy")] internal static extern void EcKeyDestroy(IntPtr r); } }
// 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.Xml.Schema { using System.IO; using System.Collections; using System.ComponentModel; using System.Xml.Serialization; using System.Threading; using System.Diagnostics; using System.Collections.Generic; [XmlRoot("schema", Namespace = XmlSchema.Namespace)] public class XmlSchema : XmlSchemaObject { public const string Namespace = XmlReservedNs.NsXs; public const string InstanceNamespace = XmlReservedNs.NsXsi; private XmlSchemaForm _attributeFormDefault = XmlSchemaForm.None; private XmlSchemaForm _elementFormDefault = XmlSchemaForm.None; private XmlSchemaDerivationMethod _blockDefault = XmlSchemaDerivationMethod.None; private XmlSchemaDerivationMethod _finalDefault = XmlSchemaDerivationMethod.None; private string _targetNs; private string _version; private XmlSchemaObjectCollection _includes = new XmlSchemaObjectCollection(); private XmlSchemaObjectCollection _items = new XmlSchemaObjectCollection(); private string _id; private XmlAttribute[] _moreAttributes; // compiled info private bool _isCompiled = false; private bool _isCompiledBySet = false; private bool _isPreprocessed = false; private bool _isRedefined = false; private int _errorCount = 0; private XmlSchemaObjectTable _attributes; private XmlSchemaObjectTable _attributeGroups = new XmlSchemaObjectTable(); private XmlSchemaObjectTable _elements = new XmlSchemaObjectTable(); private XmlSchemaObjectTable _types = new XmlSchemaObjectTable(); private XmlSchemaObjectTable _groups = new XmlSchemaObjectTable(); private XmlSchemaObjectTable _notations = new XmlSchemaObjectTable(); private XmlSchemaObjectTable _identityConstraints = new XmlSchemaObjectTable(); private static int s_globalIdCounter = -1; private ArrayList _importedSchemas; private ArrayList _importedNamespaces; private int _schemaId = -1; //Not added to a set private Uri _baseUri; private bool _isChameleon; private Hashtable _ids = new Hashtable(); private XmlDocument _document; private XmlNameTable _nameTable; public XmlSchema() { } public static XmlSchema Read(TextReader reader, ValidationEventHandler validationEventHandler) { return Read(new XmlTextReader(reader), validationEventHandler); } public static XmlSchema Read(Stream stream, ValidationEventHandler validationEventHandler) { return Read(new XmlTextReader(stream), validationEventHandler); } public static XmlSchema Read(XmlReader reader, ValidationEventHandler validationEventHandler) { XmlNameTable nameTable = reader.NameTable; Parser parser = new Parser(SchemaType.XSD, nameTable, new SchemaNames(nameTable), validationEventHandler); try { parser.Parse(reader, null); } catch (XmlSchemaException e) { if (validationEventHandler != null) { validationEventHandler(null, new ValidationEventArgs(e)); } else { throw; } return null; } return parser.XmlSchema; } public void Write(Stream stream) { Write(stream, null); } public void Write(Stream stream, XmlNamespaceManager namespaceManager) { XmlTextWriter xmlWriter = new XmlTextWriter(stream, null); xmlWriter.Formatting = Formatting.Indented; Write(xmlWriter, namespaceManager); } public void Write(TextWriter writer) { Write(writer, null); } public void Write(TextWriter writer, XmlNamespaceManager namespaceManager) { XmlTextWriter xmlWriter = new XmlTextWriter(writer); xmlWriter.Formatting = Formatting.Indented; Write(xmlWriter, namespaceManager); } public void Write(XmlWriter writer) { Write(writer, null); } public void Write(XmlWriter writer, XmlNamespaceManager namespaceManager) { XmlSerializer serializer = new XmlSerializer(typeof(XmlSchema)); XmlSerializerNamespaces ns; if (namespaceManager != null) { ns = new XmlSerializerNamespaces(); bool ignoreXS = false; if (this.Namespaces != null) { //User may have set both nsManager and Namespaces property on the XmlSchema object ignoreXS = this.Namespaces.Namespaces.ContainsKey("xs") || this.Namespaces.Namespaces.ContainsValue(XmlReservedNs.NsXs); } if (!ignoreXS && namespaceManager.LookupPrefix(XmlReservedNs.NsXs) == null && namespaceManager.LookupNamespace("xs") == null) { ns.Add("xs", XmlReservedNs.NsXs); } foreach (string prefix in namespaceManager) { if (prefix != "xml" && prefix != "xmlns") { ns.Add(prefix, namespaceManager.LookupNamespace(prefix)); } } } else if (this.Namespaces != null && this.Namespaces.Count > 0) { Dictionary<string, string> serializerNS = this.Namespaces.Namespaces; if (!serializerNS.ContainsKey("xs") && !serializerNS.ContainsValue(XmlReservedNs.NsXs)) { //Prefix xs not defined AND schema namespace not already mapped to a prefix serializerNS.Add("xs", XmlReservedNs.NsXs); } ns = this.Namespaces; } else { ns = new XmlSerializerNamespaces(); ns.Add("xs", XmlSchema.Namespace); if (_targetNs != null && _targetNs.Length != 0) { ns.Add("tns", _targetNs); } } serializer.Serialize(writer, this, ns); } [Obsolete("Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. https://go.microsoft.com/fwlink/?linkid=14202")] public void Compile(ValidationEventHandler validationEventHandler) { SchemaInfo sInfo = new SchemaInfo(); sInfo.SchemaType = SchemaType.XSD; CompileSchema(null, null, sInfo, null, validationEventHandler, NameTable, false); } [Obsolete("Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. https://go.microsoft.com/fwlink/?linkid=14202")] public void Compile(ValidationEventHandler validationEventHandler, XmlResolver resolver) { SchemaInfo sInfo = new SchemaInfo(); sInfo.SchemaType = SchemaType.XSD; CompileSchema(null, resolver, sInfo, null, validationEventHandler, NameTable, false); } #pragma warning disable 618 internal bool CompileSchema(XmlSchemaCollection xsc, XmlResolver resolver, SchemaInfo schemaInfo, string ns, ValidationEventHandler validationEventHandler, XmlNameTable nameTable, bool CompileContentModel) { //Need to lock here to prevent multi-threading problems when same schema is added to set and compiled lock (this) { //Preprocessing SchemaCollectionPreprocessor prep = new SchemaCollectionPreprocessor(nameTable, null, validationEventHandler); prep.XmlResolver = resolver; if (!prep.Execute(this, ns, true, xsc)) { return false; } //Compilation SchemaCollectionCompiler compiler = new SchemaCollectionCompiler(nameTable, validationEventHandler); _isCompiled = compiler.Execute(this, schemaInfo, CompileContentModel); this.SetIsCompiled(_isCompiled); return _isCompiled; } } #pragma warning restore 618 internal void CompileSchemaInSet(XmlNameTable nameTable, ValidationEventHandler eventHandler, XmlSchemaCompilationSettings compilationSettings) { Debug.Assert(_isPreprocessed); Compiler setCompiler = new Compiler(nameTable, eventHandler, null, compilationSettings); setCompiler.Prepare(this, true); _isCompiledBySet = setCompiler.Compile(); } [XmlAttribute("attributeFormDefault"), DefaultValue(XmlSchemaForm.None)] public XmlSchemaForm AttributeFormDefault { get { return _attributeFormDefault; } set { _attributeFormDefault = value; } } [XmlAttribute("blockDefault"), DefaultValue(XmlSchemaDerivationMethod.None)] public XmlSchemaDerivationMethod BlockDefault { get { return _blockDefault; } set { _blockDefault = value; } } [XmlAttribute("finalDefault"), DefaultValue(XmlSchemaDerivationMethod.None)] public XmlSchemaDerivationMethod FinalDefault { get { return _finalDefault; } set { _finalDefault = value; } } [XmlAttribute("elementFormDefault"), DefaultValue(XmlSchemaForm.None)] public XmlSchemaForm ElementFormDefault { get { return _elementFormDefault; } set { _elementFormDefault = value; } } [XmlAttribute("targetNamespace", DataType = "anyURI")] public string TargetNamespace { get { return _targetNs; } set { _targetNs = value; } } [XmlAttribute("version", DataType = "token")] public string Version { get { return _version; } set { _version = value; } } [XmlElement("include", typeof(XmlSchemaInclude)), XmlElement("import", typeof(XmlSchemaImport)), XmlElement("redefine", typeof(XmlSchemaRedefine))] public XmlSchemaObjectCollection Includes { get { return _includes; } } [XmlElement("annotation", typeof(XmlSchemaAnnotation)), XmlElement("attribute", typeof(XmlSchemaAttribute)), XmlElement("attributeGroup", typeof(XmlSchemaAttributeGroup)), XmlElement("complexType", typeof(XmlSchemaComplexType)), XmlElement("simpleType", typeof(XmlSchemaSimpleType)), XmlElement("element", typeof(XmlSchemaElement)), XmlElement("group", typeof(XmlSchemaGroup)), XmlElement("notation", typeof(XmlSchemaNotation))] public XmlSchemaObjectCollection Items { get { return _items; } } // Compiled info [XmlIgnore] public bool IsCompiled { get { return _isCompiled || _isCompiledBySet; } } [XmlIgnore] internal bool IsCompiledBySet { get { return _isCompiledBySet; } set { _isCompiledBySet = value; } } [XmlIgnore] internal bool IsPreprocessed { get { return _isPreprocessed; } set { _isPreprocessed = value; } } [XmlIgnore] internal bool IsRedefined { get { return _isRedefined; } set { _isRedefined = value; } } [XmlIgnore] public XmlSchemaObjectTable Attributes { get { if (_attributes == null) { _attributes = new XmlSchemaObjectTable(); } return _attributes; } } [XmlIgnore] public XmlSchemaObjectTable AttributeGroups { get { if (_attributeGroups == null) { _attributeGroups = new XmlSchemaObjectTable(); } return _attributeGroups; } } [XmlIgnore] public XmlSchemaObjectTable SchemaTypes { get { if (_types == null) { _types = new XmlSchemaObjectTable(); } return _types; } } [XmlIgnore] public XmlSchemaObjectTable Elements { get { if (_elements == null) { _elements = new XmlSchemaObjectTable(); } return _elements; } } [XmlAttribute("id", DataType = "ID")] public string Id { get { return _id; } set { _id = value; } } [XmlAnyAttribute] public XmlAttribute[] UnhandledAttributes { get { return _moreAttributes; } set { _moreAttributes = value; } } [XmlIgnore] public XmlSchemaObjectTable Groups { get { return _groups; } } [XmlIgnore] public XmlSchemaObjectTable Notations { get { return _notations; } } [XmlIgnore] internal XmlSchemaObjectTable IdentityConstraints { get { return _identityConstraints; } } [XmlIgnore] internal Uri BaseUri { get { return _baseUri; } set { _baseUri = value; } } [XmlIgnore] // Please be careful with this property. Since it lazy initialized and its value depends on a global state // if it gets called on multiple schemas in a different order the schemas will end up with different IDs // Unfortunately the IDs are used to sort the schemas in the schema set and thus changing the IDs might change // the order which would be a breaking change!! // Simply put if you are planning to add or remove a call to this getter you need to be extra carefull // or better don't do it at all. internal int SchemaId { get { if (_schemaId == -1) { _schemaId = Interlocked.Increment(ref s_globalIdCounter); } return _schemaId; } } [XmlIgnore] internal bool IsChameleon { get { return _isChameleon; } set { _isChameleon = value; } } [XmlIgnore] internal Hashtable Ids { get { return _ids; } } [XmlIgnore] internal XmlDocument Document { get { if (_document == null) _document = new XmlDocument(); return _document; } } [XmlIgnore] internal int ErrorCount { get { return _errorCount; } set { _errorCount = value; } } internal new XmlSchema Clone() { XmlSchema that = new XmlSchema(); that._attributeFormDefault = _attributeFormDefault; that._elementFormDefault = _elementFormDefault; that._blockDefault = _blockDefault; that._finalDefault = _finalDefault; that._targetNs = _targetNs; that._version = _version; that._includes = _includes; that.Namespaces = this.Namespaces; that._items = _items; that.BaseUri = this.BaseUri; SchemaCollectionCompiler.Cleanup(that); return that; } internal XmlSchema DeepClone() { XmlSchema that = new XmlSchema(); that._attributeFormDefault = _attributeFormDefault; that._elementFormDefault = _elementFormDefault; that._blockDefault = _blockDefault; that._finalDefault = _finalDefault; that._targetNs = _targetNs; that._version = _version; that._isPreprocessed = _isPreprocessed; //that.IsProcessing = this.IsProcessing; //Not sure if this is needed //Clone its Items for (int i = 0; i < _items.Count; ++i) { XmlSchemaObject newItem; XmlSchemaComplexType complexType; XmlSchemaElement element; XmlSchemaGroup group; if ((complexType = _items[i] as XmlSchemaComplexType) != null) { newItem = complexType.Clone(this); } else if ((element = _items[i] as XmlSchemaElement) != null) { newItem = element.Clone(this); } else if ((group = _items[i] as XmlSchemaGroup) != null) { newItem = group.Clone(this); } else { newItem = _items[i].Clone(); } that.Items.Add(newItem); } //Clone Includes for (int i = 0; i < _includes.Count; ++i) { XmlSchemaExternal newInclude = (XmlSchemaExternal)_includes[i].Clone(); that.Includes.Add(newInclude); } that.Namespaces = this.Namespaces; //that.includes = this.includes; //Need to verify this is OK for redefines that.BaseUri = this.BaseUri; return that; } [XmlIgnore] internal override string IdAttribute { get { return Id; } set { Id = value; } } internal void SetIsCompiled(bool isCompiled) { _isCompiled = isCompiled; } internal override void SetUnhandledAttributes(XmlAttribute[] moreAttributes) { _moreAttributes = moreAttributes; } internal override void AddAnnotation(XmlSchemaAnnotation annotation) { _items.Add(annotation); } internal XmlNameTable NameTable { get { if (_nameTable == null) _nameTable = new System.Xml.NameTable(); return _nameTable; } } internal ArrayList ImportedSchemas { get { if (_importedSchemas == null) { _importedSchemas = new ArrayList(); } return _importedSchemas; } } internal ArrayList ImportedNamespaces { get { if (_importedNamespaces == null) { _importedNamespaces = new ArrayList(); } return _importedNamespaces; } } internal void GetExternalSchemasList(IList extList, XmlSchema schema) { Debug.Assert(extList != null && schema != null); if (extList.Contains(schema)) { return; } extList.Add(schema); for (int i = 0; i < schema.Includes.Count; ++i) { XmlSchemaExternal ext = (XmlSchemaExternal)schema.Includes[i]; if (ext.Schema != null) { GetExternalSchemasList(extList, ext.Schema); } } } #if TRUST_COMPILE_STATE internal void AddCompiledInfo(SchemaInfo schemaInfo) { XmlQualifiedName itemName; foreach (XmlSchemaElement element in elements.Values) { itemName = element.QualifiedName; schemaInfo.TargetNamespaces[itemName.Namespace] = true; if (schemaInfo.ElementDecls[itemName] == null) { schemaInfo.ElementDecls.Add(itemName, element.ElementDecl); } } foreach (XmlSchemaAttribute attribute in attributes.Values) { itemName = attribute.QualifiedName; schemaInfo.TargetNamespaces[itemName.Namespace] = true; if (schemaInfo.ElementDecls[itemName] == null) { schemaInfo.AttributeDecls.Add(itemName, attribute.AttDef); } } foreach (XmlSchemaType type in types.Values) { itemName = type.QualifiedName; schemaInfo.TargetNamespaces[itemName.Namespace] = true; XmlSchemaComplexType complexType = type as XmlSchemaComplexType; if ((complexType == null || type != XmlSchemaComplexType.AnyType) && schemaInfo.ElementDeclsByType[itemName] == null) { schemaInfo.ElementDeclsByType.Add(itemName, type.ElementDecl); } } foreach (XmlSchemaNotation notation in notations.Values) { itemName = notation.QualifiedName; schemaInfo.TargetNamespaces[itemName.Namespace] = true; SchemaNotation no = new SchemaNotation(itemName); no.SystemLiteral = notation.System; no.Pubid = notation.Public; if (schemaInfo.Notations[itemName.Name] == null) { schemaInfo.Notations.Add(itemName.Name, no); } } } #endif//TRUST_COMPILE_STATE } }
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using dnlib.DotNet.MD; using dnlib.DotNet.Pdb; using dnlib.Threading; namespace dnlib.DotNet { /// <summary> /// A high-level representation of a row in the TypeSpec table /// </summary> public abstract class TypeSpec : ITypeDefOrRef, IHasCustomAttribute, IMemberRefParent, IHasCustomDebugInformation { /// <summary> /// The row id in its table /// </summary> protected uint rid; #if THREAD_SAFE readonly Lock theLock = Lock.Create(); #endif /// <inheritdoc/> public MDToken MDToken => new MDToken(Table.TypeSpec, rid); /// <inheritdoc/> public uint Rid { get => rid; set => rid = value; } /// <inheritdoc/> public int TypeDefOrRefTag => 2; /// <inheritdoc/> public int HasCustomAttributeTag => 13; /// <inheritdoc/> public int MemberRefParentTag => 4; /// <inheritdoc/> int IGenericParameterProvider.NumberOfGenericParameters { get { var ts = TypeSig; return ts is null ? 0 : ((IGenericParameterProvider)ts).NumberOfGenericParameters; } } /// <inheritdoc/> UTF8String IFullName.Name { get { var mr = ScopeType; return mr is null ? UTF8String.Empty : mr.Name; } set { var mr = ScopeType; if (mr is not null) mr.Name = value; } } /// <inheritdoc/> ITypeDefOrRef IMemberRef.DeclaringType { get { var sig = TypeSig.RemovePinnedAndModifiers(); if (sig is GenericInstSig gis) sig = gis.GenericType; if (sig is TypeDefOrRefSig tdr) { if (tdr.IsTypeDef || tdr.IsTypeRef) return tdr.TypeDefOrRef.DeclaringType; return null; // If it's another TypeSpec, just stop. Don't want possible inf recursion. } return null; } } bool IIsTypeOrMethod.IsType => true; bool IIsTypeOrMethod.IsMethod => false; bool IMemberRef.IsField => false; bool IMemberRef.IsTypeSpec => true; bool IMemberRef.IsTypeRef => false; bool IMemberRef.IsTypeDef => false; bool IMemberRef.IsMethodSpec => false; bool IMemberRef.IsMethodDef => false; bool IMemberRef.IsMemberRef => false; bool IMemberRef.IsFieldDef => false; bool IMemberRef.IsPropertyDef => false; bool IMemberRef.IsEventDef => false; bool IMemberRef.IsGenericParam => false; /// <inheritdoc/> public bool IsValueType { get { var sig = TypeSig; return sig is not null && sig.IsValueType; } } /// <inheritdoc/> public bool IsPrimitive { get { var sig = TypeSig; return sig is not null && sig.IsPrimitive; } } /// <inheritdoc/> public string TypeName => FullNameFactory.Name(this, false, null); /// <inheritdoc/> public string ReflectionName => FullNameFactory.Name(this, true, null); /// <inheritdoc/> string IType.Namespace => FullNameFactory.Namespace(this, false, null); /// <inheritdoc/> public string ReflectionNamespace => FullNameFactory.Namespace(this, true, null); /// <inheritdoc/> public string FullName => FullNameFactory.FullName(this, false, null, null); /// <inheritdoc/> public string ReflectionFullName => FullNameFactory.FullName(this, true, null, null); /// <inheritdoc/> public string AssemblyQualifiedName => FullNameFactory.AssemblyQualifiedName(this, null, null); /// <inheritdoc/> public IAssembly DefinitionAssembly => FullNameFactory.DefinitionAssembly(this); /// <inheritdoc/> public IScope Scope => FullNameFactory.Scope(this); /// <inheritdoc/> public ITypeDefOrRef ScopeType => FullNameFactory.ScopeType(this); /// <inheritdoc/> public bool ContainsGenericParameter => TypeHelper.ContainsGenericParameter(this); /// <inheritdoc/> public ModuleDef Module => FullNameFactory.OwnerModule(this); /// <summary> /// From column TypeSpec.Signature /// </summary> public TypeSig TypeSig { get { if (!typeSigAndExtraData_isInitialized) InitializeTypeSigAndExtraData(); return typeSig; } set { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif typeSig = value; if (!typeSigAndExtraData_isInitialized) GetTypeSigAndExtraData_NoLock(out extraData); typeSigAndExtraData_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } } /// <summary> /// Gets/sets the extra data that was found after the signature /// </summary> public byte[] ExtraData { get { if (!typeSigAndExtraData_isInitialized) InitializeTypeSigAndExtraData(); return extraData; } set { if (!typeSigAndExtraData_isInitialized) InitializeTypeSigAndExtraData(); extraData = value; } } /// <summary/> protected TypeSig typeSig; /// <summary/> protected byte[] extraData; /// <summary/> protected bool typeSigAndExtraData_isInitialized; void InitializeTypeSigAndExtraData() { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif if (typeSigAndExtraData_isInitialized) return; typeSig = GetTypeSigAndExtraData_NoLock(out extraData); typeSigAndExtraData_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } /// <summary>Called to initialize <see cref="typeSig"/></summary> protected virtual TypeSig GetTypeSigAndExtraData_NoLock(out byte[] extraData) { extraData = null; return null; } /// <summary> /// Gets all custom attributes /// </summary> public CustomAttributeCollection CustomAttributes { get { if (customAttributes is null) InitializeCustomAttributes(); return customAttributes; } } /// <summary/> protected CustomAttributeCollection customAttributes; /// <summary>Initializes <see cref="customAttributes"/></summary> protected virtual void InitializeCustomAttributes() => Interlocked.CompareExchange(ref customAttributes, new CustomAttributeCollection(), null); /// <inheritdoc/> public bool HasCustomAttributes => CustomAttributes.Count > 0; /// <inheritdoc/> public int HasCustomDebugInformationTag => 13; /// <inheritdoc/> public bool HasCustomDebugInfos => CustomDebugInfos.Count > 0; /// <summary> /// Gets all custom debug infos /// </summary> public IList<PdbCustomDebugInfo> CustomDebugInfos { get { if (customDebugInfos is null) InitializeCustomDebugInfos(); return customDebugInfos; } } /// <summary/> protected IList<PdbCustomDebugInfo> customDebugInfos; /// <summary>Initializes <see cref="customDebugInfos"/></summary> protected virtual void InitializeCustomDebugInfos() => Interlocked.CompareExchange(ref customDebugInfos, new List<PdbCustomDebugInfo>(), null); /// <inheritdoc/> public override string ToString() => FullName; } /// <summary> /// A TypeSpec row created by the user and not present in the original .NET file /// </summary> public class TypeSpecUser : TypeSpec { /// <summary> /// Default constructor /// </summary> public TypeSpecUser() { } /// <summary> /// Constructor /// </summary> /// <param name="typeSig">A type sig</param> public TypeSpecUser(TypeSig typeSig) { this.typeSig = typeSig; extraData = null; typeSigAndExtraData_isInitialized = true; } } /// <summary> /// Created from a row in the TypeSpec table /// </summary> sealed class TypeSpecMD : TypeSpec, IMDTokenProviderMD, IContainsGenericParameter2 { /// <summary>The module where this instance is located</summary> readonly ModuleDefMD readerModule; readonly uint origRid; readonly GenericParamContext gpContext; readonly uint signatureOffset; /// <inheritdoc/> public uint OrigRid => origRid; /// <inheritdoc/> protected override TypeSig GetTypeSigAndExtraData_NoLock(out byte[] extraData) { var sig = readerModule.ReadTypeSignature(signatureOffset, gpContext, out extraData); if (sig is not null) sig.Rid = origRid; return sig; } /// <inheritdoc/> protected override void InitializeCustomAttributes() { var list = readerModule.Metadata.GetCustomAttributeRidList(Table.TypeSpec, origRid); var tmp = new CustomAttributeCollection(list.Count, list, (list2, index) => readerModule.ReadCustomAttribute(list[index])); Interlocked.CompareExchange(ref customAttributes, tmp, null); } /// <inheritdoc/> protected override void InitializeCustomDebugInfos() { var list = new List<PdbCustomDebugInfo>(); readerModule.InitializeCustomDebugInfos(new MDToken(MDToken.Table, origRid), gpContext, list); Interlocked.CompareExchange(ref customDebugInfos, list, null); } bool IContainsGenericParameter2.ContainsGenericParameter => ContainsGenericParameter; /// <summary> /// Constructor /// </summary> /// <param name="readerModule">The module which contains this <c>TypeSpec</c> row</param> /// <param name="rid">Row ID</param> /// <param name="gpContext">Generic parameter context</param> /// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception> /// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception> public TypeSpecMD(ModuleDefMD readerModule, uint rid, GenericParamContext gpContext) { #if DEBUG if (readerModule is null) throw new ArgumentNullException("readerModule"); if (readerModule.TablesStream.TypeSpecTable.IsInvalidRID(rid)) throw new BadImageFormatException($"TypeSpec rid {rid} does not exist"); #endif origRid = rid; this.rid = rid; this.readerModule = readerModule; this.gpContext = gpContext; bool b = readerModule.TablesStream.TryReadTypeSpecRow(origRid, out var row); Debug.Assert(b); signatureOffset = row.Signature; } } }
// 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.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public class GroupJoinTests { private const int KeyFactor = 8; private const int ElementFactor = 4; public static IEnumerable<object[]> GroupJoinData(int[] leftCounts, int[] rightCounts) { foreach (object[] parms in UnorderedSources.BinaryRanges(leftCounts, rightCounts)) { yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], parms[2], parms[3] }; } } // // GroupJoin // [Theory] [MemberData("BinaryRanges", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))] public static void GroupJoin_Unordered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seen = new IntegerRangeSet(0, leftCount); foreach (var p in leftQuery.GroupJoin(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y))) { seen.Add(p.Key); if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor) { Assert.Equal(p.Key * KeyFactor, Assert.Single(p.Value)); } else { Assert.Empty(p.Value); } } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("BinaryRanges", new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 4, 1024 * 8 }, MemberType = typeof(UnorderedSources))] public static void GroupJoin_Unordered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { GroupJoin_Unordered(left, leftCount, right, rightCount); } [Theory] [MemberData("GroupJoinData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 })] public static void GroupJoin(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seen = 0; foreach (var p in leftQuery.GroupJoin(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y))) { Assert.Equal(seen++, p.Key); if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor) { Assert.Equal(p.Key * KeyFactor, Assert.Single(p.Value)); } else { Assert.Empty(p.Value); } } Assert.Equal(leftCount, seen); } [Theory] [OuterLoop] [MemberData("GroupJoinData", new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 4, 1024 * 8 })] public static void GroupJoin_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { GroupJoin(left, leftCount, right, rightCount); } [Theory] [MemberData("BinaryRanges", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))] public static void GroupJoin_Unordered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seen = new IntegerRangeSet(0, leftCount); Assert.All(leftQuery.GroupJoin(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)).ToList(), p => { seen.Add(p.Key); if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor) { Assert.Equal(p.Key * KeyFactor, Assert.Single(p.Value)); } else { Assert.Empty(p.Value); } }); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("BinaryRanges", new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 4, 1024 * 8 }, MemberType = typeof(UnorderedSources))] public static void GroupJoin_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { GroupJoin_Unordered_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("GroupJoinData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 })] public static void GroupJoin_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seen = 0; Assert.All(leftQuery.GroupJoin(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)).ToList(), p => { Assert.Equal(seen++, p.Key); if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor) { Assert.Equal(p.Key * KeyFactor, Assert.Single(p.Value)); } else { Assert.Empty(p.Value); } }); Assert.Equal(leftCount, seen); } [Theory] [OuterLoop] [MemberData("GroupJoinData", new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 4, 1024 * 8 })] public static void GroupJoin_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { GroupJoin_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("BinaryRanges", new int[] { 0, 1, 2, 15, 16 }, new int[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))] public static void GroupJoin_Unordered_Multiple(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seenOuter = new IntegerRangeSet(0, leftCount); Assert.All(leftQuery.GroupJoin(rightQuery, x => x, y => y / KeyFactor, (x, y) => KeyValuePair.Create(x, y)), p => { seenOuter.Add(p.Key); if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor) { IntegerRangeSet seenInner = new IntegerRangeSet(p.Key * KeyFactor, Math.Min(rightCount - p.Key * KeyFactor, KeyFactor)); Assert.All(p.Value, y => { Assert.Equal(p.Key, y / KeyFactor); seenInner.Add(y); }); seenInner.AssertComplete(); } else { Assert.Empty(p.Value); } }); seenOuter.AssertComplete(); } [Theory] [OuterLoop] [MemberData("BinaryRanges", new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 4, 1024 * 8 }, MemberType = typeof(UnorderedSources))] public static void GroupJoin_Unordered_Multiple_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { GroupJoin_Unordered_Multiple(left, leftCount, right, rightCount); } [Theory] [MemberData("GroupJoinData", new int[] { 0, 1, 2, 15, 16 }, new int[] { 0, 1, 16 })] // GroupJoin doesn't always return elements from the right in order. See Issue #1155 public static void GroupJoin_Multiple(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seenOuter = 0; Assert.All(leftQuery.GroupJoin(rightQuery, x => x, y => y / KeyFactor, (x, y) => KeyValuePair.Create(x, y)), p => { Assert.Equal(seenOuter++, p.Key); if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor) { IntegerRangeSet seenInner = new IntegerRangeSet(p.Key * KeyFactor, Math.Min(rightCount - p.Key * KeyFactor, KeyFactor)); Assert.All(p.Value, y => { Assert.Equal(p.Key, y / KeyFactor); seenInner.Add(y); }); seenInner.AssertComplete(); } else { Assert.Empty(p.Value); } }); Assert.Equal(leftCount, seenOuter); } [Theory] [OuterLoop] [MemberData("GroupJoinData", new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 4, 1024 * 8 })] public static void GroupJoin_Multiple_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { GroupJoin_Multiple(left, leftCount, right, rightCount); } [Theory] [MemberData("BinaryRanges", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))] public static void GroupJoin_Unordered_CustomComparator(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seenOuter = new IntegerRangeSet(0, leftCount); Assert.All(leftQuery.GroupJoin(rightQuery, x => x, y => y % ElementFactor, (x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)), p => { seenOuter.Add(p.Key); if (p.Key % KeyFactor < Math.Min(ElementFactor, rightCount)) { IntegerRangeSet seenInner = new IntegerRangeSet(0, (rightCount + (ElementFactor - 1) - p.Key % ElementFactor) / ElementFactor); Assert.All(p.Value, y => { Assert.Equal(p.Key % KeyFactor, y % ElementFactor); seenInner.Add(y / ElementFactor); }); seenInner.AssertComplete(); } else { Assert.Empty(p.Value); } }); seenOuter.AssertComplete(); } [Theory] [OuterLoop] [MemberData("BinaryRanges", new int[] { 512, 1024 }, new int[] { 0, 1, 1024, 1024 * 4 }, MemberType = typeof(UnorderedSources))] public static void GroupJoin_Unordered_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { GroupJoin_Unordered_CustomComparator(left, leftCount, right, rightCount); } [Theory] [MemberData("GroupJoinData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 })] public static void GroupJoin_CustomComparator(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seenOuter = 0; Assert.All(leftQuery.GroupJoin(rightQuery, x => x, y => y % ElementFactor, (x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)), p => { Assert.Equal(seenOuter++, p.Key); if (p.Key % KeyFactor < Math.Min(ElementFactor, rightCount)) { IntegerRangeSet seenInner = new IntegerRangeSet(0, (rightCount + (ElementFactor - 1) - p.Key % ElementFactor) / ElementFactor); Assert.All(p.Value, y => { Assert.Equal(p.Key % KeyFactor, y % ElementFactor); seenInner.Add(y / ElementFactor); }); seenInner.AssertComplete(); } else { Assert.Empty(p.Value); } }); Assert.Equal(leftCount, seenOuter); } [Theory] [OuterLoop] [MemberData("GroupJoinData", new int[] { 512, 1024 }, new int[] { 0, 1, 1024, 1024 * 4 })] public static void GroupJoin_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { GroupJoin_CustomComparator(left, leftCount, right, rightCount); } [Fact] public static void GroupJoin_NotSupportedException() { #pragma warning disable 618 Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(Enumerable.Range(0, 1), i => i, i => i, (i, j) => i)); Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(Enumerable.Range(0, 1), i => i, i => i, (i, j) => i, null)); #pragma warning restore 618 } [Fact] // Should not get the same setting from both operands. public static void GroupJoin_NoDuplicateSettings() { CancellationToken t = new CancellationTokenSource().Token; Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).GroupJoin(ParallelEnumerable.Range(0, 1).WithCancellation(t), x => x, y => y, (x, e) => e)); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).GroupJoin(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1), x => x, y => y, (x, e) => e)); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).GroupJoin(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default), x => x, y => y, (x, e) => e)); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).GroupJoin(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default), x => x, y => y, (x, e) => e)); } [Fact] public static void GroupJoin_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (i, j) => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin((ParallelQuery<int>)null, i => i, i => i, (i, j) => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), (Func<int, int>)null, i => i, (i, j) => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, (Func<int, int>)null, (i, j) => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (Func<int, IEnumerable<int>, int>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (i, j) => i, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin((ParallelQuery<int>)null, i => i, i => i, (i, j) => i, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), (Func<int, int>)null, i => i, (i, j) => i, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, (Func<int, int>)null, (i, j) => i, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (Func<int, IEnumerable<int>, int>)null, EqualityComparer<int>.Default)); } } }
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 GuardiaRegistrosDiagnostico class. /// </summary> [Serializable] public partial class GuardiaRegistrosDiagnosticoCollection : ActiveList<GuardiaRegistrosDiagnostico, GuardiaRegistrosDiagnosticoCollection> { public GuardiaRegistrosDiagnosticoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>GuardiaRegistrosDiagnosticoCollection</returns> public GuardiaRegistrosDiagnosticoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { GuardiaRegistrosDiagnostico o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Guardia_Registros_Diagnosticos table. /// </summary> [Serializable] public partial class GuardiaRegistrosDiagnostico : ActiveRecord<GuardiaRegistrosDiagnostico>, IActiveRecord { #region .ctors and Default Settings public GuardiaRegistrosDiagnostico() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public GuardiaRegistrosDiagnostico(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public GuardiaRegistrosDiagnostico(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public GuardiaRegistrosDiagnostico(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } 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("Guardia_Registros_Diagnosticos", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "id"; colvarId.DataType = DbType.Int32; colvarId.MaxLength = 0; colvarId.AutoIncrement = true; colvarId.IsNullable = false; colvarId.IsPrimaryKey = true; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; colvarId.DefaultSetting = @""; colvarId.ForeignKeyTableName = ""; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarIdRegistroGuardia = new TableSchema.TableColumn(schema); colvarIdRegistroGuardia.ColumnName = "idRegistroGuardia"; colvarIdRegistroGuardia.DataType = DbType.Int32; colvarIdRegistroGuardia.MaxLength = 0; colvarIdRegistroGuardia.AutoIncrement = false; colvarIdRegistroGuardia.IsNullable = true; colvarIdRegistroGuardia.IsPrimaryKey = false; colvarIdRegistroGuardia.IsForeignKey = true; colvarIdRegistroGuardia.IsReadOnly = false; colvarIdRegistroGuardia.DefaultSetting = @""; colvarIdRegistroGuardia.ForeignKeyTableName = "Guardia_Registros"; schema.Columns.Add(colvarIdRegistroGuardia); TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema); colvarIdEfector.ColumnName = "idEfector"; colvarIdEfector.DataType = DbType.Int32; colvarIdEfector.MaxLength = 0; colvarIdEfector.AutoIncrement = false; colvarIdEfector.IsNullable = true; colvarIdEfector.IsPrimaryKey = false; colvarIdEfector.IsForeignKey = false; colvarIdEfector.IsReadOnly = false; colvarIdEfector.DefaultSetting = @""; colvarIdEfector.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEfector); TableSchema.TableColumn colvarAuditUser = new TableSchema.TableColumn(schema); colvarAuditUser.ColumnName = "audit_user"; colvarAuditUser.DataType = DbType.Int32; colvarAuditUser.MaxLength = 0; colvarAuditUser.AutoIncrement = false; colvarAuditUser.IsNullable = false; colvarAuditUser.IsPrimaryKey = false; colvarAuditUser.IsForeignKey = false; colvarAuditUser.IsReadOnly = false; colvarAuditUser.DefaultSetting = @""; colvarAuditUser.ForeignKeyTableName = ""; schema.Columns.Add(colvarAuditUser); TableSchema.TableColumn colvarTipoAnotacion = new TableSchema.TableColumn(schema); colvarTipoAnotacion.ColumnName = "tipoAnotacion"; colvarTipoAnotacion.DataType = DbType.Int32; colvarTipoAnotacion.MaxLength = 0; colvarTipoAnotacion.AutoIncrement = false; colvarTipoAnotacion.IsNullable = false; colvarTipoAnotacion.IsPrimaryKey = false; colvarTipoAnotacion.IsForeignKey = false; colvarTipoAnotacion.IsReadOnly = false; colvarTipoAnotacion.DefaultSetting = @""; colvarTipoAnotacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarTipoAnotacion); TableSchema.TableColumn colvarObservacion = new TableSchema.TableColumn(schema); colvarObservacion.ColumnName = "Observacion"; colvarObservacion.DataType = DbType.AnsiString; colvarObservacion.MaxLength = -1; colvarObservacion.AutoIncrement = false; colvarObservacion.IsNullable = true; colvarObservacion.IsPrimaryKey = false; colvarObservacion.IsForeignKey = false; colvarObservacion.IsReadOnly = false; colvarObservacion.DefaultSetting = @""; colvarObservacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarObservacion); TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema); colvarFecha.ColumnName = "fecha"; colvarFecha.DataType = DbType.DateTime; colvarFecha.MaxLength = 0; colvarFecha.AutoIncrement = false; colvarFecha.IsNullable = true; colvarFecha.IsPrimaryKey = false; colvarFecha.IsForeignKey = false; colvarFecha.IsReadOnly = false; colvarFecha.DefaultSetting = @""; colvarFecha.ForeignKeyTableName = ""; schema.Columns.Add(colvarFecha); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Guardia_Registros_Diagnosticos",schema); } } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public int Id { get { return GetColumnValue<int>(Columns.Id); } set { SetColumnValue(Columns.Id, value); } } [XmlAttribute("IdRegistroGuardia")] [Bindable(true)] public int? IdRegistroGuardia { get { return GetColumnValue<int?>(Columns.IdRegistroGuardia); } set { SetColumnValue(Columns.IdRegistroGuardia, value); } } [XmlAttribute("IdEfector")] [Bindable(true)] public int? IdEfector { get { return GetColumnValue<int?>(Columns.IdEfector); } set { SetColumnValue(Columns.IdEfector, value); } } [XmlAttribute("AuditUser")] [Bindable(true)] public int AuditUser { get { return GetColumnValue<int>(Columns.AuditUser); } set { SetColumnValue(Columns.AuditUser, value); } } [XmlAttribute("TipoAnotacion")] [Bindable(true)] public int TipoAnotacion { get { return GetColumnValue<int>(Columns.TipoAnotacion); } set { SetColumnValue(Columns.TipoAnotacion, value); } } [XmlAttribute("Observacion")] [Bindable(true)] public string Observacion { get { return GetColumnValue<string>(Columns.Observacion); } set { SetColumnValue(Columns.Observacion, value); } } [XmlAttribute("Fecha")] [Bindable(true)] public DateTime? Fecha { get { return GetColumnValue<DateTime?>(Columns.Fecha); } set { SetColumnValue(Columns.Fecha, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a GuardiaRegistro ActiveRecord object related to this GuardiaRegistrosDiagnostico /// /// </summary> public DalSic.GuardiaRegistro GuardiaRegistro { get { return DalSic.GuardiaRegistro.FetchByID(this.IdRegistroGuardia); } set { SetColumnValue("idRegistroGuardia", value.Id); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int? varIdRegistroGuardia,int? varIdEfector,int varAuditUser,int varTipoAnotacion,string varObservacion,DateTime? varFecha) { GuardiaRegistrosDiagnostico item = new GuardiaRegistrosDiagnostico(); item.IdRegistroGuardia = varIdRegistroGuardia; item.IdEfector = varIdEfector; item.AuditUser = varAuditUser; item.TipoAnotacion = varTipoAnotacion; item.Observacion = varObservacion; item.Fecha = varFecha; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varId,int? varIdRegistroGuardia,int? varIdEfector,int varAuditUser,int varTipoAnotacion,string varObservacion,DateTime? varFecha) { GuardiaRegistrosDiagnostico item = new GuardiaRegistrosDiagnostico(); item.Id = varId; item.IdRegistroGuardia = varIdRegistroGuardia; item.IdEfector = varIdEfector; item.AuditUser = varAuditUser; item.TipoAnotacion = varTipoAnotacion; item.Observacion = varObservacion; item.Fecha = varFecha; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdRegistroGuardiaColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdEfectorColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn AuditUserColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn TipoAnotacionColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn ObservacionColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn FechaColumn { get { return Schema.Columns[6]; } } #endregion #region Columns Struct public struct Columns { public static string Id = @"id"; public static string IdRegistroGuardia = @"idRegistroGuardia"; public static string IdEfector = @"idEfector"; public static string AuditUser = @"audit_user"; public static string TipoAnotacion = @"tipoAnotacion"; public static string Observacion = @"Observacion"; public static string Fecha = @"fecha"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System.Web.UI; using System.Web.UI.WebControls; namespace Subtext.Web.Admin.WebUI { // TODO: add clear link (display: none;) plus requried js [ToolboxData("<{0}:MessagePanel runat=\"server\"></{0}:MessagePanel>")] public class MessagePanel : Panel, INamingContainer { private const string VSKEY_ERROR = "Error"; private const string VSKEY_MESSAGE = "Message"; string _errorCssClass; string _errorIconUrl; string _messageCssClass; string _messageIconUrl; bool _showErrorPanel; bool _showMessagePanel; #region Accessors public string Message { get { return (string)ViewState[VSKEY_MESSAGE]; } set { ViewState[VSKEY_MESSAGE] = value; } } public string Error { get { return (string)ViewState[VSKEY_ERROR]; } set { ViewState[VSKEY_ERROR] = value; } } public bool ShowMessagePanel { get { return _showMessagePanel; } set { _showMessagePanel = value; } } public bool ShowErrorPanel { get { return _showErrorPanel; } set { _showErrorPanel = value; } } public string MessageCssClass { get { if(_messageCssClass == null) { _messageCssClass = "MessagePanel"; } return _messageCssClass; } set { _messageCssClass = value; } } public string ErrorCssClass { get { if(_errorCssClass == null) { _errorCssClass = "ErrorPanel"; } return _errorCssClass; } set { _errorCssClass = value; } } public string MessageIconUrl { get { if(_messageIconUrl == null) { _messageIconUrl = "~/images/icons/ico_info.gif"; } return _messageIconUrl; } set { _messageIconUrl = value; } } public string ErrorIconUrl { get { if(_errorIconUrl == null) { _errorIconUrl = "~/images/icons/ico_critical.gif"; } return _errorIconUrl; } set { _errorIconUrl = value; } } #endregion protected override void Render(HtmlTextWriter writer) { if(null != Page) { Page.VerifyRenderingInServerForm(this); } if(ShowErrorPanel) { Panel errorPanel = BuildPanel(Error, ErrorCssClass, Utilities.AbsolutePath(ErrorIconUrl)); Controls.Add(errorPanel); } if(ShowMessagePanel) { Panel messagePanel = BuildPanel(Message, MessageCssClass, Utilities.AbsolutePath(MessageIconUrl)); Controls.Add(messagePanel); } base.Render(writer); } protected virtual Panel BuildPanel(string messageText, string cssClass, string imageUrl) { var result = new Panel(); if(null != imageUrl && cssClass.Length > 0) { result.CssClass = cssClass; } if(!string.IsNullOrEmpty(imageUrl)) { var image = new Image(); image.Attributes.Add("src", imageUrl); result.Controls.Add(image); } var message = new Panel(); message.Controls.Add(new LiteralControl(messageText)); result.Controls.Add(message); return result; } public void ShowMessage(string message) { ShowMessage(message, true); } public void ShowMessage(string message, bool clearExistingMessages) { if(clearExistingMessages) { Message = message; } else { Message += " " + message; } ShowMessagePanel = true; Visible = true; } public void ShowError(string message) { ShowError(message, true); } public void ShowError(string message, bool clearExistingMessages) { if(clearExistingMessages) { Error = message; } else { Error += " " + message; } ShowErrorPanel = true; Visible = true; } public void Clear() { Visible = false; } public void ResetMessages() { Message = string.Empty; Error = string.Empty; } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 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 BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using CookComputing.XmlRpc; namespace XenAPI { /// <summary> /// The metrics associated with a host /// First published in XenServer 4.0. /// </summary> public partial class Host_metrics : XenObject<Host_metrics> { public Host_metrics() { } public Host_metrics(string uuid, long memory_total, long memory_free, bool live, DateTime last_updated, Dictionary<string, string> other_config) { this.uuid = uuid; this.memory_total = memory_total; this.memory_free = memory_free; this.live = live; this.last_updated = last_updated; this.other_config = other_config; } /// <summary> /// Creates a new Host_metrics from a Proxy_Host_metrics. /// </summary> /// <param name="proxy"></param> public Host_metrics(Proxy_Host_metrics proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(Host_metrics update) { uuid = update.uuid; memory_total = update.memory_total; memory_free = update.memory_free; live = update.live; last_updated = update.last_updated; other_config = update.other_config; } internal void UpdateFromProxy(Proxy_Host_metrics proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; memory_total = proxy.memory_total == null ? 0 : long.Parse((string)proxy.memory_total); memory_free = proxy.memory_free == null ? 0 : long.Parse((string)proxy.memory_free); live = (bool)proxy.live; last_updated = proxy.last_updated; other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } public Proxy_Host_metrics ToProxy() { Proxy_Host_metrics result_ = new Proxy_Host_metrics(); result_.uuid = (uuid != null) ? uuid : ""; result_.memory_total = memory_total.ToString(); result_.memory_free = memory_free.ToString(); result_.live = live; result_.last_updated = last_updated; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } /// <summary> /// Creates a new Host_metrics from a Hashtable. /// </summary> /// <param name="table"></param> public Host_metrics(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); memory_total = Marshalling.ParseLong(table, "memory_total"); memory_free = Marshalling.ParseLong(table, "memory_free"); live = Marshalling.ParseBool(table, "live"); last_updated = Marshalling.ParseDateTime(table, "last_updated"); other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Host_metrics other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._memory_total, other._memory_total) && Helper.AreEqual2(this._memory_free, other._memory_free) && Helper.AreEqual2(this._live, other._live) && Helper.AreEqual2(this._last_updated, other._last_updated) && Helper.AreEqual2(this._other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, Host_metrics server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { Host_metrics.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given host_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> public static Host_metrics get_record(Session session, string _host_metrics) { return new Host_metrics((Proxy_Host_metrics)session.proxy.host_metrics_get_record(session.uuid, (_host_metrics != null) ? _host_metrics : "").parse()); } /// <summary> /// Get a reference to the host_metrics instance with the specified UUID. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<Host_metrics> get_by_uuid(Session session, string _uuid) { return XenRef<Host_metrics>.Create(session.proxy.host_metrics_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse()); } /// <summary> /// Get the uuid field of the given host_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> public static string get_uuid(Session session, string _host_metrics) { return (string)session.proxy.host_metrics_get_uuid(session.uuid, (_host_metrics != null) ? _host_metrics : "").parse(); } /// <summary> /// Get the memory/total field of the given host_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> public static long get_memory_total(Session session, string _host_metrics) { return long.Parse((string)session.proxy.host_metrics_get_memory_total(session.uuid, (_host_metrics != null) ? _host_metrics : "").parse()); } /// <summary> /// Get the memory/free field of the given host_metrics. /// First published in XenServer 4.0. /// Deprecated since XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> [Deprecated("XenServer 5.6")] public static long get_memory_free(Session session, string _host_metrics) { return long.Parse((string)session.proxy.host_metrics_get_memory_free(session.uuid, (_host_metrics != null) ? _host_metrics : "").parse()); } /// <summary> /// Get the live field of the given host_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> public static bool get_live(Session session, string _host_metrics) { return (bool)session.proxy.host_metrics_get_live(session.uuid, (_host_metrics != null) ? _host_metrics : "").parse(); } /// <summary> /// Get the last_updated field of the given host_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> public static DateTime get_last_updated(Session session, string _host_metrics) { return session.proxy.host_metrics_get_last_updated(session.uuid, (_host_metrics != null) ? _host_metrics : "").parse(); } /// <summary> /// Get the other_config field of the given host_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> public static Dictionary<string, string> get_other_config(Session session, string _host_metrics) { return Maps.convert_from_proxy_string_string(session.proxy.host_metrics_get_other_config(session.uuid, (_host_metrics != null) ? _host_metrics : "").parse()); } /// <summary> /// Set the other_config field of the given host_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _host_metrics, Dictionary<string, string> _other_config) { session.proxy.host_metrics_set_other_config(session.uuid, (_host_metrics != null) ? _host_metrics : "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given host_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _host_metrics, string _key, string _value) { session.proxy.host_metrics_add_to_other_config(session.uuid, (_host_metrics != null) ? _host_metrics : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given host_metrics. If the key is not in that Map, then do nothing. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _host_metrics, string _key) { session.proxy.host_metrics_remove_from_other_config(session.uuid, (_host_metrics != null) ? _host_metrics : "", (_key != null) ? _key : "").parse(); } /// <summary> /// Return a list of all the host_metrics instances known to the system. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<Host_metrics>> get_all(Session session) { return XenRef<Host_metrics>.Create(session.proxy.host_metrics_get_all(session.uuid).parse()); } /// <summary> /// Get all the host_metrics Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Host_metrics>, Host_metrics> get_all_records(Session session) { return XenRef<Host_metrics>.Create<Proxy_Host_metrics>(session.proxy.host_metrics_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// Total host memory (bytes) /// </summary> public virtual long memory_total { get { return _memory_total; } set { if (!Helper.AreEqual(value, _memory_total)) { _memory_total = value; Changed = true; NotifyPropertyChanged("memory_total"); } } } private long _memory_total; /// <summary> /// Free host memory (bytes) /// </summary> public virtual long memory_free { get { return _memory_free; } set { if (!Helper.AreEqual(value, _memory_free)) { _memory_free = value; Changed = true; NotifyPropertyChanged("memory_free"); } } } private long _memory_free; /// <summary> /// Pool master thinks this host is live /// </summary> public virtual bool live { get { return _live; } set { if (!Helper.AreEqual(value, _live)) { _live = value; Changed = true; NotifyPropertyChanged("live"); } } } private bool _live; /// <summary> /// Time at which this information was last updated /// </summary> public virtual DateTime last_updated { get { return _last_updated; } set { if (!Helper.AreEqual(value, _last_updated)) { _last_updated = value; Changed = true; NotifyPropertyChanged("last_updated"); } } } private DateTime _last_updated; /// <summary> /// additional configuration /// First published in XenServer 5.0. /// </summary> public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config; } }
// 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.Runtime.InteropServices; using System.Security.Cryptography; namespace System.Security { public sealed partial class SecureString { [System.Security.SecurityCritical] // auto-generated internal SecureString(SecureString str) { AllocateBuffer(str.EncryptedBufferLength); SafeBSTRHandle.Copy(str._encryptedBuffer, _encryptedBuffer, str.EncryptedBufferLength * sizeof(char)); _decryptedLength = str._decryptedLength; } [System.Security.SecurityCritical] // auto-generated private unsafe void InitializeSecureString(char* value, int length) { if (length == 0) { AllocateBuffer(0); _decryptedLength = 0; return; } _encryptedBuffer = SafeBSTRHandle.Allocate(null, 0); SafeBSTRHandle decryptedBuffer = SafeBSTRHandle.Allocate(null, (uint)length); _decryptedLength = length; byte* bufferPtr = null; try { decryptedBuffer.AcquirePointer(ref bufferPtr); Buffer.MemoryCopy((byte*)value, bufferPtr, decryptedBuffer.Length * sizeof(char), length * sizeof(char)); } finally { if (bufferPtr != null) decryptedBuffer.ReleasePointer(); } ProtectMemory(decryptedBuffer); } [System.Security.SecuritySafeCritical] // auto-generated private void AppendCharCore(char c) { SafeBSTRHandle decryptedBuffer = null; try { decryptedBuffer = UnProtectMemory(); EnsureCapacity(ref decryptedBuffer, _decryptedLength + 1); decryptedBuffer.Write<char>((uint)_decryptedLength * sizeof(char), c); _decryptedLength++; } finally { ProtectMemory(decryptedBuffer); } } // clears the current contents. Only available if writable [System.Security.SecuritySafeCritical] // auto-generated private void ClearCore() { _decryptedLength = 0; _encryptedBuffer.ClearBuffer(); } [System.Security.SecuritySafeCritical] // auto-generated private void DisposeCore() { if (_encryptedBuffer != null && !_encryptedBuffer.IsInvalid) { _encryptedBuffer.Dispose(); _encryptedBuffer = null; } } [System.Security.SecuritySafeCritical] // auto-generated private unsafe void InsertAtCore(int index, char c) { byte* bufferPtr = null; SafeBSTRHandle decryptedBuffer = null; try { decryptedBuffer = UnProtectMemory(); EnsureCapacity(ref decryptedBuffer, _decryptedLength + 1); decryptedBuffer.AcquirePointer(ref bufferPtr); char* pBuffer = (char*)bufferPtr; for (int i = _decryptedLength; i > index; i--) { pBuffer[i] = pBuffer[i - 1]; } pBuffer[index] = c; ++_decryptedLength; } finally { if (bufferPtr != null) decryptedBuffer.ReleasePointer(); ProtectMemory(decryptedBuffer); } } [System.Security.SecuritySafeCritical] // auto-generated private unsafe void RemoveAtCore(int index) { byte* bufferPtr = null; SafeBSTRHandle decryptedBuffer = null; try { decryptedBuffer = UnProtectMemory(); decryptedBuffer.AcquirePointer(ref bufferPtr); char* pBuffer = (char*)bufferPtr; for (int i = index; i < _decryptedLength - 1; i++) { pBuffer[i] = pBuffer[i + 1]; } pBuffer[--_decryptedLength] = (char)0; } finally { if (bufferPtr != null) decryptedBuffer.ReleasePointer(); ProtectMemory(decryptedBuffer); } } [System.Security.SecuritySafeCritical] // auto-generated private void SetAtCore(int index, char c) { SafeBSTRHandle decryptedBuffer = null; try { decryptedBuffer = UnProtectMemory(); decryptedBuffer.Write<char>((uint)index * sizeof(char), c); } finally { ProtectMemory(decryptedBuffer); } } [System.Security.SecurityCritical] // auto-generated internal unsafe IntPtr ToUniStrCore() { int length = _decryptedLength; IntPtr ptr = IntPtr.Zero; IntPtr result = IntPtr.Zero; byte* bufferPtr = null; SafeBSTRHandle decryptedBuffer = null; try { ptr = Marshal.AllocCoTaskMem((length + 1) * 2); decryptedBuffer = UnProtectMemory(); decryptedBuffer.AcquirePointer(ref bufferPtr); Buffer.MemoryCopy(bufferPtr, (byte*)ptr.ToPointer(), ((length + 1) * 2), length * 2); char* endptr = (char*)ptr.ToPointer(); *(endptr + length) = '\0'; result = ptr; } finally { if (result == IntPtr.Zero) { // If we failed for any reason, free the new buffer if (ptr != IntPtr.Zero) { Interop.NtDll.ZeroMemory(ptr, (UIntPtr)(length * 2)); Marshal.FreeCoTaskMem(ptr); } } if (bufferPtr != null) decryptedBuffer.ReleasePointer(); } return result; } [System.Security.SecurityCritical] // auto-generated private void EnsureNotDisposed() { if (_encryptedBuffer == null) { throw new ObjectDisposedException(null); } } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- [System.Security.SecurityCritical] // auto-generated private SafeBSTRHandle _encryptedBuffer; private uint EncryptedBufferLength { [System.Security.SecurityCritical] // auto-generated get { Debug.Assert(_encryptedBuffer != null, "Buffer is not initialized!"); return _encryptedBuffer.Length; } } [System.Security.SecurityCritical] // auto-generated private void AllocateBuffer(uint size) { _encryptedBuffer = SafeBSTRHandle.Allocate(null, size); } [System.Security.SecurityCritical] // auto-generated private void EnsureCapacity(ref SafeBSTRHandle decryptedBuffer, int capacity) { if (capacity > MaxLength) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_Capacity); } if (capacity <= _decryptedLength) { return; } SafeBSTRHandle newBuffer = SafeBSTRHandle.Allocate(null, (uint)capacity); SafeBSTRHandle.Copy(decryptedBuffer, newBuffer, (uint)_decryptedLength * sizeof(char)); decryptedBuffer.Dispose(); decryptedBuffer = newBuffer; } [System.Security.SecurityCritical] // auto-generated private void ProtectMemory(SafeBSTRHandle decryptedBuffer) { Debug.Assert(!decryptedBuffer.IsInvalid, "Invalid buffer!"); if (_decryptedLength == 0) { return; } try { SafeBSTRHandle newEncryptedBuffer = null; if (Interop.Crypt32.CryptProtectData(decryptedBuffer, out newEncryptedBuffer)) { _encryptedBuffer.Dispose(); _encryptedBuffer = newEncryptedBuffer; } else { throw new CryptographicException(Marshal.GetLastWin32Error()); } } finally { decryptedBuffer.ClearBuffer(); decryptedBuffer.Dispose(); } } [System.Security.SecurityCritical] // auto-generated private SafeBSTRHandle UnProtectMemory() { Debug.Assert(!_encryptedBuffer.IsInvalid, "Invalid buffer!"); SafeBSTRHandle decryptedBuffer = null; if (_decryptedLength == 0) { return _encryptedBuffer; } if (!Interop.Crypt32.CryptUnProtectData(_encryptedBuffer, out decryptedBuffer)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } return decryptedBuffer; } } }
using Microsoft.Extensions.Logging; using NBitcoin; using Stratis.Bitcoin.Configuration.Logging; using Stratis.Bitcoin.Features.SmartContracts.Networks; using Stratis.Patricia; using Stratis.SmartContracts; using Stratis.SmartContracts.Core; using Stratis.SmartContracts.Core.State; using Stratis.SmartContracts.CLR.Validation; using Stratis.SmartContracts.CLR; using Stratis.SmartContracts.CLR.Compilation; using Stratis.SmartContracts.CLR.Loader; using Stratis.SmartContracts.CLR.ResultProcessors; using Stratis.SmartContracts.CLR.Serialization; using Xunit; namespace Stratis.Bitcoin.Features.SmartContracts.Tests { public sealed class ContractExecutorTests { private const ulong BlockHeight = 0; private static readonly uint160 CoinbaseAddress = 0; private static readonly uint160 ToAddress = 1; private static readonly uint160 SenderAddress = 2; private static readonly Money MempoolFee = new Money(1_000_000); private readonly IKeyEncodingStrategy keyEncodingStrategy; private readonly ILoggerFactory loggerFactory; private readonly Network network; private readonly IContractRefundProcessor refundProcessor; private readonly IStateRepositoryRoot state; private readonly IContractTransferProcessor transferProcessor; private readonly SmartContractValidator validator; private IInternalExecutorFactory internalTxExecutorFactory; private IVirtualMachine vm; private readonly ICallDataSerializer callDataSerializer; private readonly StateFactory stateFactory; private readonly IAddressGenerator addressGenerator; private readonly ILoader assemblyLoader; private readonly IContractModuleDefinitionReader moduleDefinitionReader; private readonly IContractPrimitiveSerializer contractPrimitiveSerializer; private readonly IStateProcessor stateProcessor; private readonly ISmartContractStateFactory smartContractStateFactory; private readonly ISerializer serializer; public ContractExecutorTests() { this.keyEncodingStrategy = BasicKeyEncodingStrategy.Default; this.loggerFactory = new ExtendedLoggerFactory(); this.loggerFactory.AddConsoleWithFilters(); this.network = new SmartContractsRegTest(); this.refundProcessor = new ContractRefundProcessor(this.loggerFactory); this.state = new StateRepositoryRoot(new NoDeleteSource<byte[], byte[]>(new MemoryDictionarySource())); this.transferProcessor = new ContractTransferProcessor(this.loggerFactory, this.network); this.validator = new SmartContractValidator(); this.addressGenerator = new AddressGenerator(); this.assemblyLoader = new ContractAssemblyLoader(); this.moduleDefinitionReader = new ContractModuleDefinitionReader(); this.contractPrimitiveSerializer = new ContractPrimitiveSerializer(this.network); this.serializer = new Serializer(this.contractPrimitiveSerializer); this.vm = new ReflectionVirtualMachine(this.validator, this.loggerFactory, this.assemblyLoader, this.moduleDefinitionReader); this.stateProcessor = new StateProcessor(this.vm, this.addressGenerator); this.internalTxExecutorFactory = new InternalExecutorFactory(this.loggerFactory, this.stateProcessor); this.smartContractStateFactory = new SmartContractStateFactory(this.contractPrimitiveSerializer, this.internalTxExecutorFactory, this.serializer); this.callDataSerializer = new CallDataSerializer(this.contractPrimitiveSerializer); this.stateFactory = new StateFactory(this.smartContractStateFactory); } [Fact] public void SmartContractExecutor_CallContract_Fails_ReturnFundsToSender() { //Get the contract execution code------------------------ ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/ThrowExceptionContract.cs"); Assert.True(compilationResult.Success); byte[] contractExecutionCode = compilationResult.Compilation; //------------------------------------------------------- //Call smart contract and add to transaction------------- var contractTxData = new ContractTxData(1, 1, (Gas)500_000, ToAddress, "ThrowException"); var transactionCall = new Transaction(); TxOut callTxOut = transactionCall.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); callTxOut.Value = 100; //------------------------------------------------------- //Deserialize the contract from the transaction---------- //and get the module definition //------------------------------------------------------- this.state.SetCode(new uint160(1), contractExecutionCode); this.state.SetContractType(new uint160(1), "ThrowExceptionContract"); IContractTransactionContext transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, SenderAddress, transactionCall); var executor = new ContractExecutor(this.loggerFactory, this.callDataSerializer, this.state, this.refundProcessor, this.transferProcessor, this.stateFactory, this.stateProcessor, this.contractPrimitiveSerializer); IContractExecutionResult result = executor.Execute(transactionContext); Assert.True(result.Revert); Assert.NotNull(result.InternalTransaction); Assert.Single(result.InternalTransaction.Inputs); Assert.Single(result.InternalTransaction.Outputs); var actualSender = new uint160(result.InternalTransaction.Outputs[0].ScriptPubKey.GetDestination(this.network).ToBytes()); Assert.Equal(SenderAddress, actualSender); Assert.Equal(100, result.InternalTransaction.Outputs[0].Value); } [Fact] public void SmartContractExecutor_CallContract_DoesNotExist_Refund() { var contractTxData = new ContractTxData(1, 1, (Gas) 10000, ToAddress, "TestMethod"); var transaction = new Transaction(); TxOut txOut = transaction.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); txOut.Value = 100; IContractTransactionContext transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, new uint160(2), transaction); var executor = new ContractExecutor(this.loggerFactory, this.callDataSerializer, this.state, this.refundProcessor, this.transferProcessor, this.stateFactory, this.stateProcessor, this.contractPrimitiveSerializer); IContractExecutionResult result = executor.Execute(transactionContext); Assert.True(result.Revert); } [Fact] public void SME_CreateContract_ConstructorFails_Refund() { ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/ContractConstructorInvalid.cs"); Assert.True(compilationResult.Success); byte[] contractCode = compilationResult.Compilation; var contractTxData = new ContractTxData(0, (Gas) 1, (Gas)500_000, contractCode); var tx = new Transaction(); tx.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); IContractTransactionContext transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, new uint160(2), tx); var executor = new ContractExecutor(this.loggerFactory, this.callDataSerializer, this.state, this.refundProcessor, this.transferProcessor, this.stateFactory, this.stateProcessor, this.contractPrimitiveSerializer); IContractExecutionResult result = executor.Execute(transactionContext); Assert.NotNull(result.ErrorMessage); // Number here shouldn't be hardcoded - note this is really only to let us know of consensus failure Assert.Equal(GasPriceList.CreateCost + 18, result.GasConsumed); } [Fact] public void SME_CreateContract_MethodParameters_InvalidParameterCount() { ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/ContractInvalidParameterCount.cs"); Assert.True(compilationResult.Success); byte[] contractCode = compilationResult.Compilation; object[] methodParameters = { 5 }; var contractTxData = new ContractTxData(0, (Gas)1, (Gas)500_000, contractCode, methodParameters); var tx = new Transaction(); tx.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); IContractTransactionContext transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, new uint160(2), tx); var executor = new ContractExecutor(this.loggerFactory, this.callDataSerializer, this.state, this.refundProcessor, this.transferProcessor, this.stateFactory, this.stateProcessor, this.contractPrimitiveSerializer); IContractExecutionResult result = executor.Execute(transactionContext); Assert.NotNull(result.ErrorMessage); Assert.Equal(GasPriceList.CreateCost, result.GasConsumed); } [Fact] public void SME_CreateContract_MethodParameters_ParameterTypeMismatch() { ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/ContractMethodParameterTypeMismatch.cs"); Assert.True(compilationResult.Success); byte[] contractCode = compilationResult.Compilation; object[] methodParameters = { true }; var contractTxData = new ContractTxData(0, (Gas)1, (Gas)500_000, contractCode, methodParameters); var tx = new Transaction(); tx.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); IContractTransactionContext transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, new uint160(2), tx); var executor = new ContractExecutor(this.loggerFactory, this.callDataSerializer, this.state, this.refundProcessor, this.transferProcessor, this.stateFactory, this.stateProcessor, this.contractPrimitiveSerializer); IContractExecutionResult result = executor.Execute(transactionContext); Assert.NotNull(result.ErrorMessage); Assert.Equal(GasPriceList.CreateCost, result.GasConsumed); } [Fact] public void Execute_InterContractCall_Internal_InfiniteLoop_Fails() { // Create contract 1 //Get the contract execution code------------------------ ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/InfiniteLoop.cs"); Assert.True(compilationResult.Success); byte[] contractExecutionCode = compilationResult.Compilation; //------------------------------------------------------- // Add contract creation code to transaction------------- var contractTxData = new ContractTxData(1, (Gas)1, (Gas)500_000, contractExecutionCode); var transaction = new Transaction(); TxOut txOut = transaction.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); txOut.Value = 100; //------------------------------------------------------- //Deserialize the contract from the transaction---------- //and get the module definition IContractTransactionContext transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, SenderAddress, transaction); var executor = new ContractExecutor(this.loggerFactory, this.callDataSerializer, this.state, this.refundProcessor, this.transferProcessor, this.stateFactory, this.stateProcessor, this.contractPrimitiveSerializer); IContractExecutionResult result = executor.Execute(transactionContext); uint160 address1 = result.NewContractAddress; //------------------------------------------------------- // Create contract 2 //Get the contract execution code------------------------ compilationResult = ContractCompiler.CompileFile("SmartContracts/CallInfiniteLoopContract.cs"); Assert.True(compilationResult.Success); contractExecutionCode = compilationResult.Compilation; //------------------------------------------------------- //Call smart contract and add to transaction------------- contractTxData = new ContractTxData(1, (Gas)1, (Gas)500_000, contractExecutionCode); transaction = new Transaction(); txOut = transaction.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); txOut.Value = 100; //------------------------------------------------------- //Deserialize the contract from the transaction---------- //and get the module definition //------------------------------------------------------- transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, SenderAddress, transaction); result = executor.Execute(transactionContext); uint160 address2 = result.NewContractAddress; // Invoke infinite loop var gasLimit = (Gas)500_000; object[] parameters = { address1.ToAddress() }; contractTxData = new ContractTxData(1, (Gas)1, gasLimit, address2, "CallInfiniteLoop", parameters); transaction = new Transaction(); txOut = transaction.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); txOut.Value = 100; transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, SenderAddress, transaction); var callExecutor = new ContractExecutor(this.loggerFactory, this.callDataSerializer, this.state, this.refundProcessor, this.transferProcessor, this.stateFactory, this.stateProcessor, this.contractPrimitiveSerializer); // Because our contract contains an infinite loop, we want to kill our test after // some amount of time without achieving a result. 3 seconds is an arbitrarily high enough timeout // for the method body to have finished execution while minimising the amount of time we spend // running tests // If you're running with the debugger on this will obviously be a source of failures result = TimeoutHelper.RunCodeWithTimeout(3, () => callExecutor.Execute(transactionContext)); // Actual call was successful, but internal call failed due to gas - returned false. Assert.False(result.Revert); Assert.False((bool) result.Return); } [Fact] public void Execute_NestedLoop_ExecutionSucceeds() { AssertSuccessfulContractMethodExecution(nameof(NestedLoop), nameof(NestedLoop.GetNumbers), new object[] { (int)6 }, "1; 1,2; 1,2,3; 1,2,3,4; 1,2,3,4,5; 1,2,3,4,5,6; "); } [Fact] public void Execute_MultipleIfElseBlocks_ExecutionSucceeds() { AssertSuccessfulContractMethodExecution(nameof(MultipleIfElseBlocks), nameof(MultipleIfElseBlocks.PersistNormalizeValue), new object[] { "z" }); } private void AssertSuccessfulContractMethodExecution(string contractName, string methodName, object[] methodParameters = null, string expectedReturn = null) { var transactionValue = (Money)100; var executor = new ContractExecutor(this.loggerFactory, this.callDataSerializer, this.state, this.refundProcessor, this.transferProcessor, this.stateFactory, this.stateProcessor, this.contractPrimitiveSerializer); ContractCompilationResult compilationResult = ContractCompiler.CompileFile($"SmartContracts/{contractName}.cs"); Assert.True(compilationResult.Success); byte[] contractExecutionCode = compilationResult.Compilation; var contractTxData = new ContractTxData(1, (Gas)1, (Gas)500_000, contractExecutionCode); var transaction = new Transaction(); TxOut txOut = transaction.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); txOut.Value = transactionValue; var transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, SenderAddress, transaction); IContractExecutionResult result = executor.Execute(transactionContext); uint160 contractAddress = result.NewContractAddress; contractTxData = new ContractTxData(1, (Gas)1, (Gas)500_000, contractAddress, methodName, methodParameters); transaction = new Transaction(); txOut = transaction.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); txOut.Value = transactionValue; transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, SenderAddress, transaction); result = executor.Execute(transactionContext); Assert.NotNull(result); Assert.Null(result.ErrorMessage); if (expectedReturn != null) { Assert.NotNull(result.Return); Assert.Equal(expectedReturn, (string)result.Return); } } } }
#region License // // Copyright (c) 2018, Fluent Migrator Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using FluentMigrator.Runner.Helpers; #region License // // Copyright (c) 2007-2018, Sean Chambers <schambers80@gmail.com> // Copyright (c) 2010, Nathan Brown // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.IO; using FluentMigrator.Expressions; using FluentMigrator.Runner.BatchParser; using FluentMigrator.Runner.BatchParser.Sources; using FluentMigrator.Runner.BatchParser.SpecialTokenSearchers; using FluentMigrator.Runner.Generators.SqlServer; using FluentMigrator.Runner.Initialization; using JetBrains.Annotations; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace FluentMigrator.Runner.Processors.SqlServer { public class SqlServer2000Processor : GenericProcessorBase { [CanBeNull] private readonly IServiceProvider _serviceProvider; [Obsolete] public SqlServer2000Processor(IDbConnection connection, IMigrationGenerator generator, IAnnouncer announcer, IMigrationProcessorOptions options, IDbFactory factory) : base(connection, factory, generator, announcer, options) { } public SqlServer2000Processor( [NotNull] ILogger<SqlServer2000Processor> logger, [NotNull] SqlServer2000Generator generator, [NotNull] IOptionsSnapshot<ProcessorOptions> options, [NotNull] IConnectionStringAccessor connectionStringAccessor, [NotNull] IServiceProvider serviceProvider) : this(SqlClientFactory.Instance, logger, generator, options, connectionStringAccessor, serviceProvider) { } protected SqlServer2000Processor( DbProviderFactory factory, [NotNull] ILogger logger, [NotNull] SqlServer2000Generator generator, [NotNull] IOptionsSnapshot<ProcessorOptions> options, [NotNull] IConnectionStringAccessor connectionStringAccessor, [NotNull] IServiceProvider serviceProvider) : base(() => factory, generator, logger, options.Value, connectionStringAccessor) { _serviceProvider = serviceProvider; } public override string DatabaseType => "SqlServer2000"; public override IList<string> DatabaseTypeAliases { get; } = new List<string>() { "SqlServer" }; public override void BeginTransaction() { base.BeginTransaction(); Logger.LogSql("BEGIN TRANSACTION"); } public override void CommitTransaction() { base.CommitTransaction(); Logger.LogSql("COMMIT TRANSACTION"); } public override void RollbackTransaction() { if (Transaction == null) { return; } base.RollbackTransaction(); Logger.LogSql("ROLLBACK TRANSACTION"); } public override bool SchemaExists(string schemaName) { return true; } public override bool TableExists(string schemaName, string tableName) { try { return Exists("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{0}'", FormatHelper.FormatSqlEscape(tableName)); } catch (Exception e) { Logger.LogError(e, "There was an exception checking if table {Table} in {Schema} exists", tableName, schemaName); } return false; } public override bool ColumnExists(string schemaName, string tableName, string columnName) { return Exists("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{0}' AND COLUMN_NAME = '{1}'", FormatHelper.FormatSqlEscape(tableName), FormatHelper.FormatSqlEscape(columnName)); } public override bool ConstraintExists(string schemaName, string tableName, string constraintName) { return Exists("SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_CATALOG = DB_NAME() AND TABLE_NAME = '{0}' AND CONSTRAINT_NAME = '{1}'", FormatHelper.FormatSqlEscape(tableName), FormatHelper.FormatSqlEscape(constraintName)); } public override bool IndexExists(string schemaName, string tableName, string indexName) { return Exists("SELECT NULL FROM sysindexes WHERE name = '{0}'", FormatHelper.FormatSqlEscape(indexName)); } public override bool SequenceExists(string schemaName, string sequenceName) { return false; } public override bool DefaultValueExists(string schemaName, string tableName, string columnName, object defaultValue) { return false; } public override DataSet ReadTableData(string schemaName, string tableName) { return Read("SELECT * FROM [{0}]", tableName); } public override DataSet Read(string template, params object[] args) { EnsureConnectionIsOpen(); using (var command = CreateCommand(string.Format(template, args))) using (var reader = command.ExecuteReader()) { return reader.ReadDataSet(); } } public override bool Exists(string template, params object[] args) { EnsureConnectionIsOpen(); using (var command = CreateCommand(string.Format(template, args))) using (var reader = command.ExecuteReader()) { return reader.Read(); } } public override void Execute(string template, params object[] args) { Process(string.Format(template, args)); } protected override void Process(string sql) { Logger.LogSql(sql); if (Options.PreviewOnly || string.IsNullOrEmpty(sql)) { return; } EnsureConnectionIsOpen(); if (ContainsGo(sql)) { ExecuteBatchNonQuery(sql); } else { ExecuteNonQuery(sql); } } private bool ContainsGo(string sql) { var containsGo = false; var parser = _serviceProvider?.GetService<SqlServerBatchParser>() ?? new SqlServerBatchParser(); parser.SpecialToken += (sender, args) => containsGo = true; using (var source = new TextReaderSource(new StringReader(sql), true)) { parser.Process(source); } return containsGo; } private void ExecuteNonQuery(string sql) { using (var command = CreateCommand(sql)) { try { command.ExecuteNonQuery(); } catch (Exception ex) { using (var message = new StringWriter()) { message.WriteLine("An error occured executing the following sql:"); message.WriteLine(sql); message.WriteLine("The error was {0}", ex.Message); throw new Exception(message.ToString(), ex); } } } } private void ExecuteBatchNonQuery(string sql) { sql += "\nGO"; // make sure last batch is executed. var sqlBatch = string.Empty; try { var parser = _serviceProvider?.GetService<SqlServerBatchParser>() ?? new SqlServerBatchParser(); parser.SqlText += (sender, args) => sqlBatch = args.SqlText.Trim(); parser.SpecialToken += (sender, args) => { if (string.IsNullOrEmpty(sqlBatch)) { return; } if (args.Opaque is GoSearcher.GoSearcherParameters goParams) { using (var command = CreateCommand(sqlBatch)) { for (var i = 0; i != goParams.Count; ++i) { command.ExecuteNonQuery(); } } } sqlBatch = null; }; using (var source = new TextReaderSource(new StringReader(sql), true)) { parser.Process(source, stripComments: Options.StripComments); } } catch (Exception ex) { using (var message = new StringWriter()) { message.WriteLine("An error occured executing the following sql:"); message.WriteLine(string.IsNullOrEmpty(sqlBatch) ? sql : sqlBatch); message.WriteLine("The error was {0}", ex.Message); throw new Exception(message.ToString(), ex); } } } public override void Process(PerformDBOperationExpression expression) { EnsureConnectionIsOpen(); expression.Operation?.Invoke(Connection, Transaction); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using DotNETJumpStart.Areas.HelpPage.ModelDescriptions; using DotNETJumpStart.Areas.HelpPage.Models; namespace DotNETJumpStart.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using ICSharpCode.SharpZipLib.Checksum; using ICSharpCode.SharpZipLib.Encryption; using ICSharpCode.SharpZipLib.Zip.Compression; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; using System; using System.IO; namespace ICSharpCode.SharpZipLib.Zip { /// <summary> /// This is an InflaterInputStream that reads the files baseInputStream an zip archive /// one after another. It has a special method to get the zip entry of /// the next file. The zip entry contains information about the file name /// size, compressed size, Crc, etc. /// It includes support for Stored and Deflated entries. /// <br/> /// <br/>Author of the original java version : Jochen Hoenicke /// </summary> /// /// <example> This sample shows how to read a zip file /// <code lang="C#"> /// using System; /// using System.Text; /// using System.IO; /// /// using ICSharpCode.SharpZipLib.Zip; /// /// class MainClass /// { /// public static void Main(string[] args) /// { /// using ( ZipInputStream s = new ZipInputStream(File.OpenRead(args[0]))) { /// /// ZipEntry theEntry; /// const int size = 2048; /// byte[] data = new byte[2048]; /// /// while ((theEntry = s.GetNextEntry()) != null) { /// if ( entry.IsFile ) { /// Console.Write("Show contents (y/n) ?"); /// if (Console.ReadLine() == "y") { /// while (true) { /// size = s.Read(data, 0, data.Length); /// if (size > 0) { /// Console.Write(new ASCIIEncoding().GetString(data, 0, size)); /// } else { /// break; /// } /// } /// } /// } /// } /// } /// } /// } /// </code> /// </example> public class ZipInputStream : InflaterInputStream { #region Instance Fields /// <summary> /// Delegate for reading bytes from a stream. /// </summary> private delegate int ReadDataHandler(byte[] b, int offset, int length); /// <summary> /// The current reader this instance. /// </summary> private ReadDataHandler internalReader; private Crc32 crc = new Crc32(); private ZipEntry entry; private long size; private int method; private int flags; private string password; #endregion Instance Fields #region Constructors /// <summary> /// Creates a new Zip input stream, for reading a zip archive. /// </summary> /// <param name="baseInputStream">The underlying <see cref="Stream"/> providing data.</param> public ZipInputStream(Stream baseInputStream) : base(baseInputStream, new Inflater(true)) { internalReader = new ReadDataHandler(ReadingNotAvailable); } /// <summary> /// Creates a new Zip input stream, for reading a zip archive. /// </summary> /// <param name="baseInputStream">The underlying <see cref="Stream"/> providing data.</param> /// <param name="bufferSize">Size of the buffer.</param> public ZipInputStream(Stream baseInputStream, int bufferSize) : base(baseInputStream, new Inflater(true), bufferSize) { internalReader = new ReadDataHandler(ReadingNotAvailable); } #endregion Constructors /// <summary> /// Optional password used for encryption when non-null /// </summary> /// <value>A password for all encrypted <see cref="ZipEntry">entries </see> in this <see cref="ZipInputStream"/></value> public string Password { get { return password; } set { password = value; } } /// <summary> /// Gets a value indicating if there is a current entry and it can be decompressed /// </summary> /// <remarks> /// The entry can only be decompressed if the library supports the zip features required to extract it. /// See the <see cref="ZipEntry.Version">ZipEntry Version</see> property for more details. /// </remarks> public bool CanDecompressEntry { get { return (entry != null) && entry.CanDecompress; } } /// <summary> /// Advances to the next entry in the archive /// </summary> /// <returns> /// The next <see cref="ZipEntry">entry</see> in the archive or null if there are no more entries. /// </returns> /// <remarks> /// If the previous entry is still open <see cref="CloseEntry">CloseEntry</see> is called. /// </remarks> /// <exception cref="InvalidOperationException"> /// Input stream is closed /// </exception> /// <exception cref="ZipException"> /// Password is not set, password is invalid, compression method is invalid, /// version required to extract is not supported /// </exception> public ZipEntry GetNextEntry() { if (crc == null) { throw new InvalidOperationException("Closed."); } if (entry != null) { CloseEntry(); } int header = inputBuffer.ReadLeInt(); if (header == ZipConstants.CentralHeaderSignature || header == ZipConstants.EndOfCentralDirectorySignature || header == ZipConstants.CentralHeaderDigitalSignature || header == ZipConstants.ArchiveExtraDataSignature || header == ZipConstants.Zip64CentralFileHeaderSignature) { // No more individual entries exist Dispose(); return null; } // -jr- 07-Dec-2003 Ignore spanning temporary signatures if found // Spanning signature is same as descriptor signature and is untested as yet. if ((header == ZipConstants.SpanningTempSignature) || (header == ZipConstants.SpanningSignature)) { header = inputBuffer.ReadLeInt(); } if (header != ZipConstants.LocalHeaderSignature) { throw new ZipException("Wrong Local header signature: 0x" + String.Format("{0:X}", header)); } var versionRequiredToExtract = (short)inputBuffer.ReadLeShort(); flags = inputBuffer.ReadLeShort(); method = inputBuffer.ReadLeShort(); var dostime = (uint)inputBuffer.ReadLeInt(); int crc2 = inputBuffer.ReadLeInt(); csize = inputBuffer.ReadLeInt(); size = inputBuffer.ReadLeInt(); int nameLen = inputBuffer.ReadLeShort(); int extraLen = inputBuffer.ReadLeShort(); bool isCrypted = (flags & 1) == 1; byte[] buffer = new byte[nameLen]; inputBuffer.ReadRawBuffer(buffer); string name = ZipStrings.ConvertToStringExt(flags, buffer); entry = new ZipEntry(name, versionRequiredToExtract, ZipConstants.VersionMadeBy, (CompressionMethod)method) { Flags = flags, }; if ((flags & 8) == 0) { entry.Crc = crc2 & 0xFFFFFFFFL; entry.Size = size & 0xFFFFFFFFL; entry.CompressedSize = csize & 0xFFFFFFFFL; entry.CryptoCheckValue = (byte)((crc2 >> 24) & 0xff); } else { // This allows for GNU, WinZip and possibly other archives, the PKZIP spec // says these values are zero under these circumstances. if (crc2 != 0) { entry.Crc = crc2 & 0xFFFFFFFFL; } if (size != 0) { entry.Size = size & 0xFFFFFFFFL; } if (csize != 0) { entry.CompressedSize = csize & 0xFFFFFFFFL; } entry.CryptoCheckValue = (byte)((dostime >> 8) & 0xff); } entry.DosTime = dostime; // If local header requires Zip64 is true then the extended header should contain // both values. // Handle extra data if present. This can set/alter some fields of the entry. if (extraLen > 0) { byte[] extra = new byte[extraLen]; inputBuffer.ReadRawBuffer(extra); entry.ExtraData = extra; } entry.ProcessExtraData(true); if (entry.CompressedSize >= 0) { csize = entry.CompressedSize; } if (entry.Size >= 0) { size = entry.Size; } if (method == (int)CompressionMethod.Stored && (!isCrypted && csize != size || (isCrypted && csize - ZipConstants.CryptoHeaderSize != size))) { throw new ZipException("Stored, but compressed != uncompressed"); } // Determine how to handle reading of data if this is attempted. if (entry.IsCompressionMethodSupported()) { internalReader = new ReadDataHandler(InitialRead); } else { internalReader = new ReadDataHandler(ReadingNotSupported); } return entry; } /// <summary> /// Read data descriptor at the end of compressed data. /// </summary> private void ReadDataDescriptor() { if (inputBuffer.ReadLeInt() != ZipConstants.DataDescriptorSignature) { throw new ZipException("Data descriptor signature not found"); } entry.Crc = inputBuffer.ReadLeInt() & 0xFFFFFFFFL; if (entry.LocalHeaderRequiresZip64) { csize = inputBuffer.ReadLeLong(); size = inputBuffer.ReadLeLong(); } else { csize = inputBuffer.ReadLeInt(); size = inputBuffer.ReadLeInt(); } entry.CompressedSize = csize; entry.Size = size; } /// <summary> /// Complete cleanup as the final part of closing. /// </summary> /// <param name="testCrc">True if the crc value should be tested</param> private void CompleteCloseEntry(bool testCrc) { StopDecrypting(); if ((flags & 8) != 0) { ReadDataDescriptor(); } size = 0; if (testCrc && ((crc.Value & 0xFFFFFFFFL) != entry.Crc) && (entry.Crc != -1)) { throw new ZipException("CRC mismatch"); } crc.Reset(); if (method == (int)CompressionMethod.Deflated) { inf.Reset(); } entry = null; } /// <summary> /// Closes the current zip entry and moves to the next one. /// </summary> /// <exception cref="InvalidOperationException"> /// The stream is closed /// </exception> /// <exception cref="ZipException"> /// The Zip stream ends early /// </exception> public void CloseEntry() { if (crc == null) { throw new InvalidOperationException("Closed"); } if (entry == null) { return; } if (method == (int)CompressionMethod.Deflated) { if ((flags & 8) != 0) { // We don't know how much we must skip, read until end. byte[] tmp = new byte[4096]; // Read will close this entry while (Read(tmp, 0, tmp.Length) > 0) { } return; } csize -= inf.TotalIn; inputBuffer.Available += inf.RemainingInput; } if ((inputBuffer.Available > csize) && (csize >= 0)) { inputBuffer.Available = (int)((long)inputBuffer.Available - csize); } else { csize -= inputBuffer.Available; inputBuffer.Available = 0; while (csize != 0) { long skipped = Skip(csize); if (skipped <= 0) { throw new ZipException("Zip archive ends early."); } csize -= skipped; } } CompleteCloseEntry(false); } /// <summary> /// Returns 1 if there is an entry available /// Otherwise returns 0. /// </summary> public override int Available { get { return entry != null ? 1 : 0; } } /// <summary> /// Returns the current size that can be read from the current entry if available /// </summary> /// <exception cref="ZipException">Thrown if the entry size is not known.</exception> /// <exception cref="InvalidOperationException">Thrown if no entry is currently available.</exception> public override long Length { get { if (entry != null) { if (entry.Size >= 0) { return entry.Size; } else { throw new ZipException("Length not available for the current entry"); } } else { throw new InvalidOperationException("No current entry"); } } } /// <summary> /// Reads a byte from the current zip entry. /// </summary> /// <returns> /// The byte or -1 if end of stream is reached. /// </returns> public override int ReadByte() { byte[] b = new byte[1]; if (Read(b, 0, 1) <= 0) { return -1; } return b[0] & 0xff; } /// <summary> /// Handle attempts to read by throwing an <see cref="InvalidOperationException"/>. /// </summary> /// <param name="destination">The destination array to store data in.</param> /// <param name="offset">The offset at which data read should be stored.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <returns>Returns the number of bytes actually read.</returns> private int ReadingNotAvailable(byte[] destination, int offset, int count) { throw new InvalidOperationException("Unable to read from this stream"); } /// <summary> /// Handle attempts to read from this entry by throwing an exception /// </summary> private int ReadingNotSupported(byte[] destination, int offset, int count) { throw new ZipException("The compression method for this entry is not supported"); } /// <summary> /// Perform the initial read on an entry which may include /// reading encryption headers and setting up inflation. /// </summary> /// <param name="destination">The destination to fill with data read.</param> /// <param name="offset">The offset to start reading at.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <returns>The actual number of bytes read.</returns> private int InitialRead(byte[] destination, int offset, int count) { if (!CanDecompressEntry) { throw new ZipException("Library cannot extract this entry. Version required is (" + entry.Version + ")"); } // Handle encryption if required. if (entry.IsCrypted) { if (password == null) { throw new ZipException("No password set."); } // Generate and set crypto transform... var managed = new PkzipClassicManaged(); byte[] key = PkzipClassic.GenerateKeys(ZipStrings.ConvertToArray(password)); inputBuffer.CryptoTransform = managed.CreateDecryptor(key, null); byte[] cryptbuffer = new byte[ZipConstants.CryptoHeaderSize]; inputBuffer.ReadClearTextBuffer(cryptbuffer, 0, ZipConstants.CryptoHeaderSize); if (cryptbuffer[ZipConstants.CryptoHeaderSize - 1] != entry.CryptoCheckValue) { throw new ZipException("Invalid password"); } if (csize >= ZipConstants.CryptoHeaderSize) { csize -= ZipConstants.CryptoHeaderSize; } else if ((entry.Flags & (int)GeneralBitFlags.Descriptor) == 0) { throw new ZipException(string.Format("Entry compressed size {0} too small for encryption", csize)); } } else { inputBuffer.CryptoTransform = null; } if ((csize > 0) || ((flags & (int)GeneralBitFlags.Descriptor) != 0)) { if ((method == (int)CompressionMethod.Deflated) && (inputBuffer.Available > 0)) { inputBuffer.SetInflaterInput(inf); } internalReader = new ReadDataHandler(BodyRead); return BodyRead(destination, offset, count); } else { internalReader = new ReadDataHandler(ReadingNotAvailable); return 0; } } /// <summary> /// Read a block of bytes from the stream. /// </summary> /// <param name="buffer">The destination for the bytes.</param> /// <param name="offset">The index to start storing data.</param> /// <param name="count">The number of bytes to attempt to read.</param> /// <returns>Returns the number of bytes read.</returns> /// <remarks>Zero bytes read means end of stream.</remarks> public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), "Cannot be negative"); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), "Cannot be negative"); } if ((buffer.Length - offset) < count) { throw new ArgumentException("Invalid offset/count combination"); } return internalReader(buffer, offset, count); } /// <summary> /// Reads a block of bytes from the current zip entry. /// </summary> /// <returns> /// The number of bytes read (this may be less than the length requested, even before the end of stream), or 0 on end of stream. /// </returns> /// <exception name="IOException"> /// An i/o error occured. /// </exception> /// <exception cref="ZipException"> /// The deflated stream is corrupted. /// </exception> /// <exception cref="InvalidOperationException"> /// The stream is not open. /// </exception> private int BodyRead(byte[] buffer, int offset, int count) { if (crc == null) { throw new InvalidOperationException("Closed"); } if ((entry == null) || (count <= 0)) { return 0; } if (offset + count > buffer.Length) { throw new ArgumentException("Offset + count exceeds buffer size"); } bool finished = false; switch (method) { case (int)CompressionMethod.Deflated: count = base.Read(buffer, offset, count); if (count <= 0) { if (!inf.IsFinished) { throw new ZipException("Inflater not finished!"); } inputBuffer.Available = inf.RemainingInput; // A csize of -1 is from an unpatched local header if ((flags & 8) == 0 && (inf.TotalIn != csize && csize != 0xFFFFFFFF && csize != -1 || inf.TotalOut != size)) { throw new ZipException("Size mismatch: " + csize + ";" + size + " <-> " + inf.TotalIn + ";" + inf.TotalOut); } inf.Reset(); finished = true; } break; case (int)CompressionMethod.Stored: if ((count > csize) && (csize >= 0)) { count = (int)csize; } if (count > 0) { count = inputBuffer.ReadClearTextBuffer(buffer, offset, count); if (count > 0) { csize -= count; size -= count; } } if (csize == 0) { finished = true; } else { if (count < 0) { throw new ZipException("EOF in stored block"); } } break; } if (count > 0) { crc.Update(new ArraySegment<byte>(buffer, offset, count)); } if (finished) { CompleteCloseEntry(true); } return count; } /// <summary> /// Closes the zip input stream /// </summary> protected override void Dispose(bool disposing) { internalReader = new ReadDataHandler(ReadingNotAvailable); crc = null; entry = null; base.Dispose(disposing); } } }
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- function SpriteStressToy::create( %this ) { // Set the sandbox drag mode availability. Sandbox.allowManipulation( pan ); // Set the manipulation mode. Sandbox.useManipulation( pan ); // Turn-off the full metrics. setMetricsOption( false ); // Turn-on the FPS metrics only. setFPSMetricsOption( true ); // Configure the toy. SpriteStressToy.SpriteSceneLayer = 10; SpriteStressToy.MaxSprite = 100; SpriteStressToy.SpriteCreateRate = 50; SpriteStressToy.SpriteCreatePeriod = 100; SpriteStressToy.SpriteSize = 8; SpriteStressToy.RandomAngle = false; SpriteStressToy.RenderMode = "Static"; SpriteStressToy.RenderSortMode = "off"; // Add the configuration options. addNumericOption("Sprite Maximum", 1, 100000, 100, "setSpriteMaximum", SpriteStressToy.MaxSprite, true, "Sets the maximum number of sprites to create." ); addNumericOption("Sprite Size", 1, 75, 1, "setSpriteSize", SpriteStressToy.SpriteSize, true, "Sets the size of the sprites to create." ); addFlagOption("Random Angle", "setSpriteRandomAngle", SpriteStressToy.RandomAngle, true, "Whether to place the sprites at a random angle or not." ); addNumericOption("Sprite Create Period (ms)", 10, 1000, 10, "setSpriteCreatePeriod", SpriteStressToy.SpriteCreatePeriod, true, "Sets the time interval for creating bursts of sprites. Bigger values create the maximum sprites quicker." ); addSelectionOption( "Static,Static (Composite),Animated,Animated (Composite)", "Render Mode", 4, "setRenderMode", true, "Sets the type of object used in the stress test." ); addSelectionOption( "Off,New,Old,X,Y,Z,-X,-Y,-Z", "Render Sort Mode", 9, "setRenderSortMode", false, "Sets the render sorting mode controlling the order of rendering." ); // Reset the toy. SpriteStressToy.reset(); } //----------------------------------------------------------------------------- function SpriteStressToy::destroy( %this ) { } //----------------------------------------------------------------------------- function SpriteStressToy::reset( %this ) { // Reset sprite count. SpriteStressToy.SpriteCount = 0; // Calculate sprite bounds. SpriteStressToy.HalfSize = SpriteStressToy.SpriteSize * 0.5; SpriteStressToy.MinX = -50 + SpriteStressToy.HalfSize; SpriteStressToy.MaxX = 50 - SpriteStressToy.HalfSize; SpriteStressToy.MinY = -37.5 + SpriteStressToy.HalfSize; SpriteStressToy.MaxY = 37.5 - SpriteStressToy.HalfSize; // Clear the scene. SandboxScene.clear(); // Update the render sort mode. %this.updateRenderSortMode(); // Create background. %this.createBackground(); // Create sprite count overlay. %this.createSpriteCountOverlay(); // Handle static sprites. if ( SpriteStressToy.RenderMode $= "Static" ) { // Create the static sprites. SpriteStressToy.startTimer( "createStaticSprites", SpriteStressToy.SpriteCreatePeriod ); return; } // Handle static composite sprites. if ( SpriteStressToy.RenderMode $= "Static (Composite)" ) { // Create the static composite sprites. SpriteStressToy.startTimer( "createStaticCompositeSprites", SpriteStressToy.SpriteCreatePeriod ); return; } // Handle animated sprites. if ( SpriteStressToy.RenderMode $= "Animated" ) { // Create the animated sprites. SpriteStressToy.startTimer( "createAnimatedSprites", SpriteStressToy.SpriteCreatePeriod ); return; } // Handle animated composite sprites. if ( SpriteStressToy.RenderMode $= "Animated (Composite)" ) { // Create the animated composite sprites. SpriteStressToy.startTimer( "createAnimatedCompositeSprites", SpriteStressToy.SpriteCreatePeriod ); return; } // Error. error( "SpriteStressToy::reset() - Unknown render mode." ); } //----------------------------------------------------------------------------- function SpriteStressToy::createBackground( %this ) { // Create the sprite. %object = new Scroller(); // Set the sprite as "static" so it is not affected by gravity. %object.setBodyType( static ); // Always try to configure a scene-object prior to adding it to a scene for best performance. // Set the position. %object.Position = "0 0"; // Set the size. %object.Size = "100 75"; // Set to the furthest background layer. %object.SceneLayer = 31; // Set an image. %object.Image = "ToyAssets:checkered"; %object.ScrollX = 4; %object.ScrollY = 3; %object.RepeatX = 4; %object.RepeatY = 3; // Set the blend color. %object.BlendColor = LightSteelBlue; // Add the sprite to the scene. SandboxScene.add( %object ); } //----------------------------------------------------------------------------- function SpriteStressToy::createSpriteCountOverlay( %this ) { // Create the image font. %object = new ImageFont(); // Set the overlay font object. SpriteStressToy.OverlayFontObject = %object; // Set the sprite as "static" so it is not affected by gravity. %object.setBodyType( static ); // Always try to configure a scene-object prior to adding it to a scene for best performance. // Set the position. %object.Position = "-50 -35"; // Set the size. %object.FontSize = 2; // Set the text alignment. %object.TextAlignment = Left; // Set to the nearest layer. %object.SceneLayer = 0; // Set a font image. %object.Image = "ToyAssets:fancyFont"; // Set the blend color. %object.BlendColor = White; // Add the sprite to the scene. SandboxScene.add( %object ); // Update the overlay. %this.updateSpriteCountOverlay(); } //----------------------------------------------------------------------------- function SpriteStressToy::updateSpriteCountOverlay( %this ) { // Update sprite count overlay. SpriteStressToy.OverlayFontObject.Text = SpriteStressToy.SpriteCount; } //----------------------------------------------------------------------------- function SpriteStressToy::updateRenderSortMode( %this ) { // Set the sprite layer sort mode. SandboxScene.setLayerSortMode( SpriteStressToy.SpriteSceneLayer, SpriteStressToy.RenderSortMode ); // Finish if no composite-sprite object. if ( !isObject(SpriteStressToy.CompositeSpriteObject) ) return; // Set the batch sort mode. SpriteStressToy.CompositeSpriteObject.SetBatchSortMode( SpriteStressToy.RenderSortMode ); } //----------------------------------------------------------------------------- function SpriteStressToy::createStaticSprites( %this ) { // Finish if max sprites reached. if ( SpriteStressToy.SpriteCount >= SpriteStressToy.MaxSprite ) { // Stop the timer. SpriteStressToy.stopTimer(); return; } // Create the sprites at the specified rate. for( %n = 0; %n < SpriteStressToy.SpriteCreateRate; %n++ ) { // Create the sprite. %object = new Sprite(); // Always try to configure a scene-object prior to adding it to a scene for best performance. // The sprite is static i.e. it won't move. %object.BodyType = static; // Set the position. %object.Position = getRandom(SpriteStressToy.MinX, SpriteStressToy.MaxX) SPC getRandom(SpriteStressToy.MinY, SpriteStressToy.MaxY); // Set to just in-front of the background layer. %object.SceneLayer = SpriteStressToy.SpriteSceneLayer; // Set a random scene-layer depth. %object.SceneLayerDepth = getRandom(-100,100); // Set the size of the sprite. %object.Size = SpriteStressToy.SpriteSize; // Set a random angle if selected. if ( SpriteStressToy.RandomAngle ) %object.Angle = getRandom(0,360); // Set the sprite to use an image. This is known as "static" image mode. %object.Image = "ToyAssets:TD_Knight_CompSprite"; // We don't really need to do this as the frame is set to zero by default. %object.Frame = getRandom(0,63); // Add the sprite to the scene. SandboxScene.add( %object ); // Increase sprite count. SpriteStressToy.SpriteCount++; // Finish if max sprites reached. if ( SpriteStressToy.SpriteCount == SpriteStressToy.MaxSprite ) { // Update the overlay. %this.updateSpriteCountOverlay(); // Stop the timer. SpriteStressToy.stopTimer(); return; } } // Update the overlay. %this.updateSpriteCountOverlay(); } //----------------------------------------------------------------------------- function SpriteStressToy::createAnimatedSprites( %this ) { // Finish if max sprites reached. if ( SpriteStressToy.SpriteCount >= SpriteStressToy.MaxSprite ) { // Stop the timer. SpriteStressToy.stopTimer(); return; } // Create the sprites at the specified rate. for( %n = 0; %n < SpriteStressToy.SpriteCreateRate; %n++ ) { // Create the sprite. %object = new Sprite(); // Always try to configure a scene-object prior to adding it to a scene for best performance. // The sprite is static i.e. it won't move. %object.BodyType = static; // Set the position. %object.Position = getRandom(SpriteStressToy.MinX, SpriteStressToy.MaxX) SPC getRandom(SpriteStressToy.MinY, SpriteStressToy.MaxY); // Set to just in-front of the background layer. %object.SceneLayer = SpriteStressToy.SpriteSceneLayer; // Set a random scene-layer depth. %object.SceneLayerDepth = getRandom(-100,100); // Set the size of the sprite. %object.Size = SpriteStressToy.SpriteSize; // Set a random angle if selected. if ( SpriteStressToy.RandomAngle ) %object.Angle = getRandom(0,360); // Set the sprite to use an animation. This is known as "animated" image mode. %object.Animation = "ToyAssets:TD_Knight_MoveSouth"; // Add the sprite to the scene. SandboxScene.add( %object ); // Increase sprite count. SpriteStressToy.SpriteCount++; // Finish if max sprites reached. if ( SpriteStressToy.SpriteCount == SpriteStressToy.MaxSprite ) { // Update the overlay. %this.updateSpriteCountOverlay(); // Stop the timer. SpriteStressToy.stopTimer(); return; } } // Update the overlay. %this.updateSpriteCountOverlay(); } //----------------------------------------------------------------------------- function SpriteStressToy::createStaticCompositeSprites( %this ) { // Finish if max sprites reached. if ( SpriteStressToy.SpriteCount >= SpriteStressToy.MaxSprite ) { // Stop the timer. SpriteStressToy.stopTimer(); return; } // Do we have a composite sprite yet? if ( !isObject(SpriteStressToy.CompositeSpriteObject) ) { // No, so create it. %composite = new CompositeSprite(); // Set the composite object. SpriteStressToy.CompositeSpriteObject = %composite; // The sprite is static i.e. it won't move. %composite.BodyType = static; // Set the batch layout mode. We must do this before we add any sprites. %composite.SetBatchLayout( "off" ); // Set the batch render isolation. %composite.SetBatchIsolated( SpriteStressToy.RenderSortMode ); // Set to just in-front of the background layer. %composite.SceneLayer = SpriteStressToy.SpriteSceneLayer; // Set the batch to not cull because the sprites are always on the screen // and it's faster and takes less memory. %composite.setBatchCulling( false ); // Add to the scene. SandboxScene.add( %composite ); } // Fetch the composite object. %composite = SpriteStressToy.CompositeSpriteObject; // Create the sprites at the specified rate. for( %n = 0; %n < SpriteStressToy.SpriteCreateRate; %n++ ) { // Add a sprite with no logical position. %composite.addSprite(); // Set the sprites location position to a random location. %composite.setSpriteLocalPosition( getRandom(SpriteStressToy.MinX, SpriteStressToy.MaxX), getRandom(SpriteStressToy.MinY, SpriteStressToy.MaxY) ); // Set a random size. %composite.setSpriteSize( SpriteStressToy.SpriteSize ); // Set a random angle. if ( SpriteStressToy.RandomAngle ) %composite.setSpriteAngle( getRandom(0,360) ); // Set the sprite to use an image. %composite.setSpriteImage( "ToyAssets:TD_Knight_CompSprite", getRandom(0,63) ); // Set a random depth. %composite.SetSpriteDepth( getRandom( -100, 100 ) ); // Increase sprite count. SpriteStressToy.SpriteCount++; // Finish if max sprites reached. if ( SpriteStressToy.SpriteCount == SpriteStressToy.MaxSprite ) { // Update the overlay. %this.updateSpriteCountOverlay(); // Stop the timer. SpriteStressToy.stopTimer(); return; } } // Update the overlay. %this.updateSpriteCountOverlay(); } //----------------------------------------------------------------------------- function SpriteStressToy::createAnimatedCompositeSprites( %this ) { // Finish if max sprites reached. if ( SpriteStressToy.SpriteCount >= SpriteStressToy.MaxSprite ) { // Stop the timer. SpriteStressToy.stopTimer(); return; } // Do we have a composite sprite yet? if ( !isObject(SpriteStressToy.CompositeSpriteObject) ) { // No, so create it. %composite = new CompositeSprite(); // Set the composite object. SpriteStressToy.CompositeSpriteObject = %composite; // The sprite is static i.e. it won't move. %composite.BodyType = static; // Set the batch layout mode. We must do this before we add any sprites. %composite.SetBatchLayout( "off" ); // Set the batch render isolation. %composite.SetBatchIsolated( SpriteStressToy.RenderSortMode ); // Set to just in-front of the background layer. %composite.SceneLayer = SpriteStressToy.SpriteSceneLayer; // Set the batch to not cull because the sprites are always on the screen // and it's faster and takes less memory. %composite.setBatchCulling( false ); // Add to the scene. SandboxScene.add( %composite ); } // Fetch the composite object. %composite = SpriteStressToy.CompositeSpriteObject; // Create the sprites at the specified rate. for( %n = 0; %n < SpriteStressToy.SpriteCreateRate; %n++ ) { // Add a sprite with no logical position. %composite.addSprite(); // Set the sprites location position to a random location. %composite.setSpriteLocalPosition( getRandom(SpriteStressToy.MinX, SpriteStressToy.MaxX), getRandom(SpriteStressToy.MinY, SpriteStressToy.MaxY) ); // Set a random size. %composite.setSpriteSize( SpriteStressToy.SpriteSize ); // Set a random angle. if ( SpriteStressToy.RandomAngle ) %composite.setSpriteAngle( getRandom(0,360) ); // Set the sprite to use an animation. %composite.setSpriteAnimation( "ToyAssets:TD_Knight_MoveSouth" ); // Set a random depth. %composite.SetSpriteDepth( getRandom( -100, 100 ) ); // Increase sprite count. SpriteStressToy.SpriteCount++; // Finish if max sprites reached. if ( SpriteStressToy.SpriteCount == SpriteStressToy.MaxSprite ) { // Update the overlay. %this.updateSpriteCountOverlay(); // Stop the timer. SpriteStressToy.stopTimer(); return; } } // Update the overlay. %this.updateSpriteCountOverlay(); } //----------------------------------------------------------------------------- function SpriteStressToy::setSpriteMaximum( %this, %value ) { SpriteStressToy.MaxSprite = %value; } //----------------------------------------------------------------------------- function SpriteStressToy::setSpriteSize( %this, %value ) { SpriteStressToy.SpriteSize = %value; } //----------------------------------------------------------------------------- function SpriteStressToy::setSpriteRandomAngle( %this, %value ) { SpriteStressToy.RandomAngle = %value; } //----------------------------------------------------------------------------- function SpriteStressToy::setSpriteCreatePeriod( %this, %value ) { SpriteStressToy.SpriteCreatePeriod = %value; } //----------------------------------------------------------------------------- function SpriteStressToy::setRenderMode( %this, %value ) { SpriteStressToy.RenderMode = %value; } //----------------------------------------------------------------------------- function SpriteStressToy::setRenderSortMode( %this, %value ) { SpriteStressToy.RenderSortMode = %value; // Update the render sort mode. %this.updateRenderSortMode(); }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json.Linq; using OrchardCore.Environment.Shell; using OrchardCore.OpenId.Settings; using OrchardCore.Settings; using static OpenIddict.Abstractions.OpenIddictConstants; namespace OrchardCore.OpenId.Services { public class OpenIdServerService : IOpenIdServerService { private readonly IDataProtector _dataProtector; private readonly ILogger _logger; private readonly IMemoryCache _memoryCache; private readonly IOptionsMonitor<ShellOptions> _shellOptions; private readonly ShellSettings _shellSettings; private readonly ISiteService _siteService; private readonly IStringLocalizer S; public OpenIdServerService( IDataProtectionProvider dataProtectionProvider, ILogger<OpenIdServerService> logger, IMemoryCache memoryCache, IOptionsMonitor<ShellOptions> shellOptions, ShellSettings shellSettings, ISiteService siteService, IStringLocalizer<OpenIdServerService> stringLocalizer) { _dataProtector = dataProtectionProvider.CreateProtector(nameof(OpenIdServerService)); _logger = logger; _memoryCache = memoryCache; _shellOptions = shellOptions; _shellSettings = shellSettings; _siteService = siteService; S = stringLocalizer; } public async Task<OpenIdServerSettings> GetSettingsAsync() { var container = await _siteService.GetSiteSettingsAsync(); if (container.Properties.TryGetValue(nameof(OpenIdServerSettings), out var settings)) { return settings.ToObject<OpenIdServerSettings>(); } // If the OpenID server settings haven't been populated yet, the authorization, // logout, token and userinfo endpoints are assumed to be enabled by default. // In this case, only the authorization code and refresh token flows are used. return new OpenIdServerSettings { AuthorizationEndpointPath = "/connect/authorize", GrantTypes = { GrantTypes.AuthorizationCode, GrantTypes.RefreshToken }, LogoutEndpointPath = "/connect/logout", TokenEndpointPath = "/connect/token", UserinfoEndpointPath = "/connect/userinfo" }; } public async Task UpdateSettingsAsync(OpenIdServerSettings settings) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } var container = await _siteService.LoadSiteSettingsAsync(); container.Properties[nameof(OpenIdServerSettings)] = JObject.FromObject(settings); await _siteService.UpdateSiteSettingsAsync(container); } public Task<ImmutableArray<ValidationResult>> ValidateSettingsAsync(OpenIdServerSettings settings) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } var results = ImmutableArray.CreateBuilder<ValidationResult>(); if (settings.GrantTypes.Count == 0) { results.Add(new ValidationResult(S["At least one OpenID Connect flow must be enabled."])); } if (settings.Authority != null) { if (!settings.Authority.IsAbsoluteUri || !settings.Authority.IsWellFormedOriginalString()) { results.Add(new ValidationResult(S["The authority must be a valid absolute URL."], new[] { nameof(settings.Authority) })); } if (!string.IsNullOrEmpty(settings.Authority.Query) || !string.IsNullOrEmpty(settings.Authority.Fragment)) { results.Add(new ValidationResult(S["The authority cannot contain a query string or a fragment."], new[] { nameof(settings.Authority) })); } } if (settings.UseReferenceTokens && settings.AccessTokenFormat != OpenIdServerSettings.TokenFormat.Encrypted) { results.Add(new ValidationResult(S["Reference tokens can only be enabled when using the Encrypted token format."], new[] { nameof(settings.UseReferenceTokens) })); } if (settings.CertificateStoreLocation != null && settings.CertificateStoreName != null && !string.IsNullOrEmpty(settings.CertificateThumbprint)) { var certificate = GetCertificate( settings.CertificateStoreLocation.Value, settings.CertificateStoreName.Value, settings.CertificateThumbprint); if (certificate == null) { results.Add(new ValidationResult(S["The certificate cannot be found."], new[] { nameof(settings.CertificateThumbprint) })); } else if (!certificate.HasPrivateKey) { results.Add(new ValidationResult(S["The certificate doesn't contain the required private key."], new[] { nameof(settings.CertificateThumbprint) })); } else if (certificate.Archived) { results.Add(new ValidationResult(S["The certificate is not valid because it is marked as archived."], new[] { nameof(settings.CertificateThumbprint) })); } else if (certificate.NotBefore > DateTime.Now || certificate.NotAfter < DateTime.Now) { results.Add(new ValidationResult(S["The certificate is not valid for current date."], new[] { nameof(settings.CertificateThumbprint) })); } } if (settings.GrantTypes.Contains(GrantTypes.Password) && !settings.TokenEndpointPath.HasValue) { results.Add(new ValidationResult(S["The password flow cannot be enabled when the token endpoint is disabled."], new[] { nameof(settings.GrantTypes) })); } if (settings.GrantTypes.Contains(GrantTypes.ClientCredentials) && !settings.TokenEndpointPath.HasValue) { results.Add(new ValidationResult(S["The client credentials flow cannot be enabled when the token endpoint is disabled."], new[] { nameof(settings.GrantTypes) })); } if (settings.GrantTypes.Contains(GrantTypes.AuthorizationCode) && (!settings.AuthorizationEndpointPath.HasValue || !settings.TokenEndpointPath.HasValue)) { results.Add(new ValidationResult(S["The authorization code flow cannot be enabled when the authorization and token endpoints are disabled."], new[] { nameof(settings.GrantTypes) })); } if (settings.GrantTypes.Contains(GrantTypes.RefreshToken)) { if (!settings.TokenEndpointPath.HasValue) { results.Add(new ValidationResult(S["The refresh token flow cannot be enabled when the token endpoint is disabled."], new[] { nameof(settings.GrantTypes) })); } if (!settings.GrantTypes.Contains(GrantTypes.Password) && !settings.GrantTypes.Contains(GrantTypes.AuthorizationCode)) { results.Add(new ValidationResult(S["The refresh token flow can only be enabled if the password, authorization code or hybrid flows are enabled."], new[] { nameof(settings.GrantTypes) })); } } if (settings.GrantTypes.Contains(GrantTypes.Implicit) && !settings.AuthorizationEndpointPath.HasValue) { results.Add(new ValidationResult(S["The implicit flow cannot be enabled when the authorization endpoint is disabled."], new[] { nameof(settings.GrantTypes) })); } return Task.FromResult(results.ToImmutable()); } public Task<ImmutableArray<(X509Certificate2 certificate, StoreLocation location, StoreName name)>> GetAvailableCertificatesAsync() { var certificates = ImmutableArray.CreateBuilder<(X509Certificate2, StoreLocation, StoreName)>(); foreach (StoreLocation location in Enum.GetValues(typeof(StoreLocation))) { foreach (StoreName name in Enum.GetValues(typeof(StoreName))) { // Note: on non-Windows platforms, an exception can // be thrown if the store location/name doesn't exist. try { using (var store = new X509Store(name, location)) { store.Open(OpenFlags.ReadOnly); foreach (var certificate in store.Certificates) { if (!certificate.Archived && certificate.HasPrivateKey) { certificates.Add((certificate, location, name)); } } } } catch (CryptographicException) { continue; } } } return Task.FromResult(certificates.ToImmutable()); } public async Task<ImmutableArray<SecurityKey>> GetSigningKeysAsync() { var settings = await GetSettingsAsync(); // If a certificate was explicitly provided, return it immediately // instead of using the fallback managed certificates logic. if (settings.CertificateStoreLocation != null && settings.CertificateStoreName != null && !string.IsNullOrEmpty(settings.CertificateThumbprint)) { var certificate = GetCertificate( settings.CertificateStoreLocation.Value, settings.CertificateStoreName.Value, settings.CertificateThumbprint); if (certificate != null) { return ImmutableArray.Create<SecurityKey>(new X509SecurityKey(certificate)); } _logger.LogWarning("The signing certificate '{Thumbprint}' could not be found in the " + "{StoreLocation}/{StoreName} store.", settings.CertificateThumbprint, settings.CertificateStoreLocation.Value.ToString(), settings.CertificateStoreName.Value.ToString()); } try { var certificates = (await GetManagedSigningCertificatesAsync()).Select(tuple => tuple.certificate).ToList(); if (certificates.Any(certificate => certificate.NotAfter.AddDays(-7) > DateTime.Now)) { return ImmutableArray.CreateRange<SecurityKey>( from certificate in certificates select new X509SecurityKey(certificate)); } try { // If the certificates list is empty or only contains certificates about to expire, // generate a new certificate and add it on top of the list to ensure it's preferred // by OpenIddict to the other certificates when issuing JWT access or identity tokens. certificates.Insert(0, await GenerateSigningCertificateAsync()); return ImmutableArray.CreateRange<SecurityKey>( from certificate in certificates select new X509SecurityKey(certificate)); } catch (Exception exception) { _logger.LogError(exception, "An error occurred while trying to generate a X.509 signing certificate."); } } catch (Exception exception) { _logger.LogWarning(exception, "An error occurred while trying to retrieve the X.509 signing certificates."); } // If none of the previous attempts succeeded, try to generate an ephemeral RSA key // and add it in the tenant memory cache so that future calls to this method return it. return ImmutableArray.Create<SecurityKey>(_memoryCache.GetOrCreate(nameof(RsaSecurityKey), entry => { entry.SetPriority(CacheItemPriority.NeverRemove); return new RsaSecurityKey(GenerateRsaSigningKey(2048)); })); RSA GenerateRsaSigningKey(int size) { RSA algorithm; // By default, the default RSA implementation used by .NET Core relies on the newest Windows CNG APIs. // Unfortunately, when a new key is generated using the default RSA.Create() method, it is not bound // to the machine account, which may cause security exceptions when running Orchard on IIS using a // virtual application pool identity or without the profile loading feature enabled (off by default). // To ensure a RSA key can be generated flawlessly, it is manually created using the managed CNG APIs. // For more information, visit https://github.com/openiddict/openiddict-core/issues/204. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // Warning: ensure a null key name is specified to ensure the RSA key is not persisted by CNG. var key = CngKey.Create(CngAlgorithm.Rsa, keyName: null, new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowPlaintextExport, KeyCreationOptions = CngKeyCreationOptions.MachineKey, KeyUsage = CngKeyUsages.Signing, Parameters = { new CngProperty("Length", BitConverter.GetBytes(size), CngPropertyOptions.None) } }); algorithm = new RSACng(key); } else { algorithm = RSA.Create(size); } return algorithm; } async Task<X509Certificate2> GenerateSigningCertificateAsync() { var subject = GetSubjectName(); var algorithm = GenerateRsaSigningKey(size: 2048); // Note: ensure the digitalSignature bit is added to the certificate, so that no validation error // is returned to clients that fully validate the certificates chain and their X.509 key usages. var request = new CertificateRequest(subject, algorithm, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, critical: true)); var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddMonths(3)); // Note: setting the friendly name is not supported on Unix machines (including Linux and macOS). // To ensure an exception is not thrown by the property setter, an OS runtime check is used here. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { certificate.FriendlyName = "OrchardCore OpenID Server Signing Certificate"; } var directory = Directory.CreateDirectory(Path.Combine( _shellOptions.CurrentValue.ShellsApplicationDataPath, _shellOptions.CurrentValue.ShellsContainerName, _shellSettings.Name, "IdentityModel-Signing-Certificates")); var password = GeneratePassword(); var path = Path.Combine(directory.FullName, Guid.NewGuid().ToString()); await File.WriteAllBytesAsync(Path.ChangeExtension(path, ".pfx"), certificate.Export(X509ContentType.Pfx, password)); await File.WriteAllTextAsync(Path.ChangeExtension(path, ".pwd"), _dataProtector.Protect(password)); return certificate; X500DistinguishedName GetSubjectName() { try { return new X500DistinguishedName("CN=" + (_shellSettings.RequestUrlHost ?? "localhost")); } catch { return new X500DistinguishedName("CN=localhost"); } } string GeneratePassword() { Span<byte> data = stackalloc byte[256 / 8]; RandomNumberGenerator.Fill(data); return Convert.ToBase64String(data, Base64FormattingOptions.None); } } } public async Task PruneSigningKeysAsync() { List<Exception> exceptions = null; foreach (var (path, certificate) in await GetManagedSigningCertificatesAsync()) { // Only delete expired certificates that expired at least 7 days ago. if (certificate.NotAfter.AddDays(7) < DateTime.Now) { try { // Delete both the X.509 certificate and its password file. File.Delete(path); File.Delete(Path.ChangeExtension(path, ".pwd")); } catch (Exception exception) { if (exceptions == null) { exceptions = new List<Exception>(); } exceptions.Add(exception); } } } if (exceptions != null) { throw new AggregateException(exceptions); } } private static X509Certificate2 GetCertificate(StoreLocation location, StoreName name, string thumbprint) { using (var store = new X509Store(name, location)) { store.Open(OpenFlags.ReadOnly); var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false); switch (certificates.Count) { case 0: return null; case 1: return certificates[0]; default: throw new InvalidOperationException("Multiple certificates with the same thumbprint were found."); } } } private async Task<ImmutableArray<(string path, X509Certificate2 certificate)>> GetManagedSigningCertificatesAsync() { var directory = new DirectoryInfo(Path.Combine( _shellOptions.CurrentValue.ShellsApplicationDataPath, _shellOptions.CurrentValue.ShellsContainerName, _shellSettings.Name, "IdentityModel-Signing-Certificates")); if (!directory.Exists) { return ImmutableArray.Create<(string, X509Certificate2)>(); } var certificates = ImmutableArray.CreateBuilder<(string, X509Certificate2)>(); foreach (var file in directory.EnumerateFiles("*.pfx", SearchOption.TopDirectoryOnly)) { try { // Only add the certificate if it's still valid. var certificate = await GetCertificateAsync(file.FullName); if (certificate.NotBefore <= DateTime.Now && certificate.NotAfter > DateTime.Now) { certificates.Add((file.FullName, certificate)); } } catch (Exception exception) { _logger.LogWarning(exception, "An error occurred while trying to extract a X.509 certificate."); continue; } } return certificates.ToImmutable(); async Task<string> GetPasswordAsync(string path) { using (var stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var reader = new StreamReader(stream)) { return _dataProtector.Unprotect(await reader.ReadToEndAsync()); } } async Task<X509Certificate2> GetCertificateAsync(string path) { // Extract the certificate password from the separate .pwd file. var password = await GetPasswordAsync(Path.ChangeExtension(path, ".pwd")); try { // Note: ephemeral key sets are not supported on non-Windows platforms. var flags = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? X509KeyStorageFlags.EphemeralKeySet : X509KeyStorageFlags.MachineKeySet; return new X509Certificate2(path, password, flags); } // Some cloud platforms (e.g Azure App Service/Antares) are known to fail to import .pfx files if the // private key is not persisted or marked as exportable. To ensure X.509 certificates can be correctly // read on these platforms, a second pass is made by specifying the PersistKeySet and Exportable flags. // For more information, visit https://github.com/OrchardCMS/OrchardCore/issues/3222. catch (CryptographicException exception) { _logger.LogDebug(exception, "A first-chance exception occurred while trying to extract " + "a X.509 certificate with the default key storage options."); return new X509Certificate2(path, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); } // Don't swallow exceptions thrown from the catch handler to ensure unrecoverable exceptions // (e.g caused by malformed X.509 certificates or invalid password) are correctly logged. } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Sql.LegacySdk; using Microsoft.Azure.Management.Sql.LegacySdk.Models; namespace Microsoft.Azure.Management.Sql.LegacySdk { /// <summary> /// The Windows Azure SQL Database management API provides a RESTful set of /// web services that interact with Windows Azure SQL Database services to /// manage your databases. The API enables users to create, retrieve, /// update, and delete databases and servers. /// </summary> public partial interface ISqlManagementClient : IDisposable { /// <summary> /// Gets the API version. /// </summary> string ApiVersion { get; } /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> Uri BaseUri { get; } /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> SubscriptionCloudCredentials Credentials { get; } /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> int LongRunningOperationInitialTimeout { get; set; } /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> int LongRunningOperationRetryTimeout { get; set; } /// <summary> /// Represents all the operations to manage Azure SQL Database and /// Database Server Audit policy. Contains operations to: Create, /// Retrieve and Update audit policy. /// </summary> IAuditingPolicyOperations AuditingPolicy { get; } /// <summary> /// Represents all the operations to manage Azure SQL Database and /// Server blob auditing. Contains operations to: Create, Retrieve and /// Update blob auditing settings. /// </summary> IBlobAuditingOperations BlobAuditing { get; } /// <summary> /// Represents all the operations for determining the set of /// capabilites available in a specified region. /// </summary> ICapabilitiesOperations Capabilities { get; } /// <summary> /// Represents all the operations for operating pertaining to /// activation on Azure SQL Data Warehouse databases. Contains /// operations to: Pause and Resume databases /// </summary> IDatabaseActivationOperations DatabaseActivation { get; } /// <summary> /// Represents all the operations for managing Advisors for Azure SQL /// Databases. Contains operations to retrieve Advisors and update /// auto execute status of an Advisor. /// </summary> IDatabaseAdvisorOperations DatabaseAdvisors { get; } /// <summary> /// Represents all the operations for operating on Azure SQL Database /// database backups. /// </summary> IDatabaseBackupOperations DatabaseBackup { get; } /// <summary> /// Represents all the operations for operating on Azure SQL Databases. /// Contains operations to: Create, Retrieve, Update, and Delete /// databases, and also includes the ability to get the event logs for /// a database. /// </summary> IDatabaseOperations Databases { get; } /// <summary> /// Represents all the operations for managing recommended actions on /// Azure SQL Databases. Contains operations to retrieve recommended /// action and update its state. /// </summary> IDatabaseRecommendedActionOperations DatabaseRecommendedActions { get; } /// <summary> /// Represents all the operations for operating on Azure SQL Database /// data masking. Contains operations to: Create, Retrieve, Update, /// and Delete data masking rules, as well as Create, Retreive and /// Update data masking policy. /// </summary> IDataMaskingOperations DataMasking { get; } /// <summary> /// Represents all the operations for managing Advisors for Azure SQL /// Elastic Database Pool. Contains operations to retrieve Advisors /// and update auto execute status of an Advisor. /// </summary> IElasticPoolAdvisorOperations ElasticPoolAdvisors { get; } /// <summary> /// Represents all the operations for operating on Azure SQL Database /// Elastic Pools. Contains operations to: Create, Retrieve, Update, /// and Delete. /// </summary> IElasticPoolOperations ElasticPools { get; } /// <summary> /// Represents all the operations for managing recommended actions on /// Azure SQL Elastic Database Pools. Contains operations to retrieve /// recommended action and update its state. /// </summary> IElasticPoolRecommendedActionOperations ElasticPoolRecommendedActions { get; } /// <summary> /// Represents all the operations for operating on Azure SQL Database /// Failover Group. Contains operations to: Create, Retrieve, Update, /// and Delete. /// </summary> IFailoverGroupOperations FailoverGroups { get; } /// <summary> /// Represents all the operations for operating on Azure SQL Database /// Server Firewall Rules. Contains operations to: Create, Retrieve, /// Update, and Delete firewall rules. /// </summary> IFirewallRuleOperations FirewallRules { get; } /// <summary> /// Represents all the operations for import/export on Azure SQL /// Databases. Contains operations to: Import, Export, Get /// Import/Export status for a database. /// </summary> IImportExportOperations ImportExport { get; } /// <summary> /// Represents all the operations for operating on Azure SQL Job /// Accounts. Contains operations to: Create, Retrieve, Update, and /// Delete Job Accounts /// </summary> IJobAccountOperations JobAccounts { get; } /// <summary> /// Represents all the operations for operating on Azure SQL /// Recommended Elastic Pools. Contains operations to: Retrieve. /// </summary> IRecommendedElasticPoolOperations RecommendedElasticPools { get; } /// <summary> /// Represents all the operations for managing recommended indexes on /// Azure SQL Databases. Contains operations to retrieve recommended /// index and update state. /// </summary> IRecommendedIndexOperations RecommendedIndexes { get; } /// <summary> /// Represents all the operations for operating on Azure SQL Database /// Replication Links. Contains operations to: Delete and Retrieve /// replication links. /// </summary> IReplicationLinkOperations DatabaseReplicationLinks { get; } /// <summary> /// Represents all the operations for managing Azure SQL Database /// secure connection. Contains operations to: Create, Retrieve and /// Update secure connection policy . /// </summary> ISecureConnectionPolicyOperations SecureConnection { get; } /// <summary> /// Represents all the operations to manage Azure SQL Database and /// Database Server Security Alert policy. Contains operations to: /// Create, Retrieve and Update policy. /// </summary> ISecurityAlertPolicyOperations SecurityAlertPolicy { get; } /// <summary> /// Represents all the operations for operating on Azure SQL Server /// Active Directory Administrators. Contains operations to: Create, /// Retrieve, Update, and Delete Azure SQL Server Active Directory /// Administrators. /// </summary> IServerAdministratorOperations ServerAdministrators { get; } /// <summary> /// Represents all the operations for managing Advisors for Azure SQL /// Server. Contains operations to retrieve Advisors and update auto /// execute status of an Advisor. /// </summary> IServerAdvisorOperations ServerAdvisors { get; } /// <summary> /// Represents all the operations for operating on Azure SQL Server /// communication links. Contains operations to: Create, Retrieve, /// Update, and Delete. /// </summary> IServerCommunicationLinkOperations CommunicationLinks { get; } /// <summary> /// Represents all the operations for operating on Azure SQL Server /// disaster recovery configurations. Contains operations to: Create, /// Retrieve, Update, Failover, and Delete. /// </summary> IServerDisasterRecoveryConfigurationOperations ServerDisasterRecoveryConfigurations { get; } /// <summary> /// Represents all the operations of Azure SQL Database that interact /// with Azure Key Vault Server Keys. Contains operations to: Add, /// Delete, and Retrieve Server Ke. /// </summary> IServerKeyOperations ServerKey { get; } /// <summary> /// Represents all the operations for operating on Azure SQL Database /// Servers. Contains operations to: Create, Retrieve, Update, and /// Delete servers. /// </summary> IServerOperations Servers { get; } /// <summary> /// Represents all the operations for managing recommended actions on /// Azure SQL Server. Contains operations to retrieve recommended /// action and update its state. /// </summary> IServerRecommendedActionOperations ServerRecommendedActions { get; } /// <summary> /// Represents all the operations for Azure SQL Database Server Upgrade /// </summary> IServerUpgradeOperations ServerUpgrades { get; } /// <summary> /// Represents all the operations for operating on Azure SQL Database /// Service Objectives. Contains operations to: Retrieve service /// objectives. /// </summary> IServiceObjectiveOperations ServiceObjectives { get; } /// <summary> /// Represents all the operations for operating on service tier /// advisors. Contains operations to: Retrieve. /// </summary> IServiceTierAdvisorOperations ServiceTierAdvisors { get; } /// <summary> /// Represents all the operations of Azure SQL Database Transparent /// Data Encryption. Contains operations to: Retrieve, and Update /// Transparent Data Encryption. /// </summary> ITransparentDataEncryptionOperations TransparentDataEncryption { get; } /// <summary> /// Gets the status of an Azure Sql Database Failover Group Force /// Failover operation. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure Sql Database Failover Group /// operation. /// </returns> Task<FailoverGroupForceFailoverResponse> GetFailoverGroupForceFailoverAllowDataLossOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken); } }
// AES privacy provider // Copyright (C) 2009-2010 Lex Li, Milan Sinadinovic // // 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. /* * Created by SharpDevelop. * User: lextm * Date: 5/30/2009 * Time: 8:06 PM * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Collections.Generic; using System.IO; using System.Security.Cryptography; namespace GSF.Net.Snmp.Security { /// <summary> /// Privacy provider base for AES. /// </summary> /// <remarks> /// This is an experimental port from SNMP#NET project. As AES is not part of SNMP RFC, this class is provided as it is. /// If you want other AES providers, you can port them from SNMP#NET in a similar manner. /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "AES", Justification = "definition")] public abstract class AESPrivacyProviderBase : IPrivacyProvider { private readonly SaltGenerator _salt = new SaltGenerator(); private readonly OctetString _phrase; /// <summary> /// Verifies if the provider is supported. /// </summary> public static bool IsSupported { get { #if NETSTANDARD2_0 return false; #else //if (RuntimeInformation.FrameworkDescription.Contains(".NET Core")) //{ // // netcoreappX.X // return false; //} // netXXX, xamarin.ios10, and monoandroid80 return true; #endif } } /// <summary> /// Initializes a new instance of the <see cref="AESPrivacyProviderBase"/> class. /// </summary> /// <param name="keyBytes">Key bytes.</param> /// <param name="phrase">The phrase.</param> /// <param name="auth">The authentication provider.</param> protected AESPrivacyProviderBase(int keyBytes, OctetString phrase, IAuthenticationProvider auth) { if (keyBytes != 16 && keyBytes != 24 && keyBytes != 32) { throw new ArgumentOutOfRangeException(nameof(keyBytes), "Valid key sizes are 16, 24 and 32 bytes."); } if (auth == null) { throw new ArgumentNullException(nameof(auth)); } KeyBytes = keyBytes; // IMPORTANT: in this way privacy cannot be non-default. if (auth == DefaultAuthenticationProvider.Instance) { throw new ArgumentException("If authentication is off, then privacy cannot be used.", nameof(auth)); } _phrase = phrase ?? throw new ArgumentNullException(nameof(phrase)); AuthenticationProvider = auth; } /// <summary> /// Corresponding <see cref="IAuthenticationProvider"/>. /// </summary> public IAuthenticationProvider AuthenticationProvider { get; private set; } [Obsolete("Use EngineIds instead.")] public OctetString EngineId { get; set; } /// <summary> /// Engine IDs. /// </summary> /// <remarks>This is an optional field, and only used by TRAP v2 authentication.</remarks> public ICollection<OctetString> EngineIds { get; set; } /// <summary> /// Encrypt scoped PDU using AES encryption protocol /// </summary> /// <param name="unencryptedData">Unencrypted scoped PDU byte array</param> /// <param name="key">Encryption key. Key has to be at least 32 bytes is length</param> /// <param name="engineBoots">Engine boots.</param> /// <param name="engineTime">Engine time.</param> /// <param name="privacyParameters">Privacy parameters out buffer. This field will be filled in with information /// required to decrypt the information. Output length of this field is 8 bytes and space has to be reserved /// in the USM header to store this information</param> /// <returns>Encrypted byte array</returns> /// <exception cref="ArgumentOutOfRangeException">Thrown when encryption key is null or length of the encryption key is too short.</exception> internal byte[] Encrypt(byte[] unencryptedData, byte[] key, int engineBoots, int engineTime, byte[] privacyParameters) { if (!IsSupported) { throw new PlatformNotSupportedException(); } // check the key before doing anything else if (key == null) { throw new ArgumentNullException(nameof(key)); } if (key.Length < KeyBytes) { throw new ArgumentOutOfRangeException(nameof(key), "Invalid key length."); } if (unencryptedData == null) { throw new ArgumentNullException(nameof(unencryptedData)); } byte[] iv = new byte[16]; // Set privacy parameters to the local 64 bit salt value byte[] bootsBytes = BitConverter.GetBytes(engineBoots); iv[0] = bootsBytes[3]; iv[1] = bootsBytes[2]; iv[2] = bootsBytes[1]; iv[3] = bootsBytes[0]; byte[] timeBytes = BitConverter.GetBytes(engineTime); iv[4] = timeBytes[3]; iv[5] = timeBytes[2]; iv[6] = timeBytes[1]; iv[7] = timeBytes[0]; // Copy salt value to the iv array Buffer.BlockCopy(privacyParameters, 0, iv, 8, PrivacyParametersLength); using (RijndaelManaged rm = new RijndaelManaged()) { rm.KeySize = KeyBytes * 8; rm.FeedbackSize = 128; rm.BlockSize = 128; // we have to use Zeros padding otherwise we get encrypt buffer size exception rm.Padding = PaddingMode.Zeros; rm.Mode = CipherMode.CFB; // make sure we have the right key length byte[] pkey = new byte[MinimumKeyLength]; Buffer.BlockCopy(key, 0, pkey, 0, MinimumKeyLength); rm.Key = pkey; rm.IV = iv; using (ICryptoTransform cryptor = rm.CreateEncryptor()) { byte[] encryptedData = cryptor.TransformFinalBlock(unencryptedData, 0, unencryptedData.Length); // check if encrypted data is the same length as source data if (encryptedData.Length != unencryptedData.Length) { // cut out the padding byte[] tmp = new byte[unencryptedData.Length]; Buffer.BlockCopy(encryptedData, 0, tmp, 0, unencryptedData.Length); return tmp; } return encryptedData; } } } /// <summary> /// Decrypt AES encrypted scoped PDU. /// </summary> /// <param name="encryptedData">Source data buffer</param> /// <param name="engineBoots">Engine boots.</param> /// <param name="engineTime">Engine time.</param> /// <param name="key">Decryption key. Key length has to be 32 bytes in length or longer (bytes beyond 32 bytes are ignored).</param> /// <param name="privacyParameters">Privacy parameters extracted from USM header</param> /// <returns>Decrypted byte array</returns> /// <exception cref="ArgumentNullException">Thrown when encrypted data is null or length == 0</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when encryption key length is less then 32 byte or if privacy parameters /// argument is null or length other then 8 bytes</exception> internal byte[] Decrypt(byte[] encryptedData, byte[] key, int engineBoots, int engineTime, byte[] privacyParameters) { if (!IsSupported) { throw new PlatformNotSupportedException(); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (encryptedData == null) { throw new ArgumentNullException(nameof(encryptedData)); } if (key.Length < KeyBytes) { throw new ArgumentOutOfRangeException(nameof(key), "Invalid key length."); } byte[] iv = new byte[16]; byte[] bootsBytes = BitConverter.GetBytes(engineBoots); iv[0] = bootsBytes[3]; iv[1] = bootsBytes[2]; iv[2] = bootsBytes[1]; iv[3] = bootsBytes[0]; byte[] timeBytes = BitConverter.GetBytes(engineTime); iv[4] = timeBytes[3]; iv[5] = timeBytes[2]; iv[6] = timeBytes[1]; iv[7] = timeBytes[0]; // Copy salt value to the iv array Buffer.BlockCopy(privacyParameters, 0, iv, 8, PrivacyParametersLength); // now do CFB decryption of the encrypted data using (RijndaelManaged rm = new RijndaelManaged()) { rm.KeySize = KeyBytes * 8; rm.FeedbackSize = 128; rm.BlockSize = 128; rm.Padding = PaddingMode.Zeros; rm.Mode = CipherMode.CFB; if (key.Length > KeyBytes) { byte[] normKey = new byte[KeyBytes]; Buffer.BlockCopy(key, 0, normKey, 0, KeyBytes); rm.Key = normKey; } else { rm.Key = key; } rm.IV = iv; using (ICryptoTransform cryptor = rm.CreateDecryptor()) { // We need to make sure that cryptedData is a collection of 128 byte blocks byte[] decryptedData; if ((encryptedData.Length % KeyBytes) != 0) { byte[] buffer = new byte[encryptedData.Length]; Buffer.BlockCopy(encryptedData, 0, buffer, 0, encryptedData.Length); int div = (int)Math.Floor(buffer.Length / (double)16); int newLength = (div + 1) * 16; byte[] decryptBuffer = new byte[newLength]; Buffer.BlockCopy(buffer, 0, decryptBuffer, 0, buffer.Length); decryptedData = cryptor.TransformFinalBlock(decryptBuffer, 0, decryptBuffer.Length); // now remove padding Buffer.BlockCopy(decryptedData, 0, buffer, 0, encryptedData.Length); return buffer; } decryptedData = cryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length); return decryptedData; } } } /// <summary> /// Returns the length of privacyParameters USM header field. For AES, field length is 8. /// </summary> private static int PrivacyParametersLength { get { return 8; } } /// <summary> /// Returns minimum encryption/decryption key length. For DES, returned value is 16. /// /// DES protocol itself requires an 8 byte key. Additional 8 bytes are used for generating the /// encryption IV. For encryption itself, first 8 bytes of the key are used. /// </summary> private int MinimumKeyLength { get { return KeyBytes; } } /// <summary> /// Return maximum encryption/decryption key length. For DES, returned value is 16 /// /// DES protocol itself requires an 8 byte key. Additional 8 bytes are used for generating the /// encryption IV. For encryption itself, first 8 bytes of the key are used. /// </summary> public int MaximumKeyLength { get { return KeyBytes; } } #region IPrivacyProvider Members /// <summary> /// Decrypts the specified data. /// </summary> /// <param name="data">The data.</param> /// <param name="parameters">The parameters.</param> /// <returns></returns> public ISnmpData Decrypt(ISnmpData data, SecurityParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } if (data == null) { throw new ArgumentNullException(nameof(data)); } SnmpType code = data.TypeCode; if (code != SnmpType.OctetString) { throw new ArgumentException($"Cannot decrypt the scope data: {code}.", nameof(data)); } OctetString octets = (OctetString)data; byte[] bytes = octets.GetRaw(); byte[] pkey = PasswordToKey(_phrase.GetRaw(), parameters.EngineId.GetRaw()); // decode encrypted packet byte[] decrypted = Decrypt(bytes, pkey, parameters.EngineBoots.ToInt32(), parameters.EngineTime.ToInt32(), parameters.PrivacyParameters.GetRaw()); return DataFactory.CreateSnmpData(decrypted); } /// <summary> /// Encrypts the specified scope. /// </summary> /// <param name="data">The scope data.</param> /// <param name="parameters">The parameters.</param> /// <returns></returns> public ISnmpData Encrypt(ISnmpData data, SecurityParameters parameters) { if (data == null) { throw new ArgumentNullException(nameof(data)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } if (data.TypeCode != SnmpType.Sequence && !(data is ISnmpPdu)) { throw new ArgumentException("Invalid data type.", nameof(data)); } byte[] pkey = PasswordToKey(_phrase.GetRaw(), parameters.EngineId.GetRaw()); byte[] bytes = data.ToBytes(); int reminder = bytes.Length % 8; int count = reminder == 0 ? 0 : 8 - reminder; using (MemoryStream stream = new MemoryStream()) { stream.Write(bytes, 0, bytes.Length); for (int i = 0; i < count; i++) { stream.WriteByte(1); } bytes = stream.ToArray(); } byte[] encrypted = Encrypt(bytes, pkey, parameters.EngineBoots.ToInt32(), parameters.EngineTime.ToInt32(), parameters.PrivacyParameters.GetRaw()); return new OctetString(encrypted); } /// <summary> /// Gets the salt. /// </summary> /// <value>The salt.</value> public OctetString Salt { get { return new OctetString(_salt.GetSaltBytes()); } } /// <summary> /// Gets the key bytes. /// </summary> /// <value>The key bytes.</value> public int KeyBytes { get; private set; } = 16; /// <summary> /// Passwords to key. /// </summary> /// <param name="secret">The secret.</param> /// <param name="engineId">The engine identifier.</param> /// <returns></returns> public byte[] PasswordToKey(byte[] secret, byte[] engineId) { byte[] pkey = AuthenticationProvider.PasswordToKey(secret, engineId); if (pkey.Length < MinimumKeyLength) { pkey = ExtendShortKey(pkey, secret, engineId, AuthenticationProvider); } return pkey; } #endregion /// <summary> /// Some protocols support a method to extend the encryption or decryption key when supplied key /// is too short. /// </summary> /// <param name="shortKey">Key that needs to be extended</param> /// <param name="password">Privacy password as configured on the SNMP agent.</param> /// <param name="engineID">Authoritative engine id. Value is retrieved as part of SNMP v3 discovery procedure</param> /// <param name="authProtocol">Authentication protocol class instance cast as <see cref="IAuthenticationProvider"/></param> /// <returns>Extended key value</returns> public byte[] ExtendShortKey(byte[] shortKey, byte[] password, byte[] engineID, IAuthenticationProvider authProtocol) { byte[] extKey = new byte[MinimumKeyLength]; byte[] lastKeyBuf = new byte[shortKey.Length]; Array.Copy(shortKey, lastKeyBuf, shortKey.Length); int keyLen = shortKey.Length > MinimumKeyLength ? MinimumKeyLength : shortKey.Length; Array.Copy(shortKey, extKey, keyLen); while (keyLen < MinimumKeyLength) { byte[] tmpBuf = authProtocol.PasswordToKey(lastKeyBuf, engineID); if (tmpBuf == null) { return null; } if (tmpBuf.Length <= (MinimumKeyLength - keyLen)) { Array.Copy(tmpBuf, 0, extKey, keyLen, tmpBuf.Length); keyLen += tmpBuf.Length; } else { Array.Copy(tmpBuf, 0, extKey, keyLen, MinimumKeyLength - keyLen); keyLen += (MinimumKeyLength - keyLen); } lastKeyBuf = new byte[tmpBuf.Length]; Array.Copy(tmpBuf, lastKeyBuf, tmpBuf.Length); } return extKey; } } }
using System; namespace PCSComProcurement.Purchase.DS { [Serializable] public class PO_PurchaseOrderMasterVO { private int mMasterLocationID; private string mCode; private DateTime mOrderDate; private bool mVAT; private bool mImportTax; private bool mSpecialTax; private int mPurchaseOrderMasterID; private int mCurrencyID; private int mDeliveryTermsID; private int mPaymentTermsID; private int mCarrierID; private Decimal mTotalImportTax; private int mBuyerID; private Decimal mTotalVAT; private Decimal mTotalSpecialTax; private Decimal mTotalAmount; private Decimal mTotalDiscount; private Decimal mTotalNetAmount; private int mCCNID; private int mPartyID; private int mVendorLocID; private int mShipToLocID; private int mInvToLocID; private int mPartyContactID; private int mPurchaseTypeID; private int mDiscountTermID; private int mPauseID; private int mMakerID; private int mPricingTypeID; private int mMakerLocationID; private int mRequestDeliveryTime; private int mPriority; private bool mRecCompleted; private string mComment; private string mReferenceNo; private int mPORevision; private decimal mExchangeRate; private string mVendorSO; public string UserName { get; set; } public DateTime LastChange { get; set; } public int MasterLocationID { set { mMasterLocationID = value; } get { return mMasterLocationID; } } public string Code { set { mCode = value; } get { return mCode; } } public int PORevision { set { mPORevision = value; } get { return mPORevision; } } public DateTime OrderDate { set { mOrderDate = value; } get { return mOrderDate; } } public bool VAT { set { mVAT = value; } get { return mVAT; } } public bool ImportTax { set { mImportTax = value; } get { return mImportTax; } } public bool SpecialTax { set { mSpecialTax = value; } get { return mSpecialTax; } } public int PurchaseOrderMasterID { set { mPurchaseOrderMasterID = value; } get { return mPurchaseOrderMasterID; } } public int CurrencyID { set { mCurrencyID = value; } get { return mCurrencyID; } } public int DeliveryTermsID { set { mDeliveryTermsID = value; } get { return mDeliveryTermsID; } } public int PaymentTermsID { set { mPaymentTermsID = value; } get { return mPaymentTermsID; } } public int CarrierID { set { mCarrierID = value; } get { return mCarrierID; } } public Decimal TotalImportTax { set { mTotalImportTax = value; } get { return mTotalImportTax; } } public int BuyerID { set { mBuyerID = value; } get { return mBuyerID; } } public Decimal TotalVAT { set { mTotalVAT = value; } get { return mTotalVAT; } } public Decimal TotalSpecialTax { set { mTotalSpecialTax = value; } get { return mTotalSpecialTax; } } public Decimal TotalAmount { set { mTotalAmount = value; } get { return mTotalAmount; } } public Decimal TotalDiscount { set { mTotalDiscount = value; } get { return mTotalDiscount; } } public Decimal TotalNetAmount { set { mTotalNetAmount = value; } get { return mTotalNetAmount; } } public int CCNID { set { mCCNID = value; } get { return mCCNID; } } public int PartyID { set { mPartyID = value; } get { return mPartyID; } } public int VendorLocID { set { mVendorLocID = value; } get { return mVendorLocID; } } public int ShipToLocID { set { mShipToLocID = value; } get { return mShipToLocID; } } public int InvToLocID { set { mInvToLocID = value; } get { return mInvToLocID; } } public int PartyContactID { set { mPartyContactID = value; } get { return mPartyContactID; } } public int PurchaseTypeID { set { mPurchaseTypeID = value; } get { return mPurchaseTypeID; } } public int DiscountTermID { set { mDiscountTermID = value; } get { return mDiscountTermID; } } public int PauseID { set { mPauseID = value; } get { return mPauseID; } } public int MakerID { set { mMakerID = value; } get { return mMakerID; } } public int MakerLocationID { set { mMakerLocationID = value; } get { return mMakerLocationID; } } public int RequestDeliveryTime { set { mRequestDeliveryTime = value; } get { return mRequestDeliveryTime; } } public int Priority { set { mPriority = value; } get { return mPriority; } } public bool RecCompleted { set { mRecCompleted = value; } get { return mRecCompleted; } } public string Comment { set { mComment = value; } get { return mComment; } } public decimal ExchangeRate { set { mExchangeRate = value; } get { return mExchangeRate; } } public string VendorSO { set { mVendorSO = value; } get { return mVendorSO; } } public string ReferenceNo { set { mReferenceNo = value; } get { return mReferenceNo; } } public int PricingTypeID { get { return mPricingTypeID; } set { mPricingTypeID = value; } } } }
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2015 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 16.10Release // Tag = development-akw-16.10.00-0 //////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; using System.Threading; namespace Dynastream.Fit { /// <summary> /// This class will decode a .fit file reading the file header and any definition or data messages. /// </summary> public class Decode { #region Fields private MesgDefinition[] localMesgDefs = new MesgDefinition[Fit.MaxLocalMesgs]; private Header fileHeader; private uint timestamp = 0; private int lastTimeOffset = 0; #endregion #region Properties #endregion #region Constructors public Decode() { } #endregion #region Methods public event MesgEventHandler MesgEvent; public event MesgDefinitionEventHandler MesgDefinitionEvent; /// <summary> /// Reads the file header to check if the file is FIT. /// Does not check CRC. /// Returns true if file is FIT. /// </summary> /// <param name="fitStream"> Seekable (file)stream to parse</param> public bool IsFIT(Stream fitStream) { try { // Does the header contain the flag string ".FIT"? Header header = new Header(fitStream); return header.IsValid(); } // If the header is malformed the ctor could throw an exception catch (FitException) { return false; } } /// <summary> /// Reads the FIT binary file header and crc to check compatibility and integrity. /// Also checks data reords size. /// Returns true if file is ok (not corrupt). ///</summary> /// <param name="fitStream">Seekable (file)stream to parse.</param> public bool CheckIntegrity(Stream fitStream) { bool isValid; try { // Is there a valid header? Header header = new Header(fitStream); isValid = header.IsValid(); // Are there as many data bytes as the header claims? isValid &= ((header.Size + header.DataSize + 2) == fitStream.Length); // Is the file CRC ok? byte[] data = new byte[fitStream.Length]; fitStream.Position = 0; fitStream.Read(data, 0, data.Length); isValid &= (CRC.Calc16(data, data.Length) == 0x0000); return isValid; } catch(FitException) { return false; } } /// <summary> /// Reads a FIT binary file. /// </summary> /// <param name="fitStream">Seekable (file)stream to parse.</param> /// <returns> /// Returns true if reading finishes successfully. /// </returns> public bool Read(Stream fitStream) { bool readOK = true; try { // Attempt to read header fileHeader = new Header(fitStream); readOK &= fileHeader.IsValid(); if (!readOK) { throw new FitException("FIT decode error: File is not FIT format. Check file header data type."); } if ((fileHeader.ProtocolVersion & Fit.ProtocolVersionMajorMask) > (Fit.ProtocolMajorVersion << Fit.ProtocolVersionMajorShift)) { // The decoder does not support decode accross protocol major revisions throw new FitException(String.Format("FIT decode error: Protocol Version {0}.X not supported by SDK Protocol Ver{1}.{2} ", (fileHeader.ProtocolVersion & Fit.ProtocolVersionMajorMask) >> Fit.ProtocolVersionMajorShift, Fit.ProtocolMajorVersion, Fit.ProtocolMinorVersion)); } // Read data messages and definitions while (fitStream.Position < fitStream.Length - 2) { DecodeNextMessage(fitStream); } // Is the file CRC ok? byte[] data = new byte[fitStream.Length]; fitStream.Position = 0; fitStream.Read(data, 0, data.Length); readOK &= (CRC.Calc16(data, data.Length) == 0x0000); } catch (EndOfStreamException e) { readOK = false; Debug.WriteLine("{0} caught and ignored. ", e.GetType().Name); throw new FitException("Decode:Read - Unexpected End of File", e); } return readOK; } public void DecodeNextMessage(Stream fitStream) { BinaryReader br = new BinaryReader(fitStream); byte nextByte = br.ReadByte(); // Is it a compressed timestamp mesg? if ((nextByte & Fit.CompressedHeaderMask) == Fit.CompressedHeaderMask) { MemoryStream mesgBuffer = new MemoryStream(); int timeOffset = nextByte & Fit.CompressedTimeMask; timestamp += (uint)((timeOffset - lastTimeOffset) & Fit.CompressedTimeMask); lastTimeOffset = timeOffset; Field timestampField = new Field(Profile.mesgs[Profile.RecordIndex].GetField("Timestamp")); timestampField.SetValue(timestamp); byte localMesgNum = (byte)((nextByte & Fit.CompressedLocalMesgNumMask) >> 5); mesgBuffer.WriteByte(localMesgNum); if (localMesgDefs[localMesgNum] == null) { throw new FitException("Decode:DecodeNextMessage - FIT decode error: Missing message definition for local message number " + localMesgNum + "."); } int fieldsSize = localMesgDefs[localMesgNum].GetMesgSize() - 1; try { mesgBuffer.Write(br.ReadBytes(fieldsSize), 0, fieldsSize); } catch (IOException e) { throw new FitException("Decode:DecodeNextMessage - Compressed Data Message unexpected end of file. Wanted " + fieldsSize + " bytes at stream position " + fitStream.Position, e); } Mesg newMesg = new Mesg(mesgBuffer, localMesgDefs[localMesgNum]); newMesg.InsertField(0, timestampField); if (MesgEvent != null) { MesgEvent(this, new MesgEventArgs(newMesg)); } } // Is it a mesg def? else if ((nextByte & Fit.HeaderTypeMask) == Fit.MesgDefinitionMask) { MemoryStream mesgDefBuffer = new MemoryStream(); // Figure out number of fields (length) of our defn and build buffer mesgDefBuffer.WriteByte(nextByte); mesgDefBuffer.Write(br.ReadBytes(4), 0, 4); byte numfields = br.ReadByte(); mesgDefBuffer.WriteByte(numfields); try { mesgDefBuffer.Write(br.ReadBytes(numfields * 3), 0, numfields * 3); } catch (IOException e) { throw new FitException("Decode:DecodeNextMessage - Defn Message unexpected end of file. Wanted " + (numfields * 3) + " bytes at stream position " + fitStream.Position, e); } MesgDefinition newMesgDef = new MesgDefinition(mesgDefBuffer); localMesgDefs[newMesgDef.LocalMesgNum] = newMesgDef; if (MesgDefinitionEvent != null) { MesgDefinitionEvent(this, new MesgDefinitionEventArgs(newMesgDef)); } } // Is it a data mesg? else if ((nextByte & Fit.HeaderTypeMask) == Fit.MesgHeaderMask) { MemoryStream mesgBuffer = new MemoryStream(); byte localMesgNum = (byte)(nextByte & Fit.LocalMesgNumMask); mesgBuffer.WriteByte(localMesgNum); if (localMesgDefs[localMesgNum] == null) { throw new FitException("Decode:DecodeNextMessage - FIT decode error: Missing message definition for local message number " + localMesgNum + "."); } int fieldsSize = localMesgDefs[localMesgNum].GetMesgSize() - 1; try { mesgBuffer.Write(br.ReadBytes(fieldsSize), 0, fieldsSize); } catch (Exception e) { throw new FitException("Decode:DecodeNextMessage - Data Message unexpected end of file. Wanted " + fieldsSize + " bytes at stream position " + fitStream.Position, e); } Mesg newMesg = new Mesg(mesgBuffer, localMesgDefs[localMesgNum]); // If the new message contains a timestamp field, record the value to use as // a reference for compressed timestamp headers Field timestampField = newMesg.GetField("Timestamp"); if (timestampField != null) { timestamp = (uint)timestampField.GetValue(); lastTimeOffset = (int)timestamp & Fit.CompressedTimeMask; } // Now that the entire message is decoded we can evaluate subfields and expand any components newMesg.ExpandComponents(); if (MesgEvent != null) { MesgEvent(this, new MesgEventArgs(newMesg)); } } else { throw new FitException("Decode:Read - FIT decode error: Unexpected Record Header Byte 0x" + nextByte.ToString("X")); } } #endregion } // class } // namespace
// 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.Reflection.Metadata.Ecma335 { /// <summary> /// Encodes method body stream. /// </summary> public readonly struct MethodBodyStreamEncoder { public BlobBuilder Builder { get; } public MethodBodyStreamEncoder(BlobBuilder builder) { if (builder == null) { Throw.BuilderArgumentNull(); } // Fat methods are 4-byte aligned. We calculate the alignment relative to the start of the ILStream. // // See ECMA-335 paragraph 25.4.5, Method data section: // "At the next 4-byte boundary following the method body can be extra method data sections." if ((builder.Count % 4) != 0) { throw new ArgumentException(SR.BuilderMustAligned, nameof(builder)); } Builder = builder; } /// <summary> /// Encodes a method body and adds it to the method body stream. /// </summary> /// <param name="codeSize">Number of bytes to be reserved for instructions.</param> /// <param name="maxStack">Max stack.</param> /// <param name="exceptionRegionCount">Number of exception regions.</param> /// <param name="hasSmallExceptionRegions">True if the exception regions should be encoded in 'small' format.</param> /// <param name="localVariablesSignature">Local variables signature handle.</param> /// <param name="attributes">Attributes.</param> /// <returns>The offset of the encoded body within the method body stream.</returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="codeSize"/>, <paramref name="exceptionRegionCount"/>, or <paramref name="maxStack"/> is out of allowed range. /// </exception> public MethodBody AddMethodBody( int codeSize, int maxStack = 8, int exceptionRegionCount = 0, bool hasSmallExceptionRegions = true, StandaloneSignatureHandle localVariablesSignature = default(StandaloneSignatureHandle), MethodBodyAttributes attributes = MethodBodyAttributes.InitLocals) { if (codeSize < 0) { Throw.ArgumentOutOfRange(nameof(codeSize)); } if (unchecked((uint)maxStack) > ushort.MaxValue) { Throw.ArgumentOutOfRange(nameof(maxStack)); } if (!ExceptionRegionEncoder.IsExceptionRegionCountInBounds(exceptionRegionCount)) { Throw.ArgumentOutOfRange(nameof(exceptionRegionCount)); } int bodyOffset = SerializeHeader(codeSize, (ushort)maxStack, exceptionRegionCount, attributes, localVariablesSignature); var instructions = Builder.ReserveBytes(codeSize); var regionEncoder = (exceptionRegionCount > 0) ? ExceptionRegionEncoder.SerializeTableHeader(Builder, exceptionRegionCount, hasSmallExceptionRegions) : default(ExceptionRegionEncoder); return new MethodBody(bodyOffset, instructions, regionEncoder); } public readonly struct MethodBody { /// <summary> /// Offset of the encoded method body in method body stream. /// </summary> public int Offset { get; } /// <summary> /// Blob reserved for instructions. /// </summary> public Blob Instructions { get; } /// <summary> /// Use to encode exception regions to the method body. /// </summary> public ExceptionRegionEncoder ExceptionRegions { get; } internal MethodBody(int bodyOffset, Blob instructions, ExceptionRegionEncoder exceptionRegions) { Offset = bodyOffset; Instructions = instructions; ExceptionRegions = exceptionRegions; } } /// <summary> /// Encodes a method body and adds it to the method body stream. /// </summary> /// <param name="instructionEncoder">Instruction encoder.</param> /// <param name="maxStack">Max stack.</param> /// <param name="localVariablesSignature">Local variables signature handle.</param> /// <param name="attributes">Attributes.</param> /// <returns>The offset of the encoded body within the method body stream.</returns> /// <exception cref="ArgumentNullException"><paramref name="instructionEncoder"/> has default value.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="maxStack"/> is out of range [0, <see cref="ushort.MaxValue"/>].</exception> /// <exception cref="InvalidOperationException"> /// A label targeted by a branch in the instruction stream has not been marked, /// or the distance between a branch instruction and the target label is doesn't fit the size of the instruction operand. /// </exception> public int AddMethodBody( InstructionEncoder instructionEncoder, int maxStack = 8, StandaloneSignatureHandle localVariablesSignature = default(StandaloneSignatureHandle), MethodBodyAttributes attributes = MethodBodyAttributes.InitLocals) { if (unchecked((uint)maxStack) > ushort.MaxValue) { Throw.ArgumentOutOfRange(nameof(maxStack)); } // The branch fixup code expects the operands of branch instructions in the code builder to be contiguous. // That's true when we emit thru InstructionEncoder. Taking it as a parameter instead of separate // code and flow builder parameters ensures they match each other. var codeBuilder = instructionEncoder.CodeBuilder; var flowBuilder = instructionEncoder.ControlFlowBuilder; if (codeBuilder == null) { Throw.ArgumentNull(nameof(instructionEncoder)); } int exceptionRegionCount = flowBuilder?.ExceptionHandlerCount ?? 0; if (!ExceptionRegionEncoder.IsExceptionRegionCountInBounds(exceptionRegionCount)) { Throw.ArgumentOutOfRange(nameof(instructionEncoder), SR.TooManyExceptionRegions); } int bodyOffset = SerializeHeader(codeBuilder.Count, (ushort)maxStack, exceptionRegionCount, attributes, localVariablesSignature); if (flowBuilder?.BranchCount > 0) { flowBuilder.CopyCodeAndFixupBranches(codeBuilder, Builder); } else { codeBuilder.WriteContentTo(Builder); } flowBuilder?.SerializeExceptionTable(Builder); return bodyOffset; } private int SerializeHeader(int codeSize, ushort maxStack, int exceptionRegionCount, MethodBodyAttributes attributes, StandaloneSignatureHandle localVariablesSignature) { const int TinyFormat = 2; const int FatFormat = 3; const int MoreSections = 8; const byte InitLocals = 0x10; int offset; bool isTiny = codeSize < 64 && maxStack <= 8 && localVariablesSignature.IsNil && exceptionRegionCount == 0; if (isTiny) { offset = Builder.Count; Builder.WriteByte((byte)((codeSize << 2) | TinyFormat)); } else { Builder.Align(4); offset = Builder.Count; ushort flags = (3 << 12) | FatFormat; if (exceptionRegionCount > 0) { flags |= MoreSections; } if ((attributes & MethodBodyAttributes.InitLocals) != 0) { flags |= InitLocals; } Builder.WriteUInt16((ushort)((int)attributes | flags)); Builder.WriteUInt16(maxStack); Builder.WriteInt32(codeSize); Builder.WriteInt32(localVariablesSignature.IsNil ? 0 : MetadataTokens.GetToken(localVariablesSignature)); } return offset; } } }
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; // <auto-generated /> namespace SouthwindRepository{ /// <summary> /// Strongly-typed collection for the ProductsByCategory class. /// </summary> [Serializable] public partial class ProductsByCategoryCollection : ReadOnlyList<ProductsByCategory, ProductsByCategoryCollection> { public ProductsByCategoryCollection() {} } /// <summary> /// This is Read-only wrapper class for the products by category view. /// </summary> [Serializable] public partial class ProductsByCategory : ReadOnlyRecord<ProductsByCategory>, 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("products by category", TableType.View, DataService.GetInstance("SouthwindRepository")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @""; //columns TableSchema.TableColumn colvarCategoryName = new TableSchema.TableColumn(schema); colvarCategoryName.ColumnName = "CategoryName"; colvarCategoryName.DataType = DbType.String; colvarCategoryName.MaxLength = 15; colvarCategoryName.AutoIncrement = false; colvarCategoryName.IsNullable = false; colvarCategoryName.IsPrimaryKey = false; colvarCategoryName.IsForeignKey = false; colvarCategoryName.IsReadOnly = false; schema.Columns.Add(colvarCategoryName); TableSchema.TableColumn colvarProductName = new TableSchema.TableColumn(schema); colvarProductName.ColumnName = "ProductName"; colvarProductName.DataType = DbType.String; colvarProductName.MaxLength = 40; colvarProductName.AutoIncrement = false; colvarProductName.IsNullable = false; colvarProductName.IsPrimaryKey = false; colvarProductName.IsForeignKey = false; colvarProductName.IsReadOnly = false; schema.Columns.Add(colvarProductName); TableSchema.TableColumn colvarQuantityPerUnit = new TableSchema.TableColumn(schema); colvarQuantityPerUnit.ColumnName = "QuantityPerUnit"; colvarQuantityPerUnit.DataType = DbType.String; colvarQuantityPerUnit.MaxLength = 20; colvarQuantityPerUnit.AutoIncrement = false; colvarQuantityPerUnit.IsNullable = true; colvarQuantityPerUnit.IsPrimaryKey = false; colvarQuantityPerUnit.IsForeignKey = false; colvarQuantityPerUnit.IsReadOnly = false; schema.Columns.Add(colvarQuantityPerUnit); TableSchema.TableColumn colvarUnitsInStock = new TableSchema.TableColumn(schema); colvarUnitsInStock.ColumnName = "UnitsInStock"; colvarUnitsInStock.DataType = DbType.Int16; colvarUnitsInStock.MaxLength = 5; colvarUnitsInStock.AutoIncrement = false; colvarUnitsInStock.IsNullable = true; colvarUnitsInStock.IsPrimaryKey = false; colvarUnitsInStock.IsForeignKey = false; colvarUnitsInStock.IsReadOnly = false; schema.Columns.Add(colvarUnitsInStock); TableSchema.TableColumn colvarDiscontinued = new TableSchema.TableColumn(schema); colvarDiscontinued.ColumnName = "Discontinued"; colvarDiscontinued.DataType = DbType.Boolean; colvarDiscontinued.MaxLength = 4; colvarDiscontinued.AutoIncrement = false; colvarDiscontinued.IsNullable = false; colvarDiscontinued.IsPrimaryKey = false; colvarDiscontinued.IsForeignKey = false; colvarDiscontinued.IsReadOnly = false; schema.Columns.Add(colvarDiscontinued); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["SouthwindRepository"].AddSchema("products by category",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public ProductsByCategory() { SetSQLProps(); SetDefaults(); MarkNew(); } public ProductsByCategory(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public ProductsByCategory(object keyID) { SetSQLProps(); LoadByKey(keyID); } public ProductsByCategory(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("CategoryName")] [Bindable(true)] public string CategoryName { get { return GetColumnValue<string>("CategoryName"); } set { SetColumnValue("CategoryName", value); } } [XmlAttribute("ProductName")] [Bindable(true)] public string ProductName { get { return GetColumnValue<string>("ProductName"); } set { SetColumnValue("ProductName", value); } } [XmlAttribute("QuantityPerUnit")] [Bindable(true)] public string QuantityPerUnit { get { return GetColumnValue<string>("QuantityPerUnit"); } set { SetColumnValue("QuantityPerUnit", value); } } [XmlAttribute("UnitsInStock")] [Bindable(true)] public short? UnitsInStock { get { return GetColumnValue<short?>("UnitsInStock"); } set { SetColumnValue("UnitsInStock", value); } } [XmlAttribute("Discontinued")] [Bindable(true)] public bool Discontinued { get { return GetColumnValue<bool>("Discontinued"); } set { SetColumnValue("Discontinued", value); } } #endregion #region Columns Struct public struct Columns { public static string CategoryName = @"CategoryName"; public static string ProductName = @"ProductName"; public static string QuantityPerUnit = @"QuantityPerUnit"; public static string UnitsInStock = @"UnitsInStock"; public static string Discontinued = @"Discontinued"; } #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.ComponentModel; using System.Drawing; using System.Drawing.Design; using System.Windows.Forms; namespace SIL.Windows.Forms.SuperToolTip { [ProvideProperty("SuperStuff", typeof (Control))] [ToolboxItemFilter("System.Windows.Forms")] [ToolboxBitmap(typeof (SuperToolTip), "SuperToolTip.jpg")] public partial class SuperToolTip : Component, IExtenderProvider { #region Private Members private Dictionary<Control, SuperToolTipInfoWrapper> controlTable; private SuperToolTipWindow window; private SuperToolTipWindowData winData; private Timer fadingTimer; private enum FadingDirection { FadeIn, FadeOut } ; private FadingDirection fadingDirection; private bool _useFadding; #endregion #region Constructors public SuperToolTip() { InitializeComponent(); InternalInitialize(); } public SuperToolTip(IContainer container) { container.Add(this); InitializeComponent(); InternalInitialize(); } #endregion #region Public Properties [DefaultValue(true)] public bool UseFadding { get { return _useFadding; } set { _useFadding = value; } } [DefaultValue(50)] public int FadingInterval { get { return fadingTimer.Interval; } set { if (value > 0) { fadingTimer.Interval = value; } else { throw new ArgumentException("Value must be greater than 0.!"); } } } #endregion #region Public Provided Properties [DisplayName("SuperStuff")] [TypeConverter(typeof (ExpandableObjectConverter))] [Editor(typeof (SuperToolTipEditor), typeof (UITypeEditor))] public SuperToolTipInfoWrapper GetSuperStuff(Control control) { return GetControlInfo(control); } public void SetSuperStuff(Control control, SuperToolTipInfoWrapper info) { SetControlInfo(control, info); } public void ResetSuperStuff(Control control) { SetControlInfo(control, null); } public bool ShouldSerializeSuperStuff(Control control) { SuperToolTipInfoWrapper wrapper; if (controlTable.TryGetValue(control, out wrapper)) { return wrapper.UseSuperToolTip; } return false; } #endregion #region IExtenderProvider Members public bool CanExtend(object extendee) { return ((extendee is Control) && !(extendee is SuperToolTip) && !(extendee is Form)); } #endregion #region Control Event Handlers protected virtual void MouseEntered(object sender, EventArgs e) { Show((Control) sender); } protected virtual void MouseLeft(object sender, EventArgs e) { if (window.Bounds.Contains(Control.MousePosition)) { return; } if (controlTable[(Control)sender].UseSuperToolTip) { // if (!window.HasMouse) { Close(); } } } private void OnToolTipMouseLeave(object sender, EventArgs e) { Close(); } #endregion #region Public Methods public void Close() { if (_useFadding) { FadeOut(); } else { CloseTooltip(); } } public void Show(Control owner) { if (controlTable[owner].UseSuperToolTip) { CloseTooltip(); if (_useFadding) { FadeIn(); } winData.SuperInfo = controlTable[owner].SuperToolTipInfo; window.Size = winData.Size; if (winData.SuperInfo.OffsetForWhereToDisplay != default(Point)) { window.Location = owner.PointToScreen(winData.SuperInfo.OffsetForWhereToDisplay); } else { window.Location = owner.PointToScreen(new Point(0, owner.Height)); } winData.GotFocus += OnGotFocus; window.Show(owner); winData.GotFocus -= OnGotFocus; } } void OnGotFocus(object sender, EventArgs e) { window.Owner.Focus(); } private void CloseTooltip() { fadingTimer.Stop(); window.MouseLeave -= OnToolTipMouseLeave; window.Hide(); window.Close(); window = null; CreateTooltipWindows(); } private void CreateTooltipWindows() { window = new SuperToolTipWindow(); window.MouseLeave += OnToolTipMouseLeave; winData = new SuperToolTipWindowData(); winData.SizeChanged += OnWindowSizeChanged; window.Controls.Add(winData); } private void OnWindowSizeChanged(object sender, EventArgs e) { window.Size = winData.Size; } #endregion #region Helpers private void InternalInitialize() { _useFadding = true; fadingTimer = new Timer(); fadingTimer.Interval = 10; fadingTimer.Tick += FadeOnTick; CreateTooltipWindows(); controlTable = new Dictionary<Control, SuperToolTipInfoWrapper>(); } private void FadeOnTick(object obj, EventArgs e) { window.Opacity = window.Opacity + (fadingDirection == FadingDirection.FadeOut ? -.1 : .1); if (window.Opacity >= 1.0 && fadingDirection == FadingDirection.FadeIn) { fadingTimer.Stop(); } else if (window.Opacity <= 0.0 && fadingDirection == FadingDirection.FadeOut) { fadingTimer.Stop(); window.Close(); } } private SuperToolTipInfoWrapper GetControlInfo(Control control) { if (!controlTable.ContainsKey(control)) { controlTable.Add(control, new SuperToolTipInfoWrapper()); } return controlTable[control]; } private void SetControlInfo(Control control, SuperToolTipInfoWrapper info) { if (controlTable.ContainsKey(control)) { if (info == null) //hook events to our event handlers; { control.MouseEnter -= new EventHandler(MouseEntered); control.MouseLeave -= new EventHandler(MouseLeft); controlTable.Remove(control); return; } controlTable[control] = info; } else { controlTable.Add(control, info); //hook events to our event handlers; control.MouseEnter += new EventHandler(MouseEntered); control.MouseLeave += new EventHandler(MouseLeft); } } #region Fadding private void FadeIn() { window.Opacity = 0; fadingDirection = FadingDirection.FadeIn; fadingTimer.Start(); } private void FadeOut() { if (window.Visible) { window.Opacity = 0; fadingDirection = FadingDirection.FadeOut; fadingTimer.Start(); } } #endregion #endregion #region Designer /// <summary> /// Required designer variable. /// </summary> private 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 Component 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() { components = new System.ComponentModel.Container(); } #endregion #endregion } [ToolboxItem(false)] internal class SuperToolTipWindow : Form { private bool _hasMouse; private Timer _checkMouseLeftTimer; public SuperToolTipWindow() { FormBorderStyle = FormBorderStyle.FixedSingle; ShowInTaskbar = false; ControlBox = false; _checkMouseLeftTimer = new Timer(); _checkMouseLeftTimer.Interval = 100; _checkMouseLeftTimer.Tick += OnCheckMouseLeftTimer_Tick; StartPosition = FormStartPosition.Manual; ControlAdded += Control_ControlAdded; ControlRemoved += Control_ControlRemoved; } protected override void Dispose(bool disposing) { if(disposing) { _checkMouseLeftTimer.Dispose(); } base.Dispose(disposing); } public bool HasMouse { get { return _hasMouse; } } // changing semantics of this to mean that the mouse has entered this control or a contained control protected override void OnMouseEnter(EventArgs e) { if (!_hasMouse) { base.OnMouseEnter(e); } _hasMouse = true; } // changing semantics of this to mean that the mouse has left this control (not for a contained control) protected override void OnMouseLeave(EventArgs e) { Point point = PointToClient(MousePosition); if (!ClientRectangle.Contains(point)) { base.OnMouseLeave(e); } else { _checkMouseLeftTimer.Start(); } _hasMouse = false; } void OnCheckMouseLeftTimer_Tick(object sender, EventArgs e) { if (this._hasMouse) { _checkMouseLeftTimer.Stop(); } else { Point point = PointToClient(MousePosition); if (!ClientRectangle.Contains(point)) { base.OnMouseLeave(e); _hasMouse = false; _checkMouseLeftTimer.Stop(); } } } private void RegisterControl(Control control) { control.ControlAdded += Control_ControlAdded; control.ControlRemoved += Control_ControlRemoved; control.MouseEnter += new EventHandler(Control_MouseEnter); control.MouseLeave += new EventHandler(Control_MouseLeave); } private void UnregisterControl(Control control) { control.ControlAdded -= Control_ControlAdded; control.ControlRemoved -= Control_ControlRemoved; control.MouseEnter -= new EventHandler(Control_MouseEnter); control.MouseLeave -= new EventHandler(Control_MouseLeave); } void Control_ControlAdded(object sender, ControlEventArgs e) { RegisterControl(e.Control); foreach (Control c in e.Control.Controls) { RegisterControl(c); } } void Control_ControlRemoved(object sender, ControlEventArgs e) { Control control = e.Control; UnregisterControl(control); } void Control_MouseLeave(object sender, EventArgs e) { OnMouseLeave(e); } void Control_MouseEnter(object sender, EventArgs e) { OnMouseEnter(e); } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Globalization; using System.Linq; using Contoso.Models; namespace ContosoWeb.Utils { public class ContosoWebDbInitializer : CreateDatabaseIfNotExists<ContosoWebContext> { protected override void Seed(ContosoWebContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. var players = new List<Player> { new Player {Name = "J Hance", GoalsScored = 6}, new Player {Name = "T Perham", GoalsScored = 5}, new Player {Name = "D Pelton", GoalsScored = 5}, new Player {Name = "C Herb", GoalsScored = 4} }; context.Players.AddOrUpdate(x => x.Name, players.ToArray()); context.SaveChanges(); var teams = new List<Team> { new Team {Name = "Contoso Cubs", AbbreviatedName = "SEA", ShortName = "Cubs", LogoImageSrc = "contoso_cubs.svg", Players = players.Where(x => x.PlayerId == 1 || x.PlayerId == 2).ToList()}, new Team {Name = "Farikam Falcons", AbbreviatedName = "LA", ShortName = "Falcons", LogoImageSrc = "fabrikam_falcons.svg", Players = players.Where(x => x.PlayerId == 3 || x.PlayerId == 4).ToList()} }; context.Teams.AddOrUpdate(x => x.Name, teams.ToArray()); context.SaveChanges(); var gameStats = new List<GameStat> { new GameStat { Team = teams.Single(x => x.TeamId == 1), Goals = 0, Shots = 0, Passes = 0, FoulsLost = 0, FoulsWon = 0, Offside = 0, Corners = 0 }, new GameStat { Team = teams.Single(x => x.TeamId == 2), Goals = 0, Shots = 0, Passes = 0, FoulsLost = 0, FoulsWon = 0, Offside = 0, Corners = 0 } }; context.GameStats.AddOrUpdate(x => x.Passes, gameStats.ToArray()); context.SaveChanges(); var matches = new List<Match> { new Match { HomeTeam = teams.Single(x => x.TeamId == 1), AwayTeam = teams.Single(x => x.TeamId == 2), MatchDate = DateTime.UtcNow.AddDays(2), Progress = MatchProgress.Pending }, new Match { HomeTeam = teams.Single(x => x.TeamId == 1), AwayTeam = teams.Single(x => x.TeamId == 2), MatchDate = DateTime.UtcNow.AddMinutes(14), Progress = MatchProgress.InProgress, HomeTeamStats = gameStats.Single(x => x.Team.TeamId == 1), AwayTeamStats = gameStats.Single(x => x.Team.TeamId == 2) }, new Match { HomeTeam = teams.Single(x => x.TeamId == 1), HomeTeamScore = 0, AwayTeam = teams.Single(x => x.TeamId == 2), AwayTeamScore = 0, MatchDate = new DateTimeOffset(new DateTime(2015, 6, 19), TimeSpan.FromHours(6)), Progress = MatchProgress.Completed }, new Match { HomeTeam = teams.Single(x => x.TeamId == 1), HomeTeamScore = 1, AwayTeam = teams.Single(x => x.TeamId == 2), AwayTeamScore = 0, MatchDate = new DateTimeOffset(new DateTime(2015, 6, 17), TimeSpan.FromHours(6)), Progress = MatchProgress.Completed }, new Match { HomeTeam = teams.Single(x => x.TeamId == 2), HomeTeamScore = 0, AwayTeam = teams.Single(x => x.TeamId == 1), AwayTeamScore = 3, MatchDate = new DateTimeOffset(new DateTime(2015, 6, 14), TimeSpan.FromHours(6)), Progress = MatchProgress.Completed }, new Match { HomeTeam = teams.Single(x => x.TeamId == 1), HomeTeamScore = 1, AwayTeam = teams.Single(x => x.TeamId == 2), AwayTeamScore = 1, MatchDate = new DateTimeOffset(new DateTime(2015, 4, 12), TimeSpan.FromHours(6)), Progress = MatchProgress.Completed }, new Match { HomeTeam = teams.Single(x => x.TeamId == 1), HomeTeamScore = 3, AwayTeam = teams.Single(x => x.TeamId == 2), AwayTeamScore = 0, MatchDate = new DateTimeOffset(new DateTime(2015, 2, 14), TimeSpan.FromHours(6)), Progress = MatchProgress.Completed } }; context.Matches.AddOrUpdate(x => x.MatchDate, matches.ToArray()); context.SaveChanges(); var categories = new List<Category>{ new Category { Name = "Men", Description = "Men's apparel", ImageUrl = "sla_men.png" }, new Category { Name = "Women", Description = "Women's apparel", ImageUrl = "sla_women.png" }, new Category { Name = "Kids", Description = "Kid's apparel", ImageUrl = "sla_kids.png" }, new Category { Name = "Balls", Description = "Soccer Balls", ImageUrl = "sla_ball.jpg" }, new Category { Name = "Tickets", Description = "Match tickets", ImageUrl = "tickets_blue.png" } }; context.Categories.AddOrUpdate(x => x.Name, categories.ToArray()); context.SaveChanges(); var categoriesMap = categories.ToDictionary(c => c.Name, c => c.CategoryId); var products = new List<Product> { new Product { SkuNumber = "TIK-0001", Title = "Cubs vs. Falcons - " + DateTime.UtcNow.AddDays(2).ToString("MM/dd"), CategoryId = categoriesMap["Tickets"], Price = 59.99M, SalePrice = 59.99M, ProductArtUrl = "Tickets_blue.png", ProductDetails = "{ \"Match\" : \"Cubs vs. Falcons\" } ", Description = "Ticket to the Cubs vs Falcons match.", Inventory = 40000, LeadTime = 0, RecommendationId = 1 }, new Product { SkuNumber = "TIK-0002", Title = "Cubs vs. Falcons - " + DateTime.UtcNow.AddDays(9).ToString("MM/dd"), CategoryId = categoriesMap["Tickets"], Price = 59.99M, SalePrice = 59.99M, ProductArtUrl = "Tickets_blue.png", ProductDetails = "{ \"Match\" : \"Cubs vs. Falcons\" } ", Description = "Ticket to the Cubs vs Falcons match.", Inventory = 40000, LeadTime = 0, RecommendationId = 2 }, new Product { SkuNumber = "TIK-0003", Title = "Cubs vs. Falcons - " + DateTime.UtcNow.AddDays(16).ToString("MM/dd"), CategoryId = categoriesMap["Tickets"], Price = 59.99M, SalePrice = 59.99M, ProductArtUrl = "Tickets_blue.png", ProductDetails = "{ \"Match\" : \"Cubs vs. Falcons\" } ", Description = "Ticket to the Cubs vs Falcons match.", Inventory = 40000, LeadTime = 0, RecommendationId = 3 }, new Product { SkuNumber = "TIK-0004", Title = "Semi Final 1 - " + DateTime.UtcNow.AddDays(23).ToString("MM/dd"), CategoryId = categoriesMap["Tickets"], Price = 79.99M, SalePrice = 79.99M, ProductArtUrl = "Tickets_green.png", ProductDetails = "{ \"Match\" : \"Semi Final 1 - Teams TBC\" } ", Description = "Ticket to the Cubs vs Falcons match.", Inventory = 40000, LeadTime = 0, RecommendationId = 4 }, new Product { SkuNumber = "TIK-0005", Title = "Semi Final 2 - " + DateTime.UtcNow.AddDays(30).ToString("MM/dd"), CategoryId = categoriesMap["Tickets"], Price = 79.99M, SalePrice = 79.99M, ProductArtUrl = "Tickets_green.png", ProductDetails = "{ \"Match\" : \"Semi Final 2 - Teams TBC\" } ", Description = "Ticket to the Cubs vs Falcons match.", Inventory = 40000, LeadTime = 0, RecommendationId = 5 }, new Product { SkuNumber = "TIK-0006", Title = "Final - " + DateTime.UtcNow.AddDays(37).ToString("MM/dd"), CategoryId = categoriesMap["Tickets"], Price = 99.99M, SalePrice = 99.99M, ProductArtUrl = "Tickets_red.png", ProductDetails = "{ \"Match\" : \"Final - Teams TBC\" } ", Description = "Ticket to the Cubs vs Falcons match.", Inventory = 40000, LeadTime = 0, RecommendationId = 6 }, new Product { SkuNumber = "MEN-0001", Title = "Men's Cubs Jersey - Black", CategoryId = categoriesMap["Men"], Price = 99.99M, SalePrice = 79.99M, ProductArtUrl = "cubs_b_m_tee.png", ProductDetails = "{ \"Brand\" : \"Contoso Sports\", \"Team\" : \"Contoso Cubs\", \"Size\" : \"Large\", \"Material\" : \"Cotton/nylon\", \"Color\" : \"Black\", \"Fit\" : \"Slim\" }", Description = "This ultra light sports jersey effectively wicks moisture away from the skin to keep you cool and performing at your best.", Inventory = 4, LeadTime = 6, RecommendationId = 7 }, new Product { SkuNumber = "MEN-0002", Title = "Men's Falcons Jersey - Blue", CategoryId = categoriesMap["Men"], Price = 99.99M, SalePrice = 79.99M, ProductArtUrl = "falcon_b_m_tee.png", ProductDetails = "{ \"Brand\" : \"Contoso Sports\", \"Team\" : \"Fabrikam Falcons\", \"Size\" : \"Large\", \"Material\" : \"Cotton/nylon\", \"Color\" : \"Blue\", \"Fit\" : \"Slim\" }", Description = "This ultra light sports jersey effectively wicks moisture away from the skin to keep you cool and performing at your best.", Inventory = 4, LeadTime = 6, RecommendationId = 8 }, new Product { SkuNumber = "MEN-0003", Title = "Men's Falcons Jersey - Yellow", CategoryId = categoriesMap["Men"], Price = 99.99M, SalePrice = 79.99M, ProductArtUrl = "falcon_y_m_tee.png", ProductDetails = "{ \"Brand\" : \"Contoso Sports\", \"Team\" : \"Fabrikam Falcons\", \"Size\" : \"Large\", \"Material\" : \"Cotton/nylon\", \"Color\" : \"Yellow\", \"Fit\" : \"Slim\" }", Description = "This ultra light sports jersey effectively wicks moisture away from the skin to keep you cool and performing at your best.", Inventory = 4, LeadTime = 6, RecommendationId = 9 }, new Product { SkuNumber = "MEN-0004", Title = "Men's Cubs Jersey - White", CategoryId = categoriesMap["Men"], Price = 99.99M, SalePrice = 79.99M, ProductArtUrl = "cubs_w_m_tee.png", ProductDetails = "{ \"Brand\" : \"Contoso Sports\", \"Size\" : \"Large\", \"Material\" : \"Cotton/nylon\", \"Color\" : \"White\", \"Fit\" : \"Slim\" }", Description = "This ultra light sports jersey effectively wicks moisture away from the skin to keep you cool and performing at your best.", Inventory = 7, LeadTime = 0, RecommendationId = 10 }, new Product { SkuNumber = "MEN-0005", Title = "Men's Cubs Jersey - Orange", CategoryId = categoriesMap["Men"], Price = 99.99M, SalePrice = 79.99M, ProductArtUrl = "cubs_o_m_tee.png", ProductDetails = "{ \"Brand\" : \"Contoso Sports\", \"Size\" : \"Large\", \"Material\" : \"Cotton/nylon\", \"Color\" : \"Orange\", \"Fit\" : \"Slim\" }", Description = "This ultra light sports jersey effectively wicks moisture away from the skin to keep you cool and performing at your best.", Inventory = 7, LeadTime = 0, RecommendationId = 11 }, new Product { SkuNumber = "MEN-0006", Title = "Men's Falcons Jersey - White", CategoryId = categoriesMap["Men"], Price = 99.99M, SalePrice = 79.99M, ProductArtUrl = "falcon_w_m_tee.png", ProductDetails = "{ \"Brand\" : \"Contoso Sports\", \"Size\" : \"Large\", \"Material\" : \"Cotton/nylon\", \"Color\" : \"White\", \"Fit\" : \"Slim\" }", Description = "This ultra light sports jersey effectively wicks moisture away from the skin to keep you cool and performing at your best.", Inventory = 7, LeadTime = 0, RecommendationId = 12 }, new Product { SkuNumber = "WMN-0001", Title = "Women's Cubs Jersey - Black", CategoryId = categoriesMap["Women"], Price = 89.99M, SalePrice = 89.99M, ProductArtUrl = "cubs_b_w_tee.png", ProductDetails = "{ \"Brand\" : \"Contoso Sports\", \"Team\" : \"Contoso Cubs\", \"Size\" : \"8\", \"Material\" : \"Cotton/nylon\", \"Color\" : \"Black\", \"Fit\" : \"Slim\" }", Description = "This ultra light sports jersey effectively wicks moisture away from the skin to keep you cool and performing at your best.", Inventory = 4, LeadTime = 6, RecommendationId = 13 }, new Product { SkuNumber = "WMN-0002", Title = "Women's Falcons Jersey - Blue", CategoryId = categoriesMap["Women"], Price = 89.99M, SalePrice = 89.99M, ProductArtUrl = "falcon_b_w_tee.png", ProductDetails = "{ \"Brand\" : \"Contoso Sports\", \"Team\" : \"Fabrikam Falcons\", \"Size\" : \"8\", \"Material\" : \"Cotton/nylon\", \"Color\" : \"Blue\", \"Fit\" : \"Slim\" }", Description = "This ultra light sports jersey effectively wicks moisture away from the skin to keep you cool and performing at your best.", Inventory = 4, LeadTime = 6, RecommendationId = 14 }, new Product { SkuNumber = "WMN-0003", Title = "Women's Falcons Jersey - Yellow", CategoryId = categoriesMap["Women"], Price = 89.99M, SalePrice = 89.99M, ProductArtUrl = "falcon_y_w_tee.png", ProductDetails = "{ \"Brand\" : \"Contoso Sports\", \"Team\" : \"Fabrikam Falcons\", \"Size\" : \"8\", \"Material\" : \"Cotton/nylon\", \"Color\" : \"Yellow\", \"Fit\" : \"Slim\" }", Description = "This ultra light sports jersey effectively wicks moisture away from the skin to keep you cool and performing at your best.", Inventory = 4, LeadTime = 6, RecommendationId = 15 }, new Product { SkuNumber = "WMN-0004", Title = "Women's Cubs Jersey - White", CategoryId = categoriesMap["Women"], Price = 89.99M, SalePrice = 89.99M, ProductArtUrl = "cubs_w_w_tee.png", ProductDetails = "{ \"Brand\" : \"Contoso Sports\", \"Size\" : \"8\", \"Material\" : \"Cotton/nylon\", \"Color\" : \"White\", \"Fit\" : \"Slim\" }", Description = "This ultra light sports jersey effectively wicks moisture away from the skin to keep you cool and performing at your best.", Inventory = 7, LeadTime = 0, RecommendationId = 16 }, new Product { SkuNumber = "WMN-0005", Title = "Women's Cubs Jersey - Orange", CategoryId = categoriesMap["Women"], Price = 89.99M, SalePrice = 89.99M, ProductArtUrl = "falcon_o_w_tee.png", ProductDetails = "{ \"Brand\" : \"Contoso Sports\", \"Size\" : \"8\", \"Material\" : \"Cotton/nylon\", \"Color\" : \"Orange\", \"Fit\" : \"Slim\" }", Description = "This ultra light sports jersey effectively wicks moisture away from the skin to keep you cool and performing at your best.", Inventory = 7, LeadTime = 0, RecommendationId = 17 }, new Product { SkuNumber = "WMN-0006", Title = "Women's Falcons Jersey - White", CategoryId = categoriesMap["Women"], Price = 89.99M, SalePrice = 89.99M, ProductArtUrl = "falcon_w_w_tee.png", ProductDetails = "{ \"Brand\" : \"Contoso Sports\", \"Size\" : \"8\", \"Material\" : \"Cotton/nylon\", \"Color\" : \"White\", \"Fit\" : \"Slim\" }", Description = "This ultra light sports jersey effectively wicks moisture away from the skin to keep you cool and performing at your best.", Inventory = 7, LeadTime = 0, RecommendationId = 18 }, new Product { SkuNumber = "KID-0001", Title = "Kid's Cubs Jersey - Black", CategoryId = categoriesMap["Kids"], Price = 39.99M, SalePrice = 39.99M, ProductArtUrl = "cubs_b_k_tee.png", ProductDetails = "{ \"Brand\" : \"Contoso Sports\", \"Team\" : \"Contoso Cubs\", \"Size\" : \"Small\", \"Material\" : \"Cotton/nylon\", \"Color\" : \"Black\", \"Fit\" : \"Slim\" }", Description = "This ultra light sports jersey effectively wicks moisture away from the skin to keep you cool and performing at your best.", Inventory = 9, LeadTime = 0, RecommendationId = 19 }, new Product { SkuNumber = "KID-0002", Title = "Kid's Cubs Jersey - Orange", CategoryId = categoriesMap["Kids"], Price = 39.99M, SalePrice = 39.99M, ProductArtUrl = "cubs_o_k_tee.png", ProductDetails = "{ \"Brand\" : \"Contoso Sports\", \"Team\" : \"Contoso Cubs\", \"Size\" : \"Small\", \"Material\" : \"Cotton/nylon\", \"Color\" : \"Orange\", \"Fit\" : \"Slim\" }", Description = "This ultra light sports jersey effectively wicks moisture away from the skin to keep you cool and performing at your best.", Inventory = 9, LeadTime = 0, RecommendationId = 20 }, new Product { SkuNumber = "KID-0003", Title = "Kid's Cubs Jersey - White", CategoryId = categoriesMap["Kids"], Price = 39.99M, SalePrice = 39.99M, ProductArtUrl = "cubs_w_k_tee.png", ProductDetails = "{ \"Brand\" : \"Contoso Sports\", \"Team\" : \"Contoso Cubs\", \"Size\" : \"Small\", \"Material\" : \"Cotton/nylon\", \"Color\" : \"White\", \"Fit\" : \"Slim\" }", Description = "This ultra light sports jersey effectively wicks moisture away from the skin to keep you cool and performing at your best.", Inventory = 9, LeadTime = 0, RecommendationId = 21 }, new Product { SkuNumber = "KID-0004", Title = "Kid's Falcons Jersey - Blue", CategoryId = categoriesMap["Kids"], Price = 39.99M, SalePrice = 39.99M, ProductArtUrl = "falcon_b_k_tee.png", ProductDetails = "{ \"Brand\" : \"Contoso Sports\", \"Team\" : \"Fabrikam Falcons\", \"Size\" : \"Small\", \"Material\" : \"Cotton/nylon\", \"Color\" : \"Blue\", \"Fit\" : \"Slim\" }", Description = "This ultra light sports jersey effectively wicks moisture away from the skin to keep you cool and performing at your best.", Inventory = 9, LeadTime = 0, RecommendationId = 22 }, new Product { SkuNumber = "KID-0005", Title = "Kid's Falcons Jersey - White", CategoryId = categoriesMap["Kids"], Price = 39.99M, SalePrice = 39.99M, ProductArtUrl = "falcon_w_k_tee.png", ProductDetails = "{ \"Brand\" : \"Contoso Sports\", \"Team\" : \"Fabrikam Falcons\", \"Size\" : \"Small\", \"Material\" : \"Cotton/nylon\", \"Color\" : \"White\", \"Fit\" : \"Slim\" }", Description = "This ultra light sports jersey effectively wicks moisture away from the skin to keep you cool and performing at your best.", Inventory = 9, LeadTime = 0, RecommendationId = 23 }, new Product { SkuNumber = "KID-0006", Title = "Kid's Falcons Jersey - Yellow", CategoryId = categoriesMap["Kids"], Price = 39.99M, SalePrice = 39.99M, ProductArtUrl = "falcon_y_k_tee.png", ProductDetails = "{ \"Brand\" : \"Contoso Sports\", \"Team\" : \"Fabrikam Falcons\", \"Size\" : \"Small\", \"Material\" : \"Cotton/nylon\", \"Color\" : \"Yellow\", \"Fit\" : \"Slim\" }", Description = "This ultra light sports jersey effectively wicks moisture away from the skin to keep you cool and performing at your best.", Inventory = 9, LeadTime = 0, RecommendationId = 24 }, new Product { SkuNumber = "GEA-0001", Title = "Practice Ball", CategoryId = categoriesMap["Balls"], Price = 29.99M, SalePrice = 29.99M, ProductArtUrl = "practice_ball.jpg", ProductDetails = "{ \"Size\" : \"5\", \"Pattern\" : \"Swirl\", \"Material\" : \"Synthetic\" } ", Description = "Entry level training ball. Regulation size, all weather/season.", Inventory = 8, LeadTime = 0, RecommendationId = 25 }, new Product { SkuNumber = "GEA-0002", Title = "Match Ball", CategoryId = categoriesMap["Balls"], Price = 69.99M, SalePrice = 69.99M, ProductArtUrl = "match_ball.jpg", ProductDetails = "{ \"Size\" : \"5\", \"Pattern\" : \"Swirl\", \"Material\" : \"Leather\" } ", Description = "High quality leather match ball. Regulation size, all weather/season.", Inventory = 8, LeadTime = 0, RecommendationId = 26 }, new Product { SkuNumber = "GEA-0003", Title = "Contoso Cubs Ball", CategoryId = categoriesMap["Balls"], Price = 49.99M, SalePrice = 49.99M, ProductArtUrl = "cubs_ball.jpg", ProductDetails = "{ \"Size\" : \"5\", \"Pattern\" : \"Swirl\", \"Material\" : \"Synthetic\" } ", Description = "Cubs supporter's ball. Regulation size, all weather/season.", Inventory = 8, LeadTime = 0, RecommendationId = 27 }, new Product { SkuNumber = "GEA-0004", Title = "Fabrikam Falcons Ball", CategoryId = categoriesMap["Balls"], Price = 39.99M, SalePrice = 39.99M, ProductArtUrl = "falcon_ball.jpg", ProductDetails = "{ \"Size\" : \"5\", \"Pattern\" : \"Swirl\", \"Material\" : \"Synthetic\" } ", Description = "Falcons supporter's ball. Regulation size, all weather/season.", Inventory = 8, LeadTime = 0, RecommendationId = 28 } }; context.Products.AddOrUpdate(x => x.Title, products.ToArray()); context.SaveChanges(); var stores = Enumerable.Range(1, 20).Select(id => new Store { StoreId = id, Name = string.Format(CultureInfo.InvariantCulture, "Store{0}", id) }).ToList(); context.Stores.AddOrUpdate(x => x.Name, stores.ToArray()); context.SaveChanges(); var rainchecks = GetRainchecks(stores, products); context.RainChecks.AddOrUpdate(x => x.StoreId, rainchecks.ToArray()); context.SaveChanges(); var orders = new List<Order> { new Order { Name = "Order1", Username = "Admin", OrderDate = DateTime.Now, OrderStatus = "Processing", Total = 123, Email = "admin@contososla.com", Address = "123 Fake St", City = "Brooklyn", Country = "USA", Phone = "1111111111", PostalCode = "11111", State = "New York", OrderDetails = new List<OrderDetail> { new OrderDetail { Product = context.Products.ToList()[0], Quantity = 1, UnitPrice = 10 } } }, new Order { Name = "Order2", Username = "Admin", OrderDate = DateTime.Now, OrderStatus = "Completed", Total = 234, Email = "admin@contososla.com", Address = "234 Fake St", City = "Brooklyn", Country = "USA", Phone = "2222222222", PostalCode = "22222", State = "New York", OrderDetails = new List<OrderDetail> { new OrderDetail { Product = context.Products.ToList()[1], Quantity = 2, UnitPrice = 20 }, new OrderDetail { Product = context.Products.ToList()[2], Quantity = 19, UnitPrice = 2 }, new OrderDetail { Product = context.Products.ToList()[3], Quantity = 3, UnitPrice = 202 } } } }; context.Orders.AddOrUpdate(x => x.Name, orders.ToArray()); context.SaveChanges(); } /// <summary> /// Generate an enumeration of rainchecks. The random number generator uses a seed to ensure /// that the sequence is consistent, but provides somewhat random looking data. /// </summary> public static IEnumerable<Raincheck> GetRainchecks(IList<Store> stores, IList<Product> products) { var random = new Random(1234); foreach (var store in stores) { for (var i = 0; i < random.Next(1, 5); i++) { yield return new Raincheck { StoreId = store.StoreId, Name = string.Format("John Smith{0}", random.Next()), Quantity = random.Next(1, 10), ProductId = products[random.Next(0, products.Count)].ProductId, SalePrice = Math.Round(100 * random.NextDouble(), 2) }; } } } } }
//////////////////////////////////////////////////////////////////////////////// // ________ _____ __ // / _____/_______ _____ ____ ____ _/ ____\__ __ | | // / \ ___\_ __ \\__ \ _/ ___\_/ __ \\ __\| | \| | // \ \_\ \| | \/ / __ \_\ \___\ ___/ | | | | /| |__ // \______ /|__| (____ / \___ >\___ >|__| |____/ |____/ // \/ \/ \/ \/ // ============================================================================= // Designed & Developed by Brad Jones <brad @="bjc.id.au" /> // ============================================================================= //////////////////////////////////////////////////////////////////////////////// namespace Graceful.Utils.Visitors { using System; using System.Text; using Graceful.Query; using System.Reflection; using System.Linq.Expressions; using System.Collections.Generic; /** * Given an Expression Tree, we will convert it into a SQL WHERE clause. * * ``` * Expression<Func<TModel, bool>> expression = * m => m.Id == 1; * * var converter = new PredicateConverter(); * converter.Visit(expression.Body); * * // converter.Sql == "Id = {0}" * // converter.Parameters == new object[] { 1 } * ``` */ public class PredicateConverter : ExpressionVisitor { /** * The portion of the SQL query that will come after a WHERE clause. */ public string Sql { get { return this.sql.ToString().Trim(); } } private StringBuilder sql = new StringBuilder(); /** * A list of parameter values that go along with our sql query segment. */ public object[] Parameters { get { return this.parameters.ToArray(); } } private List<object> parameters = new List<object>(); /** * When we recurse into a MemberExpression, looking for a * ConstantExpression, we do not want to write anything to * the sql StringBuilder. */ private bool blockWriting = false; /** * In some cases, we need to save the value we get from a MemberInfo * and save it for later use, when we are at the correct * MemberExpression. */ private object value; protected override Expression VisitBinary(BinaryExpression node) { // Open the binary expression in SQL this.sql.Append("("); // Go and visit the left hand side of this expression this.Visit(node.Left); // Add the operator in the middle switch (node.NodeType) { case ExpressionType.Equal: this.sql.Append("="); break; case ExpressionType.NotEqual: this.sql.Append("!="); break; case ExpressionType.GreaterThan: this.sql.Append(">"); break; case ExpressionType.GreaterThanOrEqual: this.sql.Append(">="); break; case ExpressionType.LessThan: this.sql.Append("<"); break; case ExpressionType.LessThanOrEqual: this.sql.Append("<="); break; case ExpressionType.And: case ExpressionType.AndAlso: this.sql.Append("AND"); break; case ExpressionType.Or: case ExpressionType.OrElse: this.sql.Append("OR"); break; default: throw new UnknownOperatorException(node.NodeType); } // Operator needs a space after it. this.sql.Append(" "); // Now visit the right hand side of this expression. this.Visit(node.Right); // Close the binary expression in SQL this.sql.Append(") "); return node; } protected override Expression VisitMember(MemberExpression node) { // This will get filled with the "actual" value from our child // ConstantExpression if happen to have a child ConstantExpression. // see: http://stackoverflow.com/questions/6998523 object value = null; // Recurse down to see if we can simplify... this.blockWriting = true; var expression = this.Visit(node.Expression); this.blockWriting = false; // If we've ended up with a constant, and it's a property // or a field, we can simplify ourselves to a constant. if (expression is ConstantExpression) { MemberInfo member = node.Member; object container = ((ConstantExpression)expression).Value; if (member is FieldInfo) { value = ((FieldInfo)member).GetValue(container); } else if (member is PropertyInfo) { value = ((PropertyInfo)member).GetValue(container, null); } // If we managed to actually get a value, lets now create a // ConstantExpression with the expected value and Vist it. if (value != null) { if (TypeMapper.IsClrType(value)) { this.Visit(Expression.Constant(value)); } else { // So if we get to here, what has happened is that // the value returned by the FieldInfo GetValue call // is actually the container, so we save it for later. this.value = value; } } } else if (expression is MemberExpression) { // Now we can use the value we saved earlier to actually grab // the constant value that we expected. I guess this sort of // recursion could go on for ages and hence why the accepted // answer used DyanmicInvoke. Anyway we will hope that this // does the job for our needs. MemberInfo member = node.Member; object container = this.value; if (member is FieldInfo) { value = ((FieldInfo)member).GetValue(container); } else if (member is PropertyInfo) { value = ((PropertyInfo)member).GetValue(container, null); } this.value = null; if (TypeMapper.IsClrType(value)) { this.Visit(Expression.Constant(value)); } else { throw new ExpressionTooComplexException(); } } // We only need to do this if we did not // have a child ConstantExpression if (value == null) { this.sql.Append(new SqlId(node.Member.Name).Value); this.sql.Append(" "); } return node; } protected override Expression VisitConstant(ConstantExpression node) { if (!this.blockWriting) { var value = node.Value; if (value == null) { if (this.sql[this.sql.Length - 2] == '=') { if (this.sql[this.sql.Length - 3] == '!') { this.sql.Remove(this.sql.Length - 3, 3); this.sql.Append("IS NOT NULL"); } else { this.sql.Remove(this.sql.Length - 2, 2); this.sql.Append("IS NULL"); } } } else { this.sql.Append("{"); this.sql.Append(this.parameters.Count); this.sql.Append("}"); this.parameters.Add(node.Value); } } return node; } } }
namespace Microsoft.eShopOnContainers.Services.Catalog.API; public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddAppInsight(Configuration) .AddGrpc().Services .AddCustomMVC(Configuration) .AddCustomDbContext(Configuration) .AddCustomOptions(Configuration) .AddIntegrationServices(Configuration) .AddEventBus(Configuration) .AddSwagger(Configuration) .AddCustomHealthCheck(Configuration); var container = new ContainerBuilder(); container.Populate(services); return new AutofacServiceProvider(container.Build()); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { //Configure logs //loggerFactory.AddAzureWebAppDiagnostics(); //loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace); var pathBase = Configuration["PATH_BASE"]; if (!string.IsNullOrEmpty(pathBase)) { loggerFactory.CreateLogger<Startup>().LogDebug("Using PATH BASE '{pathBase}'", pathBase); app.UsePathBase(pathBase); } app.UseSwagger() .UseSwaggerUI(c => { c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Catalog.API V1"); }); app.UseRouting(); app.UseCors("CorsPolicy"); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); endpoints.MapControllers(); endpoints.MapGet("/_proto/", async ctx => { ctx.Response.ContentType = "text/plain"; using var fs = new FileStream(Path.Combine(env.ContentRootPath, "Proto", "catalog.proto"), FileMode.Open, FileAccess.Read); using var sr = new StreamReader(fs); while (!sr.EndOfStream) { var line = await sr.ReadLineAsync(); if (line != "/* >>" || line != "<< */") { await ctx.Response.WriteAsync(line); } } }); endpoints.MapGrpcService<CatalogService>(); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse }); endpoints.MapHealthChecks("/liveness", new HealthCheckOptions { Predicate = r => r.Name.Contains("self") }); }); ConfigureEventBus(app); } protected virtual void ConfigureEventBus(IApplicationBuilder app) { var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>(); eventBus.Subscribe<OrderStatusChangedToAwaitingValidationIntegrationEvent, OrderStatusChangedToAwaitingValidationIntegrationEventHandler>(); eventBus.Subscribe<OrderStatusChangedToPaidIntegrationEvent, OrderStatusChangedToPaidIntegrationEventHandler>(); } } public static class CustomExtensionMethods { public static IServiceCollection AddAppInsight(this IServiceCollection services, IConfiguration configuration) { services.AddApplicationInsightsTelemetry(configuration); services.AddApplicationInsightsKubernetesEnricher(); return services; } public static IServiceCollection AddCustomMVC(this IServiceCollection services, IConfiguration configuration) { services.AddControllers(options => { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); }) .AddJsonOptions(options => options.JsonSerializerOptions.WriteIndented = true); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder .SetIsOriginAllowed((host) => true) .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); return services; } public static IServiceCollection AddCustomHealthCheck(this IServiceCollection services, IConfiguration configuration) { var accountName = configuration.GetValue<string>("AzureStorageAccountName"); var accountKey = configuration.GetValue<string>("AzureStorageAccountKey"); var hcBuilder = services.AddHealthChecks(); hcBuilder .AddCheck("self", () => HealthCheckResult.Healthy()) .AddSqlServer( configuration["ConnectionString"], name: "CatalogDB-check", tags: new string[] { "catalogdb" }); if (!string.IsNullOrEmpty(accountName) && !string.IsNullOrEmpty(accountKey)) { hcBuilder .AddAzureBlobStorage( $"DefaultEndpointsProtocol=https;AccountName={accountName};AccountKey={accountKey};EndpointSuffix=core.windows.net", name: "catalog-storage-check", tags: new string[] { "catalogstorage" }); } if (configuration.GetValue<bool>("AzureServiceBusEnabled")) { hcBuilder .AddAzureServiceBusTopic( configuration["EventBusConnection"], topicName: "eshop_event_bus", name: "catalog-servicebus-check", tags: new string[] { "servicebus" }); } else { hcBuilder .AddRabbitMQ( $"amqp://{configuration["EventBusConnection"]}", name: "catalog-rabbitmqbus-check", tags: new string[] { "rabbitmqbus" }); } return services; } public static IServiceCollection AddCustomDbContext(this IServiceCollection services, IConfiguration configuration) { services.AddEntityFrameworkSqlServer() .AddDbContext<CatalogContext>(options => { options.UseSqlServer(configuration["ConnectionString"], sqlServerOptionsAction: sqlOptions => { sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name); //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); }); }); services.AddDbContext<IntegrationEventLogContext>(options => { options.UseSqlServer(configuration["ConnectionString"], sqlServerOptionsAction: sqlOptions => { sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name); //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); }); }); return services; } public static IServiceCollection AddCustomOptions(this IServiceCollection services, IConfiguration configuration) { services.Configure<CatalogSettings>(configuration); services.Configure<ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = context => { var problemDetails = new ValidationProblemDetails(context.ModelState) { Instance = context.HttpContext.Request.Path, Status = StatusCodes.Status400BadRequest, Detail = "Please refer to the errors property for additional details." }; return new BadRequestObjectResult(problemDetails) { ContentTypes = { "application/problem+json", "application/problem+xml" } }; }; }); return services; } public static IServiceCollection AddSwagger(this IServiceCollection services, IConfiguration configuration) { services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "eShopOnContainers - Catalog HTTP API", Version = "v1", Description = "The Catalog Microservice HTTP API. This is a Data-Driven/CRUD microservice sample" }); }); return services; } public static IServiceCollection AddIntegrationServices(this IServiceCollection services, IConfiguration configuration) { services.AddTransient<Func<DbConnection, IIntegrationEventLogService>>( sp => (DbConnection c) => new IntegrationEventLogService(c)); services.AddTransient<ICatalogIntegrationEventService, CatalogIntegrationEventService>(); if (configuration.GetValue<bool>("AzureServiceBusEnabled")) { services.AddSingleton<IServiceBusPersisterConnection>(sp => { var settings = sp.GetRequiredService<IOptions<CatalogSettings>>().Value; var serviceBusConnection = settings.EventBusConnection; return new DefaultServiceBusPersisterConnection(serviceBusConnection); }); } else { services.AddSingleton<IRabbitMQPersistentConnection>(sp => { var settings = sp.GetRequiredService<IOptions<CatalogSettings>>().Value; var logger = sp.GetRequiredService<ILogger<DefaultRabbitMQPersistentConnection>>(); var factory = new ConnectionFactory() { HostName = configuration["EventBusConnection"], DispatchConsumersAsync = true }; if (!string.IsNullOrEmpty(configuration["EventBusUserName"])) { factory.UserName = configuration["EventBusUserName"]; } if (!string.IsNullOrEmpty(configuration["EventBusPassword"])) { factory.Password = configuration["EventBusPassword"]; } var retryCount = 5; if (!string.IsNullOrEmpty(configuration["EventBusRetryCount"])) { retryCount = int.Parse(configuration["EventBusRetryCount"]); } return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount); }); } return services; } public static IServiceCollection AddEventBus(this IServiceCollection services, IConfiguration configuration) { if (configuration.GetValue<bool>("AzureServiceBusEnabled")) { services.AddSingleton<IEventBus, EventBusServiceBus>(sp => { var serviceBusPersisterConnection = sp.GetRequiredService<IServiceBusPersisterConnection>(); var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>(); var logger = sp.GetRequiredService<ILogger<EventBusServiceBus>>(); var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>(); string subscriptionName = configuration["SubscriptionClientName"]; return new EventBusServiceBus(serviceBusPersisterConnection, logger, eventBusSubcriptionsManager, iLifetimeScope, subscriptionName); }); } else { services.AddSingleton<IEventBus, EventBusRabbitMQ>(sp => { var subscriptionClientName = configuration["SubscriptionClientName"]; var rabbitMQPersistentConnection = sp.GetRequiredService<IRabbitMQPersistentConnection>(); var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>(); var logger = sp.GetRequiredService<ILogger<EventBusRabbitMQ>>(); var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>(); var retryCount = 5; if (!string.IsNullOrEmpty(configuration["EventBusRetryCount"])) { retryCount = int.Parse(configuration["EventBusRetryCount"]); } return new EventBusRabbitMQ(rabbitMQPersistentConnection, logger, iLifetimeScope, eventBusSubcriptionsManager, subscriptionClientName, retryCount); }); } services.AddSingleton<IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>(); services.AddTransient<OrderStatusChangedToAwaitingValidationIntegrationEventHandler>(); services.AddTransient<OrderStatusChangedToPaidIntegrationEventHandler>(); return services; } }