context
stringlengths
2.52k
185k
gt
stringclasses
1 value
namespace More.Collections.Generic { using FluentAssertions; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Xunit; public class ObservableQueueTTest { [Fact] public void new_observable_queue_should_initialize_items() { // arrange var expected = new[] { "1", "2", "3" }; // act var queue = new ObservableQueue<string>( expected ); // assert queue.Should().Equal( expected ); } [Fact] public void enqueue_should_raise_events() { // arrange var expected = "1"; var queue = new ObservableQueue<string>(); queue.MonitorEvents(); // act queue.Enqueue( expected ); // assert queue.Peek().Should().Be( expected ); queue.ShouldRaisePropertyChangeFor( q => q.Count ); } [Fact] public void dequeue_should_raise_events() { // arrange var expected = "1"; var queue = new ObservableQueue<string>(); queue.Enqueue( expected ); queue.MonitorEvents(); // act queue.Dequeue(); // assert queue.Should().BeEmpty(); queue.ShouldRaisePropertyChangeFor( q => q.Count ); } [Fact] public void dequeue_should_not_be_allowed_when_empty() { // arrange var queue = new ObservableQueue<string>(); // act Action dequeue = () => queue.Dequeue(); // assert dequeue.ShouldThrow<InvalidOperationException>(); } [Fact] public void peek_should_return_first_item() { // arrange var queue = new ObservableQueue<string>(); queue.Enqueue( "2" ); queue.Enqueue( "1" ); queue.Enqueue( "3" ); // act var result = queue.Peek(); // assert result.Should().Be( "2" ); } [Fact] public void peek_should_not_be_allowed_when_empty() { // arrange var queue = new ObservableQueue<string>(); // act Action peek = () => queue.Peek(); // assert peek.ShouldThrow<InvalidOperationException>(); } [Fact] public void to_array_should_return_items_in_seqence() { // arrange var queue = new ObservableQueue<string>(); var expected = new[] { "1", "2", "3" }; queue.Enqueue( "1" ); queue.Enqueue( "2" ); queue.Enqueue( "3" ); // act var items = queue.ToArray(); // assert items.Should().Equal( expected ); } [Fact] public void trim_should_remove_excess() { // arrange var queue = new ObservableQueue<string>( 10 ); queue.Enqueue( "1" ); queue.Enqueue( "2" ); queue.Enqueue( "3" ); // act Action trimExcess = queue.TrimExcess; // assert trimExcess.ShouldNotThrow(); } [Theory] [InlineData( "Two", true )] [InlineData( "Four", false )] [InlineData( null, false )] public void contains_should_return_expected_result( string value, bool expected ) { // arrange var queue = new ObservableQueue<string>(); queue.Enqueue( "One" ); queue.Enqueue( "Two" ); queue.Enqueue( "Three" ); // act var result = queue.Contains( value ); // assert result.Should().Be( expected ); } [Fact] public void copy_to_should_copy_items() { // arrange var expected = new[] { "1", "2" }; var queue = new ObservableQueue<string>( expected ); queue.Enqueue( "1" ); queue.Enqueue( "2" ); var items = new string[2]; // act queue.CopyTo( items, 0 ); // assert items.Should().Equal( expected ); } [Fact] public void copy_to_should_copy_items_with_offset() { // arrange var expected = new[] { "1", "2" }; var queue = new ObservableQueue<string>( expected ); queue.Enqueue( "1" ); queue.Enqueue( "2" ); var items = new string[4]; // act queue.CopyTo( items, 2 ); // assert items.Skip( 2 ).Should().Equal( expected ); } [Fact] public void copy_to_should_copy_untyped_items() { // arrange var queue = new ObservableQueue<string>(); var collection = (ICollection) queue; var expected = new[] { "1", "2" }; var items = new string[2]; queue.Enqueue( "1" ); queue.Enqueue( "2" ); // act collection.CopyTo( items, 0 ); // assert items.Should().Equal( expected ); } [Fact] public void clear_should_raise_events() { // arrange var queue = new ObservableQueue<string>(); queue.Enqueue( "1" ); queue.MonitorEvents(); // act queue.Clear(); // assert queue.Should().BeEmpty(); queue.ShouldRaisePropertyChangeFor( q => q.Count ); } [Fact] public void observable_queue_should_not_be_synchronized() { // arrange var queue = (ICollection) new ObservableQueue<string>(); // act // assert queue.IsSynchronized.Should().BeFalse(); queue.SyncRoot.Should().NotBeNull(); } [Fact] public void observable_queue_should_enumerate_in_typed_sequence() { // arrange var queue = new ObservableQueue<string>(); queue.Enqueue( "1" ); queue.Enqueue( "2" ); queue.Enqueue( "3" ); // act IEnumerable<string> items = queue; // assert items.Should().Equal( new []{ "1", "2", "3" } ); } [Fact] public void observable_queue_should_enumerate_in_untyped_sequence() { // arrange var queue = new ObservableQueue<string>(); queue.Enqueue( "1" ); queue.Enqueue( "2" ); queue.Enqueue( "3" ); // act IEnumerable items = queue; // assert items.Should().Equal( new[] { "1", "2", "3" } ); } [Fact] public void observable_queue_should_grow_dynamically() { // arrange var queue = new ObservableQueue<string>( 3 ); // act for ( var i = 0; i < 10; i++ ) { queue.Enqueue( ( i + 1 ).ToString() ); } // assert queue.Clear(); queue.TrimExcess(); } } }
//The MIT License(MIT) //Copyright(c) 2016 Alberto Rodriguez & LiveCharts Contributors //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. using System; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Windows.Controls; using System.Windows.Forms.Integration; using LiveCharts.Events; using LiveCharts.Wpf; namespace LiveCharts.WinForms { /// <summary> /// /// </summary> /// <seealso cref="System.Windows.Forms.Integration.ElementHost" /> [Designer("System.Windows.Forms.Design.ControlDesigner, System.Design")] [DesignerSerializer("System.ComponentModel.Design.Serialization.TypeCodeDomSerializer , System.Design", "System.ComponentModel.Design.Serialization.CodeDomSerializer, System.Design")] public class PieChart : ElementHost { /// <summary> /// The WPF base /// </summary> protected readonly Wpf.PieChart WpfBase = new Wpf.PieChart(); /// <summary> /// Initializes a new instance of the <see cref="PieChart"/> class. /// </summary> public PieChart() { Child = WpfBase; //workaround for windows 7 focus issue //https://github.com/beto-rodriguez/Live-Charts/issues/515 HostContainer.MouseEnter += (sender, args) => { Focus(); }; if (LicenseManager.UsageMode == LicenseUsageMode.Designtime) { WpfBase.Series = WpfBase.GetDesignerModeCollection(); } } /// <summary> /// Occurs when the users clicks any point in the chart /// </summary> public event DataClickHandler DataClick { add { WpfBase.DataClick += value; } remove { WpfBase.DataClick += value; } } /// <summary> /// Occurs when the users hovers over any point in the chart /// </summary> public event DataHoverHandler DataHover { add { WpfBase.DataHover += value; } remove { WpfBase.DataHover += value; } } /// <summary> /// Occurs every time the chart updates /// </summary> public event UpdaterTickHandler UpdaterTick { add { WpfBase.UpdaterTick += value; } remove { WpfBase.UpdaterTick += value; } } #region ChartProperties /// <summary> /// Gets or sets the axis y. /// </summary> /// <value> /// The axis y. /// </value> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public AxesCollection AxisY { get { return WpfBase.AxisY; } set { WpfBase.AxisY = value; } } /// <summary> /// Gets or sets the axis x. /// </summary> /// <value> /// The axis x. /// </value> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public AxesCollection AxisX { get { return WpfBase.AxisX; } set { WpfBase.AxisX = value; } } /// <summary> /// Gets or sets the default legend. /// </summary> /// <value> /// The default legend. /// </value> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public UserControl DefaultLegend { get { return WpfBase.ChartLegend; } set { WpfBase.ChartLegend = value; } } /// <summary> /// Gets or sets the zoom. /// </summary> /// <value> /// The zoom. /// </value> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public ZoomingOptions Zoom { get { return WpfBase.Zoom; } set { WpfBase.Zoom = value; } } /// <summary> /// Gets or sets the legend location. /// </summary> /// <value> /// The legend location. /// </value> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public LegendLocation LegendLocation { get { return WpfBase.LegendLocation; } set { WpfBase.LegendLocation = value; } } /// <summary> /// Gets or sets the series. /// </summary> /// <value> /// The series. /// </value> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public SeriesCollection Series { get { return WpfBase.Series; } set { WpfBase.Series = value; } } /// <summary> /// Gets or sets the animations speed. /// </summary> /// <value> /// The animations speed. /// </value> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public TimeSpan AnimationsSpeed { get { return WpfBase.AnimationsSpeed; } set { WpfBase.AnimationsSpeed = value; } } /// <summary> /// Gets or sets a value indicating whether [disable animations]. /// </summary> /// <value> /// <c>true</c> if [disable animations]; otherwise, <c>false</c>. /// </value> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool DisableAnimations { get { return WpfBase.DisableAnimations; } set { WpfBase.DisableAnimations = value; } } /// <summary> /// Gets or sets the data tooltip. /// </summary> /// <value> /// The data tooltip. /// </value> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public UserControl DataTooltip { get { return WpfBase.DataTooltip; } set { WpfBase.DataTooltip = value; } } #endregion #region ThisChartProperties /// <summary> /// Gets or sets the inner radius. /// </summary> /// <value> /// The inner radius. /// </value> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public double InnerRadius { get { return WpfBase.InnerRadius; } set { WpfBase.InnerRadius = value; } } /// <summary> /// Gets or sets the starting rotation angle. /// </summary> /// <value> /// The starting rotation angle. /// </value> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public double StartingRotationAngle { get { return WpfBase.StartingRotationAngle; } set { WpfBase.StartingRotationAngle = value; } } /// <summary> /// Gets or sets the state of the updater. /// </summary> /// <value> /// The state of the updater. /// </value> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public UpdaterState UpdaterState { get { return WpfBase.UpdaterState; } set { WpfBase.UpdaterState = value; } } /// <summary> /// Gets or sets the units that a slice is pushed out when a user moves the mouse over data point. /// </summary> /// <value> /// The hover push out. /// </value> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public double HoverPushOut { get { return WpfBase.HoverPushOut; } set { WpfBase.HoverPushOut = value; } } #endregion #region Methods /// <summary> /// Updates the specified restart view. /// </summary> /// <param name="restartView">if set to <c>true</c> [restart view].</param> /// <param name="force">if set to <c>true</c> [force].</param> public void Update(bool restartView, bool force) { WpfBase.Update(restartView, force); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; #if SRM namespace System.Reflection.Metadata.Ecma335.Blobs #else namespace Roslyn.Reflection.Metadata.Ecma335.Blobs #endif { [Flags] #if SRM public #endif enum MethodBodyAttributes { None = 0, InitLocals = 1, LargeExceptionRegions = 2, } #if SRM public #endif struct MethodBodiesEncoder { public BlobBuilder Builder { get; } public MethodBodiesEncoder(BlobBuilder builder = null) { if (builder == null) { builder = new BlobBuilder(); } // 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) { // TODO: error message throw new ArgumentException("Builder has to be aligned to 4 byte boundary", nameof(builder)); } Builder = builder; } public MethodBodyEncoder AddMethodBody( int maxStack = 8, int exceptionRegionCount = 0, StandaloneSignatureHandle localVariablesSignature = default(StandaloneSignatureHandle), MethodBodyAttributes attributes = MethodBodyAttributes.InitLocals) { if (unchecked((ushort)maxStack) > ushort.MaxValue) { throw new ArgumentOutOfRangeException(nameof(maxStack)); } if (exceptionRegionCount < 0) { throw new ArgumentOutOfRangeException(nameof(exceptionRegionCount)); } return new MethodBodyEncoder(Builder, (ushort)maxStack, exceptionRegionCount, localVariablesSignature, attributes); } } #if SRM public #endif struct MethodBodyEncoder { public BlobBuilder Builder { get; } private readonly ushort _maxStack; private readonly int _exceptionRegionCount; private readonly StandaloneSignatureHandle _localVariablesSignature; private readonly byte _attributes; internal MethodBodyEncoder( BlobBuilder builder, ushort maxStack, int exceptionRegionCount, StandaloneSignatureHandle localVariablesSignature, MethodBodyAttributes attributes) { Builder = builder; _maxStack = maxStack; _localVariablesSignature = localVariablesSignature; _attributes = (byte)attributes; _exceptionRegionCount = exceptionRegionCount; } internal bool IsTiny(int codeSize) { return codeSize < 64 && _maxStack <= 8 && _localVariablesSignature.IsNil && _exceptionRegionCount == 0; } private int WriteHeader(int codeSize) { Blob blob; return WriteHeader(codeSize, false, out blob); } private int WriteHeader(int codeSize, bool codeSizeFixup, out Blob codeSizeBlob) { const int TinyFormat = 2; const int FatFormat = 3; const int MoreSections = 8; const byte InitLocals = 0x10; int offset; if (IsTiny(codeSize)) { offset = Builder.Count; Builder.WriteByte((byte)((codeSize << 2) | TinyFormat)); Debug.Assert(!codeSizeFixup); codeSizeBlob = default(Blob); } else { Builder.Align(4); offset = Builder.Count; ushort flags = (3 << 12) | FatFormat; if (_exceptionRegionCount > 0) { flags |= MoreSections; } if ((_attributes & (int)MethodBodyAttributes.InitLocals) != 0) { flags |= InitLocals; } Builder.WriteUInt16((ushort)(_attributes | flags)); Builder.WriteUInt16(_maxStack); if (codeSizeFixup) { codeSizeBlob = Builder.ReserveBytes(sizeof(int)); } else { codeSizeBlob = default(Blob); Builder.WriteInt32(codeSize); } Builder.WriteInt32(_localVariablesSignature.IsNil ? 0 : MetadataTokens.GetToken(_localVariablesSignature)); } return offset; } private ExceptionRegionEncoder CreateExceptionEncoder() { return new ExceptionRegionEncoder( Builder, _exceptionRegionCount, hasLargeRegions: (_attributes & (int)MethodBodyAttributes.LargeExceptionRegions) != 0); } public ExceptionRegionEncoder WriteInstructions(ImmutableArray<byte> instructions, out int bodyOffset) { bodyOffset = WriteHeader(instructions.Length); Builder.WriteBytes(instructions); return CreateExceptionEncoder(); } public ExceptionRegionEncoder WriteInstructions(ImmutableArray<byte> instructions, out int bodyOffset, out Blob instructionBlob) { bodyOffset = WriteHeader(instructions.Length); instructionBlob = Builder.ReserveBytes(instructions.Length); new BlobWriter(instructionBlob).WriteBytes(instructions); return CreateExceptionEncoder(); } public ExceptionRegionEncoder WriteInstructions(BlobBuilder codeBuilder, out int bodyOffset) { bodyOffset = WriteHeader(codeBuilder.Count); codeBuilder.WriteContentTo(Builder); return CreateExceptionEncoder(); } public ExceptionRegionEncoder WriteInstructions(BlobBuilder codeBuilder, BranchBuilder branchBuilder, out int bodyOffset) { if (branchBuilder == null || branchBuilder.BranchCount == 0) { return WriteInstructions(codeBuilder, out bodyOffset); } // When emitting branches we emitted short branches. int initialCodeSize = codeBuilder.Count; Blob codeSizeFixup; if (IsTiny(initialCodeSize)) { // If the method is tiny so far then all branches have to be short // (the max distance between any label and a branch instruction is < 64). bodyOffset = WriteHeader(initialCodeSize); codeSizeFixup = default(Blob); } else { // Otherwise, it's fat format and we can fixup the size later on: bodyOffset = WriteHeader(initialCodeSize, true, out codeSizeFixup); } int codeStartOffset = Builder.Count; branchBuilder.FixupBranches(codeBuilder, Builder); if (!codeSizeFixup.IsDefault) { new BlobWriter(codeSizeFixup).WriteInt32(Builder.Count - codeStartOffset); } else { Debug.Assert(initialCodeSize == Builder.Count - codeStartOffset); } return CreateExceptionEncoder(); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // // // WindowsIdentity.cs // // Representation of a process/thread token. // namespace System.Security.Principal { using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.CompilerServices; #if FEATURE_CORRUPTING_EXCEPTIONS using System.Runtime.ExceptionServices; #endif // FEATURE_CORRUPTING_EXCEPTIONS using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security.AccessControl; using System.Security.Permissions; using System.Text; using System.Threading; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; #if !FEATURE_CORECLR using System.Security.Claims; using System.Collections.ObjectModel; using System.Collections.Generic; using System.Globalization; #endif [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public enum WindowsAccountType { Normal = 0, Guest = 1, System = 2, Anonymous = 3 } // Keep in [....] with vm\comprincipal.h internal enum WinSecurityContext { Thread = 1, // OpenAsSelf = false Process = 2, // OpenAsSelf = true Both = 3 // OpenAsSelf = true, then OpenAsSelf = false } internal enum ImpersonationQueryResult { Impersonated = 0, // current thread is impersonated NotImpersonated = 1, // current thread is not impersonated Failed = 2 // failed to query } [Serializable] [System.Runtime.InteropServices.ComVisible(true)] #if !FEATURE_CORECLR public class WindowsIdentity : ClaimsIdentity, ISerializable, IDeserializationCallback, IDisposable { #else public class WindowsIdentity : IIdentity, ISerializable, IDeserializationCallback, IDisposable { #endif [System.Security.SecurityCritical] // auto-generated static SafeAccessTokenHandle s_invalidTokenHandle = SafeAccessTokenHandle.InvalidHandle; private string m_name = null; private SecurityIdentifier m_owner = null; private SecurityIdentifier m_user = null; private object m_groups = null; [System.Security.SecurityCritical] // auto-generated private SafeAccessTokenHandle m_safeTokenHandle = SafeAccessTokenHandle.InvalidHandle; private string m_authType = null; private int m_isAuthenticated = -1; private volatile TokenImpersonationLevel m_impersonationLevel; private volatile bool m_impersonationLevelInitialized; private static RuntimeConstructorInfo s_specialSerializationCtor; #if !FEATURE_CORECLR [NonSerialized] public new const string DefaultIssuer = @"AD AUTHORITY"; [NonSerialized] string m_issuerName = DefaultIssuer; [NonSerialized] private object m_claimsIntiailizedLock = new object(); [NonSerialized] volatile bool m_claimsInitialized; [NonSerialized] List<Claim> m_deviceClaims; [NonSerialized] List<Claim> m_userClaims; #endif // // Constructors. // [System.Security.SecuritySafeCritical] // auto-generated static WindowsIdentity() { s_specialSerializationCtor = typeof(WindowsIdentity).GetConstructor( BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(SerializationInfo) }, null) as RuntimeConstructorInfo; } [System.Security.SecurityCritical] // auto-generated #if !FEATURE_CORECLR private WindowsIdentity () : base( null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid ) {} #else private WindowsIdentity () {} #endif [System.Security.SecurityCritical] // auto-generated internal WindowsIdentity (SafeAccessTokenHandle safeTokenHandle) : this (safeTokenHandle.DangerousGetHandle(), null, -1) { GC.KeepAlive(safeTokenHandle); } [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPrincipal)] [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)] public WindowsIdentity (IntPtr userToken) : this (userToken, null, -1) {} [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPrincipal)] [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)] public WindowsIdentity (IntPtr userToken, string type) : this (userToken, type, -1) {} [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPrincipal)] [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)] public WindowsIdentity (IntPtr userToken, string type, WindowsAccountType acctType) : this (userToken, type, -1) {} [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPrincipal)] [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)] public WindowsIdentity (IntPtr userToken, string type, WindowsAccountType acctType, bool isAuthenticated) : this (userToken, type, isAuthenticated ? 1 : 0) {} [System.Security.SecurityCritical] // auto-generated private WindowsIdentity (IntPtr userToken, string authType, int isAuthenticated ) #if !FEATURE_CORECLR : base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid) #endif { CreateFromToken(userToken); m_authType = authType; m_isAuthenticated = isAuthenticated; } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] private void CreateFromToken (IntPtr userToken) { if (userToken == IntPtr.Zero) throw new ArgumentException(Environment.GetResourceString("Argument_TokenZero")); Contract.EndContractBlock(); // Find out if the specified token is a valid. uint dwLength = (uint) Marshal.SizeOf(typeof(uint)); bool result = Win32Native.GetTokenInformation(userToken, (uint) TokenInformationClass.TokenType, SafeLocalAllocHandle.InvalidHandle, 0, out dwLength); if (Marshal.GetLastWin32Error() == Win32Native.ERROR_INVALID_HANDLE) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidImpersonationToken")); if (!Win32Native.DuplicateHandle(Win32Native.GetCurrentProcess(), userToken, Win32Native.GetCurrentProcess(), ref m_safeTokenHandle, 0, true, Win32Native.DUPLICATE_SAME_ACCESS)) throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error())); } [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPrincipal)] public WindowsIdentity (string sUserPrincipalName) : this (sUserPrincipalName, null) {} [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPrincipal)] public WindowsIdentity (string sUserPrincipalName, string type ) #if !FEATURE_CORECLR : base( null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid ) #endif { KerbS4ULogon(sUserPrincipalName, ref m_safeTokenHandle); } // // We cannot make sure the token will stay alive // until it is being deserialized in another AppDomain. We do not have a way to capture // the state of a token (just a pointer to kernel memory) and re-construct it later // and even if we did (via calling NtQueryInformationToken and relying on the token undocumented // format), constructing a token requires TCB privilege. We need to address the "serializable" // nature of WindowsIdentity since it is not obvious that can be achieved at all. // [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPrincipal)] [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.SerializationFormatter )] public WindowsIdentity (SerializationInfo info, StreamingContext context) : this(info) { } // This is a copy of the serialization constructor above but without the // security demand that's slow and breaks partial trust scenarios // without an expensive assert in place in the remoting code. Instead we // special case this class and call the private constructor directly // (changing the demand above is considered a breaking change, even // though nobody else should have been using a serialization constructor // directly). [System.Security.SecurityCritical] // auto-generated private WindowsIdentity(SerializationInfo info) #if !FEATURE_CORECLR : base(info) #endif { #if !FEATURE_CORECLR m_claimsInitialized = false; #endif IntPtr userToken = (IntPtr) info.GetValue("m_userToken", typeof(IntPtr)); if (userToken != IntPtr.Zero) CreateFromToken(userToken); } /// <internalonly/> [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context) { #if !FEATURE_CORECLR base.GetObjectData(info, context); #endif info.AddValue("m_userToken", m_safeTokenHandle.DangerousGetHandle()); } /// <internalonly/> void IDeserializationCallback.OnDeserialization (Object sender) {} // // Factory methods. // [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPrincipal)] public static WindowsIdentity GetCurrent () { return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, false); } [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPrincipal)] public static WindowsIdentity GetCurrent (bool ifImpersonating) { return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, ifImpersonating); } [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPrincipal)] public static WindowsIdentity GetCurrent (TokenAccessLevels desiredAccess) { return GetCurrentInternal(desiredAccess, false); } // GetAnonymous() is used heavily in ASP.NET requests as a dummy identity to indicate // the request is anonymous. It does not represent a real process or thread token so // it cannot impersonate or do anything useful. Note this identity does not represent the // usual concept of an anonymous token, and the name is simply misleading but we cannot change it now. [System.Security.SecuritySafeCritical] // auto-generated public static WindowsIdentity GetAnonymous () { return new WindowsIdentity(); } // // Properties. // // this is defined 'override sealed' for back compat. Il generated is 'virtual final' and this needs to be the same. #if !FEATURE_CORECLR public override sealed string AuthenticationType { #else public string AuthenticationType { #endif [System.Security.SecuritySafeCritical] // auto-generated get { // If this is an anonymous identity, return an empty string if (m_safeTokenHandle.IsInvalid) return String.Empty; if (m_authType == null) { Win32Native.LUID authId = GetLogonAuthId(m_safeTokenHandle); if (authId.LowPart == Win32Native.ANONYMOUS_LOGON_LUID) return String.Empty; // no authentication, just return an empty string SafeLsaReturnBufferHandle pLogonSessionData = SafeLsaReturnBufferHandle.InvalidHandle; try { int status = Win32Native.LsaGetLogonSessionData(ref authId, ref pLogonSessionData); if (status < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(status); pLogonSessionData.Initialize((uint)Marshal.SizeOf(typeof(Win32Native.SECURITY_LOGON_SESSION_DATA))); Win32Native.SECURITY_LOGON_SESSION_DATA logonSessionData = pLogonSessionData.Read<Win32Native.SECURITY_LOGON_SESSION_DATA>(0); return Marshal.PtrToStringUni(logonSessionData.AuthenticationPackage.Buffer); } finally { if (!pLogonSessionData.IsInvalid) pLogonSessionData.Dispose(); } } return m_authType; } } [ComVisible(false)] public TokenImpersonationLevel ImpersonationLevel { [System.Security.SecuritySafeCritical] // auto-generated get { // If two threads ---- here, they'll both set m_impersonationLevel to the same value, // which is ok. if (!m_impersonationLevelInitialized) { TokenImpersonationLevel impersonationLevel = TokenImpersonationLevel.None; // If this is an anonymous identity if (m_safeTokenHandle.IsInvalid) { impersonationLevel = TokenImpersonationLevel.Anonymous; } else { TokenType tokenType = (TokenType)GetTokenInformation<int>(TokenInformationClass.TokenType); if (tokenType == TokenType.TokenPrimary) { impersonationLevel = TokenImpersonationLevel.None; // primary token; } else { /// This is an impersonation token, get the impersonation level int level = GetTokenInformation<int>(TokenInformationClass.TokenImpersonationLevel); impersonationLevel = (TokenImpersonationLevel)level + 1; } } m_impersonationLevel = impersonationLevel; m_impersonationLevelInitialized = true; } return m_impersonationLevel; } } #if !FEATURE_CORECLR public override bool IsAuthenticated { #else public virtual bool IsAuthenticated { #endif get { if (m_isAuthenticated == -1) { // There is a known bug where this approach will not work correctly for domain guests (will return false // instead of true). But this is a corner-case that is not very interesting. #if !FEATURE_CORECLR m_isAuthenticated = CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { Win32Native.SECURITY_AUTHENTICATED_USER_RID })) ? 1 : 0; #else WindowsPrincipal wp = new WindowsPrincipal(this); SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] {Win32Native.SECURITY_AUTHENTICATED_USER_RID}); m_isAuthenticated = wp.IsInRole(sid) ? 1 : 0; #endif } return m_isAuthenticated == 1; } } #if !FEATURE_CORECLR [System.Security.SecuritySafeCritical] [ComVisible(false)] bool CheckNtTokenForSid (SecurityIdentifier sid) { Contract.EndContractBlock(); // special case the anonymous identity. if (m_safeTokenHandle.IsInvalid) return false; // CheckTokenMembership expects an impersonation token SafeAccessTokenHandle token = SafeAccessTokenHandle.InvalidHandle; TokenImpersonationLevel til = ImpersonationLevel; bool isMember = false; try { if (til == TokenImpersonationLevel.None) { if (!Win32Native.DuplicateTokenEx(m_safeTokenHandle, (uint) TokenAccessLevels.Query, IntPtr.Zero, (uint) TokenImpersonationLevel.Identification, (uint) TokenType.TokenImpersonation, ref token)) throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error())); } // CheckTokenMembership will check if the SID is both present and enabled in the access token. if (!Win32Native.CheckTokenMembership((til != TokenImpersonationLevel.None ? m_safeTokenHandle : token), sid.BinaryForm, ref isMember)) throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error())); } finally { if (token != SafeAccessTokenHandle.InvalidHandle) { token.Dispose(); } } return isMember; } #endif // // IsGuest, IsSystem and IsAnonymous are maintained for compatibility reasons. It is always // possible to extract this same information from the User SID property and the new // (and more general) methods defined in the SID class (IsWellKnown, etc...). // public virtual bool IsGuest { [System.Security.SecuritySafeCritical] // auto-generated get { // special case the anonymous identity. if (m_safeTokenHandle.IsInvalid) return false; #if !FEATURE_CORECLR return CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { Win32Native.SECURITY_BUILTIN_DOMAIN_RID, (int)WindowsBuiltInRole.Guest })); #else WindowsPrincipal principal = new WindowsPrincipal(this); return principal.IsInRole(WindowsBuiltInRole.Guest); #endif } } public virtual bool IsSystem { [System.Security.SecuritySafeCritical] // auto-generated get { // special case the anonymous identity. if (m_safeTokenHandle.IsInvalid) return false; SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] {Win32Native.SECURITY_LOCAL_SYSTEM_RID}); return (this.User == sid); } } public virtual bool IsAnonymous { [System.Security.SecuritySafeCritical] // auto-generated get { // special case the anonymous identity. if (m_safeTokenHandle.IsInvalid) return true; SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] {Win32Native.SECURITY_ANONYMOUS_LOGON_RID}); return (this.User == sid); } } #if !FEATURE_CORECLR public override string Name { #else public virtual string Name { #endif [System.Security.SecuritySafeCritical] // auto-generated get { return GetName(); } } [System.Security.SecurityCritical] // auto-generated [DynamicSecurityMethodAttribute()] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable internal String GetName() { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; // special case the anonymous identity. if (m_safeTokenHandle.IsInvalid) return String.Empty; if (m_name == null) { // revert thread impersonation for the duration of the call to get the name. using (SafeRevertToSelf(ref stackMark)) { NTAccount ntAccount = this.User.Translate(typeof(NTAccount)) as NTAccount; m_name = ntAccount.ToString(); } } return m_name; } [ComVisible(false)] public SecurityIdentifier Owner { [System.Security.SecuritySafeCritical] // auto-generated get { // special case the anonymous identity. if (m_safeTokenHandle.IsInvalid) return null; if (m_owner == null) { using (SafeLocalAllocHandle tokenOwner = GetTokenInformation(m_safeTokenHandle, TokenInformationClass.TokenOwner)) { m_owner = new SecurityIdentifier(tokenOwner.Read<IntPtr>(0), true); } } return m_owner; } } [ComVisible(false)] public SecurityIdentifier User { [System.Security.SecuritySafeCritical] // auto-generated get { // special case the anonymous identity. if (m_safeTokenHandle.IsInvalid) return null; if (m_user == null) { using (SafeLocalAllocHandle tokenUser = GetTokenInformation(m_safeTokenHandle, TokenInformationClass.TokenUser)) { m_user = new SecurityIdentifier(tokenUser.Read<IntPtr>(0), true); } } return m_user; } } public IdentityReferenceCollection Groups { [System.Security.SecuritySafeCritical] // auto-generated get { // special case the anonymous identity. if (m_safeTokenHandle.IsInvalid) return null; if (m_groups == null) { IdentityReferenceCollection groups = new IdentityReferenceCollection(); using (SafeLocalAllocHandle pGroups = GetTokenInformation(m_safeTokenHandle, TokenInformationClass.TokenGroups)) { uint groupCount = pGroups.Read<uint>(0); // Work-around bug on WS03 that only populates the GroupCount field of TOKEN_GROUPS if the count is 0 // In that situation, attempting to read the entire TOKEN_GROUPS structure will lead to InsufficientBuffer exception // since the field is only 4 bytes long (uint only, for GroupCount), but we try to read more (including the pointer to GroupDetails). if (groupCount != 0) { Win32Native.TOKEN_GROUPS tokenGroups = pGroups.Read<Win32Native.TOKEN_GROUPS>(0); Win32Native.SID_AND_ATTRIBUTES[] groupDetails = new Win32Native.SID_AND_ATTRIBUTES[tokenGroups.GroupCount]; pGroups.ReadArray((uint)Marshal.OffsetOf(typeof(Win32Native.TOKEN_GROUPS), "Groups").ToInt32(), groupDetails, 0, groupDetails.Length); foreach (Win32Native.SID_AND_ATTRIBUTES group in groupDetails) { // Ignore disabled, logon ID, and deny-only groups. uint mask = Win32Native.SE_GROUP_ENABLED | Win32Native.SE_GROUP_LOGON_ID | Win32Native.SE_GROUP_USE_FOR_DENY_ONLY; if ((group.Attributes & mask) == Win32Native.SE_GROUP_ENABLED) { groups.Add(new SecurityIdentifier(group.Sid, true )); } } } } Interlocked.CompareExchange(ref m_groups, groups, null); } return m_groups as IdentityReferenceCollection; } } // // Note this property does not duplicate the token. This is also the same as V1/Everett behaviour. // public virtual IntPtr Token { [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)] get { return m_safeTokenHandle.DangerousGetHandle(); } } // // Public methods. // [SecuritySafeCritical] public static void RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action) { if (action == null) throw new ArgumentNullException("action"); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; WindowsIdentity wi = null; if (!safeAccessTokenHandle.IsInvalid) wi = new WindowsIdentity(safeAccessTokenHandle); using (WindowsImpersonationContext wiContext = SafeImpersonate(safeAccessTokenHandle, wi, ref stackMark)) { action(); } } [SecuritySafeCritical] public static T RunImpersonated<T>(SafeAccessTokenHandle safeAccessTokenHandle, Func<T> func) { if (func == null) throw new ArgumentNullException("func"); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; WindowsIdentity wi = null; if (!safeAccessTokenHandle.IsInvalid) wi = new WindowsIdentity(safeAccessTokenHandle); T result = default(T); using (WindowsImpersonationContext wiContext = SafeImpersonate(safeAccessTokenHandle, wi, ref stackMark)) { result = func(); } return result; } [System.Security.SecuritySafeCritical] // auto-generated [DynamicSecurityMethodAttribute()] [ResourceExposure(ResourceScope.Process)] // Call from within a CER, or use a RunAsUser helper. [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public virtual WindowsImpersonationContext Impersonate () { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return Impersonate(ref stackMark); } [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal | SecurityPermissionFlag.UnmanagedCode)] [DynamicSecurityMethodAttribute()] [ResourceExposure(ResourceScope.Process)] // Call from within a CER, or use a RunAsUser helper. [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static WindowsImpersonationContext Impersonate (IntPtr userToken) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; if (userToken == IntPtr.Zero) return SafeRevertToSelf(ref stackMark); WindowsIdentity wi = new WindowsIdentity(userToken, null, -1); return wi.Impersonate(ref stackMark); } [System.Security.SecurityCritical] // auto-generated internal WindowsImpersonationContext Impersonate (ref StackCrawlMark stackMark) { if (m_safeTokenHandle.IsInvalid) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AnonymousCannotImpersonate")); return SafeImpersonate(m_safeTokenHandle, this, ref stackMark); } [System.Security.SecuritySafeCritical] // auto-generated [ComVisible(false)] protected virtual void Dispose(bool disposing) { if (disposing) { if (m_safeTokenHandle != null && !m_safeTokenHandle.IsClosed) m_safeTokenHandle.Dispose(); } m_name = null; m_owner = null; m_user = null; } [ComVisible(false)] public void Dispose() { Dispose(true); } public SafeAccessTokenHandle AccessToken { [System.Security.SecurityCritical] // auto-generated get { return m_safeTokenHandle; } } // // internal. // [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] internal static WindowsImpersonationContext SafeRevertToSelf(ref StackCrawlMark stackMark) { return SafeImpersonate(s_invalidTokenHandle, null, ref stackMark); } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] internal static WindowsImpersonationContext SafeImpersonate (SafeAccessTokenHandle userToken, WindowsIdentity wi, ref StackCrawlMark stackMark) { bool isImpersonating; int hr = 0; SafeAccessTokenHandle safeTokenHandle = GetCurrentToken(TokenAccessLevels.MaximumAllowed, false, out isImpersonating, out hr); if (safeTokenHandle == null || safeTokenHandle.IsInvalid) throw new SecurityException(Win32Native.GetMessage(hr)); // Set the SafeAccessTokenHandle on the FSD: FrameSecurityDescriptor secObj = SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true); if (secObj == null) { // Security: REQ_SQ flag is missing. Bad compiler ? // This can happen when you create delegates over functions that need the REQ_SQ throw new SecurityException(Environment.GetResourceString( "ExecutionEngine_MissingSecurityDescriptor" ) ); } WindowsImpersonationContext context = new WindowsImpersonationContext(safeTokenHandle, GetCurrentThreadWI(), isImpersonating, secObj); if (userToken.IsInvalid) { // impersonating a zero token means clear the token on the thread hr = Win32.RevertToSelf(); if (hr < 0) Environment.FailFast(Win32Native.GetMessage(hr)); // update identity on the thread UpdateThreadWI(wi); secObj.SetTokenHandles(safeTokenHandle, (wi == null?null:wi.AccessToken)); } else { hr = Win32.RevertToSelf(); if (hr < 0) Environment.FailFast(Win32Native.GetMessage(hr)); hr = Win32.ImpersonateLoggedOnUser(userToken); if (hr < 0) { context.Undo(); throw new SecurityException(Environment.GetResourceString("Argument_ImpersonateUser")); } UpdateThreadWI(wi); secObj.SetTokenHandles(safeTokenHandle, (wi == null?null:wi.AccessToken)); } return context; } [System.Security.SecurityCritical] // auto-generated internal static WindowsIdentity GetCurrentThreadWI() { return SecurityContext.GetCurrentWI(Thread.CurrentThread.GetExecutionContextReader()); } [SecurityCritical] internal static void UpdateThreadWI(WindowsIdentity wi) { // Set WI on Thread.CurrentThread.ExecutionContext.SecurityContext Thread currentThread = Thread.CurrentThread; if (currentThread.GetExecutionContextReader().SecurityContext.WindowsIdentity != wi) { ExecutionContext ec = currentThread.GetMutableExecutionContext(); SecurityContext sc = ec.SecurityContext; if (wi != null && sc == null) { // create a new security context on the thread sc = new SecurityContext(); ec.SecurityContext = sc; } if (sc != null) // null-check needed here since we will not create an sc if wi is null { sc.WindowsIdentity = wi; } } } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] internal static WindowsIdentity GetCurrentInternal (TokenAccessLevels desiredAccess, bool threadOnly) { int hr = 0; bool isImpersonating; SafeAccessTokenHandle safeTokenHandle = GetCurrentToken(desiredAccess, threadOnly, out isImpersonating, out hr); if (safeTokenHandle == null || safeTokenHandle.IsInvalid) { // either we wanted only ThreadToken - return null if (threadOnly && !isImpersonating) return null; // or there was an error throw new SecurityException(Win32Native.GetMessage(hr)); } WindowsIdentity wi = new WindowsIdentity(); wi.m_safeTokenHandle.Dispose(); wi.m_safeTokenHandle = safeTokenHandle; return wi; } internal static RuntimeConstructorInfo GetSpecialSerializationCtor() { return s_specialSerializationCtor; } // // private. // private static int GetHRForWin32Error (int dwLastError) { if ((dwLastError & 0x80000000) == 0x80000000) return dwLastError; else return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000); } [System.Security.SecurityCritical] // auto-generated private static Exception GetExceptionFromNtStatus (int status) { if ((uint) status == Win32Native.STATUS_ACCESS_DENIED) return new UnauthorizedAccessException(); if ((uint) status == Win32Native.STATUS_INSUFFICIENT_RESOURCES || (uint) status == Win32Native.STATUS_NO_MEMORY) return new OutOfMemoryException(); int win32ErrorCode = Win32Native.LsaNtStatusToWinError(status); return new SecurityException(Win32Native.GetMessage(win32ErrorCode)); } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] private static SafeAccessTokenHandle GetCurrentToken(TokenAccessLevels desiredAccess, bool threadOnly, out bool isImpersonating, out int hr) { isImpersonating = true; SafeAccessTokenHandle safeTokenHandle = GetCurrentThreadToken(desiredAccess, out hr); if (safeTokenHandle == null && hr == GetHRForWin32Error(Win32Native.ERROR_NO_TOKEN)) { // No impersonation isImpersonating = false; if (!threadOnly) safeTokenHandle = GetCurrentProcessToken(desiredAccess, out hr); } return safeTokenHandle; } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] private static SafeAccessTokenHandle GetCurrentProcessToken (TokenAccessLevels desiredAccess, out int hr) { hr = 0; SafeAccessTokenHandle safeTokenHandle; if (!Win32Native.OpenProcessToken(Win32Native.GetCurrentProcess(), desiredAccess, out safeTokenHandle)) hr = GetHRForWin32Error(Marshal.GetLastWin32Error()); return safeTokenHandle; } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] internal static SafeAccessTokenHandle GetCurrentThreadToken(TokenAccessLevels desiredAccess, out int hr) { SafeAccessTokenHandle safeTokenHandle; hr = Win32.OpenThreadToken(desiredAccess, WinSecurityContext.Both, out safeTokenHandle); return safeTokenHandle; } /// <summary> /// Get a property from the current token /// </summary> [System.Security.SecurityCritical] // auto-generated private T GetTokenInformation<T>(TokenInformationClass tokenInformationClass) where T : struct{ Contract.Assert(!m_safeTokenHandle.IsInvalid && !m_safeTokenHandle.IsClosed, "!m_safeTokenHandle.IsInvalid && !m_safeTokenHandle.IsClosed"); using (SafeLocalAllocHandle information = GetTokenInformation(m_safeTokenHandle, tokenInformationClass)) { Contract.Assert(information.ByteLength >= (ulong)Marshal.SizeOf(typeof(T)), "information.ByteLength >= (ulong)Marshal.SizeOf(typeof(T))"); return information.Read<T>(0); } } // // QueryImpersonation used to test if the current thread is impersonated. // This method doesn't return the thread token (WindowsIdentity). // Although GetCurrentInternal can be used to perform the same test but // QueryImpersonation is optimized for the perf. // [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] internal static ImpersonationQueryResult QueryImpersonation() { SafeAccessTokenHandle safeTokenHandle = null; int hr = Win32.OpenThreadToken(TokenAccessLevels.Query, WinSecurityContext.Thread, out safeTokenHandle); if (safeTokenHandle != null) { Contract.Assert(hr == 0, "[WindowsIdentity..QueryImpersonation] - hr == 0"); safeTokenHandle.Close(); return ImpersonationQueryResult.Impersonated; } if (hr == GetHRForWin32Error(Win32Native.ERROR_ACCESS_DENIED)) { // thread is impersonated because the thread was there (and we failed to open it). return ImpersonationQueryResult.Impersonated; } if (hr == GetHRForWin32Error(Win32Native.ERROR_NO_TOKEN)) { // definitely not impersonating return ImpersonationQueryResult.NotImpersonated; } // Unexpected failure. return ImpersonationQueryResult.Failed; } [System.Security.SecurityCritical] // auto-generated private static Win32Native.LUID GetLogonAuthId (SafeAccessTokenHandle safeTokenHandle) { using (SafeLocalAllocHandle pStatistics = GetTokenInformation(safeTokenHandle, TokenInformationClass.TokenStatistics)) { Win32Native.TOKEN_STATISTICS statistics = pStatistics.Read<Win32Native.TOKEN_STATISTICS>(0); return statistics.AuthenticationId; } } [System.Security.SecurityCritical] private static SafeLocalAllocHandle GetTokenInformation (SafeAccessTokenHandle tokenHandle, TokenInformationClass tokenInformationClass) { SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle; uint dwLength = (uint) Marshal.SizeOf(typeof(uint)); bool result = Win32Native.GetTokenInformation(tokenHandle, (uint) tokenInformationClass, safeLocalAllocHandle, 0, out dwLength); int dwErrorCode = Marshal.GetLastWin32Error(); switch (dwErrorCode) { case Win32Native.ERROR_BAD_LENGTH: // special case for TokenSessionId. Falling through case Win32Native.ERROR_INSUFFICIENT_BUFFER: // ptrLength is an [In] param to LocalAlloc UIntPtr ptrLength = new UIntPtr(dwLength); safeLocalAllocHandle.Dispose(); safeLocalAllocHandle = Win32Native.LocalAlloc(Win32Native.LMEM_FIXED, ptrLength); if (safeLocalAllocHandle == null || safeLocalAllocHandle.IsInvalid) throw new OutOfMemoryException(); safeLocalAllocHandle.Initialize(dwLength); result = Win32Native.GetTokenInformation(tokenHandle, (uint) tokenInformationClass, safeLocalAllocHandle, dwLength, out dwLength); if (!result) throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error())); break; case Win32Native.ERROR_INVALID_HANDLE: throw new ArgumentException(Environment.GetResourceString("Argument_InvalidImpersonationToken")); default: throw new SecurityException(Win32Native.GetMessage(dwErrorCode)); } return safeLocalAllocHandle; } [System.Security.SecurityCritical] // auto-generated #if FEATURE_CORRUPTING_EXCEPTIONS [HandleProcessCorruptedStateExceptions] // #endif // FEATURE_CORRUPTING_EXCEPTIONS private unsafe static SafeAccessTokenHandle KerbS4ULogon (string upn, ref SafeAccessTokenHandle safeTokenHandle) { // source name byte[] sourceName = new byte[] { (byte)'C', (byte)'L', (byte)'R' }; // we set the source name to "CLR". // ptrLength is an [In] param to LocalAlloc UIntPtr ptrLength = new UIntPtr((uint)(sourceName.Length + 1)); using (SafeLocalAllocHandle pSourceName = Win32Native.LocalAlloc(Win32Native.LPTR, ptrLength)) { if (pSourceName == null || pSourceName.IsInvalid) throw new OutOfMemoryException(); pSourceName.Initialize((ulong)sourceName.Length + 1); pSourceName.WriteArray(0, sourceName, 0, sourceName.Length); Win32Native.UNICODE_INTPTR_STRING Name = new Win32Native.UNICODE_INTPTR_STRING(sourceName.Length, pSourceName); int status; SafeLsaLogonProcessHandle logonHandle = SafeLsaLogonProcessHandle.InvalidHandle; SafeLsaReturnBufferHandle profile = SafeLsaReturnBufferHandle.InvalidHandle; try { Privilege privilege = null; RuntimeHelpers.PrepareConstrainedRegions(); // Try to get an impersonation token. try { // Try to enable the TCB privilege if possible try { privilege = new Privilege("SeTcbPrivilege"); privilege.Enable(); } catch (PrivilegeNotHeldException) { } IntPtr dummy = IntPtr.Zero; status = Win32Native.LsaRegisterLogonProcess(ref Name, ref logonHandle, ref dummy); if (Win32Native.ERROR_ACCESS_DENIED == Win32Native.LsaNtStatusToWinError(status)) { // We don't have the Tcb privilege. The best we can hope for is to get an Identification token. status = Win32Native.LsaConnectUntrusted(ref logonHandle); } } catch { // protect against exception filter-based luring attacks if (privilege != null) privilege.Revert(); throw; } finally { if (privilege != null) privilege.Revert(); } if (status < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(status); // package name ("Kerberos") byte[] arrayPackageName = new byte[Win32Native.MICROSOFT_KERBEROS_NAME.Length + 1]; Encoding.ASCII.GetBytes(Win32Native.MICROSOFT_KERBEROS_NAME, 0, Win32Native.MICROSOFT_KERBEROS_NAME.Length, arrayPackageName, 0); // ptrLength is an [In] param to LocalAlloc ptrLength = new UIntPtr((uint)arrayPackageName.Length); using (SafeLocalAllocHandle pPackageName = Win32Native.LocalAlloc(Win32Native.LMEM_FIXED, ptrLength)) { if (pPackageName == null || pPackageName.IsInvalid) throw new OutOfMemoryException(); pPackageName.Initialize((ulong)(uint)arrayPackageName.Length); pPackageName.WriteArray(0, arrayPackageName, 0, arrayPackageName.Length); Win32Native.UNICODE_INTPTR_STRING PackageName = new Win32Native.UNICODE_INTPTR_STRING(Win32Native.MICROSOFT_KERBEROS_NAME.Length, pPackageName); uint packageId = 0; status = Win32Native.LsaLookupAuthenticationPackage(logonHandle, ref PackageName, ref packageId); if (status < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(status); // source context Win32Native.TOKEN_SOURCE sourceContext = new Win32Native.TOKEN_SOURCE(); if (!Win32Native.AllocateLocallyUniqueId(ref sourceContext.SourceIdentifier)) throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error())); sourceContext.Name = new char[8]; sourceContext.Name[0] = 'C'; sourceContext.Name[1] = 'L'; sourceContext.Name[2] = 'R'; uint profileSize = 0; Win32Native.LUID logonId = new Win32Native.LUID(); Win32Native.QUOTA_LIMITS quotas = new Win32Native.QUOTA_LIMITS(); int subStatus = 0; // // Build the KERB_S4U_LOGON structure. Note that the LSA expects this entire // structure to be contained within the same block of memory, so we need to allocate // enough room for both the structure itself and the UPN string in a single buffer // and do the marshalling into this buffer by hand. // byte[] upnBytes = Encoding.Unicode.GetBytes(upn); Contract.Assert(Marshal.SizeOf(typeof(Win32Native.KERB_S4U_LOGON)) % IntPtr.Size == 0, "Potential allignment issue setting up S4U logon buffer"); uint logonInfoSize = (uint) (Marshal.SizeOf(typeof(Win32Native.KERB_S4U_LOGON)) + upnBytes.Length); using (SafeLocalAllocHandle logonInfoBuffer = Win32Native.LocalAlloc(Win32Native.LPTR, new UIntPtr(logonInfoSize))) { if (logonInfoBuffer == null || logonInfoBuffer.IsInvalid) { throw new OutOfMemoryException(); } logonInfoBuffer.Initialize((ulong)logonInfoSize); // Write the UPN to the end of the serialized buffer ulong upnOffset = (ulong)Marshal.SizeOf(typeof(Win32Native.KERB_S4U_LOGON)); logonInfoBuffer.WriteArray(upnOffset, upnBytes, 0, upnBytes.Length); unsafe { byte* pLogonInfoBuffer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { logonInfoBuffer.AcquirePointer(ref pLogonInfoBuffer); // Setup the KERB_S4U_LOGON structure Win32Native.KERB_S4U_LOGON logonInfo = new Win32Native.KERB_S4U_LOGON(); logonInfo.MessageType = (uint)KerbLogonSubmitType.KerbS4ULogon; logonInfo.Flags = 0; // Point the ClientUpn at the UPN written at the end of this buffer logonInfo.ClientUpn = new Win32Native.UNICODE_INTPTR_STRING(upnBytes.Length, new IntPtr(pLogonInfoBuffer + upnOffset)); logonInfoBuffer.Write(0, logonInfo); // logon user status = Win32Native.LsaLogonUser(logonHandle, ref Name, (uint)SecurityLogonType.Network, packageId, new IntPtr(pLogonInfoBuffer), (uint)logonInfoBuffer.ByteLength, IntPtr.Zero, ref sourceContext, ref profile, ref profileSize, ref logonId, ref safeTokenHandle, ref quotas, ref subStatus); // If both status and substatus are < 0, substatus is preferred. if (status == Win32Native.STATUS_ACCOUNT_RESTRICTION && subStatus < 0) status = subStatus; if (status < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(status); if (subStatus < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(subStatus); } finally { if (pLogonInfoBuffer != null) { logonInfoBuffer.ReleasePointer(); } } } } return safeTokenHandle; } } finally { if (!logonHandle.IsInvalid) logonHandle.Dispose(); if (!profile.IsInvalid) profile.Dispose(); } } } #if !FEATURE_CORECLR [SecuritySafeCritical] protected WindowsIdentity (WindowsIdentity identity) : base( identity, null, identity.m_authType, null, null, false ) { if (identity == null) throw new ArgumentNullException("identity"); Contract.EndContractBlock(); bool mustDecrement = false; RuntimeHelpers.PrepareConstrainedRegions(); try { if (!identity.m_safeTokenHandle.IsInvalid && identity.m_safeTokenHandle != SafeAccessTokenHandle.InvalidHandle && identity.m_safeTokenHandle.DangerousGetHandle() != IntPtr.Zero) { identity.m_safeTokenHandle.DangerousAddRef(ref mustDecrement); if (!identity.m_safeTokenHandle.IsInvalid && identity.m_safeTokenHandle.DangerousGetHandle() != IntPtr.Zero) CreateFromToken(identity.m_safeTokenHandle.DangerousGetHandle()); m_authType = identity.m_authType; m_isAuthenticated = identity.m_isAuthenticated; } } finally { if (mustDecrement) identity.m_safeTokenHandle.DangerousRelease(); } } [SecurityCritical] internal IntPtr GetTokenInternal() { return m_safeTokenHandle.DangerousGetHandle(); } [SecurityCritical] internal WindowsIdentity(ClaimsIdentity claimsIdentity, IntPtr userToken) : base(claimsIdentity) { if (userToken != IntPtr.Zero && userToken.ToInt64() > 0) { CreateFromToken(userToken); } } /// <summary> /// Returns a new instance of the base, used when serializing the WindowsIdentity. /// </summary> internal ClaimsIdentity CloneAsBase() { return base.Clone(); } /// <summary> /// Returns a new instance of <see cref="WindowsIdentity"/> with values copied from this object. /// </summary> public override ClaimsIdentity Clone() { return new WindowsIdentity(this); } /// <summary> /// Gets the 'User Claims' from the NTToken that represents this identity /// </summary> public virtual IEnumerable<Claim> UserClaims { get { InitializeClaims(); return m_userClaims.AsReadOnly(); } } /// <summary> /// Gets the 'Device Claims' from the NTToken that represents the device the identity is using /// </summary> public virtual IEnumerable<Claim> DeviceClaims { get { InitializeClaims(); return m_deviceClaims.AsReadOnly(); } } /// <summary> /// Gets the claims as <see cref="IEnumerable{Claim}"/>, associated with this <see cref="WindowsIdentity"/>. /// Includes UserClaims and DeviceClaims. /// </summary> public override IEnumerable<Claim> Claims { get { if (!m_claimsInitialized) { InitializeClaims(); } foreach (Claim claim in base.Claims) yield return claim; foreach (Claim claim in m_userClaims) yield return claim; foreach (Claim claim in m_deviceClaims) yield return claim; } } /// <summary> /// Intenal method to initialize the claim collection. /// Lazy init is used so claims are not initialzed until needed /// </summary> [SecuritySafeCritical] void InitializeClaims() { if (!m_claimsInitialized) { lock (m_claimsIntiailizedLock) { if (!m_claimsInitialized) { m_userClaims = new List<Claim>(); m_deviceClaims = new List<Claim>(); if (!String.IsNullOrEmpty(Name)) { // // Add the name claim only if the WindowsIdentity.Name is populated // WindowsIdentity.Name will be null when it is the fake anonymous user // with a token value of IntPtr.Zero // m_userClaims.Add(new Claim(NameClaimType, Name, ClaimValueTypes.String, m_issuerName, m_issuerName, this)); } // primary sid AddPrimarySidClaim(m_userClaims); // group sids AddGroupSidClaims(m_userClaims); // The following TokenInformationClass's were part of the Win8 release if (Environment.IsWindows8OrAbove) { // Device group sids AddDeviceGroupSidClaims(m_deviceClaims, TokenInformationClass.TokenDeviceGroups); // User token claims AddTokenClaims(m_userClaims, TokenInformationClass.TokenUserClaimAttributes, ClaimTypes.WindowsUserClaim); // Device token claims AddTokenClaims(m_deviceClaims, TokenInformationClass.TokenDeviceClaimAttributes, ClaimTypes.WindowsDeviceClaim); } m_claimsInitialized = true; } } } } /// <summary> /// Creates a collection of SID claims that represent the DeviceSidGroups. /// </summary> /// this is SafeCritical as it accesss the NT token. [SecurityCritical] void AddDeviceGroupSidClaims(List<Claim> instanceClaims, TokenInformationClass tokenInformationClass) { // special case the anonymous identity. if (m_safeTokenHandle.IsInvalid) return; SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle; try { // Retrieve all group sids safeAllocHandle = GetTokenInformation(m_safeTokenHandle, tokenInformationClass); int count = Marshal.ReadInt32(safeAllocHandle.DangerousGetHandle()); IntPtr pSidAndAttributes = new IntPtr((long)safeAllocHandle.DangerousGetHandle() + (long)Marshal.OffsetOf(typeof(Win32Native.TOKEN_GROUPS), "Groups")); string claimType = null; for (int i = 0; i < count; ++i) { Win32Native.SID_AND_ATTRIBUTES group = (Win32Native.SID_AND_ATTRIBUTES)Marshal.PtrToStructure(pSidAndAttributes, typeof(Win32Native.SID_AND_ATTRIBUTES)); uint mask = Win32Native.SE_GROUP_ENABLED | Win32Native.SE_GROUP_LOGON_ID | Win32Native.SE_GROUP_USE_FOR_DENY_ONLY; SecurityIdentifier groupSid = new SecurityIdentifier(group.Sid, true); if ((group.Attributes & mask) == Win32Native.SE_GROUP_ENABLED) { claimType = ClaimTypes.WindowsDeviceGroup; Claim claim = new Claim(claimType, groupSid.Value, ClaimValueTypes.String, m_issuerName, m_issuerName, this, ClaimTypes.WindowsSubAuthority, Convert.ToString(groupSid.IdentifierAuthority, CultureInfo.InvariantCulture)); claim.Properties.Add(claimType, ""); instanceClaims.Add(claim); } else if ((group.Attributes & mask) == Win32Native.SE_GROUP_USE_FOR_DENY_ONLY) { claimType = ClaimTypes.DenyOnlyWindowsDeviceGroup; Claim claim = new Claim(claimType, groupSid.Value, ClaimValueTypes.String, m_issuerName, m_issuerName, this, ClaimTypes.WindowsSubAuthority, Convert.ToString(groupSid.IdentifierAuthority, CultureInfo.InvariantCulture)); claim.Properties.Add(claimType, ""); instanceClaims.Add(claim); } pSidAndAttributes = new IntPtr((long)pSidAndAttributes + Win32Native.SID_AND_ATTRIBUTES.SizeOf); } } finally { safeAllocHandle.Close(); } } /// <summary> /// Creates a collection of SID claims that represent the users groups. /// </summary> /// this is SafeCritical as it accesss the NT token. [SecurityCritical] void AddGroupSidClaims(List<Claim> instanceClaims) { // special case the anonymous identity. if (m_safeTokenHandle.IsInvalid) return; SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle; SafeLocalAllocHandle safeAllocHandlePrimaryGroup = SafeLocalAllocHandle.InvalidHandle; try { // Retrieve the primary group sid safeAllocHandlePrimaryGroup = GetTokenInformation(m_safeTokenHandle, TokenInformationClass.TokenPrimaryGroup); Win32Native.TOKEN_PRIMARY_GROUP primaryGroup = (Win32Native.TOKEN_PRIMARY_GROUP)Marshal.PtrToStructure(safeAllocHandlePrimaryGroup.DangerousGetHandle(), typeof(Win32Native.TOKEN_PRIMARY_GROUP)); SecurityIdentifier primaryGroupSid = new SecurityIdentifier(primaryGroup.PrimaryGroup, true); // only add one primary group sid bool foundPrimaryGroupSid = false; // Retrieve all group sids, primary group sid is one of them safeAllocHandle = GetTokenInformation(m_safeTokenHandle, TokenInformationClass.TokenGroups); int count = Marshal.ReadInt32(safeAllocHandle.DangerousGetHandle()); IntPtr pSidAndAttributes = new IntPtr((long)safeAllocHandle.DangerousGetHandle() + (long)Marshal.OffsetOf(typeof(Win32Native.TOKEN_GROUPS), "Groups")); for (int i = 0; i < count; ++i) { Win32Native.SID_AND_ATTRIBUTES group = (Win32Native.SID_AND_ATTRIBUTES)Marshal.PtrToStructure(pSidAndAttributes, typeof(Win32Native.SID_AND_ATTRIBUTES)); uint mask = Win32Native.SE_GROUP_ENABLED | Win32Native.SE_GROUP_LOGON_ID | Win32Native.SE_GROUP_USE_FOR_DENY_ONLY; SecurityIdentifier groupSid = new SecurityIdentifier(group.Sid, true); if ((group.Attributes & mask) == Win32Native.SE_GROUP_ENABLED) { if (!foundPrimaryGroupSid && StringComparer.Ordinal.Equals( groupSid.Value, primaryGroupSid.Value)) { instanceClaims.Add(new Claim(ClaimTypes.PrimaryGroupSid, groupSid.Value, ClaimValueTypes.String, m_issuerName, m_issuerName, this, ClaimTypes.WindowsSubAuthority, Convert.ToString(groupSid.IdentifierAuthority, CultureInfo.InvariantCulture))); foundPrimaryGroupSid = true; } //Primary group sid generates both regular groupsid claim and primary groupsid claim instanceClaims.Add(new Claim(ClaimTypes.GroupSid, groupSid.Value, ClaimValueTypes.String, m_issuerName, m_issuerName, this, ClaimTypes.WindowsSubAuthority, Convert.ToString(groupSid.IdentifierAuthority, CultureInfo.InvariantCulture))); } else if ((group.Attributes & mask) == Win32Native.SE_GROUP_USE_FOR_DENY_ONLY) { if (!foundPrimaryGroupSid && StringComparer.Ordinal.Equals( groupSid.Value, primaryGroupSid.Value)) { instanceClaims.Add(new Claim(ClaimTypes.DenyOnlyPrimaryGroupSid, groupSid.Value, ClaimValueTypes.String, m_issuerName, m_issuerName, this, ClaimTypes.WindowsSubAuthority, Convert.ToString(groupSid.IdentifierAuthority, CultureInfo.InvariantCulture))); foundPrimaryGroupSid = true; } //Primary group sid generates both regular groupsid claim and primary groupsid claim instanceClaims.Add(new Claim(ClaimTypes.DenyOnlySid, groupSid.Value, ClaimValueTypes.String, m_issuerName, m_issuerName, this, ClaimTypes.WindowsSubAuthority, Convert.ToString(groupSid.IdentifierAuthority, CultureInfo.InvariantCulture))); } pSidAndAttributes = new IntPtr((long)pSidAndAttributes + Win32Native.SID_AND_ATTRIBUTES.SizeOf); } } finally { safeAllocHandle.Close(); safeAllocHandlePrimaryGroup.Close(); } } /// <summary> /// Creates a Windows SID Claim and adds to collection of claims. /// </summary> /// this is SafeCritical as it accesss the NT token. [SecurityCritical] void AddPrimarySidClaim(List<Claim> instanceClaims) { // special case the anonymous identity. if (m_safeTokenHandle.IsInvalid) return; SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle; try { safeAllocHandle = GetTokenInformation(m_safeTokenHandle, TokenInformationClass.TokenUser); Win32Native.SID_AND_ATTRIBUTES user = (Win32Native.SID_AND_ATTRIBUTES)Marshal.PtrToStructure(safeAllocHandle.DangerousGetHandle(), typeof(Win32Native.SID_AND_ATTRIBUTES)); uint mask = Win32Native.SE_GROUP_USE_FOR_DENY_ONLY; SecurityIdentifier sid = new SecurityIdentifier(user.Sid, true); if (user.Attributes == 0) { instanceClaims.Add(new Claim(ClaimTypes.PrimarySid, sid.Value, ClaimValueTypes.String, m_issuerName, m_issuerName, this, ClaimTypes.WindowsSubAuthority, Convert.ToString(sid.IdentifierAuthority, CultureInfo.InvariantCulture))); } else if ((user.Attributes & mask) == Win32Native.SE_GROUP_USE_FOR_DENY_ONLY) { instanceClaims.Add(new Claim(ClaimTypes.DenyOnlyPrimarySid, sid.Value, ClaimValueTypes.String, m_issuerName, m_issuerName, this, ClaimTypes.WindowsSubAuthority, Convert.ToString(sid.IdentifierAuthority, CultureInfo.InvariantCulture))); } } finally { safeAllocHandle.Close(); } } [SecurityCritical] void AddTokenClaims(List<Claim> instanceClaims, TokenInformationClass tokenInformationClass, string propertyValue) { // special case the anonymous identity. if (m_safeTokenHandle.IsInvalid) return; SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle; try { SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle; safeAllocHandle = GetTokenInformation(m_safeTokenHandle, tokenInformationClass); Win32Native.CLAIM_SECURITY_ATTRIBUTES_INFORMATION claimAttributes = (Win32Native.CLAIM_SECURITY_ATTRIBUTES_INFORMATION)Marshal.PtrToStructure(safeAllocHandle.DangerousGetHandle(), typeof(Win32Native.CLAIM_SECURITY_ATTRIBUTES_INFORMATION)); // An attribute represents a collection of claims. Inside each attribute a claim can be multivalued, we create a claim for each value. // It is a ragged multi-dimentional array, where each cell can be of different lenghts. // index into array of claims. long offset = 0; for (int attribute = 0; attribute < claimAttributes.AttributeCount; attribute++) { IntPtr pAttribute = new IntPtr(claimAttributes.Attribute.pAttributeV1.ToInt64() + offset); Win32Native.CLAIM_SECURITY_ATTRIBUTE_V1 windowsClaim = (Win32Native.CLAIM_SECURITY_ATTRIBUTE_V1)Marshal.PtrToStructure(pAttribute, typeof(Win32Native.CLAIM_SECURITY_ATTRIBUTE_V1)); // the switch was written this way, which appears to have multiple for loops, because each item in the ValueCount is of the same ValueType. This saves the type check each item. switch (windowsClaim.ValueType) { case Win32Native.CLAIM_SECURITY_ATTRIBUTE_TYPE_STRING: IntPtr[] stringPointers = new IntPtr[windowsClaim.ValueCount]; Marshal.Copy(windowsClaim.Values.ppString, stringPointers, 0, (int)windowsClaim.ValueCount); for (int item = 0; item < windowsClaim.ValueCount; item++) { instanceClaims.Add( new Claim(windowsClaim.Name, Marshal.PtrToStringAuto(stringPointers[item]), ClaimValueTypes.String, m_issuerName, m_issuerName, this, propertyValue, string.Empty)); } break; case Win32Native.CLAIM_SECURITY_ATTRIBUTE_TYPE_INT64: Int64[] intValues = new Int64[windowsClaim.ValueCount]; Marshal.Copy(windowsClaim.Values.pInt64, intValues, 0, (int)windowsClaim.ValueCount); for (int item = 0; item < windowsClaim.ValueCount; item++) { instanceClaims.Add(new Claim(windowsClaim.Name, Convert.ToString(intValues[item], CultureInfo.InvariantCulture), ClaimValueTypes.Integer64, m_issuerName, m_issuerName, this, propertyValue, string.Empty)); } break; case Win32Native.CLAIM_SECURITY_ATTRIBUTE_TYPE_UINT64: Int64[] uintValues = new Int64[windowsClaim.ValueCount]; Marshal.Copy(windowsClaim.Values.pUint64, uintValues, 0, (int)windowsClaim.ValueCount); for (int item = 0; item < windowsClaim.ValueCount; item++) { instanceClaims.Add( new Claim(windowsClaim.Name, Convert.ToString((UInt64)uintValues[item], CultureInfo.InvariantCulture), ClaimValueTypes.UInteger64, m_issuerName, m_issuerName, this, propertyValue, string.Empty)); } break; case Win32Native.CLAIM_SECURITY_ATTRIBUTE_TYPE_BOOLEAN: Int64[] boolValues = new Int64[windowsClaim.ValueCount]; Marshal.Copy(windowsClaim.Values.pUint64, boolValues, 0, (int)windowsClaim.ValueCount); for (int item = 0; item < windowsClaim.ValueCount; item++) { instanceClaims.Add(new Claim(windowsClaim.Name, ((UInt64)boolValues[item] == 0 ? Convert.ToString(false, CultureInfo.InvariantCulture) : Convert.ToString(true, CultureInfo.InvariantCulture)), ClaimValueTypes.Boolean, m_issuerName, m_issuerName, this, propertyValue, string.Empty)); } break; // These claim types are defined in the structure found in winnt.h, but I haven't received confirmation (may 2011) that they are supported and are not enabled. //case Win32Native.CLAIM_SECURITY_ATTRIBUTE_TYPE_FQBN: // break; //case Win32Native.CLAIM_SECURITY_ATTRIBUTE_TYPE_SID: // break; //case Win32Native.CLAIM_SECURITY_ATTRIBUTE_TYPE_OCTET_STRING: // break; } offset += Marshal.SizeOf(windowsClaim); } } finally { safeAllocHandle.Close(); } } } #endif [Serializable] internal enum KerbLogonSubmitType : int { KerbInteractiveLogon = 2, KerbSmartCardLogon = 6, KerbWorkstationUnlockLogon = 7, KerbSmartCardUnlockLogon = 8, KerbProxyLogon = 9, KerbTicketLogon = 10, KerbTicketUnlockLogon = 11, KerbS4ULogon = 12 } [Serializable] internal enum SecurityLogonType : int { Interactive = 2, Network, Batch, Service, Proxy, Unlock } [Serializable] internal enum TokenType : int { TokenPrimary = 1, TokenImpersonation } [Serializable] internal enum TokenInformationClass : int { TokenUser = 1, TokenGroups, TokenPrivileges, TokenOwner, TokenPrimaryGroup, TokenDefaultDacl, TokenSource, TokenType, TokenImpersonationLevel, TokenStatistics, TokenRestrictedSids, TokenSessionId, TokenGroupsAndPrivileges, TokenSessionReference, TokenSandBoxInert, TokenAuditPolicy, TokenOrigin, TokenElevationType, TokenLinkedToken, TokenElevation, TokenHasRestrictions, TokenAccessInformation, TokenVirtualizationAllowed, TokenVirtualizationEnabled, TokenIntegrityLevel, TokenUIAccess, TokenMandatoryPolicy, TokenLogonSid, TokenIsAppContainer, TokenCapabilities, TokenAppContainerSid, TokenAppContainerNumber, TokenUserClaimAttributes, TokenDeviceClaimAttributes, TokenRestrictedUserClaimAttributes, TokenRestrictedDeviceClaimAttributes, TokenDeviceGroups, TokenRestrictedDeviceGroups, MaxTokenInfoClass // MaxTokenInfoClass should always be the last enum } }
// 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.Text; using TestLibrary; using System.Globalization; class StringBuilderLength { static int Main() { StringBuilderLength test = new StringBuilderLength(); TestFramework.BeginTestCase("StringBuilder.Length"); if (test.RunTests()) { TestFramework.EndTestCase(); TestFramework.LogInformation("PASS"); return 100; } else { TestFramework.EndTestCase(); TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool ret = true; // Positive Tests ret &= Test1(); ret &= Test2(); ret &= Test3(); ret &= Test4(); ret &= Test5(); // Negative Tests ret &= Test6(); ret &= Test7(); return ret; } public bool Test1() { string id = "Scenario1"; bool result = true; TestFramework.BeginScenario("Scenario 1: Setting Length to 0"); try { StringBuilder sb = new StringBuilder("Test"); sb.Length = 0; string output = sb.ToString(); int length = sb.Length; if (output != string.Empty) { result = false; TestFramework.LogError("001", "Error in " + id + ", unexpected string. Actual string " + output + ", Expected: " + string.Empty); } if (length != 0) { result = false; TestFramework.LogError("002", "Error in " + id + ", unexpected legnth. Actual length " + length + ", Expected: 0"); } } catch (Exception exc) { result = false; TestFramework.LogError("003", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } return result; } public bool Test2() { string id = "Scenario2"; bool result = true; TestFramework.BeginScenario("Scenario 2: Setting Length to current length"); try { StringBuilder sb = new StringBuilder("Test"); sb.Length = 4; string output = sb.ToString(); int length = sb.Length; if (output != "Test") { result = false; TestFramework.LogError("004", "Error in " + id + ", unexpected string. Actual string " + output + ", Expected: Test"); } if (length != 4) { result = false; TestFramework.LogError("005", "Error in " + id + ", unexpected legnth. Actual length " + length + ", Expected: 4"); } } catch (Exception exc) { result = false; TestFramework.LogError("006", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } return result; } public bool Test3() { string id = "Scenario3"; bool result = true; TestFramework.BeginScenario("Scenario 3: Setting Length to > length < capacity"); try { StringBuilder sb = new StringBuilder("Test", 10); sb.Length = 8; string output = sb.ToString(); int length = sb.Length; if (output != "Test\0\0\0\0") { result = false; TestFramework.LogError("007", "Error in " + id + ", unexpected string. Actual string " + output + ", Expected: Test\0\0\0\0"); } if (length != 8) { result = false; TestFramework.LogError("008", "Error in " + id + ", unexpected legnth. Actual length " + length + ", Expected: 8"); } } catch (Exception exc) { result = false; TestFramework.LogError("009", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } return result; } public bool Test4() { string id = "Scenario4"; bool result = true; TestFramework.BeginScenario("Scenario 4: Setting Length to > capacity"); try { StringBuilder sb = new StringBuilder("Test", 10); sb.Length = 12; string output = sb.ToString(); int length = sb.Length; if (output != "Test\0\0\0\0\0\0\0\0") { result = false; TestFramework.LogError("010", "Error in " + id + ", unexpected string. Actual string " + output + ", Expected: Test\0\0\0\0\0\0\0\0"); } if (length != 12) { result = false; TestFramework.LogError("011", "Error in " + id + ", unexpected legnth. Actual length " + length + ", Expected: 12"); } } catch (Exception exc) { result = false; TestFramework.LogError("012", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } return result; } public bool Test5() { string id = "Scenario5"; bool result = true; TestFramework.BeginScenario("Scenario 5: Setting Length to something very large"); try { StringBuilder sb = new StringBuilder("Test"); sb.Length = 10004; string output = sb.ToString(); int length = sb.Length; if (output != ("Test" + new string('\0',10000))) { result = false; TestFramework.LogError("013", "Error in " + id + ", unexpected string. Actual string " + output + ", Expected: Test"); } if (length != 10004) { result = false; TestFramework.LogError("014", "Error in " + id + ", unexpected legnth. Actual length " + length + ", Expected: 10004"); } } catch (Exception exc) { result = false; TestFramework.LogError("015", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } return result; } public bool Test6() { string id = "Scenario6"; bool result = true; TestFramework.BeginScenario("Scenario 6: Setting Length to > max capacity"); try { StringBuilder sb = new StringBuilder(4, 10); sb.Append("Test"); sb.Length = 12; string output = sb.ToString(); result = false; TestFramework.LogError("016", "Error in " + id + ", Expected exception not thrown. No exception. Actual string " + output + ", Expected: " + typeof(ArgumentOutOfRangeException).ToString()); } catch (Exception exc) { if (exc.GetType() != typeof(ArgumentOutOfRangeException)) { result = false; TestFramework.LogError("017", "Unexpected exception in " + id + ", expected type: " + typeof(ArgumentOutOfRangeException).ToString() + ", Actual excpetion: " + exc.ToString()); } } return result; } public bool Test7() { string id = "Scenario7"; bool result = true; TestFramework.BeginScenario("Scenario 7: Setting Length to < 0 capacity"); try { StringBuilder sb = new StringBuilder(4, 10); sb.Append("Test"); sb.Length = -1; string output = sb.ToString(); result = false; TestFramework.LogError("018", "Error in " + id + ", Expected exception not thrown. No exception. Actual string " + output + ", Expected: " + typeof(ArgumentOutOfRangeException).ToString()); } catch (Exception exc) { if (exc.GetType() != typeof(ArgumentOutOfRangeException)) { result = false; TestFramework.LogError("018", "Unexpected exception in " + id + ", expected type: " + typeof(ArgumentOutOfRangeException).ToString() + ", Actual excpetion: " + exc.ToString()); } } return result; } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V8.Resources { /// <summary>Resource name for the <c>CallView</c> resource.</summary> public sealed partial class CallViewName : gax::IResourceName, sys::IEquatable<CallViewName> { /// <summary>The possible contents of <see cref="CallViewName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/callViews/{call_detail_id}</c>. /// </summary> CustomerCallDetail = 1, } private static gax::PathTemplate s_customerCallDetail = new gax::PathTemplate("customers/{customer_id}/callViews/{call_detail_id}"); /// <summary>Creates a <see cref="CallViewName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="CallViewName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static CallViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CallViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CallViewName"/> with the pattern <c>customers/{customer_id}/callViews/{call_detail_id}</c> /// . /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="callDetailId">The <c>CallDetail</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="CallViewName"/> constructed from the provided ids.</returns> public static CallViewName FromCustomerCallDetail(string customerId, string callDetailId) => new CallViewName(ResourceNameType.CustomerCallDetail, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), callDetailId: gax::GaxPreconditions.CheckNotNullOrEmpty(callDetailId, nameof(callDetailId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CallViewName"/> with pattern /// <c>customers/{customer_id}/callViews/{call_detail_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="callDetailId">The <c>CallDetail</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CallViewName"/> with pattern /// <c>customers/{customer_id}/callViews/{call_detail_id}</c>. /// </returns> public static string Format(string customerId, string callDetailId) => FormatCustomerCallDetail(customerId, callDetailId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CallViewName"/> with pattern /// <c>customers/{customer_id}/callViews/{call_detail_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="callDetailId">The <c>CallDetail</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CallViewName"/> with pattern /// <c>customers/{customer_id}/callViews/{call_detail_id}</c>. /// </returns> public static string FormatCustomerCallDetail(string customerId, string callDetailId) => s_customerCallDetail.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(callDetailId, nameof(callDetailId))); /// <summary>Parses the given resource name string into a new <see cref="CallViewName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/callViews/{call_detail_id}</c></description></item> /// </list> /// </remarks> /// <param name="callViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CallViewName"/> if successful.</returns> public static CallViewName Parse(string callViewName) => Parse(callViewName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CallViewName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/callViews/{call_detail_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="callViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="CallViewName"/> if successful.</returns> public static CallViewName Parse(string callViewName, bool allowUnparsed) => TryParse(callViewName, allowUnparsed, out CallViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CallViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/callViews/{call_detail_id}</c></description></item> /// </list> /// </remarks> /// <param name="callViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CallViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string callViewName, out CallViewName result) => TryParse(callViewName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CallViewName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/callViews/{call_detail_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="callViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="CallViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string callViewName, bool allowUnparsed, out CallViewName result) { gax::GaxPreconditions.CheckNotNull(callViewName, nameof(callViewName)); gax::TemplatedResourceName resourceName; if (s_customerCallDetail.TryParseName(callViewName, out resourceName)) { result = FromCustomerCallDetail(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(callViewName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private CallViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string callDetailId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; CallDetailId = callDetailId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="CallViewName"/> class from the component parts of pattern /// <c>customers/{customer_id}/callViews/{call_detail_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="callDetailId">The <c>CallDetail</c> ID. Must not be <c>null</c> or empty.</param> public CallViewName(string customerId, string callDetailId) : this(ResourceNameType.CustomerCallDetail, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), callDetailId: gax::GaxPreconditions.CheckNotNullOrEmpty(callDetailId, nameof(callDetailId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>CallDetail</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CallDetailId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerCallDetail: return s_customerCallDetail.Expand(CustomerId, CallDetailId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as CallViewName); /// <inheritdoc/> public bool Equals(CallViewName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CallViewName a, CallViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CallViewName a, CallViewName b) => !(a == b); } public partial class CallView { /// <summary> /// <see cref="CallViewName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal CallViewName ResourceNameAsCallViewName { get => string.IsNullOrEmpty(ResourceName) ? null : CallViewName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; // ERROR: Not supported in C#: OptionDeclaration using Microsoft.VisualBasic.PowerPacks; namespace _4PosBackOffice.NET { internal partial class frmChannel : System.Windows.Forms.Form { private ADODB.Recordset withEventsField_adoPrimaryRS; public ADODB.Recordset adoPrimaryRS { get { return withEventsField_adoPrimaryRS; } set { if (withEventsField_adoPrimaryRS != null) { withEventsField_adoPrimaryRS.MoveComplete -= adoPrimaryRS_MoveComplete; withEventsField_adoPrimaryRS.WillChangeRecord -= adoPrimaryRS_WillChangeRecord; } withEventsField_adoPrimaryRS = value; if (withEventsField_adoPrimaryRS != null) { withEventsField_adoPrimaryRS.MoveComplete += adoPrimaryRS_MoveComplete; withEventsField_adoPrimaryRS.WillChangeRecord += adoPrimaryRS_WillChangeRecord; } } } bool mbChangedByCode; int mvBookMark; bool mbEditFlag; bool mbAddNewFlag; bool mbDataChanged; List<TextBox> txtFields = new List<TextBox>(); List<RadioButton> optType = new List<RadioButton>(); List<CheckBox> chkFields = new List<CheckBox>(); int gID; private void loadLanguage() { //frmChannel = No Code [Edit Sale Channel Details] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then frmChannel.Caption = rsLang("LanguageLayoutLnk_Description"): frmChannel.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1074; //Undo|Checked if (modRecordSet.rsLang.RecordCount){cmdCancel.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdCancel.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004; //Exit|Checked if (modRecordSet.rsLang.RecordCount){cmdClose.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdClose.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1010; //General|Checked if (modRecordSet.rsLang.RecordCount){_lbl_5.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_5.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} //_lblLabels_1 = No Code [Name] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then _lblLabels_1.Caption = rsLang("LanguageLayoutLnk_Description"): _lblLabels_1.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //_lblLabels_2 = No Code [Short Name] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then _lblLabels_2.Caption = rsLang("LanguageLayoutLnk_Description"): _lblLabels_2.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //_chkFields_3 = No Code [Disable this sale Channel on the POS] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then _chkFields_3.Caption = rsLang("LanguageLayoutLnk_Description"): _chkFields_3.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //_chkFields_4 = No Code [Do not use Pricing Strategy when doing pricing update] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0 //If rsLang.RecordCount Then _chkFields_4.Caption = rsLang("LanguageLayoutLnk_Description"): _chkFields_4.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //_chkFields_5 = No Code [Treat a case/carton price as the unit price when doing the price update] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then _chkFields_5.Caption = rsLang("LanguageLayoutLnk_Description"): _chkFields_5.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //Label1(0) = No Code [When doing the pricing calculation this sale channel relationship to the first sale channel is] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then Label1(0).Caption = rsLang("LanguageLayoutLnk_Description"): Label1(0).RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //Label1(1) = No Code [When calculating exit price percentages, prices are calculated as] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then Label1(1).Caption = rsLang("LanguageLayoutLnk_Description"): Label1(1).RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //optType(0) = No Code [Cost plus pricing group group percentage] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then optType(0).Caption = rsLang("LanguageLayoutLnk_Description"): optType(0).RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //optType(1) = No Code [Price of Default sales channel plus pricing group percentage] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then optType(1).Caption = rsLang("LanguageLayoutLnk_Description"): optType(1).RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'"; //UPGRADE_ISSUE: Form property frmChannel.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' if (modRecordSet.rsHelp.RecordCount) this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value; } private void buildDataControls() { // doDataControl Me.cmbChannel, "SELECT ChannelID, Channel_Name FROM Channel ORDER BY ChannelID", "Customer_ChannelID", "ChannelID", "Channel_Name" } private void doDataControl(ref myDataGridView dataControl, ref string sql, ref string DataField, ref string boundColumn, ref string listField) { //Dim rs As ADODB.Recordset //rs = getRS(sql) //dataControl.DataSource = rs //dataControl.DataSource = adoPrimaryRS //dataControl.DataField = DataField //dataControl.boundColumn = boundColumn //dataControl.listField = listField } public void loadItem(ref int id) { System.Windows.Forms.TextBox oText = null; System.Windows.Forms.CheckBox oCheck = null; // ERROR: Not supported in C#: OnErrorStatement if (id) { adoPrimaryRS = modRecordSet.getRS(ref "select * from Channel WHERE ChannelID = " + id); // If IsNull(adoPrimaryRS("Channel_PriceToChannel1")) Then // cmbChannelPrice.ListIndex = 0 // Else switch (adoPrimaryRS.Fields("Channel_PriceToChannel1").Value) { case -1: cmbChannelPrice.SelectedIndex = 1; break; case 1: cmbChannelPrice.SelectedIndex = 2; break; default: cmbChannelPrice.SelectedIndex = 0; break; } // End If } else { adoPrimaryRS = modRecordSet.getRS(ref "select * from POS"); adoPrimaryRS.AddNew(); this.Text = this.Text + " [New record]"; mbAddNewFlag = true; } setup(); foreach (TextBox oText_loopVariable in txtFields) { oText = oText_loopVariable; oText.DataBindings.Add(adoPrimaryRS); oText.MaxLength = adoPrimaryRS.Fields(oText.DataBindings).DefinedSize; } this.optType[Convert.ToInt16(_txtFields_0.Text)].Checked = true; if (id == 1) { _optType_0.Enabled = false; _optType_1.Enabled = false; } // For Each oText In Me.txtInteger // Set oText.DataBindings.Add(adoPrimaryRS) // txtInteger_LostFocus oText.Index // Next // For Each oText In Me.txtFloat // Set oText.DataBindings.Add(adoPrimaryRS) // If oText.Text = "" Then oText.Text = "0" // oText.Text = oText.Text * 100 // txtFloat_LostFocus oText.Index // Next // For Each oText In Me.txtFloatNegative // Set oText.DataBindings.Add(adoPrimaryRS) // If oText.Text = "" Then oText.Text = "0" // oText.Text = oText.Text * 100 // txtFloatNegative_LostFocus oText.Index // Next //Bind the check boxes to the data provider foreach (CheckBox oCheck_loopVariable in chkFields) { oCheck = oCheck_loopVariable; oCheck.DataBindings.Add(adoPrimaryRS); } buildDataControls(); mbDataChanged = false; loadLanguage(); ShowDialog(); } private void setup() { } private void Command1_Click() { } private void frmChannel_Load(object sender, System.EventArgs e) { txtFields.AddRange(new TextBox[] { _txtFields_0, _txtFields_1, _txtFields_2 }); optType.AddRange(new RadioButton[] { _optType_0, _optType_1 }); chkFields.AddRange(new CheckBox[] { _chkFields_3, _chkFields_4, _chkFields_5 }); TextBox txt = new TextBox(); RadioButton rb = new RadioButton(); foreach (TextBox txt_loopVariable in txtFields) { txt = txt_loopVariable; txt.Enter += txtFields_Enter; } foreach (RadioButton rb_loopVariable in optType) { rb = rb_loopVariable; rb.CheckedChanged += optType_CheckedChanged; } } //UPGRADE_WARNING: Event frmChannel.Resize may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"' private void frmChannel_Resize(System.Object eventSender, System.EventArgs eventArgs) { Button cmdLast = new Button(); Button cmdnext = new Button(); Label lblStatus = new Label(); // ERROR: Not supported in C#: OnErrorStatement lblStatus.Width = sizeConvertors.pixelToTwips(this.Width, true) - 1500; cmdnext.Left = lblStatus.Width + 700; cmdLast.Left = cmdnext.Left + 340; } private void frmChannel_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); switch (KeyAscii) { case System.Windows.Forms.Keys.Escape: KeyAscii = 0; System.Windows.Forms.Application.DoEvents(); adoPrimaryRS.Move(0); cmdClose_Click(cmdClose, new System.EventArgs()); break; } eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void frmChannel_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs) { System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; } private void adoPrimaryRS_MoveComplete(ADODB.EventReasonEnum adReason, ADODB.Error pError, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset) { //This will display the current record position for this recordset } private void adoPrimaryRS_WillChangeRecord(ADODB.EventReasonEnum adReason, int cRecords, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset) { //This is where you put validation code //This event gets called when the following actions occur bool bCancel = false; switch (adReason) { case ADODB.EventReasonEnum.adRsnAddNew: break; case ADODB.EventReasonEnum.adRsnClose: break; case ADODB.EventReasonEnum.adRsnDelete: break; case ADODB.EventReasonEnum.adRsnFirstChange: break; case ADODB.EventReasonEnum.adRsnMove: break; case ADODB.EventReasonEnum.adRsnRequery: break; case ADODB.EventReasonEnum.adRsnResynch: break; case ADODB.EventReasonEnum.adRsnUndoAddNew: break; case ADODB.EventReasonEnum.adRsnUndoDelete: break; case ADODB.EventReasonEnum.adRsnUndoUpdate: break; case ADODB.EventReasonEnum.adRsnUpdate: break; } if (bCancel) adStatus = ADODB.EventStatusEnum.adStatusCancel; } private void cmdCancel_Click(System.Object eventSender, System.EventArgs eventArgs) { // ERROR: Not supported in C#: OnErrorStatement if (mbAddNewFlag) { this.Close(); } else { mbEditFlag = false; mbAddNewFlag = false; adoPrimaryRS.CancelUpdate(); if (mvBookMark > 0) { adoPrimaryRS.Bookmark = mvBookMark; } else { adoPrimaryRS.MoveFirst(); } mbDataChanged = false; } } //UPGRADE_NOTE: update was upgraded to update_Renamed. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"' private bool update_Renamed() { bool functionReturnValue = false; // ERROR: Not supported in C#: OnErrorStatement bool lDirty = false; short x = 0; lDirty = false; functionReturnValue = true; if (mbAddNewFlag) { adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll); adoPrimaryRS.MoveLast(); //move to the new record } else { adoPrimaryRS.Fields("Channel_PriceToChannel1").Value = Convert.ToDecimal(cmbChannelPrice.SelectedIndex); adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll); } mbEditFlag = false; mbAddNewFlag = false; mbDataChanged = false; return functionReturnValue; UpdateErr: Interaction.MsgBox(Err().Description); functionReturnValue = false; return functionReturnValue; } private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs) { cmdClose.Focus(); System.Windows.Forms.Application.DoEvents(); if (update_Renamed()) { this.Close(); } } //UPGRADE_WARNING: Event optType.CheckedChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"' private void optType_CheckedChanged(System.Object eventSender, System.EventArgs eventArgs) { if (eventSender.Checked) { RadioButton opt = new RadioButton(); opt = (RadioButton)eventSender; int Index = GetIndex.GetIndexer(ref opt, ref optType); this._txtFields_0.Text = Convert.ToString(Index); } } private void txtFields_Enter(System.Object eventSender, System.EventArgs eventArgs) { TextBox txt = new TextBox(); txt = (TextBox)eventSender; int Index = GetIndex.GetIndexer(ref txt, ref txtFields); modUtilities.MyGotFocus(ref txtFields[Index]); } private void txtInteger_MyGotFocus(ref short Index) { // MyGotFocusNumeric txtInteger(Index) } private void txtInteger_KeyPress(ref short Index, ref short KeyAscii) { // KeyPress KeyAscii } private void txtInteger_MyLostFocus(ref short Index) { // LostFocus txtInteger(Index), 0 } private void txtFloat_MyGotFocus(ref short Index) { // MyGotFocusNumeric txtFloat(Index) } private void txtFloat_KeyPress(ref short Index, ref short KeyAscii) { // KeyPress KeyAscii } private void txtFloat_MyLostFocus(ref short Index) { // LostFocus txtFloat(Index), 2 } private void txtFloatNegative_MyGotFocus(ref short Index) { // MyGotFocusNumeric txtFloatNegative(Index) } private void txtFloatNegative_KeyPress(ref short Index, ref short KeyAscii) { // KeyPressNegative txtFloatNegative(Index), KeyAscii } private void txtFloatNegative_MyLostFocus(ref short Index) { // LostFocus txtFloatNegative(Index), 2 } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Net.Http; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Common.Core; using Microsoft.Common.Core.Disposables; using Microsoft.Common.Core.Services; using Microsoft.Common.Core.Telemetry; using Microsoft.R.Components.InteractiveWorkflow; using Microsoft.R.Containers; using Newtonsoft.Json.Linq; namespace Microsoft.R.Components.Containers.Implementation { internal class ContainerManager : IContainerManager { private const string RtvsImageName = "rtvs-image"; private const string LatestVersion = "latest"; private const string TelemetryEvent_BeginCreatingPredefined = "Begin creating predefined"; private const string TelemetryEvent_EndCreatingPredefined = "End creating predefined"; private const string TelemetryEvent_BeginCreatingFromFile = "Begin creating from file"; private const string TelemetryEvent_EndCreatingFromFile = "End creating from file"; private const string TelemetryEvent_Delete = "End creating from file"; private readonly IContainerService _containerService; private readonly ITelemetryService _telemetry; private readonly CountdownDisposable _containersChangedCountdown; private ImmutableArray<IContainer> _containers; private ImmutableArray<IContainer> _runningContainers; private CancellationTokenSource _updateContainersCts; private int _status; private string _error; private event Action ContainersChanged; public event EventHandler ContainersStatusChanged; public ContainersStatus Status { get => (ContainersStatus)_status; private set { if (Interlocked.Exchange(ref _status, (int) value) != (int) value) { ContainersStatusChanged?.Invoke(this, EventArgs.Empty); } } } public string Error { get => _error; private set => Interlocked.Exchange(ref _error, value); } public ContainerManager(IRInteractiveWorkflow interactiveWorkflow) { _containerService = interactiveWorkflow.Services.GetService<IContainerService>(); _telemetry = interactiveWorkflow.Services.Telemetry(); _updateContainersCts = new CancellationTokenSource(); _containers = ImmutableArray<IContainer>.Empty; _runningContainers = ImmutableArray<IContainer>.Empty; _containersChangedCountdown = new CountdownDisposable(StartUpdatingContainers, EndUpdatingContainers); Status = ContainersStatus.Running; } public IReadOnlyList<IContainer> GetContainers() => _containers; public IReadOnlyList<IContainer> GetRunningContainers() => _runningContainers; public async Task<IEnumerable<string>> GetLocalDockerVersions(CancellationToken cancellationToken = default (CancellationToken)) { await TaskUtilities.SwitchToBackgroundThread(); const string imageName = "microsoft/rtvs"; // change to microsoft/rtvs; try { return await GetVersionsFromDockerHubAsync(imageName, cancellationToken); } catch (Exception ex) when (!(ex is OperationCanceledException)) { try { return await GetVersionsFromLocalImagesAsync(imageName, cancellationToken); } catch (ContainerException) { return Enumerable.Empty<string>(); } } } public IDisposable SubscribeOnChanges(Action containersChanged) { ContainersChanged += containersChanged; _containersChangedCountdown.Increment(); return Disposable.Create(() => { ContainersChanged -= containersChanged; _containersChangedCountdown.Decrement(); }); } public async Task StartAsync(string containerId, CancellationToken cancellationToken) { try { await _containerService.StartContainerAsync(containerId, cancellationToken); } finally { await UpdateContainersOnceAsync(cancellationToken); } } public async Task StopAsync(string containerId, CancellationToken cancellationToken) { try { await _containerService.StopContainerAsync(containerId, cancellationToken); } finally { await UpdateContainersOnceAsync(cancellationToken); } } public async Task DeleteAsync(string containerId, CancellationToken cancellationToken) { try { _telemetry.ReportEvent(TelemetryArea.Containers, TelemetryEvent_Delete); await _containerService.DeleteContainerAsync(containerId, cancellationToken); } finally { await UpdateContainersOnceAsync(cancellationToken); } } public Task<IContainer> CreateLocalDockerAsync(string name, string username, string password, string version, int port, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrWhiteSpace(version)) { version = LatestVersion; } _telemetry.ReportEvent(TelemetryArea.Containers, TelemetryEvent_BeginCreatingPredefined, version); var basePath = Path.GetDirectoryName(GetType().GetTypeInfo().Assembly.GetAssemblyPath()); var dockerfilePath = Path.Combine(basePath, "DockerTemplate\\Dockerfile"); var hash = $"{username}|{password}".ToGuid().ToString("N"); var parameters = new BuildImageParameters(dockerfilePath, $"{RtvsImageName}{hash}", version, new Dictionary<string, string> { ["RTVS_VERSION"] = version, ["USERNAME"] = username, ["PASSWORD"] = password }, name, port); var container = CreateLocalDockerFromContentAsync(parameters, cancellationToken); _telemetry.ReportEvent(TelemetryArea.Containers, TelemetryEvent_EndCreatingPredefined, version); return container; } public Task<IContainer> CreateLocalDockerFromFileAsync(string name, string filePath, int port, CancellationToken cancellationToken = default(CancellationToken)) { _telemetry.ReportEvent(TelemetryArea.Containers, TelemetryEvent_BeginCreatingFromFile); var container = CreateLocalDockerFromContentAsync(new BuildImageParameters(filePath, Guid.NewGuid().ToString(), LatestVersion, name, port), cancellationToken); _telemetry.ReportEvent(TelemetryArea.Containers, TelemetryEvent_EndCreatingFromFile); return container; } private async Task<IContainer> CreateLocalDockerFromContentAsync(BuildImageParameters buildOptions, CancellationToken cancellationToken) { try { return await _containerService.CreateContainerFromFileAsync(buildOptions, cancellationToken); } finally { await UpdateContainersOnceAsync(cancellationToken); } } public void Restart() { var cts = new CancellationTokenSource(); var oldCts = Interlocked.Exchange(ref _updateContainersCts, cts); oldCts.Cancel(); if (_containersChangedCountdown.Count > 0) { UpdateContainersAsync(cts.Token).DoNotWait(); } } public void Dispose() => _updateContainersCts.Cancel(); private static async Task<IEnumerable<string>> GetVersionsFromDockerHubAsync(string imageName, CancellationToken cancellationToken) { using (var client = new HttpClient()) { var uri = new Uri($"https://registry.hub.docker.com/v1/repositories/{imageName}/tags", UriKind.Absolute); using (var response = await client.GetAsync(uri, cancellationToken)) { if (!response.IsSuccessStatusCode) { throw new HttpRequestException(); } var result = await response.Content.ReadAsStringAsync(); return JArray.Parse(result) .OfType<JObject>() .Select(o => o.GetValue("name")) .OfType<JValue>() .Select(v => (string) v.Value) .Where(s => !s.EndsWith("-base")); } } } private async Task<IEnumerable<string>> GetVersionsFromLocalImagesAsync(string imageName, CancellationToken cancellationToken) { var images = await _containerService.ListImagesAsync(true, cancellationToken); return images .Where(i => i.Name.EqualsIgnoreCase(imageName)) .Select(i => i.Tag); } private void StartUpdatingContainers() => UpdateContainersAsync(_updateContainersCts.Token).DoNotWait(); private void EndUpdatingContainers() => Interlocked.Exchange(ref _updateContainersCts, new CancellationTokenSource()).Cancel(); private async Task UpdateContainersAsync(CancellationToken updateContainersCancellationToken) { Error = null; Status = ContainersStatus.Running; while (!updateContainersCancellationToken.IsCancellationRequested) { var cts = CancellationTokenSource.CreateLinkedTokenSource(updateContainersCancellationToken); cts.CancelAfter(5000); await UpdateContainersOnceAsync(cts.Token); await Task.Delay(10000, updateContainersCancellationToken); } } private async Task UpdateContainersOnceAsync(CancellationToken token) { try { UpdateContainers(await _containerService.ListContainersAsync(true, token)); } catch (ContainerServiceNotInstalledException) { EndUpdatingContainers(); Status = ContainersStatus.NotInstalled; } catch (ContainerServiceNotRunningException) { EndUpdatingContainers(); Status = ContainersStatus.Stopped; } catch (ContainerException ex) { var message = ex.Message; if (message.EqualsOrdinal(Error)) { EndUpdatingContainers(); Status = ContainersStatus.HasErrors; } else { Error = ex.Message; } } catch (OperationCanceledException) { } } private void UpdateContainers(IEnumerable<IContainer> newContainers) { var containers = newContainers.Where(c => c.HostPorts.Any()).ToImmutableArray(); var runningContainers = containers.RemoveRange(containers.Where(c => !c.IsRunning)); var hasChanges = containers.Length != _containers.Length || containers.Where((t, i) => !t.Id.EqualsOrdinal(_containers[i].Id) || t.IsRunning != _containers[i].IsRunning).Any(); _containers = containers; _runningContainers = runningContainers; if (hasChanges) { ContainersChanged?.Invoke(); } } } }
// 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; using Xunit; namespace System.Linq.Expressions.Tests { public class PostDecrementAssignTests : IncDecAssignTests { [Theory] [PerCompilationType(nameof(Int16sAndDecrements))] [PerCompilationType(nameof(NullableInt16sAndDecrements))] [PerCompilationType(nameof(UInt16sAndDecrements))] [PerCompilationType(nameof(NullableUInt16sAndDecrements))] [PerCompilationType(nameof(Int32sAndDecrements))] [PerCompilationType(nameof(NullableInt32sAndDecrements))] [PerCompilationType(nameof(UInt32sAndDecrements))] [PerCompilationType(nameof(NullableUInt32sAndDecrements))] [PerCompilationType(nameof(Int64sAndDecrements))] [PerCompilationType(nameof(NullableInt64sAndDecrements))] [PerCompilationType(nameof(UInt64sAndDecrements))] [PerCompilationType(nameof(NullableUInt64sAndDecrements))] [PerCompilationType(nameof(DecimalsAndDecrements))] [PerCompilationType(nameof(NullableDecimalsAndDecrements))] [PerCompilationType(nameof(SinglesAndDecrements))] [PerCompilationType(nameof(NullableSinglesAndDecrements))] [PerCompilationType(nameof(DoublesAndDecrements))] [PerCompilationType(nameof(NullableDoublesAndDecrements))] public void ReturnsCorrectValues(Type type, object value, object _, bool useInterpreter) { ParameterExpression variable = Expression.Variable(type); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant(value, type)), Expression.PostDecrementAssign(variable) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(value, type), block)).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(Int16sAndDecrements))] [PerCompilationType(nameof(NullableInt16sAndDecrements))] [PerCompilationType(nameof(UInt16sAndDecrements))] [PerCompilationType(nameof(NullableUInt16sAndDecrements))] [PerCompilationType(nameof(Int32sAndDecrements))] [PerCompilationType(nameof(NullableInt32sAndDecrements))] [PerCompilationType(nameof(UInt32sAndDecrements))] [PerCompilationType(nameof(NullableUInt32sAndDecrements))] [PerCompilationType(nameof(Int64sAndDecrements))] [PerCompilationType(nameof(NullableInt64sAndDecrements))] [PerCompilationType(nameof(UInt64sAndDecrements))] [PerCompilationType(nameof(NullableUInt64sAndDecrements))] [PerCompilationType(nameof(DecimalsAndDecrements))] [PerCompilationType(nameof(NullableDecimalsAndDecrements))] [PerCompilationType(nameof(SinglesAndDecrements))] [PerCompilationType(nameof(NullableSinglesAndDecrements))] [PerCompilationType(nameof(DoublesAndDecrements))] [PerCompilationType(nameof(NullableDoublesAndDecrements))] public void AssignsCorrectValues(Type type, object value, object result, bool useInterpreter) { ParameterExpression variable = Expression.Variable(type); LabelTarget target = Expression.Label(type); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant(value, type)), Expression.PostDecrementAssign(variable), Expression.Return(target, variable), Expression.Label(target, Expression.Default(type)) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile(useInterpreter)()); } [Theory] [ClassData(typeof(CompilationTypes))] public void SingleNanToNan(bool useInterpreter) { TestPropertyClass<float> instance = new TestPropertyClass<float>(); instance.TestInstance = float.NaN; Assert.True(float.IsNaN( Expression.Lambda<Func<float>>( Expression.PostDecrementAssign( Expression.Property( Expression.Constant(instance), typeof(TestPropertyClass<float>), "TestInstance" ) ) ).Compile(useInterpreter)() )); Assert.True(float.IsNaN(instance.TestInstance)); } [Theory] [ClassData(typeof(CompilationTypes))] public void DoubleNanToNan(bool useInterpreter) { TestPropertyClass<double> instance = new TestPropertyClass<double>(); instance.TestInstance = double.NaN; Assert.True(double.IsNaN( Expression.Lambda<Func<double>>( Expression.PostDecrementAssign( Expression.Property( Expression.Constant(instance), typeof(TestPropertyClass<double>), "TestInstance" ) ) ).Compile(useInterpreter)() )); Assert.True(double.IsNaN(instance.TestInstance)); } [Theory] [PerCompilationType(nameof(DecrementOverflowingValues))] public void OverflowingValuesThrow(object value, bool useInterpreter) { ParameterExpression variable = Expression.Variable(value.GetType()); Action overflow = Expression.Lambda<Action>( Expression.Block( typeof(void), new[] { variable }, Expression.Assign(variable, Expression.Constant(value)), Expression.PostDecrementAssign(variable) ) ).Compile(useInterpreter); Assert.Throws<OverflowException>(overflow); } [Theory] [MemberData(nameof(UnincrementableAndUndecrementableTypes))] public void InvalidOperandType(Type type) { ParameterExpression variable = Expression.Variable(type); Assert.Throws<InvalidOperationException>(() => Expression.PostDecrementAssign(variable)); } [Theory] [ClassData(typeof(CompilationTypes))] public void MethodCorrectResult(bool useInterpreter) { ParameterExpression variable = Expression.Variable(typeof(string)); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant("hello")), Expression.PostDecrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")) ); Assert.Equal("hello", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)()); } [Theory] [ClassData(typeof(CompilationTypes))] public void MethodCorrectAssign(bool useInterpreter) { ParameterExpression variable = Expression.Variable(typeof(string)); LabelTarget target = Expression.Label(typeof(string)); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant("hello")), Expression.PostDecrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")), Expression.Return(target, variable), Expression.Label(target, Expression.Default(typeof(string))) ); Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)()); } [Fact] public void IncorrectMethodType() { Expression variable = Expression.Variable(typeof(int)); MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod"); Assert.Throws<InvalidOperationException>(() => Expression.PostDecrementAssign(variable, method)); } [Fact] public void IncorrectMethodParameterCount() { Expression variable = Expression.Variable(typeof(string)); MethodInfo method = typeof(object).GetTypeInfo().GetDeclaredMethod("ReferenceEquals"); Assert.Throws<ArgumentException>("method", () => Expression.PostDecrementAssign(variable, method)); } [Fact] public void IncorrectMethodReturnType() { Expression variable = Expression.Variable(typeof(int)); MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("GetString"); Assert.Throws<ArgumentException>(null, () => Expression.PostDecrementAssign(variable, method)); } [Theory] [ClassData(typeof(CompilationTypes))] public void StaticMemberAccessCorrect(bool useInterpreter) { TestPropertyClass<double>.TestStatic = 2.0; Assert.Equal( 2.0, Expression.Lambda<Func<double>>( Expression.PostDecrementAssign( Expression.Property(null, typeof(TestPropertyClass<double>), "TestStatic") ) ).Compile(useInterpreter)() ); Assert.Equal(1.0, TestPropertyClass<double>.TestStatic); } [Theory] [ClassData(typeof(CompilationTypes))] public void InstanceMemberAccessCorrect(bool useInterpreter) { TestPropertyClass<int> instance = new TestPropertyClass<int>(); instance.TestInstance = 2; Assert.Equal( 2, Expression.Lambda<Func<int>>( Expression.PostDecrementAssign( Expression.Property( Expression.Constant(instance), typeof(TestPropertyClass<int>), "TestInstance" ) ) ).Compile(useInterpreter)() ); Assert.Equal(1, instance.TestInstance); } [Theory] [ClassData(typeof(CompilationTypes))] public void ArrayAccessCorrect(bool useInterpreter) { int[] array = new int[1]; array[0] = 2; Assert.Equal( 2, Expression.Lambda<Func<int>>( Expression.PostDecrementAssign( Expression.ArrayAccess(Expression.Constant(array), Expression.Constant(0)) ) ).Compile(useInterpreter)() ); Assert.Equal(1, array[0]); } [Fact] public void CanReduce() { ParameterExpression variable = Expression.Variable(typeof(int)); UnaryExpression op = Expression.PostDecrementAssign(variable); Assert.True(op.CanReduce); Assert.NotSame(op, op.ReduceAndCheck()); } [Fact] public void NullOperand() { Assert.Throws<ArgumentNullException>("expression", () => Expression.PostDecrementAssign(null)); } [Fact] public void UnwritableOperand() { Assert.Throws<ArgumentException>("expression", () => Expression.PostDecrementAssign(Expression.Constant(1))); } [Fact] public void UnreadableOperand() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("expression", () => Expression.PostDecrementAssign(value)); } [Fact] public void UpdateSameOperandSameNode() { UnaryExpression op = Expression.PostDecrementAssign(Expression.Variable(typeof(int))); Assert.Same(op, op.Update(op.Operand)); Assert.Same(op, NoOpVisitor.Instance.Visit(op)); } [Fact] public void UpdateDiffOperandDiffNode() { UnaryExpression op = Expression.PostDecrementAssign(Expression.Variable(typeof(int))); Assert.NotSame(op, op.Update(Expression.Variable(typeof(int)))); } [Fact] public void ToStringTest() { var e = Expression.PostDecrementAssign(Expression.Parameter(typeof(int), "x")); Assert.Equal("x--", e.ToString()); } } }
/* * Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Runtime.Serialization; using OpenMetaverse; using Aurora.Framework; namespace Aurora.ScriptEngine.AuroraDotNetEngine { [Serializable] public class EventAbortException : Exception { public EventAbortException() { } protected EventAbortException( SerializationInfo info, StreamingContext context) { } } [Serializable] public class MinEventDelayException : Exception { public MinEventDelayException() { } protected MinEventDelayException( SerializationInfo info, StreamingContext context) { } } [Serializable] public class SelfDeleteException : Exception { public SelfDeleteException() { } protected SelfDeleteException( SerializationInfo info, StreamingContext context) { } } [Serializable] public class ScriptDeleteException : Exception { public ScriptDeleteException() { } protected ScriptDeleteException( SerializationInfo info, StreamingContext context) { } } [Serializable] public class ScriptPermissionsException : Exception { public ScriptPermissionsException(string message) : base(message) { } protected ScriptPermissionsException( SerializationInfo info, StreamingContext context) { } } public class DetectParams { public UUID Group; public UUID Key; public int LinkNum; public string Name; public LSL_Types.Vector3 OffsetPos; public UUID Owner; public LSL_Types.Vector3 Position; public LSL_Types.Quaternion Rotation; public int Type; public LSL_Types.Vector3 Velocity; private LSL_Types.Vector3 touchBinormal; private int touchFace; private LSL_Types.Vector3 touchNormal; private LSL_Types.Vector3 touchPos; private LSL_Types.Vector3 touchST; private LSL_Types.Vector3 touchUV; public DetectParams() { Key = UUID.Zero; OffsetPos = new LSL_Types.Vector3(); LinkNum = 0; Group = UUID.Zero; Name = String.Empty; Owner = UUID.Zero; Position = new LSL_Types.Vector3(); Rotation = new LSL_Types.Quaternion(); Type = 0; Velocity = new LSL_Types.Vector3(); initializeSurfaceTouch(); } public LSL_Types.Vector3 TouchST { get { return touchST; } } public LSL_Types.Vector3 TouchNormal { get { return touchNormal; } } public LSL_Types.Vector3 TouchBinormal { get { return touchBinormal; } } public LSL_Types.Vector3 TouchPos { get { return touchPos; } } public LSL_Types.Vector3 TouchUV { get { return touchUV; } } public int TouchFace { get { return touchFace; } } // This can be done in two places including the constructor // so be carefull what gets added here /* * Set up the surface touch detected values */ public SurfaceTouchEventArgs SurfaceTouchArgs { set { if (value == null) { // Initialise to defaults if no value initializeSurfaceTouch(); } else { // Set the values from the touch data provided by the client touchST = new LSL_Types.Vector3(value.STCoord.X, value.STCoord.Y, value.STCoord.Z); touchUV = new LSL_Types.Vector3(value.UVCoord.X, value.UVCoord.Y, value.UVCoord.Z); touchNormal = new LSL_Types.Vector3(value.Normal.X, value.Normal.Y, value.Normal.Z); touchBinormal = new LSL_Types.Vector3(value.Binormal.X, value.Binormal.Y, value.Binormal.Z); touchPos = new LSL_Types.Vector3(value.Position.X, value.Position.Y, value.Position.Z); touchFace = value.FaceIndex; } } } private void initializeSurfaceTouch() { touchST = new LSL_Types.Vector3(-1.0, -1.0, 0.0); touchNormal = new LSL_Types.Vector3(); touchBinormal = new LSL_Types.Vector3(); touchPos = new LSL_Types.Vector3(); touchUV = new LSL_Types.Vector3(-1.0, -1.0, 0.0); touchFace = -1; } public void Populate(IScene scene) { ISceneChildEntity part = scene.GetSceneObjectPart(Key); Vector3 tmp; if (part == null) // Avatar, maybe? { IScenePresence presence = scene.GetScenePresence(Key); if (presence == null) return; Name = presence.Name; Owner = Key; tmp = presence.AbsolutePosition; Position = new LSL_Types.Vector3( tmp.X, tmp.Y, tmp.Z); Quaternion rtmp = presence.Rotation; Rotation = new LSL_Types.Quaternion( rtmp.X, rtmp.Y, rtmp.Z, rtmp.W); tmp = presence.Velocity; Velocity = new LSL_Types.Vector3( tmp.X, tmp.Y, tmp.Z); Type = 0x01; // Avatar if (presence.Velocity != Vector3.Zero) Type |= 0x02; // Active Group = presence.ControllingClient.ActiveGroupId; return; } part = part.ParentEntity.RootChild; // We detect objects only LinkNum = 0; // Not relevant Group = part.GroupID; Name = part.Name; Owner = part.OwnerID; Type = part.Velocity == Vector3.Zero ? 0x04 : 0x02; foreach (ISceneChildEntity child in part.ParentEntity.ChildrenEntities()) if (child.Inventory.ContainsScripts()) Type |= 0x08; // Scripted tmp = part.AbsolutePosition; Position = new LSL_Types.Vector3(tmp.X, tmp.Y, tmp.Z); Quaternion wr = part.ParentEntity.GroupRotation; Rotation = new LSL_Types.Quaternion(wr.X, wr.Y, wr.Z, wr.W); tmp = part.Velocity; Velocity = new LSL_Types.Vector3(tmp.X, tmp.Y, tmp.Z); } } /// <summary> /// Holds all the data required to execute a scripting event. /// </summary> public class EventParams { public DetectParams[] DetectParams; public string EventName; public Object[] Params; public EventParams(string eventName, Object[] eventParams, DetectParams[] detectParams) { EventName = eventName; Params = eventParams; DetectParams = detectParams; } } /// <summary> /// Queue item structure /// </summary> public class QueueItemStruct { public EnumeratorInfo CurrentlyAt; public ScriptEventsProcData EventsProcData; public ScriptData ID; public int RunningNumber; //The currently running state that this event will be fired under public string State; public long VersionID; //Name of the method to fire public string functionName; //Params to give the script event public DetectParams[] llDetectParams; //Parameters to fire the function public object[] param; //This is the current spot that the event is at in processing } public struct StateQueueItem { public bool Create; public ScriptData ID; } // Load/Unload structure public struct LUStruct { public LUType Action; public ScriptData ID; } public enum LUType { Unknown = 0, Load = 1, Unload = 2, Reupload = 3 } public enum EventPriority { FirstStart = 0, Suspended = 1, Continued = 2 } public enum ScriptEventsState { Idle = 0, Sleep = 1, Suspended = 2, Running = 3, //? InExec = 4, InExecAbort = 5, Delete = 6, Deleted = -1 //? } public class ScriptEventsProcData { public ScriptEventsState State; public DateTime TimeCheck; } public enum LoadPriority { FirstStart = 0, Restart = 1, Stop = 2 } /// <summary> /// Threat Level for a scripting function /// </summary> public enum ThreatLevel { /// <summary> /// Function is no threat at all. It doesn't constitute a threat to either users or the system and has no known side effects /// </summary> None = 0, /// <summary> /// Abuse of this command can cause a nuisance to the region operator, such as log message spew /// </summary> Nuisance = 1, /// <summary> /// Extreme levels of abuse of this function can cause impaired functioning of the region, or very gullible users can be tricked into experiencing harmless effects /// </summary> VeryLow = 2, /// <summary> /// Intentional abuse can cause crashes or malfunction under certain circumstances, which can easily be rectified, or certain users can be tricked into certain situations in an avoidable manner. /// </summary> Low = 3, /// <summary> /// Intentional abuse can cause denial of service and crashes with potential of data or state loss, or trusting users can be tricked into embarrassing or uncomfortable situations. /// </summary> Moderate = 4, /// <summary> /// Casual abuse can cause impaired functionality or temporary denial of service conditions. Intentional abuse can easily cause crashes with potential data loss, or can be used to trick experienced and cautious users into unwanted situations, or changes global data permanently and without undo ability /// Malicious scripting can allow theft of content /// </summary> High = 5, /// <summary> /// Even normal use may, depending on the number of instances, or frequency of use, result in severe service impairment or crash with loss of data, or can be used to cause unwanted or harmful effects on users without giving the user a means to avoid it. /// </summary> VeryHigh = 6, /// <summary> /// Even casual use is a danger to region stability, or function allows console or OS command execution, or function allows taking money without consent, or allows deletion or modification of user data, or allows the compromise of sensitive data by design. /// </summary> Severe = 7, NoAccess = 8 } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Ductus.FluentDocker.Executors; using Ductus.FluentDocker.Executors.Parsers; using Ductus.FluentDocker.Extensions; using Ductus.FluentDocker.Model.Common; using Ductus.FluentDocker.Model.Containers; using Ductus.FluentDocker.Model.Images; namespace Ductus.FluentDocker.Commands { public static class Compose { public static CommandResponse<IList<string>> ComposeBuild(this DockerUri host, string altProjectName = null, bool forceRm = false, bool dontUseCache = false, bool alwaysPull = false, string[] services = null /*all*/, IDictionary<string, string> env = null, ICertificatePaths certificates = null, params string[] composeFile) { var cwd = WorkingDirectory(composeFile); var args = $"{host.RenderBaseArgs(certificates)}"; if (null != composeFile && 0 != composeFile.Length) foreach (var cf in composeFile) if (!string.IsNullOrEmpty(cf)) args += $" -f \"{cf}\""; if (!string.IsNullOrEmpty(altProjectName)) args += $" -p {altProjectName}"; var options = string.Empty; if (forceRm) options += " --force-rm"; if (alwaysPull) options += " --pull"; if (forceRm) options += " --force-rm"; if (null != services && 0 != services.Length) options += " " + string.Join(" ", services); return new ProcessExecutor<StringListResponseParser, IList<string>>( "docker-compose".ResolveBinary(), $"{args} build {options}", cwd.NeedCwd ? cwd.Cwd : null).ExecutionEnvironment(env).Execute(); } public static CommandResponse<IList<string>> ComposeCreate(this DockerUri host, string altProjectName = null, bool forceRecreate = false, bool noRecreate = false, bool dontBuild = false, bool buildBeforeCreate = false, string[] services = null /*all*/, IDictionary<string, string> env = null, ICertificatePaths certificates = null, params string[] composeFile) { var cwd = WorkingDirectory(composeFile); var args = $"{host.RenderBaseArgs(certificates)}"; if (null != composeFile && 0 != composeFile.Length) foreach (var cf in composeFile) if (!string.IsNullOrEmpty(cf)) args += $" -f \"{cf}\""; if (!string.IsNullOrEmpty(altProjectName)) args += $" -p {altProjectName}"; var options = string.Empty; if (forceRecreate) options += " --force-recreate"; if (noRecreate) options += " --no-recreate"; if (dontBuild) options += " --no-build"; if (buildBeforeCreate) options += " --build"; if (null != services && 0 != services.Length) options += " " + string.Join(" ", services); return new ProcessExecutor<StringListResponseParser, IList<string>>( "docker-compose".ResolveBinary(), $"{args} create {options}", cwd.NeedCwd ? cwd.Cwd : null).ExecutionEnvironment(env).Execute(); } public static CommandResponse<IList<string>> ComposeStart(this DockerUri host, string altProjectName = null, string[] services = null /*all*/, IDictionary<string, string> env = null, ICertificatePaths certificates = null, params string[] composeFile) { var cwd = WorkingDirectory(composeFile); var args = $"{host.RenderBaseArgs(certificates)}"; if (null != composeFile && 0 != composeFile.Length) foreach (var cf in composeFile) if (!string.IsNullOrEmpty(cf)) args += $" -f \"{cf}\""; if (!string.IsNullOrEmpty(altProjectName)) args += $" -p {altProjectName}"; var options = string.Empty; if (null != services && 0 != services.Length) options += " " + string.Join(" ", services); return new ProcessExecutor<StringListResponseParser, IList<string>>( "docker-compose".ResolveBinary(), $"{args} start -d {options}", cwd.NeedCwd ? cwd.Cwd : null).ExecutionEnvironment(env).Execute(); } public static CommandResponse<IList<string>> ComposeKill(this DockerUri host, string altProjectName = null, UnixSignal signal = UnixSignal.SIGKILL, string[] services = null /*all*/, IDictionary<string, string> env = null, ICertificatePaths certificates = null, params string[] composeFile) { var cwd = WorkingDirectory(composeFile); var args = $"{host.RenderBaseArgs(certificates)}"; if (null != composeFile && 0 != composeFile.Length) foreach (var cf in composeFile) if (!string.IsNullOrEmpty(cf)) args += $" -f \"{cf}\""; if (!string.IsNullOrEmpty(altProjectName)) args += $" -p {altProjectName}"; var options = string.Empty; if (UnixSignal.SIGKILL != signal) options += $" -s {signal}"; if (null != services && 0 != services.Length) options += " " + string.Join(" ", services); return new ProcessExecutor<StringListResponseParser, IList<string>>( "docker-compose".ResolveBinary(), $"{args} kill {options}", cwd.NeedCwd ? cwd.Cwd : null).ExecutionEnvironment(env).Execute(); } public static CommandResponse<IList<string>> ComposeStop(this DockerUri host, string altProjectName = null, TimeSpan? timeout = null, string[] services = null /*all*/, IDictionary<string, string> env = null, ICertificatePaths certificates = null, params string[] composeFile) { var cwd = WorkingDirectory(composeFile); var args = $"{host.RenderBaseArgs(certificates)}"; if (null != composeFile && 0 != composeFile.Length) foreach (var cf in composeFile) if (!string.IsNullOrEmpty(cf)) args += $" -f \"{cf}\""; if (!string.IsNullOrEmpty(altProjectName)) args += $" -p {altProjectName}"; var options = string.Empty; if (null != timeout) options += $" -t {Math.Round(timeout.Value.TotalSeconds, 0)}"; if (null != services && 0 != services.Length) options += " " + string.Join(" ", services); return new ProcessExecutor<StringListResponseParser, IList<string>>( "docker-compose".ResolveBinary(), $"{args} stop {options}", cwd.NeedCwd ? cwd.Cwd : null).ExecutionEnvironment(env).Execute(); } public static CommandResponse<IList<string>> ComposePause(this DockerUri host, string altProjectName = null, string[] services = null /*all*/, IDictionary<string, string> env = null, ICertificatePaths certificates = null, params string[] composeFile) { var cwd = WorkingDirectory(composeFile); var args = $"{host.RenderBaseArgs(certificates)}"; if (null != composeFile && 0 != composeFile.Length) foreach (var cf in composeFile) if (!string.IsNullOrEmpty(cf)) args += $" -f \"{cf}\""; if (!string.IsNullOrEmpty(altProjectName)) args += $" -p {altProjectName}"; var options = string.Empty; if (null != services && 0 != services.Length) options += " " + string.Join(" ", services); return new ProcessExecutor<StringListResponseParser, IList<string>>( "docker-compose".ResolveBinary(), $"{args} pause {options}", cwd.NeedCwd ? cwd.Cwd : null).ExecutionEnvironment(env).Execute(); } public static CommandResponse<IList<string>> ComposeUnPause(this DockerUri host, string altProjectName = null, string[] services = null /*all*/, IDictionary<string, string> env = null, ICertificatePaths certificates = null, params string[] composeFile) { var cwd = WorkingDirectory(composeFile); var args = $"{host.RenderBaseArgs(certificates)}"; if (null != composeFile && 0 != composeFile.Length) foreach (var cf in composeFile) if (!string.IsNullOrEmpty(cf)) args += $" -f \"{cf}\""; if (!string.IsNullOrEmpty(altProjectName)) args += $" -p {altProjectName}"; var options = string.Empty; if (null != services && 0 != services.Length) options += " " + string.Join(" ", services); return new ProcessExecutor<StringListResponseParser, IList<string>>( "docker-compose".ResolveBinary(), $"{args} unpause {options}", cwd.NeedCwd ? cwd.Cwd : null).ExecutionEnvironment(env).Execute(); } public static CommandResponse<IList<string>> ComposeScale(this DockerUri host, string altProjectName = null, TimeSpan? shutdownTimeout = null, string[] serviceEqNumber = null /*all*/, IDictionary<string, string> env = null, ICertificatePaths certificates = null, params string[] composeFile) { var cwd = WorkingDirectory(composeFile); var args = $"{host.RenderBaseArgs(certificates)}"; if (null != composeFile && 0 != composeFile.Length) foreach (var cf in composeFile) if (!string.IsNullOrEmpty(cf)) args += $" -f \"{cf}\""; if (!string.IsNullOrEmpty(altProjectName)) args += $" -p {altProjectName}"; var options = string.Empty; if (null != shutdownTimeout) options = $" -t {Math.Round(shutdownTimeout.Value.TotalSeconds, 0)}"; var services = string.Empty; if (null != serviceEqNumber && 0 != serviceEqNumber.Length) services += " " + string.Join(" ", serviceEqNumber); return new ProcessExecutor<StringListResponseParser, IList<string>>( "docker-compose".ResolveBinary(), $"{args} scale {options} {services}", cwd.NeedCwd ? cwd.Cwd : null).ExecutionEnvironment(env).Execute(); } public static CommandResponse<IList<string>> ComposeVersion(this DockerUri host, string altProjectName = null, bool shortVersion = false, IDictionary<string, string> env = null, ICertificatePaths certificates = null, params string[] composeFile) { var cwd = WorkingDirectory(composeFile); var args = $"{host.RenderBaseArgs(certificates)}"; if (null != composeFile && 0 != composeFile.Length) foreach (var cf in composeFile) if (!string.IsNullOrEmpty(cf)) args += $" -f \"{cf}\""; if (!string.IsNullOrEmpty(altProjectName)) args += $" -p {altProjectName}"; var options = string.Empty; if (shortVersion) options = "--short"; return new ProcessExecutor<StringListResponseParser, IList<string>>( "docker-compose".ResolveBinary(), $"{args} version {options}", cwd.NeedCwd ? cwd.Cwd : null).ExecutionEnvironment(env).Execute(); } public static CommandResponse<IList<string>> ComposeRestart(this DockerUri host, string altProjectName = null, string[] composeFile = null, TimeSpan? timeout = null, IDictionary<string, string> env = null, ICertificatePaths certificates = null, params string[] containerId) { var cwd = WorkingDirectory(composeFile); var args = $"{host.RenderBaseArgs(certificates)}"; if (null != composeFile && 0 != composeFile.Length) foreach (var cf in composeFile) if (!string.IsNullOrEmpty(cf)) args += $" -f \"{cf}\""; if (!string.IsNullOrEmpty(altProjectName)) args += $" -p {altProjectName}"; var ids = string.Empty; if (null != containerId && 0 != containerId.Length) ids += " " + string.Join(" ", containerId); var options = string.Empty; if (null != timeout) options = $" -t {Math.Round(timeout.Value.TotalSeconds, 0)}"; return new ProcessExecutor<StringListResponseParser, IList<string>>( "docker-compose".ResolveBinary(), $"{args} restart {options} {ids}", cwd.NeedCwd ? cwd.Cwd : null).ExecutionEnvironment(env).Execute(); } public static CommandResponse<IList<string>> ComposePort(this DockerUri host, string containerId, string privatePortAndProto = null, string altProjectName = null, IDictionary<string, string> env = null, ICertificatePaths certificates = null, params string[] composeFile) { var cwd = WorkingDirectory(composeFile); var args = $"{host.RenderBaseArgs(certificates)}"; if (null != composeFile && 0 != composeFile.Length) foreach (var cf in composeFile) if (!string.IsNullOrEmpty(cf)) args += $" -f \"{cf}\""; if (!string.IsNullOrEmpty(altProjectName)) args += $" -p {altProjectName}"; if (string.IsNullOrEmpty(privatePortAndProto)) privatePortAndProto = string.Empty; return new ProcessExecutor<StringListResponseParser, IList<string>>( "docker-compose".ResolveBinary(), $"{args} port {containerId} {privatePortAndProto}", cwd.NeedCwd ? cwd.Cwd : null).ExecutionEnvironment(env).Execute(); } public static CommandResponse<IList<string>> ComposeConfig(this DockerUri host, string altProjectName = null, bool quiet = true, bool outputServices = false, IDictionary<string, string> env = null, ICertificatePaths certificates = null, params string[] composeFile) { var cwd = WorkingDirectory(composeFile); var args = $"{host.RenderBaseArgs(certificates)}"; if (null != composeFile && 0 != composeFile.Length) foreach (var cf in composeFile) if (!string.IsNullOrEmpty(cf)) args += $" -f \"{cf}\""; if (!string.IsNullOrEmpty(altProjectName)) args += $" -p {altProjectName}"; var options = string.Empty; if (quiet) options += " -q"; if (outputServices) options += " --services"; return new ProcessExecutor<StringListResponseParser, IList<string>>( "docker-compose".ResolveBinary(), $"{args} config {options}", cwd.NeedCwd ? cwd.Cwd : null).ExecutionEnvironment(env).Execute(); } public static CommandResponse<IList<string>> ComposeDown(this DockerUri host, string altProjectName = null, ImageRemovalOption removeImagesFrom = ImageRemovalOption.None, bool removeVolumes = false, bool removeOrphanContainers = false, IDictionary<string, string> env = null, ICertificatePaths certificates = null, params string[] composeFile) { var cwd = WorkingDirectory(composeFile); var args = $"{host.RenderBaseArgs(certificates)}"; if (null != composeFile && 0 != composeFile.Length) foreach (var cf in composeFile) if (!string.IsNullOrEmpty(cf)) args += $" -f \"{cf}\""; if (!string.IsNullOrEmpty(altProjectName)) args += $" -p {altProjectName}"; var options = string.Empty; if (removeOrphanContainers) options += " --remove-orphans"; if (removeVolumes) options += " -v"; if (removeImagesFrom != ImageRemovalOption.None) options += removeImagesFrom == ImageRemovalOption.Local ? " --rmi local" : " --rmi all"; return new ProcessExecutor<StringListResponseParser, IList<string>>( "docker-compose".ResolveBinary(), $"{args} down {options}", cwd.NeedCwd ? cwd.Cwd : null).ExecutionEnvironment(env).Execute(); } [Obsolete("Use ComposeUpCommand(...)")] public static CommandResponse<IList<string>> ComposeUp(this DockerUri host, string altProjectName = null, bool forceRecreate = false, bool noRecreate = false, bool dontBuild = false, bool buildBeforeCreate = false, TimeSpan? timeout = null, bool removeOrphans = false, bool useColor = false, bool noStart = false, string[] services = null /*all*/, IDictionary<string, string> env = null, ICertificatePaths certificates = null, params string[] composeFile) { return host.ComposeUpCommand(new ComposeUpCommandArgs { AltProjectName = altProjectName, ForceRecreate = forceRecreate, NoRecreate = noRecreate, DontBuild = dontBuild, BuildBeforeCreate = buildBeforeCreate, Timeout = timeout, RemoveOrphans = removeOrphans, UseColor = useColor, NoStart = noStart, Services = services, Env = env, Certificates = certificates, ComposeFiles = composeFile }); } public struct ComposeUpCommandArgs { public string AltProjectName {get;set;} public bool ForceRecreate {get;set;} public bool NoRecreate {get;set;} public bool DontBuild {get;set;} public bool BuildBeforeCreate {get;set;} public TimeSpan? Timeout {get;set;} public bool RemoveOrphans {get;set;} public bool UseColor {get;set;} public bool NoStart {get;set;} public IList<string> Services {get;set;} public IDictionary<string, string> Env {get;set;} public ICertificatePaths Certificates {get;set;} public IList<string> ComposeFiles {get;set;} public TemplateString ProjectDirectory {get;set;} } public static CommandResponse<IList<string>> ComposeUpCommand(this DockerUri host, ComposeUpCommandArgs ca) { if (ca.ForceRecreate && ca.NoRecreate) { throw new InvalidOperationException("ForceRecreate and NoRecreate are incompatible."); } var cwd = WorkingDirectory(ca.ComposeFiles.ToArray()); var args = $"{host.RenderBaseArgs(ca.Certificates)}"; if (null != ca.ComposeFiles && 0 != ca.ComposeFiles.Count) foreach (var cf in ca.ComposeFiles) if (!string.IsNullOrEmpty(cf)) args += $" -f \"{cf}\""; if (!string.IsNullOrEmpty(ca.AltProjectName)) args += $" -p {ca.AltProjectName}"; var options = ca.NoStart ? "--no-start" : "--detach"; if (ca.ForceRecreate) options += " --force-recreate"; if (ca.NoRecreate) options += " --no-recreate"; if (ca.DontBuild) options += " --no-build"; if (ca.BuildBeforeCreate) options += " --build"; if (!ca.UseColor) options += " --no-color"; if (null != ca.Timeout) options += $" -t {Math.Round(ca.Timeout.Value.TotalSeconds, 0)}"; if (ca.RemoveOrphans) options += " --remove-orphans"; if (!string.IsNullOrEmpty(ca.ProjectDirectory)) { options += $" --project-directory {ca.ProjectDirectory.Rendered}"; } if (null != ca.Services && 0 != ca.Services.Count) options += " " + string.Join(" ", ca.Services); return new ProcessExecutor<StringListResponseParser, IList<string>>( "docker-compose".ResolveBinary(), $"{args} up {options}", cwd.NeedCwd ? cwd.Cwd : null).ExecutionEnvironment(ca.Env).Execute(); } public static CommandResponse<IList<string>> ComposeRm(this DockerUri host, string altProjectName = null, bool force = false, bool removeVolumes = false, string[] services = null /*all*/, IDictionary<string, string> env = null, ICertificatePaths certificates = null, params string[] composeFile) { var cwd = WorkingDirectory(composeFile); var args = $"{host.RenderBaseArgs(certificates)}"; if (null != composeFile && 0 != composeFile.Length) foreach (var cf in composeFile) if (!string.IsNullOrEmpty(cf)) args += $" -f \"{cf}\""; if (!string.IsNullOrEmpty(altProjectName)) args += $" -p {altProjectName}"; var options = string.Empty; options += " -f"; // Don't ask to confirm removal if (force) options += " -s"; if (removeVolumes) options += " -v"; if (null != services && 0 != services.Length) options += " " + string.Join(" ", services); return new ProcessExecutor<StringListResponseParser, IList<string>>( "docker-compose".ResolveBinary(), $"{args} rm {options}", cwd.NeedCwd ? cwd.Cwd : null).ExecutionEnvironment(env).Execute(); } public static CommandResponse<IList<string>> ComposePs(this DockerUri host, string altProjectName = null, string[] services = null, IDictionary<string, string> env = null, ICertificatePaths certificates = null, params string[] composeFile) { var cwd = WorkingDirectory(composeFile); var args = $"{host.RenderBaseArgs(certificates)}"; if (null != composeFile && 0 != composeFile.Length) foreach (var cf in composeFile) if (!string.IsNullOrEmpty(cf)) args += $" -f \"{cf}\""; if (!string.IsNullOrEmpty(altProjectName)) args += $" -p {altProjectName}"; var options = string.Empty; if (null != services && 0 != services.Length) options += " " + string.Join(" ", services); return new ProcessExecutor<StringListResponseParser, IList<string>>( "docker-compose".ResolveBinary(), $"{args} ps -q {options}", cwd.NeedCwd ? cwd.Cwd : null).ExecutionEnvironment(env).Execute(); } public static CommandResponse<IList<string>> ComposePull(this DockerUri host, string image, string altProjectName = null, bool downloadAllTagged = false, bool skipImageverficiation = false, IDictionary<string, string> env = null, ICertificatePaths certificates = null, params string[] composeFile) { var cwd = WorkingDirectory(composeFile); var args = $"{host.RenderBaseArgs(certificates)}"; if (null != composeFile && 0 != composeFile.Length) foreach (var cf in composeFile) if (!string.IsNullOrEmpty(cf)) args += $" -f \"{cf}\""; if (!string.IsNullOrEmpty(altProjectName)) args += $" -p {altProjectName}"; var options = string.Empty; if (downloadAllTagged) options += " -a"; if (skipImageverficiation) options += " --disable-content-trust=true"; return new ProcessExecutor<StringListResponseParser, IList<string>>( "docker-compose".ResolveBinary(), $"{args} pull {options} {image}", cwd.NeedCwd ? cwd.Cwd : null).ExecutionEnvironment(env).Execute(); } private static WorkingDirectoryInfo WorkingDirectory(params string[] composeFile) { var curr = Directory.GetCurrentDirectory(); var cwd = curr; if (null == composeFile || 0 == composeFile.Length) return new WorkingDirectoryInfo { Curr = curr, Cwd = cwd }; if (!string.IsNullOrEmpty(composeFile[0])) // First is assumed to be baseline cwd = Path.GetDirectoryName(Path.IsPathRooted(composeFile[0]) ? composeFile[0] : Path.Combine(curr, composeFile[0])); return new WorkingDirectoryInfo { Curr = curr, Cwd = cwd }; } private struct WorkingDirectoryInfo { public string Cwd { get; set; } public string Curr { get; set; } public bool NeedCwd => Cwd != Curr; } } }
// ------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this // file except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR // NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------------------ using Amqp; using Amqp.Framing; using Amqp.Sasl; using Amqp.Types; using System; using System.Text; using System.Threading; #if !(NETMF || COMPACT_FRAMEWORK) using Microsoft.VisualStudio.TestTools.UnitTesting; #endif namespace Test.Amqp { #if !(NETMF || COMPACT_FRAMEWORK) [TestClass] #endif public class LinkTests { public static Address address = new Address("amqp://guest:guest@localhost:5672"); #if !COMPACT_FRAMEWORK bool waitExitContext = true; #else bool waitExitContext = false; #endif #if !(NETMF || COMPACT_FRAMEWORK) [ClassInitialize] public static void Initialize(TestContext context) { Connection.DisableServerCertValidation = true; // uncomment the following to write frame traces //Trace.TraceLevel = TraceLevel.Frame; //Trace.TraceListener = (f, a) => System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString("[hh:ss.fff]") + " " + string.Format(f, a)); } [TestMethod] #endif public void TestMethod_BasicSendReceive() { string testName = "BasicSendReceive"; const int nMsgs = 200; Connection connection = new Connection(address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); for (int i = 0; i < nMsgs; ++i) { Message message = new Message("msg" + i); message.Properties = new Properties() { GroupId = "abcdefg" }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = i; sender.Send(message, null, null); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); for (int i = 0; i < nMsgs; ++i) { Message message = receiver.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.ApplicationProperties["sn"]); receiver.Accept(message); } sender.Close(); receiver.Close(); session.Close(); connection.Close(); } #if !(NETMF || COMPACT_FRAMEWORK) [TestMethod] #endif public void TestMethod_ConnectionFrameSize() { string testName = "ConnectionFrameSize"; const int nMsgs = 200; Connection connection = new Connection(address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); int frameSize = 16 * 1024; for (int i = 0; i < nMsgs; ++i) { Message message = new Message(new string('A', frameSize + (i - nMsgs / 2))); sender.Send(message, null, null); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); for (int i = 0; i < nMsgs; ++i) { Message message = receiver.Receive(); string value = (string)message.Body; Trace.WriteLine(TraceLevel.Information, "receive: {0}x{1}", value[0], value.Length); receiver.Accept(message); } sender.Close(); receiver.Close(); session.Close(); connection.Close(); } #if !(NETMF || COMPACT_FRAMEWORK) [TestMethod] #endif public void TestMethod_ConnectionChannelMax() { ushort channelMax = 5; Connection connection = new Connection( address, null, new Open() { ContainerId = "ConnectionChannelMax", HostName = address.Host, ChannelMax = channelMax }, (c, o) => Trace.WriteLine(TraceLevel.Information, "{0}", o)); for (int i = 0; i <= channelMax; i++) { Session session = new Session(connection); } try { Session session = new Session(connection); Fx.Assert(false, "Created more sessions than allowed."); } catch (AmqpException exception) { Fx.Assert(exception.Error.Condition.Equals((Symbol)ErrorCode.NotAllowed), "Wrong error code"); } connection.Close(); } #if !(NETMF || COMPACT_FRAMEWORK) [TestMethod] #endif public void TestMethod_ConnectionRemoteProperties() { string testName = "ConnectionRemoteProperties"; ManualResetEvent opened = new ManualResetEvent(false); Open remoteOpen = null; OnOpened onOpen = (c, o) => { remoteOpen = o; opened.Set(); }; Open open = new Open() { ContainerId = testName, Properties = new Fields() { { new Symbol("p1"), "abcd" } }, DesiredCapabilities = new Symbol[] { new Symbol("dc1"), new Symbol("dc2") }, OfferedCapabilities = new Symbol[] { new Symbol("oc") } }; Connection connection = new Connection(address, null, open, onOpen); opened.WaitOne(10000, waitExitContext); connection.Close(); Assert.IsTrue(remoteOpen != null, "remote open not set"); } #if !(NETMF || COMPACT_FRAMEWORK) [TestMethod] #endif public void TestMethod_OnMessage() { string testName = "OnMessage"; const int nMsgs = 200; Connection connection = new Connection(address); Session session = new Session(connection); ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); ManualResetEvent done = new ManualResetEvent(false); int received = 0; receiver.Start(10, (link, m) => { Trace.WriteLine(TraceLevel.Information, "receive: {0}", m.ApplicationProperties["sn"]); link.Accept(m); received++; if (received == nMsgs) { done.Set(); } }); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); for (int i = 0; i < nMsgs; ++i) { Message message = new Message() { BodySection = new Data() { Binary = Encoding.UTF8.GetBytes("msg" + i) } }; message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = i; sender.Send(message, null, null); } int last = -1; while (!done.WaitOne(10000, waitExitContext) && received > last) { last = received; } sender.Close(); receiver.Close(); session.Close(); connection.Close(); Assert.AreEqual(nMsgs, received, "not all messages are received."); } #if !(NETMF || COMPACT_FRAMEWORK) [TestMethod] #endif public void TestMethod_CloseBusyReceiver() { string testName = "CloseBusyReceiver"; const int nMsgs = 20; Connection connection = new Connection(address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); for (int i = 0; i < nMsgs; ++i) { Message message = new Message(); message.Properties = new Properties() { MessageId = "msg" + i }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = i; sender.Send(message, null, null); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); ManualResetEvent closed = new ManualResetEvent(false); receiver.Closed += (o, e) => closed.Set(); receiver.Start( nMsgs, (r, m) => { if (m.Properties.MessageId == "msg0") r.Close(0); }); Assert.IsTrue(closed.WaitOne(10000, waitExitContext)); ReceiverLink receiver2 = new ReceiverLink(session, "receiver2-" + testName, "q1"); for (int i = 0; i < nMsgs; ++i) { Message message = receiver2.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.Properties.MessageId); receiver2.Accept(message); } receiver2.Close(); sender.Close(); session.Close(); connection.Close(); } #if !(NETMF || COMPACT_FRAMEWORK) [TestMethod] #endif public void TestMethod_ReleaseMessage() { string testName = "ReleaseMessage"; const int nMsgs = 20; Connection connection = new Connection(address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); for (int i = 0; i < nMsgs; ++i) { Message message = new Message(); message.Properties = new Properties() { MessageId = "msg" + i }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = i; sender.Send(message, null, null); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); for (int i = 0; i < nMsgs; ++i) { Message message = receiver.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.Properties.MessageId); if (i % 2 == 0) { receiver.Accept(message); } else { receiver.Release(message); } } receiver.Close(); ReceiverLink receiver2 = new ReceiverLink(session, "receiver2-" + testName, "q1"); for (int i = 0; i < nMsgs / 2; ++i) { Message message = receiver2.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.Properties.MessageId); receiver2.Accept(message); } receiver2.Close(); sender.Close(); session.Close(); connection.Close(); } #if !(NETMF || COMPACT_FRAMEWORK) [TestMethod] #endif public void TestMethod_SendAck() { string testName = "SendAck"; const int nMsgs = 20; Connection connection = new Connection(address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); ManualResetEvent done = new ManualResetEvent(false); OutcomeCallback callback = (m, o, s) => { Trace.WriteLine(TraceLevel.Information, "send complete: sn {0} outcome {1}", m.ApplicationProperties["sn"], o.Descriptor.Name); if ((int)m.ApplicationProperties["sn"] == (nMsgs - 1)) { done.Set(); } }; for (int i = 0; i < nMsgs; ++i) { Message message = new Message(); message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = i; sender.Send(message, callback, null); } done.WaitOne(10000, waitExitContext); ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); for (int i = 0; i < nMsgs; ++i) { Message message = receiver.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.ApplicationProperties["sn"]); receiver.Accept(message); } sender.Close(); receiver.Close(); session.Close(); connection.Close(); } #if !(NETMF || COMPACT_FRAMEWORK) [TestMethod] #endif public void TestMethod_ReceiveWaiter() { string testName = "ReceiveWaiter"; Connection connection = new Connection(address); Session session = new Session(connection); ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); Thread t = new Thread(() => { Message message = receiver.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.Properties.MessageId); receiver.Accept(message); }); t.Start(); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); Message msg = new Message() { Properties = new Properties() { MessageId = "123456" } }; sender.Send(msg, null, null); t.Join(10000); sender.Close(); receiver.Close(); session.Close(); connection.Close(); } #if !(NETMF || COMPACT_FRAMEWORK) [TestMethod] #endif public void TestMethod_ReceiveWithFilter() { string testName = "ReceiveWithFilter"; Connection connection = new Connection(address); Session session = new Session(connection); Message message = new Message("I can match a filter"); message.Properties = new Properties() { GroupId = "abcdefg" }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = 100; SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); sender.Send(message, null, null); // update the filter descriptor and expression according to the broker Map filters = new Map(); // JMS selector filter: code = 0x0000468C00000004L, symbol="apache.org:selector-filter:string" filters.Add(new Symbol("f1"), new DescribedValue(new Symbol("apache.org:selector-filter:string"), "sn = 100")); ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, new Source() { Address = "q1", FilterSet = filters }, null); Message message2 = receiver.Receive(); receiver.Accept(message2); sender.Close(); receiver.Close(); session.Close(); connection.Close(); } #if !(NETMF || COMPACT_FRAMEWORK) [TestMethod] #endif public void TestMethod_LinkCloseWithPendingSend() { string testName = "LinkCloseWithPendingSend"; Connection connection = new Connection(address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); bool cancelled = false; Message message = new Message("released"); sender.Send(message, (m, o, s) => cancelled = true, null); sender.Close(0); // assume that Close is called before connection/link is open so message is still queued in link // but this is not very reliable, so just do a best effort check if (cancelled) { Trace.WriteLine(TraceLevel.Information, "The send was cancelled as expected"); } else { Trace.WriteLine(TraceLevel.Information, "The send was not cancelled as expected. This can happen if close call loses the race"); } try { message = new Message("failed"); sender.Send(message, (m, o, s) => cancelled = true, null); Assert.IsTrue(false, "Send should fail after link is closed"); } catch (AmqpException exception) { Trace.WriteLine(TraceLevel.Information, "Caught exception: ", exception.Error); } session.Close(); connection.Close(); } #if !(NETMF || COMPACT_FRAMEWORK) [TestMethod] #endif public void TestMethod_SynchronousSend() { string testName = "SynchronousSend"; Connection connection = new Connection(address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); Message message = new Message("hello"); sender.Send(message, 60000); ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); message = receiver.Receive(); Assert.IsTrue(message != null, "no message was received."); receiver.Accept(message); sender.Close(); receiver.Close(); session.Close(); connection.Close(); } #if !(NETMF || COMPACT_FRAMEWORK) [TestMethod] #endif public void TestMethod_DynamicSenderLink() { string testName = "DynamicSenderLink"; Connection connection = new Connection(address); Session session = new Session(connection); string targetAddress = null; OnAttached onAttached = (link, attach) => { targetAddress = ((Target)attach.Target).Address; }; SenderLink sender = new SenderLink(session, "sender-" + testName, new Target() { Dynamic = true }, onAttached); Message message = new Message("hello"); sender.Send(message, 60000); Assert.IsTrue(targetAddress != null, "dynamic target not attached"); ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, targetAddress); message = receiver.Receive(); Assert.IsTrue(message != null, "no message was received."); receiver.Accept(message); sender.Close(); receiver.Close(); session.Close(); connection.Close(); } #if !(NETMF || COMPACT_FRAMEWORK) [TestMethod] #endif public void TestMethod_DynamicReceiverLink() { string testName = "DynamicReceiverLink"; Connection connection = new Connection(address); Session session = new Session(connection); string remoteSource = null; ManualResetEvent attached = new ManualResetEvent(false); OnAttached onAttached = (link, attach) => { remoteSource = ((Source)attach.Source).Address; attached.Set(); }; ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, new Source() { Dynamic = true }, onAttached); attached.WaitOne(10000, waitExitContext); Assert.IsTrue(remoteSource != null, "dynamic source not attached"); SenderLink sender = new SenderLink(session, "sender-" + testName, remoteSource); Message message = new Message("hello"); sender.Send(message, 60000); message = receiver.Receive(); Assert.IsTrue(message != null, "no message was received."); receiver.Accept(message); sender.Close(); receiver.Close(); session.Close(); connection.Close(); } #if !(NETMF || COMPACT_FRAMEWORK) [TestMethod] #endif public void TestMethod_RequestResponse() { string testName = "RequestResponse"; Connection connection = new Connection(address); Session session = new Session(connection); // server app: the request handler ReceiverLink requestLink = new ReceiverLink(session, "srv.requester-" + testName, "q1"); requestLink.Start(10, (l, m) => { l.Accept(m); // got a request, send back a reply SenderLink sender = new SenderLink(session, "srv.replier-" + testName, m.Properties.ReplyTo); Message reply = new Message("received"); reply.Properties = new Properties() { CorrelationId = m.Properties.MessageId }; sender.Send(reply, (a, b, c) => ((Link)c).Close(0), sender); }); // client: setup a temp queue and waits for responses OnAttached onAttached = (l, at) => { // client: sends a request to the request queue, specifies the temp queue as the reply queue SenderLink sender = new SenderLink(session, "cli.requester-" + testName, "q1"); Message request = new Message("hello"); request.Properties = new Properties() { MessageId = "request1", ReplyTo = ((Source)at.Source).Address }; sender.Send(request, (a, b, c) => ((Link)c).Close(0), sender); }; ReceiverLink responseLink = new ReceiverLink(session, "cli.responder-" + testName, new Source() { Dynamic = true }, onAttached); Message response = responseLink.Receive(); Assert.IsTrue(response != null, "no response was received"); responseLink.Accept(response); requestLink.Close(); responseLink.Close(); session.Close(); connection.Close(); } #if !(NETMF || COMPACT_FRAMEWORK) [TestMethod] #endif public void TestMethod_AdvancedLinkFlowControl() { string testName = "AdvancedLinkFlowControl"; int nMsgs = 20; Connection connection = new Connection(address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); for (int i = 0; i < nMsgs; ++i) { Message message = new Message(); message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName }; sender.Send(message, null, null); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); receiver.SetCredit(2, false); Message m1 = receiver.Receive(); Message m2 = receiver.Receive(); Assert.AreEqual("msg0", m1.Properties.MessageId); Assert.AreEqual("msg1", m2.Properties.MessageId); receiver.Accept(m1); receiver.Accept(m2); ReceiverLink receiver2 = new ReceiverLink(session, "receiver2-" + testName, "q1"); receiver2.SetCredit(2, false); Message m3 = receiver2.Receive(); Message m4 = receiver2.Receive(); Assert.AreEqual("msg2", m3.Properties.MessageId); Assert.AreEqual("msg3", m4.Properties.MessageId); receiver2.Accept(m3); receiver2.Accept(m4); receiver.SetCredit(4); for (int i = 4; i < nMsgs; i++) { Message m = receiver.Receive(); Assert.AreEqual("msg" + i, m.Properties.MessageId); receiver.Accept(m); } sender.Close(); receiver.Close(); receiver2.Close(); session.Close(); connection.Close(); } } }
// ------------------------------------------------------------------------------------------- // <copyright file="Totals.cs" company="Sitecore Corporation"> // Copyright (c) Sitecore Corporation 1999-2015 // </copyright> // ------------------------------------------------------------------------------------------- // Copyright 2015 Sitecore Corporation A/S // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // ------------------------------------------------------------------------------------------- namespace Sitecore.Ecommerce.DomainModel.Prices { using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; /// <summary> /// The product prices list abstract class. /// </summary> [Serializable, CollectionDataContract] public class Totals : IDictionary<string, decimal> { /// <summary> /// The totals dictionary. /// </summary> private readonly IDictionary<string, decimal> totals; /// <summary> /// Initializes a new instance of the <see cref="Totals"/> class. /// </summary> public Totals() { this.totals = new Dictionary<string, decimal>(); } /// <summary> /// Initializes a new instance of the <see cref="Totals"/> class. /// </summary> /// <param name="totals">The totals.</param> public Totals(IDictionary<string, decimal> totals) { this.totals = totals; } /// <summary> /// Gets or sets the member price. /// </summary> /// <value>The member price.</value> public virtual decimal MemberPrice { get { return this["MemberPrice"]; } set { this["MemberPrice"] = value; } } /// <summary> /// Gets or sets the indirect tax. /// </summary> /// <value>The indirect tax.</value> public virtual decimal VAT { get { return this["VAT"]; } set { this["VAT"] = value; } } /// <summary> /// Gets or sets the total vat. /// </summary> /// <value>The total vat.</value> public virtual decimal TotalVat { get { return this["TotalVat"]; } set { this["TotalVat"] = value; } } /// <summary> /// Gets or sets the price inc vat. /// </summary> /// <value>The price inc vat.</value> public virtual decimal PriceIncVat { get { return this["PriceIncVat"]; } set { this["PriceIncVat"] = value; } } /// <summary> /// Gets or sets the price ex vat. /// </summary> /// <value>The price ex vat.</value> public virtual decimal PriceExVat { get { return this["PriceExVat"]; } set { this["PriceExVat"] = value; } } /// <summary> /// Gets or sets the discount inc vat. /// </summary> /// <value>The discount inc vat.</value> public virtual decimal DiscountIncVat { get { return this["DiscountIncVat"]; } set { this["DiscountIncVat"] = value; } } /// <summary> /// Gets or sets the discount ex vat. /// </summary> /// <value>The discount ex vat.</value> public virtual decimal DiscountExVat { get { return this["DiscountExVat"]; } set { this["DiscountExVat"] = value; } } /// <summary> /// Gets or sets the possible discount inc vat. /// </summary> /// <value>The possible discount inc vat.</value> public virtual decimal PossibleDiscountIncVat { get { return this["PossibleDiscountIncVat"]; } set { this["PossibleDiscountIncVat"] = value; } } /// <summary> /// Gets or sets the possible discount ex vat. /// </summary> /// <value>The possible discount ex vat.</value> public virtual decimal PossibleDiscountExVat { get { return this["PossibleDiscountExVat"]; } set { this["PossibleDiscountExVat"] = value; } } /// <summary> /// Gets or sets the total price ex vat. /// </summary> /// <value>The total price ex vat.</value> public virtual decimal TotalPriceExVat { get { return this["TotalPriceExVat"]; } set { this["TotalPriceExVat"] = value; } } /// <summary> /// Gets or sets the total price inc vat. /// </summary> /// <value>The total price inc vat.</value> public virtual decimal TotalPriceIncVat { get { return this["TotalPriceIncVat"]; } set { this["TotalPriceIncVat"] = value; } } #region Implementation of IEnumerable /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> /// <filterpriority>1</filterpriority> public virtual IEnumerator<KeyValuePair<string, decimal>> GetEnumerator() { return this.totals.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> /// <filterpriority>2</filterpriority> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion #region Implementation of ICollection<KeyValuePair<string,decimal>> /// <summary> /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </exception> public virtual void Add(KeyValuePair<string, decimal> item) { this.totals.Add(item); } /// <summary> /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </exception> public virtual void Clear() { this.totals.Clear(); } /// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value. /// </summary> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. /// </returns> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </param> public virtual bool Contains(KeyValuePair<string, decimal> item) { return this.totals.Contains(item); } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> /// <exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0. /// </exception> /// <exception cref="T:System.ArgumentException"><paramref name="array"/> is multidimensional. /// -or- /// <paramref name="arrayIndex"/> is equal to or greater than the length of <paramref name="array"/>. /// -or- /// The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>. /// -or- /// </exception> public virtual void CopyTo(KeyValuePair<string, decimal>[] array, int arrayIndex) { this.totals.CopyTo(array, arrayIndex); } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </exception> public virtual bool Remove(KeyValuePair<string, decimal> item) { return this.totals.Remove(item); } /// <summary> /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <value>The count.</value> /// <returns> /// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> public virtual int Count { get { return this.totals.Count; } } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </summary> /// <returns> /// true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false. /// </returns> public virtual bool IsReadOnly { get { return this.totals.IsReadOnly; } } #endregion #region Implementation of IDictionary<string,decimal> /// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key. /// </summary> /// <returns> /// true if the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the key; otherwise, false. /// </returns> /// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null. /// </exception> public virtual bool ContainsKey(string key) { return this.totals.ContainsKey(key); } /// <summary> /// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <param name="key">The object to use as the key of the element to add. /// </param><param name="value">The object to use as the value of the element to add. /// </param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null. /// </exception><exception cref="T:System.ArgumentException">An element with the same key already exists in the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only. /// </exception> public virtual void Add(string key, decimal value) { this.totals.Add(key, value); } /// <summary> /// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <returns> /// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </returns> /// <param name="key">The key of the element to remove. /// </param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null. /// </exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only. /// </exception> public virtual bool Remove(string key) { return this.totals.Remove(key); } /// <summary> /// Gets the value associated with the specified key. /// </summary> /// <returns> /// true if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key; otherwise, false. /// </returns> /// <param name="key">The key whose value to get. /// </param><param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value"/> parameter. This parameter is passed uninitialized. /// </param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null. /// </exception> public virtual bool TryGetValue(string key, out decimal value) { return this.totals.TryGetValue(key, out value); } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <returns> /// The element with the specified key. /// </returns> /// <param name="key">The key of the element to get or set. /// </param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null. /// </exception><exception cref="T:System.Collections.Generic.KeyNotFoundException">The property is retrieved and <paramref name="key"/> is not found. /// </exception><exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only. /// </exception> public virtual decimal this[string key] { get { return this.totals.ContainsKey(key) ? this.totals[key] : default(decimal); } set { this.totals[key] = value; } } /// <summary> /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <returns> /// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </returns> public virtual ICollection<string> Keys { get { return this.totals.Keys; } } /// <summary> /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <returns> /// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </returns> public virtual ICollection<decimal> Values { get { return this.totals.Values; } } #endregion } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using mshtml; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Interop.Com; using OpenLiveWriter.Mshtml; namespace OpenLiveWriter.HtmlEditor { public class HtmlStyleHelper { private MshtmlMarkupServices _markupServices; private HtmlStyleHelper(MshtmlMarkupServices markupServices) { _markupServices = markupServices; } public static void SplitInlineTags(MshtmlMarkupServices markupServices, MarkupPointer splitPoint) { HtmlStyleHelper htmlStyleHelper = new HtmlStyleHelper(markupServices); htmlStyleHelper.SplitInlineTags(splitPoint); } public static MarkupRange ApplyInlineTag(MshtmlMarkupServices markupServices, _ELEMENT_TAG_ID tagId, string attributes, MarkupRange selection, bool toggle) { HtmlStyleHelper htmlStyleHelper = new HtmlStyleHelper(markupServices); // Aligning the with the behavior of Word, we will make <SUP> and <SUB> mutually exclusive. // That is, if you are applying <SUB> to a selection that has <SUP> applied already, we will first remove the <SUP>, and vice versa. // Wait, if empty and we're on the very end of the already existing formatting, then we just want to jump out and apply... MarkupRange selectionToApply = selection.Clone(); if (toggle) { // If already entirely inside the tag // If empty and just inside of the closing tag, then jump outside the closing tag // Else remove the tag // If already entirely outside the tag // If empty, apply the tag and put selection inside // If non-empty, then apply tag and reselect // If partially inside the tag // Remove the tag _ELEMENT_TAG_ID mutuallyExclusiveTagId = _ELEMENT_TAG_ID.TAGID_NULL; switch (tagId) { case _ELEMENT_TAG_ID.TAGID_SUP: mutuallyExclusiveTagId = _ELEMENT_TAG_ID.TAGID_SUB; break; case _ELEMENT_TAG_ID.TAGID_SUB: mutuallyExclusiveTagId = _ELEMENT_TAG_ID.TAGID_SUP; break; default: break; } if (selection.IsEmpty()) { // If the selection is empty and we're just inside the tagId closing tag (meaning that there is no text before the closing tag), // then we just hop outside of the tagId closing tag. bool exitScopeMatchesTagIdToBeApplied; MarkupPointer pointerOutsideTagIdScope = htmlStyleHelper.NextExitScopeWithoutInterveningText(selection, tagId, mutuallyExclusiveTagId, out exitScopeMatchesTagIdToBeApplied); if (pointerOutsideTagIdScope != null) { selectionToApply = markupServices.CreateMarkupRange(pointerOutsideTagIdScope, pointerOutsideTagIdScope); if (exitScopeMatchesTagIdToBeApplied) { return selectionToApply; } // else we still need to apply tagId } } // If a mutually exclusive tag is applied, then remove it. if (selectionToApply.IsTagId(mutuallyExclusiveTagId, true)) { selectionToApply.RemoveElementsByTagId(mutuallyExclusiveTagId, false); } // If this tag is already applied, then remove it and return. if (selectionToApply.IsTagId(tagId, true)) { selectionToApply.RemoveElementsByTagId(tagId, false); return selectionToApply; } } return htmlStyleHelper.ApplyInlineTag(tagId, attributes, selectionToApply); } private MarkupRange ApplyInlineTag(_ELEMENT_TAG_ID tagId, string attributes, MarkupRange selection) { MarkupRange newSelection = _markupServices.CreateMarkupRange(); // If the selection is empty, then just insert the tag if (selection.IsEmpty()) { newSelection.MoveToElement(WrapRangeInSpanElement(tagId, attributes, selection), false); return newSelection; } // Start at the beginning of the selection move forward until you hit a block start/exit context or the end of the selection bool keepApplying = true; MarkupContext contextStart = new MarkupContext(); MarkupRange blockFreeRange = _markupServices.CreateMarkupRange(selection.Start.Clone(), selection.Start.Clone()); MarkupPointer currentPointer = _markupServices.CreateMarkupPointer(blockFreeRange.Start); while (keepApplying) { // Check if moving right would be beyond the bounds of the selection. if (currentPointer.IsRightOfOrEqualTo(selection.End)) { // We've hit the end of the selection, so we're done. keepApplying = false; Debug.Assert(blockFreeRange.Start.IsLeftOfOrEqualTo(selection.End)); blockFreeRange.End.MoveToPointer(selection.End.IsLeftOf(currentPointer) ? selection.End : currentPointer); if (ShouldApplyInlineTagToBlockFreeSelection(blockFreeRange)) newSelection.ExpandToInclude(ApplyInlineTagToBlockFreeSelection(tagId, attributes, blockFreeRange)); break; } // Check if the next context is entering or exiting a block. currentPointer.Right(false, contextStart); if (contextStart.Element != null && ElementFilters.IsBlockElement(contextStart.Element)) { switch (contextStart.Context) { case _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope: case _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_ExitScope: { blockFreeRange.End.MoveToPointer(selection.End.IsLeftOf(currentPointer) ? selection.End : currentPointer); if (ShouldApplyInlineTagToBlockFreeSelection(blockFreeRange)) newSelection.ExpandToInclude(ApplyInlineTagToBlockFreeSelection(tagId, attributes, blockFreeRange)); if (contextStart.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope) blockFreeRange.Start.MoveAdjacentToElement(contextStart.Element, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin); else if (contextStart.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_ExitScope) blockFreeRange.Start.MoveAdjacentToElement(contextStart.Element, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd); blockFreeRange.Collapse(true); } break; case _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_None: { keepApplying = false; blockFreeRange.End.MoveToPointer(selection.End.IsLeftOf(currentPointer) ? selection.End : currentPointer); if (ShouldApplyInlineTagToBlockFreeSelection(blockFreeRange)) newSelection.ExpandToInclude(ApplyInlineTagToBlockFreeSelection(tagId, attributes, blockFreeRange)); } break; default: break; } } // Finally, move our pointer currentPointer.Right(true); } if (newSelection.Positioned) newSelection.Trim(); return newSelection; } private bool ShouldApplyInlineTagToBlockFreeSelection(MarkupRange blockFreeRange) { return !String.IsNullOrEmpty(blockFreeRange.Text) || blockFreeRange.ContainsElements(ElementFilters.INLINE_ELEMENTS); } private MarkupRange ApplyInlineTagToBlockFreeSelection(_ELEMENT_TAG_ID tagId, string attributes, MarkupRange blockFreeSelection) { // @RIBBON TODO: May want to be a bit more sophisticated and eliminate redundant tags return _markupServices.CreateMarkupRange(WrapRangeInSpanElement(tagId, attributes, blockFreeSelection)); } private IHTMLElement WrapRangeInSpanElement(_ELEMENT_TAG_ID tagId, string attributes, MarkupRange spanRange) { MarkupRange insertionRange = _markupServices.CreateMarkupRange(); IHTMLElement newSpanElement = _markupServices.CreateElement(tagId, attributes); //insert the new span element in front of the span content insertionRange.Start.MoveToPointer(spanRange.Start); insertionRange.End.MoveToPointer(spanRange.Start); _markupServices.InsertElement(newSpanElement, insertionRange.Start, insertionRange.End); //move the span content inside the new span element insertionRange.Start.MoveAdjacentToElement(newSpanElement, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin); spanRange.Start.MoveAdjacentToElement(newSpanElement, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd); _markupServices.Move(spanRange.Start, spanRange.End, insertionRange.Start); return newSpanElement; } /// <summary> /// Returns the markup pointer to the position of the first exit scope of type tagId or type terminatingTagId which follows this markup range. /// Returns null if text exists between the range and such an exit scope, or if there is no such exit scope. /// </summary> /// <param name="terminatingTagId"></param> /// <returns></returns> internal MarkupPointer NextExitScopeWithoutInterveningText(MarkupRange selection, _ELEMENT_TAG_ID tagId, _ELEMENT_TAG_ID terminatingTagId, out bool primaryTagIdMatch) { MarkupContext context = new MarkupContext(); MarkupPointer pointer = selection.End.Clone(); primaryTagIdMatch = false; while (true) { pointer.Right(true, context); if (context.Element == null) return null; switch (context.Context) { case _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_None: return null; case _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_ExitScope: { if (_markupServices.GetElementTagId(context.Element) == tagId) { primaryTagIdMatch = true; return pointer; } if (terminatingTagId != _ELEMENT_TAG_ID.TAGID_NULL && terminatingTagId == _markupServices.GetElementTagId(context.Element)) { return pointer; } } break; case _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope: case _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_NoScope: break; case _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_Text: return null; } } } /// <summary> /// <font><span>aaa[splitPoint]bbb</span></font> --> <font><span>aaa</span></font><font>[splitPoint]<span>bbb</span></font> /// </summary> private void SplitInlineTags(MarkupPointer splitPoint) { Debug.Assert(splitPoint.Positioned); IHTMLElement currentElement = splitPoint.GetParentElement(ElementFilters.CreateElementPassFilter()); while (currentElement != null) { if (!ElementFilters.IsInlineElement(currentElement)) return; IHTMLElement parentElement = currentElement.parentElement; MarkupRange currentElementRange = _markupServices.CreateMarkupRange(currentElement, false); MarkupRange leftRange = _markupServices.CreateMarkupRange(); IHTMLElement leftElement = _markupServices.CreateElement(_markupServices.GetElementTagId(currentElement), null); HTMLElementHelper.CopyAttributes(currentElement, leftElement); leftRange.MoveToPointers(currentElementRange.Start, splitPoint); _markupServices.InsertElement(leftElement, leftRange.Start, leftRange.End); splitPoint.MoveAdjacentToElement(leftElement, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd); MarkupRange rightRange = _markupServices.CreateMarkupRange(); IHTMLElement rightElement = _markupServices.CreateElement(_markupServices.GetElementTagId(currentElement), null); HTMLElementHelper.CopyAttributes(currentElement, rightElement); rightRange.MoveToPointers(splitPoint, currentElementRange.End); #if DEBUG // Verify that the right range does not overlap the left *element* MarkupRange leftElementRange = _markupServices.CreateMarkupRange(leftElement, true); Debug.Assert(leftElementRange.End.IsLeftOfOrEqualTo(rightRange.Start), "Your right range overlaps the left element that you just created!"); #endif _markupServices.InsertElement(rightElement, rightRange.Start, rightRange.End); splitPoint.MoveAdjacentToElement(rightElement, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin); _markupServices.RemoveElement(currentElement); currentElement = parentElement; } } public static void ChangeElementTagIds(MshtmlMarkupServices markupServices, MarkupRange selection, _ELEMENT_TAG_ID[] tagBefore, _ELEMENT_TAG_ID tagAfter) { HtmlStyleHelper htmlStyleHelper = new HtmlStyleHelper(markupServices); int parentStartDiff = 0; MarkupRange rangeToChange; bool selectionStartedEmpty = selection.IsEmpty(); if (selectionStartedEmpty) { // Operate on parent block element rangeToChange = markupServices.CreateMarkupRange(selection.ParentBlockElement()); parentStartDiff = selection.Start.MarkupPosition - rangeToChange.Start.MarkupPosition; } else { rangeToChange = selection; // If expanding the selection would not include any new text, then expand it. // <h1>|abc|</h1> --> |<h1>abc</h1>| rangeToChange.MoveOutwardIfNoText(); } IHTMLElementFilter[] filters = new IHTMLElementFilter[tagBefore.Length]; for (int i = 0; i < tagBefore.Length; i++) filters[i] = ElementFilters.CreateTagIdFilter(markupServices.GetNameForTagId(tagBefore[i])); IHTMLElement[] elements = rangeToChange.GetElements(ElementFilters.CreateCompoundElementFilter(filters), false); foreach (IHTMLElement element in elements) { MarkupRange elementRange = markupServices.CreateMarkupRange(element); int startPositionDiff = rangeToChange.Start.MarkupPosition - elementRange.Start.MarkupPosition; int endPositionDiff = rangeToChange.End.MarkupPosition - elementRange.End.MarkupPosition; // @RIBBON TODO: Appropriately preserve element attributes when changing tag ids? MarkupRange newElementRange = markupServices.CreateMarkupRange(htmlStyleHelper.WrapRangeInSpanElement(tagAfter, null, elementRange)); markupServices.RemoveElement(element); MarkupPointer startPointer = rangeToChange.Start.Clone(); startPointer.MoveToMarkupPosition(startPointer.Container, newElementRange.Start.MarkupPosition + startPositionDiff); if (startPointer.IsLeftOf(rangeToChange.Start)) rangeToChange.Start.MoveToPointer(startPointer); MarkupPointer endPointer = rangeToChange.End.Clone(); endPointer.MoveToMarkupPosition(endPointer.Container, newElementRange.End.MarkupPosition + endPositionDiff); if (endPointer.IsLeftOf(elementRange.End)) rangeToChange.End.MoveToPointer(endPointer); } if (selectionStartedEmpty) { selection.Start.MoveToMarkupPosition(selection.Start.Container, rangeToChange.Start.MarkupPosition + parentStartDiff); selection.Collapse(true); } } public static void ClearBackgroundColor(MshtmlMarkupServices markupServices, MarkupRange selection) { HtmlStyleHelper htmlStyleHelper = new HtmlStyleHelper(markupServices); htmlStyleHelper.SplitInlineTags(selection.Start); htmlStyleHelper.SplitInlineTags(selection.End); IHTMLElement[] elements = selection.GetElements(ElementFilters.CreateTagIdFilter("font"), false); foreach (IHTMLElement element in elements) { element.style.backgroundColor = ""; } // We may now be left with empty font tags, e.g. <font>blah</font>. // After switching between editors this becomes <font size="+0">blah</font>, which // causes blah to be rendered differently. // To avoid that we need to remove any empty-attribute font tags. selection.RemoveElementsByTagId(_ELEMENT_TAG_ID.TAGID_FONT, true); } public static void RemoveAttributes(MshtmlMarkupServices markupServices, MarkupRange selection, string[] attributesToRemove) { IHTMLElementFilter[] filters = new IHTMLElementFilter[attributesToRemove.Length]; for (int i = 0; i < attributesToRemove.Length; i++) filters[i] = ElementFilters.CreateElementAttributeFilter(attributesToRemove[i]); IHTMLElement[] elements = selection.GetElements(ElementFilters.CreateCompoundElementFilter(filters), false); foreach (IHTMLElement element in elements) { foreach (string attribute in attributesToRemove) element.removeAttribute(attribute, 0); } } public static IHTMLElement WrapRangeInElement(MshtmlMarkupServices services, MarkupRange range, _ELEMENT_TAG_ID tagId) { return WrapRangeInElement(services, range, tagId, string.Empty); } public static IHTMLElement WrapRangeInElement(MshtmlMarkupServices services, MarkupRange range, _ELEMENT_TAG_ID tagId, string attributes) { IHTMLElement newElement = services.CreateElement(tagId, attributes); services.InsertElement(newElement, range.Start, range.End); return newElement; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using RootMotion; namespace RootMotion.Dynamics { /// <summary> /// The master of puppets. Enables character animation to be played physically in muscle space. /// </summary> [HelpURL("https://www.youtube.com/watch?v=LYusqeqHAUc")] [AddComponentMenu("Scripts/RootMotion.Dynamics/PuppetMaster/Puppet Master")] public partial class PuppetMaster: MonoBehaviour { // Open the User Manual URL [ContextMenu("User Manual (Setup)")] void OpenUserManualSetup() { Application.OpenURL("http://root-motion.com/puppetmasterdox/html/page4.html"); } // Open the User Manual URL [ContextMenu("User Manual (Component)")] void OpenUserManualComponent() { Application.OpenURL("http://root-motion.com/puppetmasterdox/html/page5.html"); } [ContextMenu("User Manual (Performance)")] void OpenUserManualPerformance() { Application.OpenURL("http://root-motion.com/puppetmasterdox/html/page8.html"); } // Open the Script Reference URL [ContextMenu("Scrpt Reference")] void OpenScriptReference() { Application.OpenURL("http://root-motion.com/puppetmasterdox/html/class_root_motion_1_1_dynamics_1_1_puppet_master.html"); } // Open a video tutorial about setting up the component [ContextMenu("TUTORIAL VIDEO (SETUP)")] void OpenSetupTutorial() { Application.OpenURL("https://www.youtube.com/watch?v=mIN9bxJgfOU&index=2&list=PLVxSIA1OaTOuE2SB9NUbckQ9r2hTg4mvL"); } // Open a video tutorial about setting up the component [ContextMenu("TUTORIAL VIDEO (COMPONENT)")] void OpenComponentTutorial() { Application.OpenURL("https://www.youtube.com/watch?v=LYusqeqHAUc"); } /// <summary> /// Active mode means all muscles are active and the character is physically simulated. Kinematic mode sets rigidbody.isKinematic to true for all the muscles and simply updates their position/rotation to match the target's. Disabled mode disables the ragdoll. Switching modes is done by simply changing this value, blending in/out will be handled automatically by the PuppetMaster. /// </summary> [System.Serializable] public enum Mode { Active, Kinematic, Disabled } /// <summary> /// The root Transform of the animated target character. /// </summary> public Transform targetRoot;// { get; private set; } [LargeHeader("Simulation")] [Tooltip("Sets/sets the state of the puppet (Alive, Dead or Frozen). Frozen means the ragdoll will be deactivated once it comes to stop in dead state.")] /// <summary> /// Sets/sets the state of the puppet (Alive, Dead or Frozen) Frozen means the ragdoll will be deactivated once it comes to stop in dead state.. /// </summary> public State state; [ContextMenuItem("Reset To Default", "ResetStateSettings")] [Tooltip("Settings for killing and freezing the puppet.")] /// <summary> /// Settings for killing and freezing the puppet.. /// </summary> public StateSettings stateSettings = StateSettings.Default; void ResetStateSettings() { stateSettings = StateSettings.Default; } [Tooltip("Active mode means all muscles are active and the character is physically simulated. Kinematic mode sets rigidbody.isKinematic to true for all the muscles and simply updates their position/rotation to match the target's. Disabled mode disables the ragdoll. Switching modes is done by simply changing this value, blending in/out will be handled automatically by the PuppetMaster.")] /// <summary> /// Active mode means all muscles are active and the character is physically simulated. Kinematic mode sets rigidbody.isKinematic to true for all the muscles and simply updates their position/rotation to match the target's. Disabled mode disables the ragdoll. Switching modes is done by simply changing this value, blending in/out will be handled automatically by the PuppetMaster. /// </summary> public Mode mode; [Tooltip("The time of blending when switching from Active to Kinematic/Disabled or from Kinematic/Disabled to Active. Switching from Kinematic to Disabled or vice versa will be done instantly.")] /// <summary> /// The time of blending when switching from Active to Kinematic/Disabled or from Kinematic/Disabled to Active. Switching from Kinematic to Disabled or vice versa will be done instantly. /// </summary> public float blendTime = 0.1f; [Tooltip("If true, will fix the target character's Transforms to their default local positions and rotations in each update cycle to avoid drifting from additive reading-writing. Use this only if the target contains unanimated bones.")] /// <summary> /// If true, will fix the target character's Transforms to their default local positions and rotations in each update cycle to avoid drifting from additive reading-writing. Use this only if the target contains unanimated bones. /// </summary> public bool fixTargetTransforms = true; [Tooltip("Rigidbody.solverIterationCount for the muscles of this Puppet.")] /// <summary> /// Rigidbody.solverIterationCount for the muscles of this Puppet. /// </summary> public int solverIterationCount = 6; [Tooltip("If true, will draw the target's pose as green lines in the Scene view. This runs in the Editor only. If you wish to profile PuppetMaster, switch this off.")] /// <summary> /// If true, will draw the target's pose as green lines in the Scene view. This runs in the Editor only. If you wish to profile PuppetMaster, switch this off. /// </summary> public bool visualizeTargetPose = true; [LargeHeader("Master Weights")] [Tooltip("The weight of mapping the animated character to the ragdoll pose.")] /// <summary> /// The weight of mapping the animated character to the ragdoll pose. /// </summary> [Range(0f, 1f)] public float mappingWeight = 1f; [Tooltip("The weight of pinning the muscles to the position of their animated targets using simple AddForce.")] /// <summary> /// The weight of pinning the muscles to the position of their animated targets using simple AddForce. /// </summary> [Range(0f, 1f)] public float pinWeight = 1f; [Tooltip("The normalized strength of the muscles.")] /// <summary> /// The normalized strength of the muscles. /// </summary> [Range(0f, 1f)] public float muscleWeight = 1f; [LargeHeader("Joint and Muscle Settings")] [Tooltip("The positionSpring of the ConfigurableJoints' Slerp Drive.")] /// <summary> /// The positionSpring of the ConfigurableJoints' Slerp Drive. /// </summary> public float muscleSpring = 100f; [Tooltip("The positionDamper of the ConfigurableJoints' Slerp Drive.")] /// <summary> /// The positionDamper of the ConfigurableJoints' Slerp Drive. /// </summary> public float muscleDamper = 0f; [Tooltip("Adjusts the slope of the pinWeight curve. Has effect only while interpolating pinWeight from 0 to 1 and back.")] /// <summary> /// Adjusts the slope of the pinWeight curve. Has effect only while interpolating pinWeight from 0 to 1 and back. /// </summary> [Range(1f, 8f)] public float pinPow = 4f; [Tooltip("Reduces pinning force the farther away the target is. Bigger value loosens the pinning, resulting in sloppier behaviour.")] /// <summary> /// Reduces pinning force the farther away the target is. Bigger value loosens the pinning, resulting in sloppier behaviour. /// </summary> [Range(0f, 100f)] public float pinDistanceFalloff = 5; [Tooltip("When the target has animated bones between the muscle bones, the joint anchors need to be updated in every update cycle because the muscles' targets move relative to each other in position space. This gives much more accurate results, but is computationally expensive so consider leaving it off.")] /// <summary> /// When the target has animated bones between the muscle bones, the joint anchors need to be updated in every update cycle because the muscles' targets move relative to each other in position space. This gives much more accurate results, but is computationally expensive so consider leaving it off. /// </summary> public bool updateJointAnchors = true; [Tooltip("Enable this if any of the target's bones has translation animation.")] /// <summary> /// Enable this if any of the target's bones has translation animation. /// </summary> public bool supportTranslationAnimation; [Tooltip("Should the joints use angular limits? If the PuppetMaster fails to match the target's pose, it might be because the joint limits are too stiff and do not allow for such motion. Uncheck this to see if the limits are clamping the range of your puppet's animation. Since the joints are actuated, most PuppetMaster simulations will not actually require using joint limits at all.")] /// <summary> /// Should the joints use angular limits? If the PuppetMaster fails to match the target's pose, it might be because the joint limits are too stiff and do not allow for such motion. Uncheck this to see if the limits are clamping the range of your puppet's animation. Since the joints are actuated, most PuppetMaster simulations will not actually require using joint limits at all. /// </summary> public bool angularLimits; [Tooltip("Should the muscles collide with each other? Consider leaving this off while the puppet is pinned for performance and better accuracy. Since the joints are actuated, most PuppetMaster simulations will not actually require internal collisions at all.")] /// <summary> /// Should the muscles collide with each other? Consider leaving this off while the puppet is pinned for performance and better accuracy. Since the joints are actuated, most PuppetMaster simulations will not actually require internal collisions at all. /// </summary> public bool internalCollisions; [LargeHeader("Individual Muscle Settings")] [Tooltip("The Muscles managed by this PuppetMaster.")] /// <summary> /// The Muscles managed by this PuppetMaster. /// </summary> public Muscle[] muscles = new Muscle[0]; public delegate void UpdateDelegate(); /// <summary> /// Called after the puppet has initiated. /// </summary> public UpdateDelegate OnPostInitiate; /// <summary> /// Called before (and only if) reading. /// </summary> public UpdateDelegate OnRead; /// <summary> /// Called after (and only if) writing /// </summary> public UpdateDelegate OnWrite; /// <summary> /// Called after each LateUpdate. /// </summary> public UpdateDelegate OnPostLateUpdate; /// <summary> /// Called when it's the right time to fix target transforms. /// </summary> public UpdateDelegate OnFixTransforms; /// <summary> /// Called when the puppet hierarchy has changed by adding/removing muscles /// </summary> public UpdateDelegate OnHierarchyChanged; /// <summary> /// Gets the Animator on the target. /// </summary> public Animator targetAnimator { get { // Protect from the Animator being replaced (UMA) if (_targetAnimator == null) _targetAnimator = targetRoot.GetComponentInChildren<Animator>(); if (_targetAnimator == null && targetRoot.parent != null) _targetAnimator = targetRoot.parent.GetComponentInChildren<Animator>(); return _targetAnimator; } set { _targetAnimator = value; } } private Animator _targetAnimator; /// <summary> /// Gets the Animation component on the target. /// </summary> public Animation targetAnimation { get; private set; } /// <summary> /// Array of all Puppet Behaviours /// </summary> /// <value>The behaviours.</value> public BehaviourBase[] behaviours { get; private set; } // @todo add/remove behaviours in runtime (add OnDestroy to BehaviourBase) /// <summary> /// Returns true if the PuppetMaster is in active mode or blending in/out of it. /// </summary> public bool isActive { get { return isActiveAndEnabled && initiated && (activeMode == Mode.Active || isBlending); }} /// <summary> /// Has this PuppetMaster successfully initiated? /// </summary> public bool initiated { get; private set; } /// <summary> /// The list of solvers that will be updated by this PuppetMaster. When you add a Final-IK component in runtime after PuppetMaster has initiated, add it to this list using solver.Add(SolverManager solverManager). /// </summary> [HideInInspector] public List<SolverManager> solvers = new List<SolverManager>(); /// <summary> /// Normal means Animator is in Normal or Unscaled Time or Animation has Animate Physics unchecked. /// AnimatePhysics is Legacy only, when the Animation component has Animate Physics checked. /// FixedUpdate means Animator is used and in Animate Physics mode. In this case PuppetMaster will take control of updating the Animator in FixedUpdate. /// </summary> [System.Serializable] public enum UpdateMode { Normal, AnimatePhysics, FixedUpdate } /// <summary> /// Gets the current update mode. /// </summary> /// <value>The update mode.</value> public UpdateMode updateMode { get { return targetUpdateMode == AnimatorUpdateMode.AnimatePhysics? (isLegacy? UpdateMode.AnimatePhysics: UpdateMode.FixedUpdate): UpdateMode.Normal; } } /// <summary> /// If the Animator's update mode is "Animate Phyics", PuppetMaster will take control of updating the Animator (in FixedUpdate). This does not happen with Legacy. /// </summary> public bool controlsAnimator { get { return isActiveAndEnabled && isActive && initiated && updateMode == UpdateMode.FixedUpdate; } } /// <summary> /// Is the PuppetMaster currently switching state or mode? /// </summary> public bool isBlending { get { return isSwitchingMode || isSwitchingState; } } #region Update Sequence private bool internalCollisionsEnabled = true; private bool angularLimitsEnabled = true; private bool fixedFrame; private int lastSolverIterationCount; private bool isLegacy; private bool animatorDisabled; private bool awakeFailed; private bool interpolated; private bool freezeFlag; private bool hasBeenDisabled; // If PuppetMaster has been deactivated externally void OnDisable() { if (!gameObject.activeInHierarchy && initiated && Application.isPlaying) { foreach (Muscle m in muscles) m.Reset(); } hasBeenDisabled = true; } // If reactivating a PuppetMaster that has been forcefully deactivated and state/mode switching interrupted void OnEnable() { if (gameObject.activeInHierarchy && initiated && hasBeenDisabled && Application.isPlaying) { // Reset mode isSwitchingMode = false; activeMode = mode; lastMode = mode; mappingBlend = mode == Mode.Active? 1f: 0f; // Reset state activeState = state; lastState = state; isKilling = false; freezeFlag = false; // Animation SetAnimationEnabled(state == State.Alive); if (state == State.Alive && targetAnimator != null) { targetAnimator.Update(0.001f); } // Muscle weights foreach (Muscle m in muscles) { m.state.pinWeightMlp = state == State.Alive? 1f: 0f; m.state.muscleWeightMlp = state == State.Alive? 1f: stateSettings.deadMuscleWeight; m.state.muscleDamperAdd = 0f; m.state.immunity = 0f; } // Ragdoll and behaviours if (state != State.Frozen && mode != Mode.Disabled) { ActivateRagdoll(mode == Mode.Kinematic); foreach (BehaviourBase behaviour in behaviours) { behaviour.gameObject.SetActive(true); } } else { // Deactivate/Freeze foreach (Muscle m in muscles) { m.joint.gameObject.SetActive(false); } // Freeze if (state == State.Frozen) { foreach (BehaviourBase behaviour in behaviours) { if (behaviour.gameObject.activeSelf) { behaviour.deactivated = true; behaviour.gameObject.SetActive(false); } } if (stateSettings.freezePermanently) { if (behaviours.Length > 0 && behaviours[0] != null) { Destroy(behaviours[0].transform.parent.gameObject); } Destroy(gameObject); return; } } } // Reactivate behaviours foreach (BehaviourBase behaviour in behaviours) { behaviour.OnReactivate(); } } } void Awake() { #if UNITY_5_1 Debug.LogError("PuppetMaster requires at least Unity 5.2.2."); awakeFailed = true; return; #endif // Do not initiate when the component has been added in run-time. The muscles have not been set up yet. if (muscles.Length == 0) return; Initiate(); if (!initiated) awakeFailed = true; } void Start() { #if UNITY_EDITOR if (Profiler.enabled && visualizeTargetPose) Debug.Log("Switch 'Visualize Target Pose' off when profiling PuppetMaster.", transform); #endif if (!initiated && !awakeFailed) { Initiate(); } if (!initiated) return; // Find the SolverManagers on the Target hierarchy var solversArray = (SolverManager[])targetRoot.GetComponentsInChildren<SolverManager>(); solvers.AddRange(solversArray); } private Transform FindTargetRootRecursive(Transform t) { if (t.parent == null) return null; foreach (Transform child in t.parent) { if (child == transform) return t; } return FindTargetRootRecursive(t.parent); } private void Initiate() { initiated = false; // Find the target root if (muscles.Length > 0 && muscles[0].target != null && targetRoot == null) targetRoot = FindTargetRootRecursive(muscles[0].target); if (targetRoot != null && targetAnimator == null) { targetAnimator = targetRoot.GetComponentInChildren<Animator>(); targetAnimation = targetRoot.GetComponentInChildren<Animation>(); } // Validation if (!IsValid(true)) return; isLegacy = targetAnimator == null && targetAnimation != null; behaviours = transform.GetComponentsInChildren<BehaviourBase>(); if (behaviours.Length == 0 && transform.parent != null) behaviours = transform.parent.GetComponentsInChildren<BehaviourBase>(); for (int i = 0; i < muscles.Length; i++) { // Initiating the muscles muscles[i].Initiate(muscles); // Collision event broadcasters if (behaviours.Length > 0) { muscles[i].broadcaster = muscles[i].joint.gameObject.AddComponent<MuscleCollisionBroadcaster>(); muscles[i].broadcaster.puppetMaster = this; muscles[i].broadcaster.muscleIndex = i; } } UpdateHierarchies(); initiated = true; // Initiate behaviours foreach (BehaviourBase behaviour in behaviours) { behaviour.Initiate(this); } // Switching states SwitchStates(); // Switching modes SwitchModes(); foreach (Muscle m in muscles) m.Read(); // Mapping StoreTargetMappedState(); if (PuppetMasterSettings.instance != null) { PuppetMasterSettings.instance.Register(this); } if (OnPostInitiate != null) OnPostInitiate(); } void OnDestroy() { if (PuppetMasterSettings.instance != null) { PuppetMasterSettings.instance.Unregister(this); } } private bool IsInterpolated() { if (!initiated) return false; foreach (Muscle m in muscles) { if (m.rigidbody.interpolation != RigidbodyInterpolation.None) return true; } return false; } protected virtual void FixedUpdate() { if (!initiated) return; interpolated = IsInterpolated(); fixedFrame = true; if (!isActive) return; pinWeight = Mathf.Clamp(pinWeight, 0f, 1f); muscleWeight = Mathf.Clamp(muscleWeight, 0f, 1f); muscleSpring = Mathf.Clamp(muscleSpring, 0f, muscleSpring); muscleDamper = Mathf.Clamp(muscleDamper, 0f, muscleDamper); pinPow = Mathf.Clamp(pinPow, 1f, 8f); pinDistanceFalloff = Mathf.Max(pinDistanceFalloff, 0f); // If updating the Animator manually here in FixedUpdate if (updateMode == UpdateMode.FixedUpdate) { FixTargetTransforms(); if (targetAnimator.enabled || (!targetAnimator.enabled && animatorDisabled)) { targetAnimator.enabled = false; animatorDisabled = true; targetAnimator.Update(Time.fixedDeltaTime); } else { animatorDisabled = false; targetAnimator.enabled = false; } foreach (SolverManager solver in solvers) { if (solver != null) solver.UpdateSolverExternal(); } Read(); } if (!isFrozen) { // Update internal collision ignoring SetInternalCollisions(internalCollisions); // Update angular limit ignoring SetAngularLimits(angularLimits); // Update anchors if (isAlive && updateJointAnchors) { // @todo not last animated pose here, but last mapped pose, move this to LateUpdate maybe, remove muscle.targetLocalPosition // @todo might thi be that when Kinematic, joints are under stress for not having their anchors updated and will fly away when the puppet is activated? for (int i = 0; i < muscles.Length; i++) muscles[i].UpdateAnchor(supportTranslationAnimation); } // Set solver iteration count if (solverIterationCount != lastSolverIterationCount) { for (int i = 0; i < muscles.Length; i++) { muscles[i].rigidbody.solverIterationCount = solverIterationCount; } lastSolverIterationCount = solverIterationCount; } // Update Muscles for (int i = 0; i < muscles.Length; i++) { muscles[i].Update(pinWeight, muscleWeight, muscleSpring, muscleDamper, pinPow, pinDistanceFalloff, true); } } // Fix transforms to be sure of not having any drifting when the target bones are not animated if (updateMode == UpdateMode.AnimatePhysics) FixTargetTransforms(); } protected virtual void Update() { if (!initiated) return; if (animatorDisabled) { targetAnimator.enabled = true; animatorDisabled = false; } if (updateMode != UpdateMode.Normal) return; // Fix transforms to be sure of not having any drifting when the target bones are not animated FixTargetTransforms(); } protected virtual void LateUpdate() { OnLateUpdate(); if (OnPostLateUpdate != null) OnPostLateUpdate(); } protected virtual void OnLateUpdate() { if (!initiated) return; if (animatorDisabled) { targetAnimator.enabled = true; animatorDisabled = false; } // Switching states SwitchStates(); // Switching modes SwitchModes(); // Update modes switch(updateMode) { case UpdateMode.FixedUpdate: if (!fixedFrame && !interpolated) return; break; case UpdateMode.AnimatePhysics: if (!fixedFrame && !interpolated) return; if (isActive && !fixedFrame) Read(); break; case UpdateMode.Normal: if (isActive) Read(); break; } // Below is common code for all update modes! For AnimatePhysics modes the following code will run only in fixed frames fixedFrame = false; // Mapping if (!isFrozen) { mappingWeight = Mathf.Clamp(mappingWeight, 0f, 1f); float mW = mappingWeight * mappingBlend; if (mW > 0f) { if (isActive) { for (int i = 0; i < muscles.Length; i++) muscles[i].Map(mW); } } else { // Moving to Target when in Kinematic mode if (activeMode == Mode.Kinematic) MoveToTarget(); } foreach (BehaviourBase behaviour in behaviours) behaviour.OnWrite(); if (OnWrite != null) OnWrite(); StoreTargetMappedState(); //@todo no need to do this all the time } // Freezing if (freezeFlag) OnFreezeFlag(); } // Moves the muscles to where their targets are. private void MoveToTarget() { if (PuppetMasterSettings.instance == null || (PuppetMasterSettings.instance != null && PuppetMasterSettings.instance.UpdateMoveToTarget(this))) { foreach (Muscle m in muscles) { m.MoveToTarget(); } } } // Read the current animated target pose private void Read() { if (OnRead != null) OnRead(); foreach (BehaviourBase behaviour in behaviours) behaviour.OnRead(); if (!isAlive) return; #if UNITY_EDITOR VisualizeTargetPose(); #endif foreach (Muscle m in muscles) m.Read(); } // Fix transforms to be sure of not having any drifting when the target bones are not animated private void FixTargetTransforms() { if (!isAlive) return; if (OnFixTransforms != null) OnFixTransforms(); foreach (BehaviourBase behaviour in behaviours) behaviour.OnFixTransforms(); if (!fixTargetTransforms && !hasProp) return; if (!isActive) return; mappingWeight = Mathf.Clamp(mappingWeight, 0f, 1f); float mW = mappingWeight * mappingBlend; if (mW <= 0f) return; for (int i = 0; i < muscles.Length; i++) { if (fixTargetTransforms || muscles[i].props.group == Muscle.Group.Prop) { muscles[i].FixTargetTransforms(); } } } // Which update mode is the target's Animator/Animation using? private AnimatorUpdateMode targetUpdateMode { get { if (targetAnimator != null) return targetAnimator.updateMode; if (targetAnimation != null) return targetAnimation.animatePhysics? AnimatorUpdateMode.AnimatePhysics: AnimatorUpdateMode.Normal; return AnimatorUpdateMode.Normal; } } #endregion Update Sequence // Visualizes the target pose exactly as it is read by the PuppetMaster private void VisualizeTargetPose() { if (!visualizeTargetPose) return; if (!Application.isEditor) return; if (!isActive) return; foreach (Muscle m in muscles) { if (m.joint.connectedBody != null && m.connectedBodyTarget != null) { Debug.DrawLine(m.target.position, m.connectedBodyTarget.position, Color.cyan); bool isEndMuscle = true; foreach (Muscle m2 in muscles) { if (m != m2 && m2.joint.connectedBody == m.rigidbody) { isEndMuscle = false; break; } } if (isEndMuscle) VisualizeHierarchy(m.target, Color.cyan); } } } // Recursively visualizes a bone hierarchy private void VisualizeHierarchy(Transform t, Color color) { for (int i = 0; i < t.childCount; i++) { Debug.DrawLine(t.position, t.GetChild(i).position, color); VisualizeHierarchy(t.GetChild(i), color); } } // Update internal collision ignoring private void SetInternalCollisions(bool collide) { if (internalCollisionsEnabled == collide) return; for (int i = 0; i < muscles.Length; i++) { for (int i2 = i; i2 < muscles.Length; i2++) { if (i != i2) { muscles[i].IgnoreCollisions(muscles[i2], !collide); } } } internalCollisionsEnabled = collide; } // Update angular limit ignoring private void SetAngularLimits(bool limited) { if (angularLimitsEnabled == limited) return; for (int i = 0; i < muscles.Length; i++) { muscles[i].IgnoreAngularLimits(!limited); } angularLimitsEnabled = limited; } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- extern alias MicrosoftAzureCommandsResources; using Microsoft.Azure.Commands.Common.Authentication.Abstractions; using Microsoft.Azure.Commands.Sql.ServerActiveDirectoryAdministrator.Model; using Microsoft.Azure.Commands.Sql.Services; using Microsoft.Azure.Management.Sql.LegacySdk.Models; using MicrosoftAzureCommandsResources::Microsoft.Azure.Commands.Resources.Models.ActiveDirectory; using System; using System.Collections.Generic; using System.Linq; namespace Microsoft.Azure.Commands.Sql.ServerActiveDirectoryAdministrator.Services { /// <summary> /// Adapter for Azure SQL Server Active Directory administrator operations /// </summary> public class AzureSqlServerActiveDirectoryAdministratorAdapter { /// <summary> /// Gets or sets the AzureSqlServerActiveDirectoryAdministratorCommunicator which has all the needed management clients /// </summary> private AzureSqlServerActiveDirectoryAdministratorCommunicator Communicator { get; set; } /// <summary> /// Gets or sets the Azure profile /// </summary> public IAzureContext Context { get; set; } /// <summary> /// Gets or sets the Azure Subscription /// </summary> private IAzureSubscription _subscription { get; set; } /// <summary> /// A private instance of ActiveDirectoryClient /// </summary> private ActiveDirectoryClient _activeDirectoryClient; /// <summary> /// Gets or sets the Azure ActiveDirectoryClient instance /// </summary> public ActiveDirectoryClient ActiveDirectoryClient { get { if (_activeDirectoryClient == null) { _activeDirectoryClient = new ActiveDirectoryClient(Context); if (!Context.Environment.IsEndpointSet(AzureEnvironment.Endpoint.Graph)) { throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.InvalidGraphEndpoint)); } _activeDirectoryClient = new ActiveDirectoryClient(Context); } return this._activeDirectoryClient; } set { this._activeDirectoryClient = value; } } /// <summary> /// Constructs a Azure SQL Server Active Directory administrator adapter /// </summary> /// <param name="profile">The current azure profile</param> /// <param name="subscription">The current azure subscription</param> public AzureSqlServerActiveDirectoryAdministratorAdapter(IAzureContext context) { Context = context; _subscription = context.Subscription; Communicator = new AzureSqlServerActiveDirectoryAdministratorCommunicator(Context); } /// <summary> /// Gets an Azure SQL Server Active Directory administrator by name. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure SQL Server that contains the Azure Active Directory administrator</param> /// <returns>The Azure Sql ServerActiveDirectoryAdministrator object</returns> internal AzureSqlServerActiveDirectoryAdministratorModel GetServerActiveDirectoryAdministrator(string resourceGroupName, string serverName) { var resp = Communicator.Get(resourceGroupName, serverName); return CreateServerActiveDirectoryAdministratorModelFromResponse(resourceGroupName, serverName, resp); } /// <summary> /// Gets a list of Azure SQL Server Active Directory administrators. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure SQL Server that contains the Azure Active Directory administrator</param> /// <returns>A list of Azure SQL Server Active Directory administrators objects</returns> internal ICollection<AzureSqlServerActiveDirectoryAdministratorModel> ListServerActiveDirectoryAdministrators(string resourceGroupName, string serverName) { var resp = Communicator.List(resourceGroupName, serverName); return resp.Select((activeDirectoryAdmin) => { return CreateServerActiveDirectoryAdministratorModelFromResponse(resourceGroupName, serverName, activeDirectoryAdmin); }).ToList(); } /// <summary> /// Creates or updates an Azure SQL Server Active Directory administrator. /// </summary> /// <param name="resourceGroup">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql ServerActiveDirectoryAdministrator Server</param> /// <param name="model">The input parameters for the create/update operation</param> /// <returns>The upserted Azure SQL Server Active Directory administrator</returns> internal AzureSqlServerActiveDirectoryAdministratorModel UpsertServerActiveDirectoryAdministrator(string resourceGroup, string serverName, AzureSqlServerActiveDirectoryAdministratorModel model) { var resp = Communicator.CreateOrUpdate(resourceGroup, serverName, new ServerAdministratorCreateOrUpdateParameters() { Properties = GetActiveDirectoryInformation(model.DisplayName, model.ObjectId) }); return CreateServerActiveDirectoryAdministratorModelFromResponse(resourceGroup, serverName, resp); } /// <summary> /// Deletes a Azure SQL Server Active Directory administrator /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql ServerActiveDirectoryAdministrator Server</param> public void RemoveServerActiveDirectoryAdministrator(string resourceGroupName, string serverName) { Communicator.Remove(resourceGroupName, serverName); } /// <summary> /// Converts the response from the service to a powershell database object /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql ServerActiveDirectoryAdministrator Server</param> /// <param name="admin">The service response</param> /// <returns>The converted model</returns> public static AzureSqlServerActiveDirectoryAdministratorModel CreateServerActiveDirectoryAdministratorModelFromResponse(string resourceGroup, string serverName, Management.Sql.LegacySdk.Models.ServerAdministrator admin) { AzureSqlServerActiveDirectoryAdministratorModel model = new AzureSqlServerActiveDirectoryAdministratorModel(); model.ResourceGroupName = resourceGroup; model.ServerName = serverName; model.DisplayName = admin.Properties.Login; model.ObjectId = admin.Properties.Sid; return model; } /// <summary> /// Verifies that the Azure Active Directory user or group exists, and will get the object id if it is not set. /// </summary> /// <param name="displayName">Azure Active Directory user or group display name</param> /// <param name="objectId">Azure Active Directory user or group object id</param> /// <returns></returns> protected ServerAdministratorCreateOrUpdateProperties GetActiveDirectoryInformation(string displayName, Guid objectId) { // Gets the default Tenant id for the subscriptions Guid tenantId = GetTenantId(); // Check for a Azure Active Directory group. Recommended to always use group. IEnumerable<PSADGroup> groupList = null; var filter = new ADObjectFilterOptions() { Id = (objectId != null && objectId != Guid.Empty) ? objectId.ToString() : null, SearchString = displayName, Paging = true, }; // Get a list of groups from Azure Active Directory groupList = ActiveDirectoryClient.FilterGroups(filter).Where(gr => string.Equals(gr.DisplayName, displayName, StringComparison.OrdinalIgnoreCase)); if (groupList.Count() > 1) { // More than one group was found with that display name. throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.ADGroupMoreThanOneFound, displayName)); } else if (groupList.Count() == 1) { // Only one group was found. Get the group display name and object id var group = groupList.First(); // Only support Security Groups if (group.SecurityEnabled.HasValue && !group.SecurityEnabled.Value) { throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.InvalidADGroupNotSecurity, displayName)); } return new ServerAdministratorCreateOrUpdateProperties() { Login = group.DisplayName, Sid = group.Id, TenantId = tenantId, }; } // No group was found. Check for a user filter = new ADObjectFilterOptions() { Id = (objectId != null && objectId != Guid.Empty) ? objectId.ToString() : null, SearchString = displayName, Paging = true, }; // Get a list of user from Azure Active Directory var userList = ActiveDirectoryClient.FilterUsers(filter).Where(gr => string.Equals(gr.DisplayName, displayName, StringComparison.OrdinalIgnoreCase)); // No user was found. Check if the display name is a UPN if (userList == null || userList.Count() == 0) { // Check if the display name is the UPN filter = new ADObjectFilterOptions() { Id = (objectId != null && objectId != Guid.Empty) ? objectId.ToString() : null, UPN = displayName, Paging = true, }; userList = ActiveDirectoryClient.FilterUsers(filter).Where(gr => string.Equals(gr.UserPrincipalName, displayName, StringComparison.OrdinalIgnoreCase)); } // No user was found if (userList == null || userList.Count() == 0) { throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.ADObjectNotFound, displayName)); } else if (userList.Count() > 1) { // More than one user was found. throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.ADUserMoreThanOneFound, displayName)); } else { // Only one user was found. Get the user display name and object id var obj = userList.First(); return new ServerAdministratorCreateOrUpdateProperties() { Login = displayName, Sid = obj.Id, TenantId = tenantId, }; } } /// <summary> /// Get the default tenantId for the current subscription /// </summary> /// <returns></returns> protected Guid GetTenantId() { var tenantIdStr = Context.Tenant.Id.ToString(); string adTenant = Context.Environment.GetEndpoint(AzureEnvironment.Endpoint.AdTenant); string graph = Context.Environment.GetEndpoint(AzureEnvironment.Endpoint.Graph); var tenantIdGuid = Guid.Empty; if (string.IsNullOrWhiteSpace(tenantIdStr) || !Guid.TryParse(tenantIdStr, out tenantIdGuid)) { throw new InvalidOperationException(Microsoft.Azure.Commands.Sql.Properties.Resources.InvalidTenantId); } return tenantIdGuid; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Drawing; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.Xml; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using umbraco.cms.businesslogic.Files; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Services; namespace Umbraco.Web.PropertyEditors { [PropertyEditor(Constants.PropertyEditors.UploadFieldAlias, "File upload", "fileupload", Icon = "icon-download-alt", Group = "media")] public class FileUploadPropertyEditor : PropertyEditor { /// <summary> /// We're going to bind to the MediaService Saving event so that we can populate the umbracoFile size, type, etc... label fields /// if we find any attached to the current media item. /// </summary> /// <remarks> /// I think this kind of logic belongs on this property editor, I guess it could exist elsewhere but it all has to do with the upload field. /// </remarks> static FileUploadPropertyEditor() { MediaService.Saving += MediaServiceSaving; MediaService.Created += MediaServiceCreating; ContentService.Copied += ContentServiceCopied; MediaService.Deleted += (sender, args) => args.MediaFilesToDelete.AddRange(ServiceDeleted(args.DeletedEntities.Cast<ContentBase>())); MediaService.EmptiedRecycleBin += (sender, args) => args.Files.AddRange(ServiceEmptiedRecycleBin(args.AllPropertyData)); ContentService.Deleted += (sender, args) => args.MediaFilesToDelete.AddRange(ServiceDeleted(args.DeletedEntities.Cast<ContentBase>())); ContentService.EmptiedRecycleBin += (sender, args) => args.Files.AddRange(ServiceEmptiedRecycleBin(args.AllPropertyData)); MemberService.Deleted += (sender, args) => args.MediaFilesToDelete.AddRange(ServiceDeleted(args.DeletedEntities.Cast<ContentBase>())); } /// <summary> /// Creates our custom value editor /// </summary> /// <returns></returns> protected override PropertyValueEditor CreateValueEditor() { var baseEditor = base.CreateValueEditor(); baseEditor.Validators.Add(new UploadFileTypeValidator()); return new FileUploadPropertyValueEditor(baseEditor); } protected override PreValueEditor CreatePreValueEditor() { return new FileUploadPreValueEditor(); } /// <summary> /// Ensures any files associated are removed /// </summary> /// <param name="allPropertyData"></param> static IEnumerable<string> ServiceEmptiedRecycleBin(Dictionary<int, IEnumerable<Property>> allPropertyData) { var list = new List<string>(); //Get all values for any image croppers found foreach (var uploadVal in allPropertyData .SelectMany(x => x.Value) .Where(x => x.PropertyType.PropertyEditorAlias == Constants.PropertyEditors.UploadFieldAlias) .Select(x => x.Value) .WhereNotNull()) { if (uploadVal.ToString().IsNullOrWhiteSpace() == false) { list.Add(uploadVal.ToString()); } } return list; } /// <summary> /// Ensures any files associated are removed /// </summary> /// <param name="deletedEntities"></param> static IEnumerable<string> ServiceDeleted(IEnumerable<ContentBase> deletedEntities) { var list = new List<string>(); foreach (var property in deletedEntities.SelectMany(deletedEntity => deletedEntity .Properties .Where(x => x.PropertyType.PropertyEditorAlias == Constants.PropertyEditors.UploadFieldAlias && x.Value != null && string.IsNullOrEmpty(x.Value.ToString()) == false))) { if (property.Value != null && property.Value.ToString().IsNullOrWhiteSpace() == false) { list.Add(property.Value.ToString()); } } return list; } /// <summary> /// After the content is copied we need to check if there are files that also need to be copied /// </summary> /// <param name="sender"></param> /// <param name="e"></param> static void ContentServiceCopied(IContentService sender, Core.Events.CopyEventArgs<IContent> e) { if (e.Original.Properties.Any(x => x.PropertyType.PropertyEditorAlias == Constants.PropertyEditors.UploadFieldAlias)) { bool isUpdated = false; var fs = FileSystemProviderManager.Current.GetFileSystemProvider<MediaFileSystem>(); //Loop through properties to check if the content contains media that should be deleted foreach (var property in e.Original.Properties.Where(x => x.PropertyType.PropertyEditorAlias == Constants.PropertyEditors.UploadFieldAlias && x.Value != null && string.IsNullOrEmpty(x.Value.ToString()) == false)) { if (fs.FileExists(fs.GetRelativePath(property.Value.ToString()))) { var currentPath = fs.GetRelativePath(property.Value.ToString()); var propertyId = e.Copy.Properties.First(x => x.Alias == property.Alias).Id; var newPath = fs.GetRelativePath(propertyId, System.IO.Path.GetFileName(currentPath)); fs.CopyFile(currentPath, newPath); e.Copy.SetValue(property.Alias, fs.GetUrl(newPath)); //Copy thumbnails foreach (var thumbPath in fs.GetThumbnails(currentPath)) { var newThumbPath = fs.GetRelativePath(propertyId, System.IO.Path.GetFileName(thumbPath)); fs.CopyFile(thumbPath, newThumbPath); } isUpdated = true; } } if (isUpdated) { //need to re-save the copy with the updated path value sender.Save(e.Copy); } } } static void MediaServiceCreating(IMediaService sender, Core.Events.NewEventArgs<IMedia> e) { AutoFillProperties(e.Entity); } static void MediaServiceSaving(IMediaService sender, Core.Events.SaveEventArgs<IMedia> e) { foreach (var m in e.SavedEntities) { AutoFillProperties(m); } } static void AutoFillProperties(IContentBase model) { foreach (var p in model.Properties.Where(x => x.PropertyType.PropertyEditorAlias == Constants.PropertyEditors.UploadFieldAlias)) { var uploadFieldConfigNode = UmbracoConfig.For.UmbracoSettings().Content.ImageAutoFillProperties .FirstOrDefault(x => x.Alias == p.Alias); if (uploadFieldConfigNode != null) { model.PopulateFileMetaDataProperties(uploadFieldConfigNode, p.Value == null ? string.Empty : p.Value.ToString()); } } } /// <summary> /// A custom pre-val editor to ensure that the data is stored how the legacy data was stored in /// </summary> internal class FileUploadPreValueEditor : ValueListPreValueEditor { public FileUploadPreValueEditor() : base() { var field = Fields.First(); field.Description = "Enter a max width/height for each thumbnail"; field.Name = "Add thumbnail size"; //need to have some custom validation happening here field.Validators.Add(new ThumbnailListValidator()); } /// <summary> /// Format the persisted value to work with our multi-val editor. /// </summary> /// <param name="defaultPreVals"></param> /// <param name="persistedPreVals"></param> /// <returns></returns> public override IDictionary<string, object> ConvertDbToEditor(IDictionary<string, object> defaultPreVals, PreValueCollection persistedPreVals) { var result = new List<PreValue>(); //the pre-values just take up one field with a semi-colon delimiter so we'll just parse var dictionary = persistedPreVals.FormatAsDictionary(); if (dictionary.Any()) { //there should only be one val var delimited = dictionary.First().Value.Value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); for (var index = 0; index < delimited.Length; index++) { result.Add(new PreValue(index, delimited[index])); } } //the items list will be a dictionary of it's id -> value we need to use the id for persistence for backwards compatibility return new Dictionary<string, object> { { "items", result.ToDictionary(x => x.Id, x => PreValueAsDictionary(x)) } }; } private IDictionary<string, object> PreValueAsDictionary(PreValue preValue) { return new Dictionary<string, object> { { "value", preValue.Value }, { "sortOrder", preValue.SortOrder } }; } /// <summary> /// Take the posted values and convert them to a semi-colon separated list so that its backwards compatible /// </summary> /// <param name="editorValue"></param> /// <param name="currentValue"></param> /// <returns></returns> public override IDictionary<string, PreValue> ConvertEditorToDb(IDictionary<string, object> editorValue, PreValueCollection currentValue) { var result = base.ConvertEditorToDb(editorValue, currentValue); //this should just be a dictionary of values, we want to re-format this so that it is just one value in the dictionary that is // semi-colon delimited var values = result.Select(item => item.Value.Value).ToList(); result.Clear(); result.Add("thumbs", new PreValue(string.Join(";", values))); return result; } internal class ThumbnailListValidator : IPropertyValidator { public IEnumerable<ValidationResult> Validate(object value, PreValueCollection preValues, PropertyEditor editor) { var json = value as JArray; if (json == null) yield break; //validate each item which is a json object for (var index = 0; index < json.Count; index++) { var i = json[index]; var jItem = i as JObject; if (jItem == null || jItem["value"] == null) continue; //NOTE: we will be removing empty values when persisting so no need to validate var asString = jItem["value"].ToString(); if (asString.IsNullOrWhiteSpace()) continue; int parsed; if (int.TryParse(asString, out parsed) == false) { yield return new ValidationResult("The value " + asString + " is not a valid number", new[] { //we'll make the server field the index number of the value so it can be wired up to the view "item_" + index.ToInvariantString() }); } } } } } } }
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange (mailto:Stefan.Lange@pdfsharp.com) // // Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.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.Collections.Generic; using System.Diagnostics; using System.Collections; using System.Text; using System.IO; using PdfSharp.Internal; using PdfSharp.Pdf.Advanced; using PdfSharp.Pdf.IO; namespace PdfSharp.Pdf { /// <summary> /// Represents a PDF array object. /// </summary> [DebuggerDisplay("(elements={Elements.Count})")] public class PdfArray : PdfObject, IEnumerable<PdfItem> { ArrayElements elements; /// <summary> /// Initializes a new instance of the <see cref="PdfArray"/> class. /// </summary> public PdfArray() { } /// <summary> /// Initializes a new instance of the <see cref="PdfArray"/> class. /// </summary> /// <param name="document">The document.</param> public PdfArray(PdfDocument document) : base(document) { } /// <summary> /// Initializes a new instance of the <see cref="PdfArray"/> class. /// </summary> /// <param name="document">The document.</param> /// <param name="items">The items.</param> public PdfArray(PdfDocument document, params PdfItem[] items) : base(document) { foreach (PdfItem item in items) Elements.Add(item); } /// <summary> /// Initializes a new instance from an existing dictionary. Used for object type transformation. /// </summary> /// <param name="array">The array.</param> protected PdfArray(PdfArray array) : base(array) { if (array.elements != null) array.elements.SetOwner(this); } /// <summary> /// Creates a copy of this array. Direct elements are deep copied. Indirect references are not /// modified. /// </summary> public new PdfArray Clone() { return (PdfArray)Copy(); } /// <summary> /// Implements the copy mechanism. /// </summary> protected override object Copy() { PdfArray array = (PdfArray)base.Copy(); if (array.elements != null) { array.elements = array.elements.Clone(); int count = array.elements.Count; for (int idx = 0; idx < count; idx++) { PdfItem item = array.elements[idx]; if (item is PdfObject) array.elements[idx] = item.Clone(); } } return array; } /// <summary> /// Gets the collection containing the elements of this object. /// </summary> public ArrayElements Elements { get { if (this.elements == null) this.elements = new ArrayElements(this); return this.elements; } } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> public virtual IEnumerator<PdfItem> GetEnumerator() { return Elements.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Returns a string with the content of this object in a readable form. Useful for debugging purposes only. /// </summary> public override string ToString() { StringBuilder pdf = new StringBuilder(); pdf.Append("[ "); int count = Elements.Count; for (int idx = 0; idx < count; idx++) pdf.Append(Elements[idx].ToString() + " "); pdf.Append("]"); return pdf.ToString(); } internal override void WriteObject(PdfWriter writer) { writer.WriteBeginObject(this); int count = Elements.Count; for (int idx = 0; idx < count; idx++) { PdfItem value = Elements[idx]; value.WriteObject(writer); } writer.WriteEndObject(); } /// <summary> /// Represents the elements of an PdfArray. /// </summary> public sealed class ArrayElements : IList<PdfItem>, ICloneable { List<PdfItem> elements; PdfArray owner; internal ArrayElements(PdfArray array) { this.elements = new List<PdfItem>(); this.owner = array; } object ICloneable.Clone() { ArrayElements elements = (ArrayElements)MemberwiseClone(); elements.elements = new List<PdfItem>(elements.elements); elements.owner = null; return elements; } /// <summary> /// Creates a shallow copy of this object. /// </summary> public ArrayElements Clone() { return (ArrayElements)((ICloneable)this).Clone(); } /// <summary> /// Moves this instance to another dictionary during object type transformation. /// </summary> internal void SetOwner(PdfArray array) { this.owner = array; array.elements = this; } /// <summary> /// Converts the specified value to boolean. /// If the value not exists, the function returns false. /// If the value is not convertible, the function throws an InvalidCastException. /// If the index is out of range, the function throws an ArgumentOutOfRangeException. /// </summary> public bool GetBoolean(int index) { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", index, PSSR.IndexOutOfRange); object obj = this[index]; if (obj == null) return false; if (obj is PdfBoolean) return ((PdfBoolean)obj).Value; else if (obj is PdfBooleanObject) return ((PdfBooleanObject)obj).Value; throw new InvalidCastException("GetBoolean: Object is not a boolean."); } /// <summary> /// Converts the specified value to integer. /// If the value not exists, the function returns 0. /// If the value is not convertible, the function throws an InvalidCastException. /// If the index is out of range, the function throws an ArgumentOutOfRangeException. /// </summary> public int GetInteger(int index) { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", index, PSSR.IndexOutOfRange); object obj = this[index]; if (obj == null) return 0; if (obj is PdfInteger) return ((PdfInteger)obj).Value; if (obj is PdfIntegerObject) return ((PdfIntegerObject)obj).Value; throw new InvalidCastException("GetInteger: Object is not an integer."); } /// <summary> /// Converts the specified value to double. /// If the value not exists, the function returns 0. /// If the value is not convertible, the function throws an InvalidCastException. /// If the index is out of range, the function throws an ArgumentOutOfRangeException. /// </summary> public double GetReal(int index) { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", index, PSSR.IndexOutOfRange); object obj = this[index]; if (obj == null) return 0; if (obj is PdfReal) return ((PdfReal)obj).Value; else if (obj is PdfRealObject) return ((PdfRealObject)obj).Value; else if (obj is PdfInteger) return ((PdfInteger)obj).Value; else if (obj is PdfIntegerObject) return ((PdfIntegerObject)obj).Value; throw new InvalidCastException("GetReal: Object is not a number."); } /// <summary> /// Converts the specified value to string. /// If the value not exists, the function returns the empty string. /// If the value is not convertible, the function throws an InvalidCastException. /// If the index is out of range, the function throws an ArgumentOutOfRangeException. /// </summary> public string GetString(int index) { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", index, PSSR.IndexOutOfRange); object obj = this[index]; if (obj == null) return ""; if (obj is PdfString) return ((PdfString)obj).Value; if (obj is PdfStringObject) return ((PdfStringObject)obj).Value; throw new InvalidCastException("GetString: Object is not an integer."); } /// <summary> /// Converts the specified value to a name. /// If the value not exists, the function returns the empty string. /// If the value is not convertible, the function throws an InvalidCastException. /// If the index is out of range, the function throws an ArgumentOutOfRangeException. /// </summary> public string GetName(int index) { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", index, PSSR.IndexOutOfRange); object obj = this[index]; if (obj == null) return ""; if (obj is PdfName) return ((PdfName)obj).Value; if (obj is PdfNameObject) return ((PdfNameObject)obj).Value; throw new InvalidCastException("GetName: Object is not an integer."); } /// <summary> /// Returns the indirect object if the value at the specified index is a PdfReference. /// </summary> [Obsolete("Use GetObject, GetDictionary, GetArray, or GetReference")] public PdfObject GetIndirectObject(int index) { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", index, PSSR.IndexOutOfRange); PdfItem item = this[index]; if (item is PdfReference) return ((PdfReference)item).Value; return null; } /// <summary> /// Gets the PdfObject with the specified index, or null, if no such object exists. If the index refers to /// a reference, the referenced PdfObject is returned. /// </summary> public PdfObject GetObject(int index) { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", index, PSSR.IndexOutOfRange); PdfItem item = this[index]; if (item is PdfReference) return ((PdfReference)item).Value; return item as PdfObject; } /// <summary> /// Gets the PdfArray with the specified index, or null, if no such object exists. If the index refers to /// a reference, the referenced PdfArray is returned. /// </summary> public PdfDictionary GetDictionary(int index) { return GetObject(index) as PdfDictionary; } /// <summary> /// Gets the PdfArray with the specified index, or null, if no such object exists. If the index refers to /// a reference, the referenced PdfArray is returned. /// </summary> public PdfArray GetArray(int index) { return GetObject(index) as PdfArray; } /// <summary> /// Gets the PdfReference with the specified index, or null, if no such object exists. /// </summary> public PdfReference GetReference(int index) { PdfItem item = this[index]; return item as PdfReference; } /// <summary> /// Gets all items of this array. /// </summary> public PdfItem[] Items { get { return this.elements.ToArray(); } } ///// <summary> ///// INTERNAL USE ONLY. ///// </summary> //public List<PdfItem> GetArrayList_() //{ // // I use this hack to order the pages by ZIP code (MigraDoc ControlCode-Generator) // // TODO: implement a clean solution // return this.elements; //} #region IList Members /// <summary> /// Returns false. /// </summary> public bool IsReadOnly { get { return false; } } //object IList.this[int index] //{ // get { return this.elements[index]; } // set { this.elements[index] = value as PdfItem; } //} /// <summary> /// Gets or sets an item at the specified index. /// </summary> /// <value></value> public PdfItem this[int index] { get { return this.elements[index]; } set { if (value == null) throw new ArgumentNullException("value"); this.elements[index] = value; } } /// <summary> /// Removes the item at the specified index. /// </summary> public void RemoveAt(int index) { this.elements.RemoveAt(index); } /// <summary> /// Removes the first occurrence of a specific object from the array/>. /// </summary> public bool Remove(PdfItem item) { return this.elements.Remove(item); } /// <summary> /// Inserts the item the specified index. /// </summary> public void Insert(int index, PdfItem value) { this.elements.Insert(index, value); } /// <summary> /// Determines whether the specified value is in the array. /// </summary> public bool Contains(PdfItem value) { return this.elements.Contains(value); } /// <summary> /// Removes all items from the array. /// </summary> public void Clear() { this.elements.Clear(); } /// <summary> /// Gets the index of the specified item. /// </summary> public int IndexOf(PdfItem value) { return this.elements.IndexOf(value); } /// <summary> /// Appends the specified object to the array. /// </summary> public void Add(PdfItem value) { // TODO: ??? //Debug.Assert((value is PdfObject && ((PdfObject)value).Reference == null) | !(value is PdfObject), // "You try to set an indirect object directly into an array."); PdfObject obj = value as PdfObject; if (obj != null && obj.IsIndirect) this.elements.Add(obj.Reference); else this.elements.Add(value); } /// <summary> /// Returns false. /// </summary> public bool IsFixedSize { get { return false; } } #endregion #region ICollection Members /// <summary> /// Returns false. /// </summary> public bool IsSynchronized { get { return false; } } /// <summary> /// Gets the number of elements in the array. /// </summary> public int Count { get { return this.elements.Count; } } /// <summary> /// Copies the elements of the array to the specified array. /// </summary> public void CopyTo(PdfItem[] array, int index) { this.elements.CopyTo(array, index); } /// <summary> /// The current implementation return null. /// </summary> public object SyncRoot { get { return null; } } #endregion /// <summary> /// Returns an enumerator that iterates through the array. /// </summary> public IEnumerator<PdfItem> GetEnumerator() { return this.elements.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.elements.GetEnumerator(); } } } }
// Copyright (C) by Housemarque, Inc. namespace Hopac { using Microsoft.FSharp.Core; using System; using System.Runtime.CompilerServices; using System.Threading; using Hopac.Core; /// <summary>Represents a promise to produce a result at some point in the /// future.</summary> public class Promise<T> : Alt<T> { internal T Value; internal volatile int State; internal Cont<T> Readers; internal const int Delayed = 0; internal const int Running = 1; internal const int HasValue = 2; internal const int HasExn = 3; internal const int MakeLocked = 4; // Greater than any state. /// <summary>Creates a promise that will never be fulfilled.</summary> [MethodImpl(AggressiveInlining.Flag)] public Promise() { this.State = Running; } /// <summary>Creates a promise whose value is computed lazily with the given /// job when an attempt is made to read the promise. Although the job is /// not started immediately, the effect is that the delayed job will be run /// as a separate job, which means it is possible to communicate with it as /// long the delayed job is started before trying to communicate with /// it.</summary> [MethodImpl(AggressiveInlining.Flag)] public Promise(Job<T> tJ) { this.Readers = new Fulfill(tJ); } /// <summary>Creates a promise with the given value.</summary> [MethodImpl(AggressiveInlining.Flag)] public Promise(T value) { this.Value = value; this.State = HasValue; } /// <summary>Creates a promise with the given failure exception.</summary> [MethodImpl(AggressiveInlining.Flag)] public Promise(Exception e) { this.Readers = new Fail<T>(e); // We assume failures are infrequent. this.State = HasExn; } /// Internal implementation detail. public bool Full { [MethodImpl(AggressiveInlining.Flag)] get { return HasValue <= State; } } [MethodImpl(AggressiveInlining.Flag)] internal T Get() { if (HasValue == State) return Value; throw (this.Readers as Fail<T>).exn; } [MethodImpl(AggressiveInlining.Flag)] internal void UnsafeAddReader(Cont<T> tK) { WaitQueue.AddTaker(ref this.Readers, tK); } internal override void DoJob(ref Worker wr, Cont<T> aK) { Spin: var state = this.State; Reconsider: if (state > Running) goto Completed; if (state < Delayed) goto Spin; var check = state; state = Interlocked.CompareExchange(ref this.State, state-MakeLocked, state); if (Delayed == state) goto Delayed; if (state != check) goto Reconsider; WaitQueue.AddTaker(ref this.Readers, aK); this.State = Running; return; Delayed: var readers = this.Readers; this.Readers = null; this.State = Running; var fulfill = readers as Fulfill; fulfill.tP = this; fulfill.reader = aK; var tJ = fulfill.tJ; fulfill.tJ = null; Job.Do(tJ, ref wr, fulfill); return; Completed: if (state == HasValue) Cont.Do(aK, ref wr, this.Value); else aK.DoHandle(ref wr, (this.Readers as Fail<T>).exn); } internal override void TryAlt(ref Worker wr, int i, Cont<T> aK, Else aE) { Spin: var state = this.State; Reconsider: if (state > Running) goto Completed; if (state < Delayed) goto Spin; var check = state; state = Interlocked.CompareExchange(ref this.State, state-MakeLocked, state); if (Delayed == state) goto Delayed; if (state != check) goto Reconsider; WaitQueue.AddTaker(ref this.Readers, i, aE.pk, aK); this.State = Running; aE.TryElse(ref wr, i + 1); return; Delayed: var readers = this.Readers; var taker = new Taker<T>(); this.Readers = taker; taker.Next = taker; taker.Pick = aE.pk; taker.Me = i; taker.Cont = aK; this.State = Running; var fulfill = readers as Fulfill; fulfill.tP = this; Worker.PushNew(ref wr, fulfill); aE.TryElse(ref wr, i + i); return; Completed: var pkSelf = aE.pk; TryPick: var stSelf = Pick.TryPick(pkSelf); if (stSelf > 0) goto AlreadyPicked; if (stSelf < 0) goto TryPick; Pick.SetNacks(ref wr, i, pkSelf); if (state == HasValue) Cont.Do(aK, ref wr, this.Value); else aK.DoHandle(ref wr, (this.Readers as Fail<T>).exn); AlreadyPicked: return; } internal sealed class Fulfill : Cont<T> { internal Promise<T> tP; internal Job<T> tJ; private Cont<Unit> procFin; internal Cont<T> reader; internal int me; internal Pick pk; [MethodImpl(AggressiveInlining.Flag)] internal Fulfill(Promise<T> tP) { this.tP = tP; } [MethodImpl(AggressiveInlining.Flag)] internal Fulfill(Job<T> tJ) { this.tJ = tJ; } [MethodImpl(AggressiveInlining.Flag)] internal Fulfill(Promise<T> tP, Job<T> tJ) { this.tP = tP; this.tJ = tJ; } internal override Proc GetProc(ref Worker wr) { return Handler.GetProc(ref wr, ref this.procFin); } [MethodImpl(AggressiveInlining.Flag)] internal void Do(ref Worker wr, T t) { var tP = this.tP; tP.Value = t; Spin: var state = tP.State; if (state != Running) goto Spin; if (Running != Interlocked.CompareExchange(ref tP.State, HasValue, state)) goto Spin; WaitQueue.PickReaders(ref tP.Readers, tP.Value, ref wr); var pk = this.pk; if (null == pk) goto MaybeGotReader; TryPick: var st = Pick.TryPick(pk); if (st > 0) goto Done; if (st < 0) goto TryPick; Pick.SetNacks(ref wr, me, pk); MaybeGotReader: var reader = this.reader; if (null == reader) goto Done; wr.Handler = reader; reader.DoCont(ref wr, tP.Value); Done: return; } internal override void DoWork(ref Worker wr) { var tJ = this.tJ; if (null == tJ) { Do(ref wr, this.Value); } else { this.tJ = null; tJ.DoJob(ref wr, this); } } internal override void DoCont(ref Worker wr, T v) { Do(ref wr, v); } internal override void DoHandle(ref Worker wr, Exception e) { var tP = this.tP as Promise<T>; Spin: var state = tP.State; if (state != Running) goto Spin; if (Running != Interlocked.CompareExchange(ref tP.State, state-MakeLocked, state)) goto Spin; var readers = tP.Readers; tP.Readers = new Fail<T>(e); tP.State = HasExn; WaitQueue.FailReaders(readers, e, ref wr); var reader = this.reader; if (null == reader) return; wr.Handler = reader; reader.DoHandle(ref wr, e); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Xml.Serialization; using System.Reflection; using log4net; using OpenMetaverse; namespace OpenSim.Framework { [Flags] public enum AssetFlags : int { Normal = 0, // Immutable asset Maptile = 1, // What it says Rewritable = 2, // Content can be rewritten Collectable = 4 // Can be GC'ed after some time } /// <summary> /// Asset class. All Assets are reference by this class or a class derived from this class /// </summary> [Serializable] public class AssetBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public static readonly int MAX_ASSET_NAME = 64; public static readonly int MAX_ASSET_DESC = 64; /// <summary> /// Data of the Asset /// </summary> private byte[] m_data; /// <summary> /// Meta Data of the Asset /// </summary> private AssetMetadata m_metadata; private int m_uploadAttempts; // This is needed for .NET serialization!!! // Do NOT "Optimize" away! public AssetBase() { m_metadata = new AssetMetadata(); m_metadata.FullID = UUID.Zero; m_metadata.ID = UUID.Zero.ToString(); m_metadata.Type = (sbyte)AssetType.Unknown; m_metadata.CreatorID = String.Empty; } public AssetBase(UUID assetID, string name, sbyte assetType, string creatorID) { if (assetType == (sbyte)AssetType.Unknown) { System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(true); m_log.ErrorFormat("[ASSETBASE]: Creating asset '{0}' ({1}) with an unknown asset type\n{2}", name, assetID, trace.ToString()); } m_metadata = new AssetMetadata(); m_metadata.FullID = assetID; m_metadata.Name = name; m_metadata.Type = assetType; m_metadata.CreatorID = creatorID; } public AssetBase(string assetID, string name, sbyte assetType, string creatorID) { if (assetType == (sbyte)AssetType.Unknown) { System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(true); m_log.ErrorFormat("[ASSETBASE]: Creating asset '{0}' ({1}) with an unknown asset type\n{2}", name, assetID, trace.ToString()); } m_metadata = new AssetMetadata(); m_metadata.ID = assetID; m_metadata.Name = name; m_metadata.Type = assetType; m_metadata.CreatorID = creatorID; } public bool ContainsReferences { get { return IsTextualAsset && ( Type != (sbyte)AssetType.Notecard && Type != (sbyte)AssetType.CallingCard && Type != (sbyte)AssetType.LSLText && Type != (sbyte)AssetType.Landmark); } } public bool IsTextualAsset { get { return !IsBinaryAsset; } } /// <summary> /// Checks if this asset is a binary or text asset /// </summary> public bool IsBinaryAsset { get { return (Type == (sbyte)AssetType.Animation || Type == (sbyte)AssetType.Gesture || Type == (sbyte)AssetType.Simstate || Type == (sbyte)AssetType.Unknown || Type == (sbyte)AssetType.Object || Type == (sbyte)AssetType.Sound || Type == (sbyte)AssetType.SoundWAV || Type == (sbyte)AssetType.Texture || Type == (sbyte)AssetType.TextureTGA || Type == (sbyte)AssetType.Folder || Type == (sbyte)AssetType.ImageJPEG || Type == (sbyte)AssetType.ImageTGA || Type == (sbyte)AssetType.Mesh || Type == (sbyte) AssetType.LSLBytecode); } } public virtual byte[] Data { get { return m_data; } set { m_data = value; } } /// <summary> /// Asset UUID /// </summary> public UUID FullID { get { return m_metadata.FullID; } set { m_metadata.FullID = value; } } /// <summary> /// Asset MetaData ID (transferring from UUID to string ID) /// </summary> public string ID { get { return m_metadata.ID; } set { m_metadata.ID = value; } } public string Name { get { return m_metadata.Name; } set { m_metadata.Name = value; } } public string Description { get { return m_metadata.Description; } set { m_metadata.Description = value; } } /// <summary> /// (sbyte) AssetType enum /// </summary> public sbyte Type { get { return m_metadata.Type; } set { m_metadata.Type = value; } } public int UploadAttempts { get { return m_uploadAttempts; } set { m_uploadAttempts = value; } } /// <summary> /// Is this a region only asset, or does this exist on the asset server also /// </summary> public bool Local { get { return m_metadata.Local; } set { m_metadata.Local = value; } } /// <summary> /// Is this asset going to be saved to the asset database? /// </summary> public bool Temporary { get { return m_metadata.Temporary; } set { m_metadata.Temporary = value; } } public string CreatorID { get { return m_metadata.CreatorID; } set { m_metadata.CreatorID = value; } } public AssetFlags Flags { get { return m_metadata.Flags; } set { m_metadata.Flags = value; } } [XmlIgnore] public AssetMetadata Metadata { get { return m_metadata; } set { m_metadata = value; } } public override string ToString() { return FullID.ToString(); } } [Serializable] public class AssetMetadata { private UUID m_fullid; private string m_id; private string m_name = String.Empty; private string m_description = String.Empty; private DateTime m_creation_date; private sbyte m_type = (sbyte)AssetType.Unknown; private string m_content_type; private byte[] m_sha1; private bool m_local; private bool m_temporary; private string m_creatorid; private AssetFlags m_flags; public UUID FullID { get { return m_fullid; } set { m_fullid = value; m_id = m_fullid.ToString(); } } public string ID { //get { return m_fullid.ToString(); } //set { m_fullid = new UUID(value); } get { if (String.IsNullOrEmpty(m_id)) m_id = m_fullid.ToString(); return m_id; } set { UUID uuid = UUID.Zero; if (UUID.TryParse(value, out uuid)) { m_fullid = uuid; m_id = m_fullid.ToString(); } else m_id = value; } } public string Name { get { return m_name; } set { m_name = value; } } public string Description { get { return m_description; } set { m_description = value; } } public DateTime CreationDate { get { return m_creation_date; } set { m_creation_date = value; } } public sbyte Type { get { return m_type; } set { m_type = value; } } public string ContentType { get { if (!String.IsNullOrEmpty(m_content_type)) return m_content_type; else return SLUtil.SLAssetTypeToContentType(m_type); } set { m_content_type = value; sbyte type = (sbyte)SLUtil.ContentTypeToSLAssetType(value); if (type != -1) m_type = type; } } public byte[] SHA1 { get { return m_sha1; } set { m_sha1 = value; } } public bool Local { get { return m_local; } set { m_local = value; } } public bool Temporary { get { return m_temporary; } set { m_temporary = value; } } public string CreatorID { get { return m_creatorid; } set { m_creatorid = value; } } public AssetFlags Flags { get { return m_flags; } set { m_flags = value; } } } }
#region Licenses /*MIT License Copyright(c) 2018 Robert Garrison 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 #region Using Statements using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; #if !NET20 && !NET35 && !NET40 using System.Threading.Tasks; #endif using System.Xml; #endregion namespace ADONetHelper.SqlServer { /// <summary> /// A specialized instance of <see cref="DbClient"/> that is used to query a SQL Server database system /// </summary> /// <seealso cref="DbClient"/> /// <seealso cref="IXMLExecutor"/> public sealed class SqlServerClient : DbClient, IXMLExecutor { #region Fields/Properties /// <summary> /// An instance of <see cref="SqlConnection"/> /// </summary> /// <returns>Returns an instance of <see cref="SqlConnection"/></returns> private SqlConnection Connection { get { //Return this back to the caller return (SqlConnection)this.ExecuteSQL.Connection; } } /// <summary> /// Enables statistics gathering for the current connection when set to <c>true</c> /// </summary> /// <returns>Returns <c>true</c> if statistics are enabled, <c>false</c> otherwise</returns> public bool StatisticsEnabled { get { //Return this back to the caller return this.Connection.StatisticsEnabled; } set { this.Connection.StatisticsEnabled = value; } } /// <summary> /// The size in bytes of network packets used to communicate with an instance of sql server /// </summary> /// <returns></returns> public int PacketSize { get { //Return this back to the caller return this.Connection.PacketSize; } } /// <summary> /// Gets a string that identifies the database client. /// </summary> /// <returns>Gets a string that identifies the database client.</returns> public string WorkstationID { get { //Return this back to the caller return this.Connection.WorkstationId; } } #if NET46 || NET461 /// <summary> /// Gets or sets the access token for the connection /// </summary> /// <returns>The access token as a <see cref="string"/></returns> public string AccessToken { get { //Return this back to the caller return this.Connection.AccessToken; } set { this.Connection.AccessToken = value; } } #endif #if !NET20 && !NET35 && !NET40 /// <summary> /// The connection ID of the most recent connection attempt, regardless of whether the attempt succeeded or failed. /// </summary> /// <returns>The connection ID of the most recent connection attempt, regardless of whether the attempt succeeded or failed as a <c>string</c></returns> public Guid ClientConnectionID { get { //Return this back to the caller return this.Connection.ClientConnectionId; } } #endif #endregion #region Constructors /// <summary> /// Intializes the <see cref="SqlServerClient"/> with a <see cref="ISqlExecutor"/> /// </summary> /// <param name="executor">An instance of <see cref="ISqlExecutor"/></param> public SqlServerClient(ISqlExecutor executor) : base(executor) { } /// <summary> /// The overloaded constuctor that will initialize the <paramref name="connectionString"/>, And <paramref name="queryCommandType"/> /// </summary> /// <param name="connectionString">The connection string used to query a data store</param> /// <param name="queryCommandType">Represents how a command should be interpreted by the data provider</param> public SqlServerClient(string connectionString, CommandType queryCommandType) : base(connectionString, queryCommandType, SqlClientFactory.Instance) { } /// <summary> /// The overloaded constuctor that will initialize the <paramref name="connectionString"/> /// </summary> /// <param name="connectionString">The connection string used to query a data store</param> public SqlServerClient(string connectionString) : base(connectionString, SqlClientFactory.Instance) { } /// <summary> /// Constructor to query a database using an existing <see cref="SqlConnection"/> to initialize the <paramref name="connection"/> /// </summary> /// <param name="connection">An instance of <see cref="SqlConnection"/> to use to connect to a server and database</param> public SqlServerClient(SqlConnection connection) : base(connection) { } #endregion #region Utility Methods /// <summary> /// Empties the connection pool associated with this instance of <see cref="SqlServerClient"/> <see cref="SqlConnection"/> /// </summary> /// <remarks> /// ClearPool clears the connection pool that is associated with the current <see cref="SqlConnection"/>. If additional connections associated with connection are in use at the time of the call, they are marked appropriately and are discarded (instead of being returned to the pool) when Close is called on them.</remarks> public void ClearPool() { //Clear the current pool SqlConnection.ClearPool(this.Connection); } /// <summary> /// Returns an instance of <see cref="XmlReader"/> based on the <paramref name="query"/> /// </summary> /// <param name="query">The query command text Or name of stored procedure to execute against the data store</param> /// <returns>Returns an instance of <see cref="XmlReader"/> based on the <paramref name="query"/> passed into the routine</returns> public XmlReader ExecuteXMLReader(string query) { //Wrap this in a using statement to automatically dispose of resources using (SqlCommand command = (SqlCommand)this.ExecuteSQL.Factory.GetDbCommand(this.QueryCommandType, query, this.ExecuteSQL.Parameters, this.Connection, this.CommandTimeout)) { try { //Return this back to the caller return command.ExecuteXmlReader(); } finally { command.Parameters.Clear(); } } } #if !NET20 && !NET35 && !NET40 /// <summary> /// Returns an instance of <see cref="XmlReader"/> based on the <paramref name="query"/> /// </summary> /// <param name="query">The query command text Or name of stored procedure to execute against the data store</param> /// <returns>Returns an instance of <see cref="XmlReader"/> based on the <paramref name="query"/> passed into the routine</returns> public async Task<XmlReader> ExecuteXMLReaderAsync(string query) { //Wrap this in a using statement to automatically dispose of resources using (SqlCommand command = (SqlCommand)this.ExecuteSQL.Factory.GetDbCommand(this.QueryCommandType, query, this.ExecuteSQL.Parameters, this.Connection, this.CommandTimeout)) { try { //Return this back to the caller return await command.ExecuteXmlReaderAsync(); } finally { //Clear parameters command.Parameters.Clear(); } } } #endif /// <summary> /// All statistics are set to zero if <see cref="SqlConnection.StatisticsEnabled"/> is <c>true</c> /// </summary> public void ResetStatistics() { this.Connection.ResetStatistics(); } /// <summary> /// Gets an instance of <see cref="SqlBulkCopy"/> based off of the existing <see cref="SqlConnection"/> being used by the instance /// </summary> /// <returns>Returns an instance of <see cref="SqlBulkCopy"/> for the client to configure</returns> public SqlBulkCopy GetSQLBulkCopy() { //Return this back to the caller return new SqlBulkCopy(this.Connection); } /// <summary> /// Gets an instance of <see cref="SqlBulkCopy"/> using the passed in <paramref name="connectionString"/> /// </summary> /// <param name="connectionString">The connection string to connect to the database as a <see cref="string"/></param> /// <returns>Returns an instance of <see cref="SqlBulkCopy"/></returns> public SqlBulkCopy GetSqlBulkCopy(string connectionString) { //Return this back to the caller return new SqlBulkCopy(connectionString); } /// <summary> /// Gets an instance of <see cref="SqlBulkCopy"/> using the passed in <paramref name="connectionString"/> and <paramref name="options"/> /// </summary> /// <param name="connectionString">The connection string to connect to the database as a <see cref="string"/></param> /// <param name="options">The <see cref="SqlBulkCopyOptions"/> to configure the <see cref="SqlBulkCopy"/></param> /// <returns>Returns an instance of <see cref="SqlBulkCopy"/></returns> public SqlBulkCopy GetSqlBulkCopy(string connectionString, SqlBulkCopyOptions options) { //Return this back to the caller return new SqlBulkCopy(connectionString, options); } /// <summary> /// Gets an instance of <see cref="SqlBulkCopy"/> based off of the existing <see cref="SqlConnection"/> being used by the instance /// </summary> /// <param name="options">The <see cref="SqlBulkCopyOptions"/> to configure the <see cref="SqlBulkCopy"/></param> /// <param name="transaction">An instance of <see cref="SqlTransaction"/></param> /// <returns>Returns an instance of <see cref="SqlBulkCopy"/></returns> public SqlBulkCopy GetSQLBulkCopy(SqlBulkCopyOptions options, SqlTransaction transaction) { //Return this back to the caller return new SqlBulkCopy(this.Connection, options, transaction); } /// <summary> /// Returns a name value pair collection of statistics at the point in time the method is called /// </summary> /// <returns>Returns a reference of <see cref="IDictionary{TKey, TValue}"/> of <see cref="DictionaryEntry"/></returns> /// <remarks>When this method is called, the values retrieved are those at the current point in time. /// If you continue using the connection, the values are incorrect. You need to re-execute the method to obtain the most current values. /// </remarks> public IDictionary<string, object> GetConnectionStatisticts() { //Return this back to the caller return (IDictionary<string, object>)this.Connection.RetrieveStatistics(); } #endregion } }
// 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 NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Testing.Dependencies; namespace osu.Framework.Tests.Dependencies { [TestFixture] public class ResolvedAttributeTest { [Test] public void TestInjectIntoNothing() { var receiver = new Receiver1(); createDependencies().Inject(receiver); Assert.AreEqual(null, receiver.Obj); } [Test] public void TestInjectIntoDependency() { var receiver = new Receiver2(); BaseObject testObject; createDependencies(testObject = new BaseObject()).Inject(receiver); Assert.AreEqual(testObject, receiver.Obj); } [Test] public void TestInjectNullIntoNonNull() { var receiver = new Receiver2(); Assert.Throws<DependencyNotRegisteredException>(() => createDependencies().Inject(receiver)); } [Test] public void TestInjectNullIntoNullable() { var receiver = new Receiver3(); Assert.DoesNotThrow(() => createDependencies().Inject(receiver)); } [Test] public void TestInjectIntoSubClasses() { var receiver = new Receiver4(); BaseObject testObject; createDependencies(testObject = new BaseObject()).Inject(receiver); Assert.AreEqual(testObject, receiver.Obj); Assert.AreEqual(testObject, receiver.Obj2); } [Test] public void TestInvalidPublicAccessor() { var receiver = new Receiver5(); Assert.Throws<AccessModifierNotAllowedForPropertySetterException>(() => createDependencies().Inject(receiver)); } [Test] public void TestInvalidExplicitProtectedAccessor() { var receiver = new Receiver6(); Assert.Throws<AccessModifierNotAllowedForPropertySetterException>(() => createDependencies().Inject(receiver)); } [Test] public void TestInvalidExplicitPrivateAccessor() { var receiver = new Receiver7(); Assert.Throws<AccessModifierNotAllowedForPropertySetterException>(() => createDependencies().Inject(receiver)); } [Test] public void TestExplicitPrivateAccessor() { var receiver = new Receiver8(); Assert.DoesNotThrow(() => createDependencies().Inject(receiver)); } [Test] public void TestExplicitInvalidProtectedInternalAccessor() { var receiver = new Receiver9(); Assert.Throws<AccessModifierNotAllowedForPropertySetterException>(() => createDependencies().Inject(receiver)); } [Test] public void TestNoSetter() { var receiver = new Receiver10(); Assert.Throws<PropertyNotWritableException>(() => createDependencies().Inject(receiver)); } [Test] public void TestWriteToBaseClassWithPublicProperty() { var receiver = new Receiver11(); BaseObject testObject; var dependencies = createDependencies(testObject = new BaseObject()); Assert.DoesNotThrow(() => dependencies.Inject(receiver)); Assert.AreEqual(testObject, receiver.Obj); } [Test] public void TestResolveInternalStruct() { var receiver = new Receiver12(); var testObject = new CachedStructProvider(); var dependencies = DependencyActivator.MergeDependencies(testObject, new DependencyContainer()); Assert.DoesNotThrow(() => dependencies.Inject(receiver)); Assert.AreEqual(testObject.CachedObject.Value, receiver.Obj.Value); } [TestCase(null)] [TestCase(10)] public void TestResolveNullableInternal(int? testValue) { var receiver = new Receiver13(); var testObject = new CachedNullableProvider(); testObject.SetValue(testValue); var dependencies = DependencyActivator.MergeDependencies(testObject, new DependencyContainer()); dependencies.Inject(receiver); Assert.AreEqual(testValue, receiver.Obj); } [Test] public void TestResolveStructWithoutNullPermits() { Assert.Throws<DependencyNotRegisteredException>(() => new DependencyContainer().Inject(new Receiver14())); } [Test] public void TestResolveStructWithNullPermits() { var receiver = new Receiver15(); Assert.DoesNotThrow(() => new DependencyContainer().Inject(receiver)); Assert.AreEqual(0, receiver.Obj); } [Test] public void TestResolveBindable() { var receiver = new Receiver16(); var bindable = new Bindable<int>(10); var dependencies = createDependencies(bindable); dependencies.CacheAs<IBindable<int>>(bindable); dependencies.Inject(receiver); Assert.AreNotSame(bindable, receiver.Obj); Assert.AreNotSame(bindable, receiver.Obj2); Assert.AreEqual(bindable.Value, receiver.Obj.Value); Assert.AreEqual(bindable.Value, receiver.Obj2.Value); bindable.Value = 5; Assert.AreEqual(bindable.Value, receiver.Obj.Value); Assert.AreEqual(bindable.Value, receiver.Obj2.Value); } private DependencyContainer createDependencies(params object[] toCache) { var dependencies = new DependencyContainer(); toCache?.ForEach(o => dependencies.Cache(o)); return dependencies; } private class BaseObject { } private class Receiver1 { #pragma warning disable 649, IDE0032 private BaseObject obj; #pragma warning restore 649, IDE0032 // ReSharper disable once ConvertToAutoProperty public BaseObject Obj => obj; } private class Receiver2 { [Resolved] private BaseObject obj { get; set; } public BaseObject Obj => obj; } private class Receiver3 { [Resolved(CanBeNull = true)] private BaseObject obj { get; set; } } private class Receiver4 : Receiver2 { [Resolved] private BaseObject obj { get; set; } public BaseObject Obj2 => obj; } private class Receiver5 { [Resolved(CanBeNull = true)] public BaseObject Obj { get; set; } } private class Receiver6 { [Resolved(CanBeNull = true)] public BaseObject Obj { get; protected set; } } private class Receiver7 { [Resolved(CanBeNull = true)] public BaseObject Obj { get; internal set; } } private class Receiver8 { [Resolved(CanBeNull = true)] public BaseObject Obj { get; private set; } } private class Receiver9 { [Resolved(CanBeNull = true)] public BaseObject Obj { get; protected internal set; } } private class Receiver10 { [Resolved(CanBeNull = true)] public BaseObject Obj { get; } } private class Receiver11 : Receiver8 { } private class Receiver12 { [Resolved] public CachedStructProvider.Struct Obj { get; private set; } } private class Receiver13 { [Resolved] public int? Obj { get; private set; } } private class Receiver14 { [Resolved] public int Obj { get; private set; } } private class Receiver15 { [Resolved(CanBeNull = true)] public int Obj { get; private set; } = 1; } private class Receiver16 { [Resolved] public Bindable<int> Obj { get; private set; } [Resolved] public IBindable<int> Obj2 { get; private set; } } } }
//------------------------------------------------------------------------------ // <copyright file="DiagnosticsConfiguration.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ #if CONFIGURATION_DEP namespace System.Diagnostics { using System; using System.Reflection; using System.Collections; using System.Configuration; using System.Threading; using System.Runtime.Versioning; internal enum InitState { NotInitialized, Initializing, Initialized } internal static class DiagnosticsConfiguration { private static volatile SystemDiagnosticsSection configSection; private static volatile InitState initState = InitState.NotInitialized; // setting for Switch.switchSetting internal static SwitchElementsCollection SwitchSettings { get { Initialize(); SystemDiagnosticsSection configSectionSav = configSection; if (configSectionSav != null) return configSectionSav.Switches; else return null; } } // setting for DefaultTraceListener.AssertUIEnabled internal static bool AssertUIEnabled { get { Initialize(); SystemDiagnosticsSection configSectionSav = configSection; if (configSectionSav != null && configSectionSav.Assert != null) return configSectionSav.Assert.AssertUIEnabled; else return true; // the default } } internal static string ConfigFilePath { [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] get { Initialize(); SystemDiagnosticsSection configSectionSav = configSection; if (configSectionSav != null) return configSectionSav.ElementInformation.Source; else return string.Empty; // the default } } // setting for DefaultTraceListener.LogFileName internal static string LogFileName { [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] get { Initialize(); SystemDiagnosticsSection configSectionSav = configSection; if (configSectionSav != null && configSectionSav.Assert != null) return configSectionSav.Assert.LogFileName; else return string.Empty; // the default } } // setting for TraceInternal.AutoFlush internal static bool AutoFlush { get { Initialize(); SystemDiagnosticsSection configSectionSav = configSection; if (configSectionSav != null && configSectionSav.Trace != null) return configSectionSav.Trace.AutoFlush; else return false; // the default } } // setting for TraceInternal.UseGlobalLock internal static bool UseGlobalLock { get { Initialize(); SystemDiagnosticsSection configSectionSav = configSection; if (configSectionSav != null && configSectionSav.Trace != null) return configSectionSav.Trace.UseGlobalLock; else return true; // the default } } // setting for TraceInternal.IndentSize internal static int IndentSize { get { Initialize(); SystemDiagnosticsSection configSectionSav = configSection; if (configSectionSav != null && configSectionSav.Trace != null) return configSectionSav.Trace.IndentSize; else return 4; // the default } } #if !FEATURE_PAL // perfcounter internal static int PerfomanceCountersFileMappingSize { get { for (int retryCount = 0; !CanInitialize() && retryCount <= 5; ++retryCount) { if (retryCount == 5) return SharedPerformanceCounter.DefaultCountersFileMappingSize; System.Threading.Thread.Sleep(200); } Initialize(); SystemDiagnosticsSection configSectionSav = configSection; if (configSectionSav != null && configSectionSav.PerfCounters != null) { int size = configSectionSav.PerfCounters.FileMappingSize; if (size < SharedPerformanceCounter.MinCountersFileMappingSize) size = SharedPerformanceCounter.MinCountersFileMappingSize; if (size > SharedPerformanceCounter.MaxCountersFileMappingSize) size = SharedPerformanceCounter.MaxCountersFileMappingSize; return size; } else return SharedPerformanceCounter.DefaultCountersFileMappingSize; } } #endif // !FEATURE_PAL internal static ListenerElementsCollection SharedListeners { get { Initialize(); SystemDiagnosticsSection configSectionSav = configSection; if (configSectionSav != null) return configSectionSav.SharedListeners; else return null; } } internal static SourceElementsCollection Sources { get { Initialize(); SystemDiagnosticsSection configSectionSav = configSection; if (configSectionSav != null && configSectionSav.Sources != null) return configSectionSav.Sources; else return null; } } internal static SystemDiagnosticsSection SystemDiagnosticsSection { get { Initialize(); return configSection; } } private static SystemDiagnosticsSection GetConfigSection() { SystemDiagnosticsSection configSection = (SystemDiagnosticsSection) PrivilegedConfigurationManager.GetSection("system.diagnostics"); return configSection; } internal static bool IsInitializing() { return initState == InitState.Initializing; } internal static bool IsInitialized() { return initState == InitState.Initialized; } internal static bool CanInitialize() { return (initState != InitState.Initializing) && !ConfigurationManagerInternalFactory.Instance.SetConfigurationSystemInProgress; } internal static void Initialize() { // Initialize() is also called by other components outside of Trace (such as PerformanceCounter) // as a result using one lock for this critical section and another for Trace API critical sections // (such as Trace.WriteLine) could potentially lead to deadlock between 2 threads that are // executing these critical sections (and consequently obtaining the 2 locks) in the reverse order. // Using the same lock for DiagnosticsConfiguration as well as TraceInternal avoids this issue. // Sequential locks on TraceInternal.critSec by the same thread is a non issue for this critical section. lock (TraceInternal.critSec) { // because some of the code used to load config also uses diagnostics // we can't block them while we initialize from config. Therefore we just // return immediately and they just use the default values. if ( initState != InitState.NotInitialized || ConfigurationManagerInternalFactory.Instance.SetConfigurationSystemInProgress) { return; } initState = InitState.Initializing; // used for preventing recursion try { configSection = GetConfigSection(); } finally { initState = InitState.Initialized; } } } internal static void Refresh() { ConfigurationManager.RefreshSection("system.diagnostics"); // There might still be some persistant state left behind for // ConfigPropertyCollection (for ex, swtichelements), probably for perf. // We need to explicitly cleanup any unrecognized attributes that we // have added during last deserialization, so that they are re-added // during the next Config.GetSection properly and we get a chance to // populate the Attributes collection for re-deserialization. // Another alternative could be to expose the properties collection // directly as Attributes collection (currently we keep a local // hashtable which we explicitly need to keep in sycn and hence the // cleanup logic below) but the down side of that would be we need to // explicitly compute what is recognized Vs unrecognized from that // collection when we expose the unrecognized Attributes publically SystemDiagnosticsSection configSectionSav = configSection; if (configSectionSav != null) { if (configSectionSav.Switches != null) { foreach (SwitchElement swelem in configSectionSav.Switches) swelem.ResetProperties(); } if (configSectionSav.SharedListeners != null) { foreach (ListenerElement lnelem in configSectionSav.SharedListeners) lnelem.ResetProperties(); } if (configSectionSav.Sources != null) { foreach (SourceElement srelem in configSectionSav.Sources) srelem.ResetProperties(); } } configSection = null; initState = InitState.NotInitialized; Initialize(); } } } #endif
////////////////////////////////////////////////////////////////////////////////////////////////// // // file: misc_blending.cs // // composition toolkit // // Author Sergey Solokhin (Neill3d) // // GitHub page - https://github.com/Neill3d/MoPlugs // Licensed under BSD 3-Clause - https://github.com/Neill3d/MoPlugs/blob/master/LICENSE // /////////////////////////////////////////////////////////////////////////////////////////////////// /* ** Copyright (c) 2012, Romain Dura romain@shazbits.com ** ** Permission to use, copy, modify, and/or distribute this software for any ** purpose with or without fee is hereby granted, provided that the above ** copyright notice and this permission notice appear in all copies. ** ** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES ** WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF ** MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ** SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ** WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ** ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR ** IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* ** Photoshop & misc math ** Blending modes, RGB/HSL/Contrast/Desaturate, levels control ** ** Romain Dura | Romz ** Blog: http://mouaif.wordpress.com ** Post: http://mouaif.wordpress.com/?p=94 */ /* ** Desaturation */ vec4 Desaturate(vec3 color, float Desaturation) { vec3 grayXfer = vec3(0.3, 0.59, 0.11); vec3 gray = vec3(dot(grayXfer, color)); return vec4(mix(color, gray, Desaturation), 1.0); } /* ** Hue, saturation, luminance */ vec3 RGBToHSL(vec3 color) { vec3 hsl; // init to 0 to avoid warnings ? (and reverse if + remove first part) float fmin = min(min(color.r, color.g), color.b); //Min. value of RGB float fmax = max(max(color.r, color.g), color.b); //Max. value of RGB float delta = fmax - fmin; //Delta RGB value hsl.z = (fmax + fmin) / 2.0; // Luminance if (delta == 0.0) //This is a gray, no chroma... { hsl.x = 0.0; // Hue hsl.y = 0.0; // Saturation } else //Chromatic data... { if (hsl.z < 0.5) hsl.y = delta / (fmax + fmin); // Saturation else hsl.y = delta / (2.0 - fmax - fmin); // Saturation float deltaR = (((fmax - color.r) / 6.0) + (delta / 2.0)) / delta; float deltaG = (((fmax - color.g) / 6.0) + (delta / 2.0)) / delta; float deltaB = (((fmax - color.b) / 6.0) + (delta / 2.0)) / delta; if (color.r == fmax ) hsl.x = deltaB - deltaG; // Hue else if (color.g == fmax) hsl.x = (1.0 / 3.0) + deltaR - deltaB; // Hue else if (color.b == fmax) hsl.x = (2.0 / 3.0) + deltaG - deltaR; // Hue if (hsl.x < 0.0) hsl.x += 1.0; // Hue else if (hsl.x > 1.0) hsl.x -= 1.0; // Hue } return hsl; } float HueToRGB(float f1, float f2, float hue) { if (hue < 0.0) hue += 1.0; else if (hue > 1.0) hue -= 1.0; float res; if ((6.0 * hue) < 1.0) res = f1 + (f2 - f1) * 6.0 * hue; else if ((2.0 * hue) < 1.0) res = f2; else if ((3.0 * hue) < 2.0) res = f1 + (f2 - f1) * ((2.0 / 3.0) - hue) * 6.0; else res = f1; return res; } vec3 HSLToRGB(vec3 hsl) { vec3 rgb; if (hsl.y == 0.0) rgb = vec3(hsl.z); // Luminance else { float f2; if (hsl.z < 0.5) f2 = hsl.z * (1.0 + hsl.y); else f2 = (hsl.z + hsl.y) - (hsl.y * hsl.z); float f1 = 2.0 * hsl.z - f2; rgb.r = HueToRGB(f1, f2, hsl.x + (1.0/3.0)); rgb.g = HueToRGB(f1, f2, hsl.x); rgb.b= HueToRGB(f1, f2, hsl.x - (1.0/3.0)); } return rgb; } /* ** Contrast, saturation, brightness ** Code of this function is from TGM's shader pack ** http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=21057 */ // For all settings: 1.0 = 100% 0.5=50% 1.5 = 150% vec3 ContrastSaturationBrightness(vec3 color, float brt, float sat, float con) { // Increase or decrease theese values to adjust r, g and b color channels seperately const float AvgLumR = 0.5; const float AvgLumG = 0.5; const float AvgLumB = 0.5; const vec3 LumCoeff = vec3(0.2125, 0.7154, 0.0721); vec3 AvgLumin = vec3(AvgLumR, AvgLumG, AvgLumB); vec3 brtColor = color * brt; vec3 intensity = vec3(dot(brtColor, LumCoeff)); vec3 satColor = mix(intensity, brtColor, sat); vec3 conColor = mix(AvgLumin, satColor, con); return conColor; } /* ** Float blending modes ** Adapted from here: http://www.nathanm.com/photoshop-blending-math/ ** But I modified the HardMix (wrong condition), Overlay, SoftLight, ColorDodge, ColorBurn, VividLight, PinLight (inverted layers) ones to have correct results */ #define BlendLinearDodgef BlendAddf #define BlendLinearBurnf BlendSubstractf #define BlendAddf(base, blend) min(base + blend, 1.0) #define BlendSubstractf(base, blend) max(base + blend - 1.0, 0.0) #define BlendLightenf(base, blend) max(blend, base) #define BlendDarkenf(base, blend) min(blend, base) #define BlendLinearLightf(base, blend) (blend < 0.5 ? BlendLinearBurnf(base, (2.0 * blend)) : BlendLinearDodgef(base, (2.0 * (blend - 0.5)))) #define BlendScreenf(base, blend) (1.0 - ((1.0 - base) * (1.0 - blend))) #define BlendOverlayf(base, blend) (base < 0.5 ? (2.0 * base * blend) : (1.0 - 2.0 * (1.0 - base) * (1.0 - blend))) #define BlendSoftLightf(base, blend) ((blend < 0.5) ? (2.0 * base * blend + base * base * (1.0 - 2.0 * blend)) : (sqrt(base) * (2.0 * blend - 1.0) + 2.0 * base * (1.0 - blend))) #define BlendColorDodgef(base, blend) ((blend == 1.0) ? blend : min(base / (1.0 - blend), 1.0)) #define BlendColorBurnf(base, blend) ((blend == 0.0) ? blend : max((1.0 - ((1.0 - base) / blend)), 0.0)) #define BlendVividLightf(base, blend) ((blend < 0.5) ? BlendColorBurnf(base, (2.0 * blend)) : BlendColorDodgef(base, (2.0 * (blend - 0.5)))) #define BlendPinLightf(base, blend) ((blend < 0.5) ? BlendDarkenf(base, (2.0 * blend)) : BlendLightenf(base, (2.0 *(blend - 0.5)))) #define BlendHardMixf(base, blend) ((BlendVividLightf(base, blend) < 0.5) ? 0.0 : 1.0) #define BlendReflectf(base, blend) ((blend == 1.0) ? blend : min(base * base / (1.0 - blend), 1.0)) /* ** Vector3 blending modes */ // Component wise blending #define Blend(base, blend, funcf) vec3(funcf(base.r, blend.r), funcf(base.g, blend.g), funcf(base.b, blend.b)) #define BlendNormal(base, blend) (blend) #define BlendLighten BlendLightenf #define BlendDarken BlendDarkenf #define BlendMultiply(base, blend) (base * blend) #define BlendAverage(base, blend) ((base + blend) / 2.0) #define BlendAdd(base, blend) min(base + blend, vec3(1.0)) #define BlendSubstract(base, blend) max(base + blend - vec3(1.0), vec3(0.0)) #define BlendDifference(base, blend) abs(base - blend) #define BlendNegation(base, blend) (vec3(1.0) - abs(vec3(1.0) - base - blend)) #define BlendExclusion(base, blend) (base + blend - 2.0 * base * blend) #define BlendScreen(base, blend) Blend(base, blend, BlendScreenf) #define BlendOverlay(base, blend) Blend(base, blend, BlendOverlayf) #define BlendSoftLight(base, blend) Blend(base, blend, BlendSoftLightf) #define BlendHardLight(base, blend) BlendOverlay(blend, base) #define BlendColorDodge(base, blend) Blend(base, blend, BlendColorDodgef) #define BlendColorBurn(base, blend) Blend(base, blend, BlendColorBurnf) #define BlendLinearDodge BlendAdd #define BlendLinearBurn BlendSubstract // Linear Light is another contrast-increasing mode // If the blend color is darker than midgray, Linear Light darkens the image by decreasing the brightness. If the blend color is lighter than midgray, the result is a brighter image due to increased brightness. #define BlendLinearLight(base, blend) Blend(base, blend, BlendLinearLightf) #define BlendVividLight(base, blend) Blend(base, blend, BlendVividLightf) #define BlendPinLight(base, blend) Blend(base, blend, BlendPinLightf) #define BlendHardMix(base, blend) Blend(base, blend, BlendHardMixf) #define BlendReflect(base, blend) Blend(base, blend, BlendReflectf) #define BlendGlow(base, blend) BlendReflect(blend, base) #define BlendPhoenix(base, blend) (min(base, blend) - max(base, blend) + vec3(1.0)) #define BlendOpacity(base, blend, F, O) (F(base, blend) * O + base * (1.0 - O)) // Hue Blend mode creates the result color by combining the luminance and saturation of the base color with the hue of the blend color. vec3 BlendHue(vec3 base, vec3 blend) { vec3 baseHSL = RGBToHSL(base); return HSLToRGB(vec3(RGBToHSL(blend).r, baseHSL.g, baseHSL.b)); } // Saturation Blend mode creates the result color by combining the luminance and hue of the base color with the saturation of the blend color. vec3 BlendSaturation(vec3 base, vec3 blend) { vec3 baseHSL = RGBToHSL(base); return HSLToRGB(vec3(baseHSL.r, RGBToHSL(blend).g, baseHSL.b)); } // Color Mode keeps the brightness of the base color and applies both the hue and saturation of the blend color. vec3 BlendColor(vec3 base, vec3 blend) { vec3 blendHSL = RGBToHSL(blend); return HSLToRGB(vec3(blendHSL.r, blendHSL.g, RGBToHSL(base).b)); } // Luminosity Blend mode creates the result color by combining the hue and saturation of the base color with the luminance of the blend color. vec3 BlendLuminosity(vec3 base, vec3 blend) { vec3 baseHSL = RGBToHSL(base); return HSLToRGB(vec3(baseHSL.r, baseHSL.g, RGBToHSL(blend).b)); } /* ** Gamma correction ** Details: http://blog.mouaif.org/2009/01/22/photoshop-gamma-correction-shader/ */ #define GammaCorrection(color, gamma) pow(color, 1.0 / gamma) /* ** Levels control (input (+gamma), output) ** Details: http://blog.mouaif.org/2009/01/28/levels-control-shader/ */ #define LevelsControlInputRange(color, minInput, maxInput) min(max(color - vec3(minInput), vec3(0.0)) / (vec3(maxInput) - vec3(minInput)), vec3(1.0)) #define LevelsControlInput(color, minInput, gamma, maxInput) GammaCorrection(LevelsControlInputRange(color, minInput, maxInput), gamma) #define LevelsControlOutputRange(color, minOutput, maxOutput) mix(vec3(minOutput), vec3(maxOutput), color) #define LevelsControl(color, minInput, gamma, maxInput, minOutput, maxOutput) LevelsControlOutputRange(LevelsControlInput(color, minInput, gamma, maxInput), minOutput, maxOutput)
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Threading; using System.Windows.Forms; using OpenLiveWriter.Controls; using OpenLiveWriter.CoreServices; using OpenLiveWriter.BlogClient; using OpenLiveWriter.Extensibility.BlogClient; using OpenLiveWriter.HtmlParser.Parser; using OpenLiveWriter.Localization; using OpenLiveWriter.Localization.Bidi; namespace OpenLiveWriter.PostEditor { public interface IPostEditorPostSource { string UniqueId { get; } string Name { get; } string EmptyPostListMessage { get; } bool VerifyCredentials() ; bool IsSlow { get; } bool HasMultipleWeblogs { get; } bool SupportsDelete { get; } bool SupportsPages { get; } RecentPostCapabilities RecentPostCapabilities { get; } PostInfo[] GetRecentPosts( RecentPostRequest request ) ; PostInfo[] GetPages( RecentPostRequest request ) ; IBlogPostEditingContext GetPost( string postId ) ; bool DeletePost( string postId, bool isPage ) ; } public class PostInfo { public static string UntitledPost { get { return Res.Get(StringId.UntitledPost) ; } } public static string UntitledPage { get { return Res.Get(StringId.UntitledPage) ; } } public string Id { get { return _id; } set { _id = value; } } private string _id = String.Empty; public bool IsPage { get { return _isPage; } set { _isPage = value; } } private bool _isPage ; public string Title { get { if ( _title == String.Empty ) return IsPage ? UntitledPage : UntitledPost ; else return _title; } set { _title = value; } } private string _title = String.Empty; public string Permalink { get { return _permalink; } set { _permalink = value; } } private string _permalink = String.Empty ; public string BlogName { get { return _blogName; } set { _blogName = value; } } private string _blogName = String.Empty ; public string BlogId { get { return _blogId; } set { _blogId = value; } } private string _blogId = String.Empty ; public string BlogPostId { get { return _blogPostId; } set { _blogPostId = value; } } private string _blogPostId = String.Empty; public string Contents { get { return _contents; } set { _contents = value; } } private string _contents = String.Empty; public string PlainTextContents { get { if ( _plainTextContents == null ) _plainTextContents = HtmlUtils.HTMLToPlainText(Contents) ; return _plainTextContents ; } } private string _plainTextContents = null ; public DateTime DateModified { get { return _dateModified; } set { _dateModified = value; } } private DateTime _dateModified = DateTime.MinValue ; public bool DateModifiedSpecified { get { return DateModified != DateTime.MinValue; } } public string PrettyDateDisplay { get { if (DateModified == DateTime.MinValue) return null; // convert to local DateTime date = DateTimeHelper.UtcToLocal(DateModified) ; string format = CultureHelper.GetDateTimeCombinedPattern("{0}", "{1}"); string time = date.ToShortTimeString(); // default format string formattedDate = CultureHelper.GetDateTimeCombinedPattern(date.ToShortDateString(), time); // see if we can shorten it DateTime dateNow = DateTime.Now ; if ( date.Year == dateNow.Year ) { if ( date.DayOfYear == dateNow.DayOfYear ) { formattedDate = String.Format(CultureInfo.CurrentCulture, format, Res.Get(StringId.Today), time); } else { int dayDiff = dateNow.DayOfYear - date.DayOfYear; if ( dayDiff > 0 && dayDiff <= 6 ) { formattedDate = String.Format(CultureInfo.CurrentCulture, format, date.ToString("dddd", CultureInfo.CurrentCulture), time); } } } return formattedDate ; } } public class TitleComparer : IComparer { public int Compare(object x, object y) { return (x as PostInfo).Title.CompareTo( (y as PostInfo).Title ) ; } } public class DateDescendingComparer : IComparer { public int Compare(object x, object y) { DateAscendingComparer dateAscendingComparer = new DateAscendingComparer() ; return -dateAscendingComparer.Compare(x,y) ; } } public class DateAscendingComparer : IComparer { public int Compare(object x, object y) { return (x as PostInfo).DateModified.CompareTo( (y as PostInfo).DateModified ) ; } } } public class RemoteWeblogBlogPostSource : IPostEditorPostSource { public RemoteWeblogBlogPostSource( string blogId ) { _blogId = blogId ; using ( Blog blog = new Blog(blogId) ) { _name = blog.Name ; _supportsPages = blog.ClientOptions.SupportsPages; } } public string UniqueId { get { return _blogId ; } } public string Name { get { return _name ; } } public string EmptyPostListMessage { get { return null ; } } public bool IsSlow { get { return true ; } } public bool HasMultipleWeblogs { get { return false ; } } public bool SupportsDelete { get { return true ; } } public bool SupportsPages { get { return _supportsPages ; } } public bool VerifyCredentials() { using ( Blog blog = new Blog(_blogId) ) return blog.VerifyCredentials(); } public RecentPostCapabilities RecentPostCapabilities { get { int maxPosts; using (Blog blog = new Blog(_blogId)) { maxPosts = blog.ClientOptions.MaxRecentPosts; if (maxPosts < 0) maxPosts = RecentPostRequest.ALL_POSTS; } int[] defaultNums = { 20, 50, 100, 500, 1000, 3000 }; ArrayList arrRequests = new ArrayList(); foreach (int num in defaultNums) { if (num < maxPosts) { arrRequests.Add(new RecentPostRequest(num)); } else { break; } } arrRequests.Add(new RecentPostRequest(maxPosts)); RecentPostRequest[] requests = (RecentPostRequest[]) arrRequests.ToArray(typeof (RecentPostRequest)); return new RecentPostCapabilities( // valid post fetches requests, new RecentPostRequest(SupportsPages ? 10 : 5) // Larger number by default for blogs that support // pages (this is so pages are not "clipped" out of // view in the default case). Alternatively we could // support separate defaults for Posts and Pages // however this would have introduced too much new // complexity into the OpenPostForm. That said, if // we are hell bent on fixing this it is definitely // do-able with a few hours of careful refactoring // of OpenPostForm. ); } } public PostInfo[] GetRecentPosts(RecentPostRequest request) { return GetPosts(request, false) ; } public PostInfo[] GetPages(RecentPostRequest request) { if ( !SupportsPages ) throw new InvalidOperationException("This post source does not support pages!") ; return GetPosts(request, true) ; } public IBlogPostEditingContext GetPost(string postId) { foreach ( BlogPost blogPost in _blogPosts ) { using ( Blog blog = new Blog(_blogId) ) { if ( blogPost.Id == postId ) { // Fix bug 457160 - New post created with a new category // becomes without a category when opened in WLW // // See also RecentPostSynchronizer.DoWork() // // Necessary even in the case of inline categories, // since the inline categories may contain categories // that Writer is not yet aware of try { blog.RefreshCategories(); } catch (Exception e) { Trace.Fail("Exception while attempting to refresh categories: " + e.ToString()); } // Get the full blog post--necessary because Atom ETag and remote post data is // only available from the full call BlogPost blogPostWithCategories = blog.GetPost(postId, blogPost.IsPage); return new BlogPostEditingContext( _blogId, blogPostWithCategories) ; } } } // if we get this far then it was a bad postId throw new ArgumentException( "PostId was not part of the headers fetched" ) ; } public bool DeletePost(string postId, bool isPage) { bool deletedRemotePost = PostDeleteHelper.SafeDeleteRemotePost(_blogId, postId, isPage) ; if ( !deletedRemotePost ) { DialogResult result = DisplayMessage.Show(MessageId.LocalDeleteConfirmation, isPage ? Res.Get(StringId.PageLower) : Res.Get(StringId.PostLower) ) ; if ( result == DialogResult.No ) return false ; } return PostDeleteHelper.SafeDeleteLocalPost(_blogId, postId) ; } private PostInfo[] GetPosts(RecentPostRequest request, bool getPages) { using ( Blog blog = new Blog(_blogId) ) { if ( getPages ) _blogPosts = blog.GetPages(request.NumberOfPosts) ; else _blogPosts = blog.GetRecentPosts(request.NumberOfPosts, false) ; ArrayList recentPosts = new ArrayList(); foreach ( BlogPost blogPost in _blogPosts ) { PostInfo postInfo = new PostInfo(); postInfo.Id = blogPost.Id ; postInfo.IsPage = blogPost.IsPage ; postInfo.Title = blogPost.Title ; postInfo.Permalink = blogPost.Permalink ; postInfo.BlogId = blog.Id ; postInfo.BlogName = blog.Name ; postInfo.BlogPostId = blogPost.Id ; postInfo.Contents = blogPost.Contents ; postInfo.DateModified = blogPost.DatePublished ; recentPosts.Add(postInfo) ; } return (PostInfo[])recentPosts.ToArray(typeof(PostInfo)) ; } } private string _blogId ; private string _name ; private bool _supportsPages ; private BlogPost[] _blogPosts ; } /// <summary> /// Chooser source for local blog storage /// </summary> public abstract class LocalStoragePostSource : IPostEditorPostSource { protected LocalStoragePostSource( string name, DirectoryInfo directory, bool supportsDelete, RecentPostRequest defaultRequest ) { _name = name ; _directory = directory ; _supportsDelete = supportsDelete ; _defaultRequest = defaultRequest ; } public abstract string UniqueId { get ; } public string Name { get { return _name ; } } public virtual string EmptyPostListMessage { get { return null; } } public bool IsSlow { get { return false ; } } public bool HasMultipleWeblogs { get { return true ; } } public bool SupportsDelete { get { return _supportsDelete ; } } public bool SupportsPages { get { // local storage doesn't differentiate between // posts and pages -- perhaps we want to differentiate // using e.g. "About Me (Page)" return false ; } } public PostInfo[] GetPages(RecentPostRequest request) { throw new NotSupportedException("Pages are not suppported for this post source!") ; } public RecentPostCapabilities RecentPostCapabilities { get { return new RecentPostCapabilities( new RecentPostRequest[] { new RecentPostRequest(25), RecentPostRequest.All }, _defaultRequest ); } } public bool VerifyCredentials() { return true ; } public PostInfo[] GetRecentPosts(RecentPostRequest request) { return PostEditorFile.GetRecentPosts(_directory, request) ; } public IBlogPostEditingContext GetPost(string postId) { PostEditorFile postEditorFile = PostEditorFile.GetExisting(new FileInfo(postId)); return postEditorFile.Load() ; } public abstract bool DeletePost(string postId, bool isPage); private string _name ; private DirectoryInfo _directory ; private bool _supportsDelete ; private RecentPostRequest _defaultRequest ; } public class LocalDraftsPostSource : LocalStoragePostSource { public LocalDraftsPostSource() : base( Res.Get(StringId.Drafts), PostEditorFile.DraftsFolder, true, RecentPostRequest.All) { } public override string UniqueId { get { return "95809BD4-B8BF-4D05-9465-3BEF5C7FB1EB" ; } } public override string EmptyPostListMessage { get { return Res.Get(StringId.OpenPostNoDraftsAvailable) ; } } public override bool DeletePost(string postId, bool isPage) { return PostDeleteHelper.SafeDeleteLocalPost(new FileInfo(postId)) ; } } public class LocalRecentPostsPostSource : LocalStoragePostSource { public LocalRecentPostsPostSource() : base( Res.Get(StringId.RecentlyPosted), PostEditorFile.RecentPostsFolder, true, new RecentPostRequest(15) ) { } public override string UniqueId { get { return "7AD7C37E-80DA-4516-B439-ACD2247B714D" ; } } public override bool DeletePost( string postId, bool isPage ) { FileInfo postFile = new FileInfo(postId); PostInfo postInfo = PostEditorFile.GetPostInfo(postFile); if ( postInfo != null ) { bool deletedRemotePost = PostDeleteHelper.SafeDeleteRemotePost(postInfo.BlogId, postInfo.BlogPostId, postInfo.IsPage) ; if ( !deletedRemotePost ) { DialogResult result = DisplayMessage.Show(MessageId.LocalDeleteConfirmation, isPage ? Res.Get(StringId.PageLower) : Res.Get(StringId.PostLower) ) ; if ( result == DialogResult.No ) return false ; } return PostDeleteHelper.SafeDeleteLocalPost(postFile) ; } else { return false ; } } } public class RecentPostCapabilities { public RecentPostCapabilities( RecentPostRequest[] validRequests, RecentPostRequest defaultRequest ) { _validRequests = validRequests ; _defaultRequest = defaultRequest ; } public RecentPostRequest[] ValidRequests { get { return _validRequests; } } private readonly RecentPostRequest[] _validRequests ; public RecentPostRequest DefaultRequest { get { return _defaultRequest; } } private readonly RecentPostRequest _defaultRequest ; } public class RecentPostRequest { public RecentPostRequest( int numberOfPosts ) { // record number of posts _numberOfPosts = numberOfPosts ; // calculate display name if ( _numberOfPosts == ALL_POSTS ) { _displayName = Res.Get(StringId.ShowAllPosts); } else _displayName = string.Format(CultureInfo.CurrentCulture, Res.Get(StringId.ShowXPosts), _numberOfPosts) ; } public static RecentPostRequest All { get { return _all; } } private static readonly RecentPostRequest _all = new RecentPostRequest(ALL_POSTS); public string DisplayName { get { return _displayName; } } public int NumberOfPosts { get { return _numberOfPosts; } } public bool AllPosts { get { return NumberOfPosts == ALL_POSTS; } } public override string ToString() { return DisplayName ; } public override bool Equals(object obj) { RecentPostRequest equalTo = obj as RecentPostRequest ; return equalTo != null && NumberOfPosts == equalTo.NumberOfPosts ; } public override int GetHashCode() { return NumberOfPosts.GetHashCode() ; } private string _displayName ; private int _numberOfPosts ; public const int ALL_POSTS = Int32.MaxValue; } }
#region Apache 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 // .NET Compact Framework 1.0 has no support for System.Runtime.Remoting #if !NETCF using System; using System.Collections; using System.Threading; using System.Runtime.Remoting.Messaging; using log4net.Layout; using log4net.Core; using log4net.Util; namespace log4net.Appender { /// <summary> /// Delivers logging events to a remote logging sink. /// </summary> /// <remarks> /// <para> /// This Appender is designed to deliver events to a remote sink. /// That is any object that implements the <see cref="IRemoteLoggingSink"/> /// interface. It delivers the events using .NET remoting. The /// object to deliver events to is specified by setting the /// appenders <see cref="RemotingAppender.Sink"/> property.</para> /// <para> /// The RemotingAppender buffers events before sending them. This allows it to /// make more efficient use of the remoting infrastructure.</para> /// <para> /// Once the buffer is full the events are still not sent immediately. /// They are scheduled to be sent using a pool thread. The effect is that /// the send occurs asynchronously. This is very important for a /// number of non obvious reasons. The remoting infrastructure will /// flow thread local variables (stored in the <see cref="CallContext"/>), /// if they are marked as <see cref="ILogicalThreadAffinative"/>, across the /// remoting boundary. If the server is not contactable then /// the remoting infrastructure will clear the <see cref="ILogicalThreadAffinative"/> /// objects from the <see cref="CallContext"/>. To prevent a logging failure from /// having side effects on the calling application the remoting call must be made /// from a separate thread to the one used by the application. A <see cref="ThreadPool"/> /// thread is used for this. If no <see cref="ThreadPool"/> thread is available then /// the events will block in the thread pool manager until a thread is available.</para> /// <para> /// Because the events are sent asynchronously using pool threads it is possible to close /// this appender before all the queued events have been sent. /// When closing the appender attempts to wait until all the queued events have been sent, but /// this will timeout after 30 seconds regardless.</para> /// <para> /// If this appender is being closed because the <see cref="AppDomain.ProcessExit"/> /// event has fired it may not be possible to send all the queued events. During process /// exit the runtime limits the time that a <see cref="AppDomain.ProcessExit"/> /// event handler is allowed to run for. If the runtime terminates the threads before /// the queued events have been sent then they will be lost. To ensure that all events /// are sent the appender must be closed before the application exits. See /// <see cref="log4net.Core.LoggerManager.Shutdown"/> for details on how to shutdown /// log4net programmatically.</para> /// </remarks> /// <seealso cref="IRemoteLoggingSink" /> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> /// <author>Daniel Cazzulino</author> public class RemotingAppender : BufferingAppenderSkeleton { #region Public Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="RemotingAppender" /> class. /// </summary> /// <remarks> /// <para> /// Default constructor. /// </para> /// </remarks> public RemotingAppender() { } #endregion Public Instance Constructors #region Public Instance Properties /// <summary> /// Gets or sets the URL of the well-known object that will accept /// the logging events. /// </summary> /// <value> /// The well-known URL of the remote sink. /// </value> /// <remarks> /// <para> /// The URL of the remoting sink that will accept logging events. /// The sink must implement the <see cref="IRemoteLoggingSink"/> /// interface. /// </para> /// </remarks> public string Sink { get { return m_sinkUrl; } set { m_sinkUrl = value; } } #endregion Public Instance Properties #region Implementation of IOptionHandler /// <summary> /// Initialize the appender based on the options set /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// </remarks> #if FRAMEWORK_4_0_OR_ABOVE [System.Security.SecuritySafeCritical] #endif override public void ActivateOptions() { base.ActivateOptions(); IDictionary channelProperties = new Hashtable(); channelProperties["typeFilterLevel"] = "Full"; m_sinkObj = (IRemoteLoggingSink)Activator.GetObject(typeof(IRemoteLoggingSink), m_sinkUrl, channelProperties); } #endregion #region Override implementation of BufferingAppenderSkeleton /// <summary> /// Send the contents of the buffer to the remote sink. /// </summary> /// <remarks> /// The events are not sent immediately. They are scheduled to be sent /// using a pool thread. The effect is that the send occurs asynchronously. /// This is very important for a number of non obvious reasons. The remoting /// infrastructure will flow thread local variables (stored in the <see cref="CallContext"/>), /// if they are marked as <see cref="ILogicalThreadAffinative"/>, across the /// remoting boundary. If the server is not contactable then /// the remoting infrastructure will clear the <see cref="ILogicalThreadAffinative"/> /// objects from the <see cref="CallContext"/>. To prevent a logging failure from /// having side effects on the calling application the remoting call must be made /// from a separate thread to the one used by the application. A <see cref="ThreadPool"/> /// thread is used for this. If no <see cref="ThreadPool"/> thread is available then /// the events will block in the thread pool manager until a thread is available. /// </remarks> /// <param name="events">The events to send.</param> override protected void SendBuffer(LoggingEvent[] events) { // Setup for an async send BeginAsyncSend(); // Send the events if (!ThreadPool.QueueUserWorkItem(new WaitCallback(SendBufferCallback), events)) { // Cancel the async send EndAsyncSend(); ErrorHandler.Error("RemotingAppender ["+Name+"] failed to ThreadPool.QueueUserWorkItem logging events in SendBuffer."); } } /// <summary> /// Override base class close. /// </summary> /// <remarks> /// <para> /// This method waits while there are queued work items. The events are /// sent asynchronously using <see cref="ThreadPool"/> work items. These items /// will be sent once a thread pool thread is available to send them, therefore /// it is possible to close the appender before all the queued events have been /// sent.</para> /// <para> /// This method attempts to wait until all the queued events have been sent, but this /// method will timeout after 30 seconds regardless.</para> /// <para> /// If the appender is being closed because the <see cref="AppDomain.ProcessExit"/> /// event has fired it may not be possible to send all the queued events. During process /// exit the runtime limits the time that a <see cref="AppDomain.ProcessExit"/> /// event handler is allowed to run for.</para> /// </remarks> override protected void OnClose() { base.OnClose(); // Wait for the work queue to become empty before closing, timeout 30 seconds if (!m_workQueueEmptyEvent.WaitOne(30 * 1000, false)) { ErrorHandler.Error("RemotingAppender ["+Name+"] failed to send all queued events before close, in OnClose."); } } #endregion /// <summary> /// A work item is being queued into the thread pool /// </summary> private void BeginAsyncSend() { // The work queue is not empty m_workQueueEmptyEvent.Reset(); // Increment the queued count Interlocked.Increment(ref m_queuedCallbackCount); } /// <summary> /// A work item from the thread pool has completed /// </summary> private void EndAsyncSend() { // Decrement the queued count if (Interlocked.Decrement(ref m_queuedCallbackCount) <= 0) { // If the work queue is empty then set the event m_workQueueEmptyEvent.Set(); } } /// <summary> /// Send the contents of the buffer to the remote sink. /// </summary> /// <remarks> /// This method is designed to be used with the <see cref="ThreadPool"/>. /// This method expects to be passed an array of <see cref="LoggingEvent"/> /// objects in the state param. /// </remarks> /// <param name="state">the logging events to send</param> private void SendBufferCallback(object state) { try { LoggingEvent[] events = (LoggingEvent[])state; // Send the events m_sinkObj.LogEvents(events); } catch(Exception ex) { ErrorHandler.Error("Failed in SendBufferCallback", ex); } finally { EndAsyncSend(); } } #region Private Instance Fields /// <summary> /// The URL of the remote sink. /// </summary> private string m_sinkUrl; /// <summary> /// The local proxy (.NET remoting) for the remote logging sink. /// </summary> private IRemoteLoggingSink m_sinkObj; /// <summary> /// The number of queued callbacks currently waiting or executing /// </summary> private int m_queuedCallbackCount = 0; /// <summary> /// Event used to signal when there are no queued work items /// </summary> /// <remarks> /// This event is set when there are no queued work items. In this /// state it is safe to close the appender. /// </remarks> private ManualResetEvent m_workQueueEmptyEvent = new ManualResetEvent(true); #endregion Private Instance Fields /// <summary> /// Interface used to deliver <see cref="LoggingEvent"/> objects to a remote sink. /// </summary> /// <remarks> /// This interface must be implemented by a remoting sink /// if the <see cref="RemotingAppender"/> is to be used /// to deliver logging events to the sink. /// </remarks> public interface IRemoteLoggingSink { /// <summary> /// Delivers logging events to the remote sink /// </summary> /// <param name="events">Array of events to log.</param> /// <remarks> /// <para> /// Delivers logging events to the remote sink /// </para> /// </remarks> void LogEvents(LoggingEvent[] events); } } } #endif // !NETCF
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void TestNotZAndNotCByte() { var test = new BooleanBinaryOpTest__TestNotZAndNotCByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class BooleanBinaryOpTest__TestNotZAndNotCByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(BooleanBinaryOpTest__TestNotZAndNotCByte testClass) { var result = Sse41.TestNotZAndNotC(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestNotZAndNotCByte testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Sse41.TestNotZAndNotC( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); testClass.ValidateResult(_fld1, _fld2, result); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private DataTable _dataTable; static BooleanBinaryOpTest__TestNotZAndNotCByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public BooleanBinaryOpTest__TestNotZAndNotCByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.TestNotZAndNotC( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.TestNotZAndNotC( Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.TestNotZAndNotC( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.TestNotZAndNotC( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<Byte>* pClsVar2 = &_clsVar2) { var result = Sse41.TestNotZAndNotC( Sse2.LoadVector128((Byte*)(pClsVar1)), Sse2.LoadVector128((Byte*)(pClsVar2)) ); ValidateResult(_clsVar1, _clsVar2, result); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = Sse41.TestNotZAndNotC(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse41.TestNotZAndNotC(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse41.TestNotZAndNotC(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new BooleanBinaryOpTest__TestNotZAndNotCByte(); var result = Sse41.TestNotZAndNotC(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new BooleanBinaryOpTest__TestNotZAndNotCByte(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<Byte>* pFld2 = &test._fld2) { var result = Sse41.TestNotZAndNotC( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); ValidateResult(test._fld1, test._fld2, result); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.TestNotZAndNotC(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Sse41.TestNotZAndNotC( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); ValidateResult(_fld1, _fld2, result); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.TestNotZAndNotC(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.TestNotZAndNotC( Sse2.LoadVector128((Byte*)(&test._fld1)), Sse2.LoadVector128((Byte*)(&test._fld2)) ); ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, bool result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Byte[] left, Byte[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult1 = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult1 &= (((left[i] & right[i]) == 0)); } var expectedResult2 = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult2 &= (((~left[i] & right[i]) == 0)); } succeeded = (((expectedResult1 == false) && (expectedResult2 == false)) == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.TestNotZAndNotC)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections; using System.Threading; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Serialization; namespace DictionayLib { internal static class HashHelpers { #if FEATURE_RANDOMIZED_STRING_HASHING public const int HashCollisionThreshold = 100; public static bool s_UseRandomizedStringHashing = String.UseRandomizedHashing(); #endif // Table of prime numbers to use as hash table sizes. // A typical resize algorithm would pick the smallest prime number in this array // that is larger than twice the previous capacity. // Suppose our Hashtable currently has capacity x and enough elements are added // such that a resize needs to occur. Resizing first computes 2x then finds the // first prime in the table greater than 2x, i.e. if primes are ordered // p_1, p_2, ..., p_i, ..., it finds p_n such that p_n-1 < 2x < p_n. // Doubling is important for preserving the asymptotic complexity of the // hashtable operations such as add. Having a prime guarantees that double // hashing does not lead to infinite loops. IE, your hash function will be // h1(key) + i*h2(key), 0 <= i < size. h2 and the size must be relatively prime. public static readonly int[] primes = { 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369}; public static readonly int Hashtable_HashPrime = 101; // Used by Hashtable and Dictionary's SeralizationInfo .ctor's to store the SeralizationInfo // object until OnDeserialization is called. private static ConditionalWeakTable<object, SerializationInfo> s_SerializationInfoTable; internal static ConditionalWeakTable<object, SerializationInfo> SerializationInfoTable { get { if(s_SerializationInfoTable == null) { ConditionalWeakTable<object, SerializationInfo> newTable = new ConditionalWeakTable<object, SerializationInfo>(); Interlocked.CompareExchange(ref s_SerializationInfoTable, newTable, null); } return s_SerializationInfoTable; } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static bool IsPrime(int candidate) { if ((candidate & 1) != 0) { int limit = (int)Math.Sqrt (candidate); for (int divisor = 3; divisor <= limit; divisor+=2) { if ((candidate % divisor) == 0) return false; } return true; } return (candidate == 2); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static int GetPrime(int min) { //if (min < 0) // throw new System.ArgumentException(System.Environment.GetResourceString("Arg_HTCapacityOverflow")); Contract.EndContractBlock(); for (int i = 0; i < primes.Length; i++) { int prime = primes[i]; if (prime >= min) return prime; } //outside of our predefined table. //compute the hard way. for (int i = (min | 1); i < Int32.MaxValue;i+=2) { if (IsPrime(i) && ((i - 1) % Hashtable_HashPrime != 0)) return i; } return min; } public static int GetMinPrime() { return primes[0]; } // Returns size of hashtable to grow to. public static int ExpandPrime(int oldSize) { int newSize = 2 * oldSize; // Allow the hashtables to grow to maximum possible size (~2G elements) before encoutering capacity overflow. // Note that this check works even when _items.Length overflowed thanks to the (uint) cast if ((uint)newSize > MaxPrimeArrayLength && MaxPrimeArrayLength > oldSize) { Contract.Assert( MaxPrimeArrayLength == GetPrime(MaxPrimeArrayLength), "Invalid MaxPrimeArrayLength"); return MaxPrimeArrayLength; } return GetPrime(newSize); } // This is the maximum prime smaller than Array.MaxArrayLength public const int MaxPrimeArrayLength = 0x7FEFFFFD; #if FEATURE_RANDOMIZED_STRING_HASHING public static bool IsWellKnownEqualityComparer(object comparer) { return (comparer == null || comparer == System.Collections.Generic.EqualityComparer<string>.Default || comparer is IWellKnownStringEqualityComparer); } public static IEqualityComparer GetRandomizedEqualityComparer(object comparer) { Contract.Assert(comparer == null || comparer == System.Collections.Generic.EqualityComparer<string>.Default || comparer is IWellKnownStringEqualityComparer); if(comparer == null) { return new System.Collections.Generic.RandomizedObjectEqualityComparer(); } if(comparer == System.Collections.Generic.EqualityComparer<string>.Default) { return new System.Collections.Generic.RandomizedStringEqualityComparer(); } IWellKnownStringEqualityComparer cmp = comparer as IWellKnownStringEqualityComparer; if(cmp != null) { return cmp.GetRandomizedEqualityComparer(); } Contract.Assert(false, "Missing case in GetRandomizedEqualityComparer!"); return null; } public static object GetEqualityComparerForSerialization(object comparer) { if(comparer == null) { return null; } IWellKnownStringEqualityComparer cmp = comparer as IWellKnownStringEqualityComparer; if(cmp != null) { return cmp.GetEqualityComparerForSerialization(); } return comparer; } private const int bufferSize = 1024; private static RandomNumberGenerator rng; private static byte[] data; private static int currentIndex = bufferSize; private static readonly object lockObj = new Object(); internal static long GetEntropy() { lock(lockObj) { long ret; if(currentIndex == bufferSize) { if(null == rng) { rng = RandomNumberGenerator.Create(); data = new byte[bufferSize]; Contract.Assert(bufferSize % 8 == 0, "We increment our current index by 8, so our buffer size must be a multiple of 8"); } rng.GetBytes(data); currentIndex = 0; } ret = BitConverter.ToInt64(data, currentIndex); currentIndex += 8; return ret; } } #endif // FEATURE_RANDOMIZED_STRING_HASHING } }
// Copyright 2019 Esri // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ArcGIS.Desktop.Framework; using ArcGIS.Desktop.Framework.Contracts; using ArcGIS.Desktop.Mapping; using System.Windows; using MessageBox = ArcGIS.Desktop.Framework.Dialogs.MessageBox; using ComboBox = ArcGIS.Desktop.Framework.Contracts.ComboBox; using ArcGIS.Desktop.Framework.Threading.Tasks; namespace ChangeColorizerForRasterLayer { /// <summary> /// Represents the Apply Colorizers ComboBox. /// </summary> internal class ApplyColorizers : ComboBox { //Collection holding the applicable colorizers for the selected layer. IEnumerable<RasterColorizerType> _applicableColorizerList = null; BasicRasterLayer basicRasterLayer = null; /// <summary> /// Combo Box constructor. Make sure the combox box is enabled if raster layer is selected /// and subscribe to the layer selection changed event. /// </summary> public ApplyColorizers() { SelectedLayersChanged(new ArcGIS.Desktop.Mapping.Events.MapViewEventArgs(MapView.Active)); ArcGIS.Desktop.Mapping.Events.TOCSelectionChangedEvent.Subscribe(SelectedLayersChanged); } /// <summary> /// Event handler for layer selection changes. /// </summary> private async void SelectedLayersChanged(ArcGIS.Desktop.Mapping.Events.MapViewEventArgs mapViewArgs) { // Clears the combo box items when layer selection changes. Clear(); // Checks the state of the active pane. // Returns the active pane state if the active pane is not null, else returns null. State state = (FrameworkApplication.Panes.ActivePane != null) ? FrameworkApplication.Panes.ActivePane.State : null; if (state != null && mapViewArgs.MapView != null) { // Gets the selected layers from the current Map. IReadOnlyList<Layer> selectedLayers = mapViewArgs.MapView.GetSelectedLayers(); // The combo box will update only if one layer is selected. if (selectedLayers.Count == 1) { // Gets the selected layer. Layer firstSelectedLayer = selectedLayers.First(); // The combo box will update only if a raster layer is selected. if (firstSelectedLayer != null && (firstSelectedLayer is BasicRasterLayer || firstSelectedLayer is MosaicLayer)) { // Gets the basic raster layer from the selected layer. if (firstSelectedLayer is BasicRasterLayer) basicRasterLayer = (BasicRasterLayer)firstSelectedLayer; else if (firstSelectedLayer is MosaicLayer) basicRasterLayer = ((MosaicLayer)firstSelectedLayer).GetImageLayer() as BasicRasterLayer; // Initiates the combox box selected item. SelectedIndex = -1; // Updates the combo box with the corresponding colorizers for the selected layer. await UpdateCombo(basicRasterLayer); // Sets the combo box to display the first combo box item. SelectedIndex = 0; } } } } /// <summary> /// Destructor. Unsubscribe from the layer selection changed event. /// </summary> ~ApplyColorizers() { ArcGIS.Desktop.Mapping.Events.TOCSelectionChangedEvent.Unsubscribe(SelectedLayersChanged); Clear(); } /// <summary> /// Updates the combo box with the colorizers that can be applied to the selected layer. /// </summary> /// <param name="basicRasterLayer">the selected layer.</param> private async Task UpdateCombo(BasicRasterLayer basicRasterLayer) { try { await QueuedTask.Run(() => { // Gets a list of raster colorizers that can be applied to the selected layer. _applicableColorizerList = basicRasterLayer.GetApplicableColorizers(); }); if (_applicableColorizerList == null) { Add(new ComboBoxItem("No colorizers found")); return; } // Adds new combox box item for how many colorizers found. Add(new ComboBoxItem($@"{_applicableColorizerList.Count()} Colorizer{(_applicableColorizerList.Count() > 1 ? "s" : "")} found")); //Iterates through the applicable colorizer collection to get the colorizer names, and add to the combo box. foreach (var rasterColorizerType in _applicableColorizerList) { // Gets the colorizer name from the RasterColorizerType enum. string ColorizerName = Enum.GetName(typeof(RasterColorizerType), rasterColorizerType); Add(new ComboBoxItem(ColorizerName)); } } catch (Exception ex) { MessageBox.Show("Exception caught on Update combo box:" + ex.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error); } } /// <summary> /// The on comboBox selection change event. /// </summary> /// <param name="item">The newly selected combo box item</param> protected override async void OnSelectionChange(ComboBoxItem item) { if (_applicableColorizerList == null) MessageBox.Show("The applicable colorizer list is null.", "Colorizer Error:", MessageBoxButton.OK, MessageBoxImage.Error); if (item == null) MessageBox.Show("The combo box item is null.", "Combo box Error:", MessageBoxButton.OK, MessageBoxImage.Error); if (string.IsNullOrEmpty(item.Text)) MessageBox.Show("The combo box item text is null or empty.", "Combo box Error:", MessageBoxButton.OK, MessageBoxImage.Error); if (MapView.Active == null) MessageBox.Show("There is no active MapView.", "Combo box Error:", MessageBoxButton.OK, MessageBoxImage.Error); try { // Gets the first selected layer in the active MapView. Layer firstSelectedLayer = MapView.Active.GetSelectedLayers().First(); // Gets the BasicRasterLayer from the selected layer. if (firstSelectedLayer is BasicRasterLayer) basicRasterLayer = (BasicRasterLayer)firstSelectedLayer; else if (firstSelectedLayer is MosaicLayer) basicRasterLayer = ((MosaicLayer)firstSelectedLayer).GetImageLayer() as BasicRasterLayer; else MessageBox.Show("The selected layer is not a basic raster layer", "Select Layer Error:", MessageBoxButton.OK, MessageBoxImage.Error); // Gets the colorizer type from the selected combo box item. RasterColorizerType ColorizerType = _applicableColorizerList.FirstOrDefault(cn => Enum.GetName(typeof(RasterColorizerType), cn) == item.Text); // Applies the selected colorizer to the layer. switch (ColorizerType) { case RasterColorizerType.RGBColorizer: { // Sets the RGB colorizer to the selected layer. await ColorizerDefinitionVM.SetToRGBColorizer(basicRasterLayer); break; } case RasterColorizerType.StretchColorizer: { // Sets the Stretch colorizer to the selected layer. await ColorizerDefinitionVM.SetToStretchColorizer(basicRasterLayer); break; } case RasterColorizerType.DiscreteColorColorizer: { // Sets the Discrete Color colorizer to the selected layer. await ColorizerDefinitionVM.SetToDiscreteColorColorizer(basicRasterLayer); break; } case RasterColorizerType.ColormapColorizer: { // Sets the ColorMap colorizer to the selected layer. await ColorizerDefinitionVM.SetToColorMapColorizer(basicRasterLayer); break; } case RasterColorizerType.ClassifyColorizer: { // Sets the Classify colorizer to the selected layer. await ColorizerDefinitionVM.SetToClassifyColorizer(basicRasterLayer); break; } case RasterColorizerType.UniqueValueColorizer: { // Sets the Unique Value colorizer to the selected layer await ColorizerDefinitionVM.SetToUniqueValueColorizer(basicRasterLayer); break; } case RasterColorizerType.VectorFieldColorizer: { // Sets the Vector Field colorizer to the selected layer await ColorizerDefinitionVM.SetToVectorFieldColorizer(basicRasterLayer); break; } } } catch (Exception ex) { MessageBox.Show("Exception caught in OnSelectionChange:" + ex.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Versions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial class SolutionCrawlerRegistrationService { private partial class WorkCoordinator { private const int MinimumDelayInMS = 50; private readonly Registration _registration; private readonly LogAggregator _logAggregator; private readonly IAsynchronousOperationListener _listener; private readonly IOptionService _optionService; private readonly CancellationTokenSource _shutdownNotificationSource; private readonly CancellationToken _shutdownToken; private readonly SimpleTaskQueue _eventProcessingQueue; // points to processor task private readonly IncrementalAnalyzerProcessor _documentAndProjectWorkerProcessor; private readonly SemanticChangeProcessor _semanticChangeProcessor; public WorkCoordinator( IAsynchronousOperationListener listener, IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders, Registration registration) { _logAggregator = new LogAggregator(); _registration = registration; _listener = listener; _optionService = _registration.GetService<IOptionService>(); _optionService.OptionChanged += OnOptionChanged; // event and worker queues _shutdownNotificationSource = new CancellationTokenSource(); _shutdownToken = _shutdownNotificationSource.Token; _eventProcessingQueue = new SimpleTaskQueue(TaskScheduler.Default); var activeFileBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.ActiveFileWorkerBackOffTimeSpanInMS); var allFilesWorkerBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpanInMS); var entireProjectWorkerBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.EntireProjectWorkerBackOffTimeSpanInMS); _documentAndProjectWorkerProcessor = new IncrementalAnalyzerProcessor( listener, analyzerProviders, _registration, activeFileBackOffTimeSpanInMS, allFilesWorkerBackOffTimeSpanInMS, entireProjectWorkerBackOffTimeSpanInMS, _shutdownToken); var semanticBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.SemanticChangeBackOffTimeSpanInMS); var projectBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.ProjectPropagationBackOffTimeSpanInMS); _semanticChangeProcessor = new SemanticChangeProcessor(listener, _registration, _documentAndProjectWorkerProcessor, semanticBackOffTimeSpanInMS, projectBackOffTimeSpanInMS, _shutdownToken); // if option is on if (_optionService.GetOption(InternalSolutionCrawlerOptions.SolutionCrawler)) { _registration.Workspace.WorkspaceChanged += OnWorkspaceChanged; _registration.Workspace.DocumentOpened += OnDocumentOpened; _registration.Workspace.DocumentClosed += OnDocumentClosed; } } public int CorrelationId { get { return _registration.CorrelationId; } } public void Shutdown(bool blockingShutdown) { _optionService.OptionChanged -= OnOptionChanged; // detach from the workspace _registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged; _registration.Workspace.DocumentOpened -= OnDocumentOpened; _registration.Workspace.DocumentClosed -= OnDocumentClosed; // cancel any pending blocks _shutdownNotificationSource.Cancel(); _documentAndProjectWorkerProcessor.Shutdown(); SolutionCrawlerLogger.LogWorkCoordiantorShutdown(CorrelationId, _logAggregator); if (blockingShutdown) { var shutdownTask = Task.WhenAll( _eventProcessingQueue.LastScheduledTask, _documentAndProjectWorkerProcessor.AsyncProcessorTask, _semanticChangeProcessor.AsyncProcessorTask); shutdownTask.Wait(TimeSpan.FromSeconds(5)); if (!shutdownTask.IsCompleted) { SolutionCrawlerLogger.LogWorkCoordiantorShutdownTimeout(CorrelationId); } } } private void OnOptionChanged(object sender, OptionChangedEventArgs e) { // if solution crawler got turned off or on. if (e.Option == InternalSolutionCrawlerOptions.SolutionCrawler) { var value = (bool)e.Value; if (value) { _registration.Workspace.WorkspaceChanged += OnWorkspaceChanged; _registration.Workspace.DocumentOpened += OnDocumentOpened; _registration.Workspace.DocumentClosed += OnDocumentClosed; } else { _registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged; _registration.Workspace.DocumentOpened -= OnDocumentOpened; _registration.Workspace.DocumentClosed -= OnDocumentClosed; } SolutionCrawlerLogger.LogOptionChanged(CorrelationId, value); return; } // TODO: remove this once prototype is done // it is here just because it was convenient to add per workspace option change monitoring // for incremental analyzer if (e.Option == Diagnostics.InternalDiagnosticsOptions.UseDiagnosticEngineV2) { _documentAndProjectWorkerProcessor.ChangeDiagnosticsEngine((bool)e.Value); } ReanalyzeOnOptionChange(sender, e); } private void ReanalyzeOnOptionChange(object sender, OptionChangedEventArgs e) { // otherwise, let each analyzer decide what they want on option change ISet<DocumentId> set = null; foreach (var analyzer in _documentAndProjectWorkerProcessor.Analyzers) { if (analyzer.NeedsReanalysisOnOptionChanged(sender, e)) { set = set ?? _registration.CurrentSolution.Projects.SelectMany(p => p.DocumentIds).ToSet(); this.Reanalyze(analyzer, set); } } } public void Reanalyze(IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds) { var asyncToken = _listener.BeginAsyncOperation("Reanalyze"); _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAsync(analyzer, documentIds), _shutdownToken).CompletesAsyncOperation(asyncToken); SolutionCrawlerLogger.LogReanalyze(CorrelationId, analyzer, documentIds); } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args) { // guard us from cancellation try { ProcessEvents(args, _listener.BeginAsyncOperation("OnWorkspaceChanged")); } catch (OperationCanceledException oce) { if (NotOurShutdownToken(oce)) { throw; } // it is our cancellation, ignore } catch (AggregateException ae) { ae = ae.Flatten(); // If we had a mix of exceptions, don't eat it if (ae.InnerExceptions.Any(e => !(e is OperationCanceledException)) || ae.InnerExceptions.Cast<OperationCanceledException>().Any(NotOurShutdownToken)) { // We had a cancellation with a different token, so don't eat it throw; } // it is our cancellation, ignore } } private bool NotOurShutdownToken(OperationCanceledException oce) { return oce.CancellationToken == _shutdownToken; } private void ProcessEvents(WorkspaceChangeEventArgs args, IAsyncToken asyncToken) { SolutionCrawlerLogger.LogWorkspaceEvent(_logAggregator, (int)args.Kind); // TODO: add telemetry that record how much it takes to process an event (max, min, average and etc) switch (args.Kind) { case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionReloaded: case WorkspaceChangeKind.SolutionRemoved: case WorkspaceChangeKind.SolutionCleared: ProcessSolutionEvent(args, asyncToken); break; case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: case WorkspaceChangeKind.ProjectRemoved: ProcessProjectEvent(args, asyncToken); break; case WorkspaceChangeKind.DocumentAdded: case WorkspaceChangeKind.DocumentReloaded: case WorkspaceChangeKind.DocumentChanged: case WorkspaceChangeKind.DocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentAdded: case WorkspaceChangeKind.AdditionalDocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentChanged: case WorkspaceChangeKind.AdditionalDocumentReloaded: ProcessDocumentEvent(args, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void OnDocumentOpened(object sender, DocumentEventArgs e) { var asyncToken = _listener.BeginAsyncOperation("OnDocumentOpened"); _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAsync(e.Document, InvocationReasons.DocumentOpened), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void OnDocumentClosed(object sender, DocumentEventArgs e) { var asyncToken = _listener.BeginAsyncOperation("OnDocumentClosed"); _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAsync(e.Document, InvocationReasons.DocumentClosed), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void ProcessDocumentEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken) { switch (e.Kind) { case WorkspaceChangeKind.DocumentAdded: EnqueueEvent(e.NewSolution, e.DocumentId, InvocationReasons.DocumentAdded, asyncToken); break; case WorkspaceChangeKind.DocumentRemoved: EnqueueEvent(e.OldSolution, e.DocumentId, InvocationReasons.DocumentRemoved, asyncToken); break; case WorkspaceChangeKind.DocumentReloaded: case WorkspaceChangeKind.DocumentChanged: EnqueueEvent(e.OldSolution, e.NewSolution, e.DocumentId, asyncToken); break; case WorkspaceChangeKind.AdditionalDocumentAdded: case WorkspaceChangeKind.AdditionalDocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentChanged: case WorkspaceChangeKind.AdditionalDocumentReloaded: // If an additional file has changed we need to reanalyze the entire project. EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.AdditionalDocumentChanged, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void ProcessProjectEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken) { switch (e.Kind) { case WorkspaceChangeKind.ProjectAdded: OnProjectAdded(e.NewSolution.GetProject(e.ProjectId)); EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.DocumentAdded, asyncToken); break; case WorkspaceChangeKind.ProjectRemoved: EnqueueEvent(e.OldSolution, e.ProjectId, InvocationReasons.DocumentRemoved, asyncToken); break; case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: EnqueueEvent(e.OldSolution, e.NewSolution, e.ProjectId, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void ProcessSolutionEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken) { switch (e.Kind) { case WorkspaceChangeKind.SolutionAdded: OnSolutionAdded(e.NewSolution); EnqueueEvent(e.NewSolution, InvocationReasons.DocumentAdded, asyncToken); break; case WorkspaceChangeKind.SolutionRemoved: EnqueueEvent(e.OldSolution, InvocationReasons.SolutionRemoved, asyncToken); break; case WorkspaceChangeKind.SolutionCleared: EnqueueEvent(e.OldSolution, InvocationReasons.DocumentRemoved, asyncToken); break; case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionReloaded: EnqueueEvent(e.OldSolution, e.NewSolution, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void OnSolutionAdded(Solution solution) { var asyncToken = _listener.BeginAsyncOperation("OnSolutionAdded"); _eventProcessingQueue.ScheduleTask(() => { var semanticVersionTrackingService = solution.Workspace.Services.GetService<ISemanticVersionTrackingService>(); if (semanticVersionTrackingService != null) { semanticVersionTrackingService.LoadInitialSemanticVersions(solution); } }, _shutdownToken).CompletesAsyncOperation(asyncToken); } private void OnProjectAdded(Project project) { var asyncToken = _listener.BeginAsyncOperation("OnProjectAdded"); _eventProcessingQueue.ScheduleTask(() => { var semanticVersionTrackingService = project.Solution.Workspace.Services.GetService<ISemanticVersionTrackingService>(); if (semanticVersionTrackingService != null) { semanticVersionTrackingService.LoadInitialSemanticVersions(project); } }, _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution oldSolution, Solution newSolution, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAsync(oldSolution, newSolution), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution solution, InvocationReasons invocationReasons, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemForSolutionAsync(solution, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution oldSolution, Solution newSolution, ProjectId projectId, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, projectId), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution solution, ProjectId projectId, InvocationReasons invocationReasons, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution solution, DocumentId documentId, InvocationReasons invocationReasons, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemForDocumentAsync(solution, documentId, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution oldSolution, Solution newSolution, DocumentId documentId, IAsyncToken asyncToken) { // document changed event is the special one. _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, documentId), _shutdownToken).CompletesAsyncOperation(asyncToken); } private async Task EnqueueWorkItemAsync(Document document, InvocationReasons invocationReasons, SyntaxNode changedMember = null) { // we are shutting down _shutdownToken.ThrowIfCancellationRequested(); var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>(); var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(document, _shutdownToken).ConfigureAwait(false); var currentMember = GetSyntaxPath(changedMember); // call to this method is serialized. and only this method does the writing. _documentAndProjectWorkerProcessor.Enqueue( new WorkItem(document.Id, document.Project.Language, invocationReasons, isLowPriority, currentMember, _listener.BeginAsyncOperation("WorkItem"))); // enqueue semantic work planner if (invocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged)) { // must use "Document" here so that the snapshot doesn't go away. we need the snapshot to calculate p2p dependency graph later. // due to this, we might hold onto solution (and things kept alive by it) little bit longer than usual. _semanticChangeProcessor.Enqueue(document, currentMember); } } private SyntaxPath GetSyntaxPath(SyntaxNode changedMember) { // using syntax path might be too expansive since it will be created on every keystroke. // but currently, we have no other way to track a node between two different tree (even for incrementally parsed one) if (changedMember == null) { return null; } return new SyntaxPath(changedMember); } private async Task EnqueueWorkItemAsync(Project project, InvocationReasons invocationReasons) { foreach (var documentId in project.DocumentIds) { var document = project.GetDocument(documentId); await EnqueueWorkItemAsync(document, invocationReasons).ConfigureAwait(false); } } private async Task EnqueueWorkItemAsync(IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds) { var solution = _registration.CurrentSolution; foreach (var documentId in documentIds) { var document = solution.GetDocument(documentId); if (document == null) { continue; } var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>(); var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(document, _shutdownToken).ConfigureAwait(false); _documentAndProjectWorkerProcessor.Enqueue( new WorkItem(documentId, document.Project.Language, InvocationReasons.Reanalyze, isLowPriority, analyzer, _listener.BeginAsyncOperation("WorkItem"))); } } private async Task EnqueueWorkItemAsync(Solution oldSolution, Solution newSolution) { var solutionChanges = newSolution.GetChanges(oldSolution); // TODO: Async version for GetXXX methods? foreach (var addedProject in solutionChanges.GetAddedProjects()) { await EnqueueWorkItemAsync(addedProject, InvocationReasons.DocumentAdded).ConfigureAwait(false); } foreach (var projectChanges in solutionChanges.GetProjectChanges()) { await EnqueueWorkItemAsync(projectChanges).ConfigureAwait(continueOnCapturedContext: false); } foreach (var removedProject in solutionChanges.GetRemovedProjects()) { await EnqueueWorkItemAsync(removedProject, InvocationReasons.DocumentRemoved).ConfigureAwait(false); } } private async Task EnqueueWorkItemAsync(ProjectChanges projectChanges) { await EnqueueProjectConfigurationChangeWorkItemAsync(projectChanges).ConfigureAwait(false); foreach (var addedDocumentId in projectChanges.GetAddedDocuments()) { await EnqueueWorkItemAsync(projectChanges.NewProject.GetDocument(addedDocumentId), InvocationReasons.DocumentAdded).ConfigureAwait(false); } foreach (var changedDocumentId in projectChanges.GetChangedDocuments()) { await EnqueueWorkItemAsync(projectChanges.OldProject.GetDocument(changedDocumentId), projectChanges.NewProject.GetDocument(changedDocumentId)) .ConfigureAwait(continueOnCapturedContext: false); } foreach (var removedDocumentId in projectChanges.GetRemovedDocuments()) { await EnqueueWorkItemAsync(projectChanges.OldProject.GetDocument(removedDocumentId), InvocationReasons.DocumentRemoved).ConfigureAwait(false); } } private async Task EnqueueProjectConfigurationChangeWorkItemAsync(ProjectChanges projectChanges) { var oldProject = projectChanges.OldProject; var newProject = projectChanges.NewProject; // TODO: why solution changes return Project not ProjectId but ProjectChanges return DocumentId not Document? var projectConfigurationChange = InvocationReasons.Empty; if (!object.Equals(oldProject.ParseOptions, newProject.ParseOptions)) { projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectParseOptionChanged); } if (projectChanges.GetAddedMetadataReferences().Any() || projectChanges.GetAddedProjectReferences().Any() || projectChanges.GetAddedAnalyzerReferences().Any() || projectChanges.GetRemovedMetadataReferences().Any() || projectChanges.GetRemovedProjectReferences().Any() || projectChanges.GetRemovedAnalyzerReferences().Any() || !object.Equals(oldProject.CompilationOptions, newProject.CompilationOptions)) { projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectConfigurationChanged); } if (!projectConfigurationChange.IsEmpty) { await EnqueueWorkItemAsync(projectChanges.NewProject, projectConfigurationChange).ConfigureAwait(false); } } private async Task EnqueueWorkItemAsync(Document oldDocument, Document newDocument) { var differenceService = newDocument.GetLanguageService<IDocumentDifferenceService>(); if (differenceService != null) { var differenceResult = await differenceService.GetDifferenceAsync(oldDocument, newDocument, _shutdownToken).ConfigureAwait(false); if (differenceResult != null) { await EnqueueWorkItemAsync(newDocument, differenceResult.ChangeType, differenceResult.ChangedMember).ConfigureAwait(false); } } } private Task EnqueueWorkItemForDocumentAsync(Solution solution, DocumentId documentId, InvocationReasons invocationReasons) { var document = solution.GetDocument(documentId); return EnqueueWorkItemAsync(document, invocationReasons); } private Task EnqueueWorkItemForProjectAsync(Solution solution, ProjectId projectId, InvocationReasons invocationReasons) { var project = solution.GetProject(projectId); return EnqueueWorkItemAsync(project, invocationReasons); } private async Task EnqueueWorkItemForSolutionAsync(Solution solution, InvocationReasons invocationReasons) { foreach (var projectId in solution.ProjectIds) { await EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons).ConfigureAwait(false); } } private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, ProjectId projectId) { var oldProject = oldSolution.GetProject(projectId); var newProject = newSolution.GetProject(projectId); await EnqueueWorkItemAsync(newProject.GetChanges(oldProject)).ConfigureAwait(continueOnCapturedContext: false); } private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, DocumentId documentId) { var oldProject = oldSolution.GetProject(documentId.ProjectId); var newProject = newSolution.GetProject(documentId.ProjectId); await EnqueueWorkItemAsync(oldProject.GetDocument(documentId), newProject.GetDocument(documentId)).ConfigureAwait(continueOnCapturedContext: false); } internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> workers) { var solution = _registration.CurrentSolution; var list = new List<WorkItem>(); foreach (var project in solution.Projects) { foreach (var document in project.Documents) { list.Add( new WorkItem(document.Id, document.Project.Language, InvocationReasons.DocumentAdded, false, _listener.BeginAsyncOperation("WorkItem"))); } } _documentAndProjectWorkerProcessor.WaitUntilCompletion_ForTestingPurposesOnly(workers, list); } internal void WaitUntilCompletion_ForTestingPurposesOnly() { _documentAndProjectWorkerProcessor.WaitUntilCompletion_ForTestingPurposesOnly(); } } } }
using System; using System.Collections; /// <summary> /// System.Math.Floor(System.Double) /// </summary> public class MathFloor { public static int Main(string[] args) { MathFloor floor = new MathFloor(); TestLibrary.TestFramework.BeginTestCase("Testing System.Math.Floor(System.Double)..."); if (floor.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Verify floor number should be equal to intefer part subtract one of negative number..."); try { double number = TestLibrary.Generator.GetDouble(-55); while (number >= 0) { number = (-TestLibrary.Generator.GetDouble(-55)) * 100; } double floorNumber = Math.Floor(number); if (floorNumber < number - 1 || floorNumber > number) { TestLibrary.TestFramework.LogError("001", "The Ceiling number should be equal to the integer part of negative number!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Verify floor number should be equal to itself when number is negative integer..."); try { double number = TestLibrary.Generator.GetDouble(-55); while (number >= 0) { number = (-TestLibrary.Generator.GetDouble(-55)) * 100; } double floorNumber = Math.Floor(number); if (floorNumber != Math.Floor(floorNumber)) { TestLibrary.TestFramework.LogError("003", "The floor number should be equal to itself when number is negative integer..."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Verify floor number should be equal to the integer part of positive number..."); try { double number = TestLibrary.Generator.GetDouble(-55); while (number <= 0) { number = (TestLibrary.Generator.GetDouble(-55)) * 100; } double floorNumber = Math.Floor(number); if (floorNumber < number - 1 || floorNumber > number) { TestLibrary.TestFramework.LogError("005", "The floor number should be equal to the integer part plus one of positive number!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Verify floor number should be equal to itself when number is positive integer..."); try { double number = TestLibrary.Generator.GetDouble(-55); while (number <= 0) { number = (TestLibrary.Generator.GetDouble(-55)) * 100; } double floorNumber = Math.Floor(number); if (floorNumber != Math.Floor(floorNumber)) { TestLibrary.TestFramework.LogError("007", "The floor number should be equal to itself when number is positive integer..."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Verify floor number should be equal to itself when number is maxvalue..."); try { double floorMax = Math.Floor(double.MaxValue); if (floorMax != double.MaxValue) { TestLibrary.TestFramework.LogError("009", "The floor number should be equal to itself when number is maxvalue!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: Verify floor number should be equal to itself when number is minvalue..."); try { double floorMin = Math.Floor(double.MinValue); if (floorMin != double.MinValue) { TestLibrary.TestFramework.LogError("011", "The floor number should be equal to itself when number is minvalue!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } }
using System; using System.Text; using NLog.Config; using NLog.LayoutRenderers; using NLog.Web.Internal; #if !ASP_NET_CORE using System.Web; #else using Microsoft.AspNetCore.Http; #endif namespace NLog.Web.LayoutRenderers { /// <summary> /// ASP.NET Request variable. /// </summary> /// <remarks> /// Use this layout renderer to insert the value of the specified parameter of the /// ASP.NET Request object. /// </remarks> /// <example> /// <para>Example usage of ${aspnet-request}:</para> /// <code lang="NLog Layout Renderer"> /// ${aspnet-request:item=v} /// ${aspnet-request:querystring=v} /// ${aspnet-request:form=v} /// ${aspnet-request:cookie=v} /// ${aspnet-request:header=h} /// ${aspnet-request:serverVariable=v} /// </code> /// </example> [LayoutRenderer("aspnet-request")] public class AspNetRequestValueLayoutRenderer : AspNetLayoutRendererBase { /// <summary> /// Gets or sets the item name. The QueryString, Form, Cookies, or ServerVariables collection variables having the specified name are rendered. /// </summary> /// <docgen category='Rendering Options' order='10' /> [DefaultParameter] public string Item { get; set; } /// <summary> /// Gets or sets the QueryString variable to be rendered. /// </summary> /// <docgen category='Rendering Options' order='10' /> public string QueryString { get; set; } /// <summary> /// Gets or sets the form variable to be rendered. /// </summary> /// <docgen category='Rendering Options' order='10' /> public string Form { get; set; } /// <summary> /// Gets or sets the cookie to be rendered. /// </summary> /// <docgen category='Rendering Options' order='10' /> public string Cookie { get; set; } #if !ASP_NET_CORE /// <summary> /// Gets or sets the ServerVariables item to be rendered. /// </summary> /// <docgen category='Rendering Options' order='10' /> public string ServerVariable { get; set; } #endif /// <summary> /// Gets or sets the Headers item to be rendered. /// </summary> /// <docgen category='Rendering Options' order='10' /> public string Header { get; set; } /// <summary> /// Renders the specified ASP.NET Request variable and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder" /> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent) { var httpRequest = HttpContextAccessor.HttpContext.TryGetRequest(); if (httpRequest == null) { return; } var value = string.Empty; if (QueryString != null) { value = LookupQueryString(QueryString, httpRequest); } else if (Form != null) { value = LookupFormValue(Form, httpRequest); } else if (Cookie != null) { value = LookupCookieValue(Cookie, httpRequest); } #if !ASP_NET_CORE else if (ServerVariable != null) { value = httpRequest.ServerVariables?.Count > 0 ? httpRequest.ServerVariables[ServerVariable] : null; } #endif else if (Header != null) { value = LookupHeaderValue(Header, httpRequest); } else if (Item != null) { value = LookupItemValue(Item, httpRequest); } builder.Append(value); } #if !ASP_NET_CORE private static string LookupQueryString(string key, HttpRequestBase httpRequest) { var collection = httpRequest.QueryString; return collection?.Count > 0 ? collection[key] : null; } private static string LookupFormValue(string key, HttpRequestBase httpRequest) { var collection = httpRequest.Form; return collection?.Count > 0 ? collection[key] : null; } private static string LookupCookieValue(string key, HttpRequestBase httpRequest) { var cookieCollection = httpRequest.Cookies; return cookieCollection?.Count > 0 ? cookieCollection[key]?.Value : null; } private static string LookupHeaderValue(string key, HttpRequestBase httpRequest) { var collection = httpRequest.Headers; return collection?.Count > 0 ? collection[key] : null; } private static string LookupItemValue(string key, HttpRequestBase httpRequest) { return httpRequest[key]; } #else private static string LookupQueryString(string key, HttpRequest httpRequest) { var query = httpRequest.Query; if (query != null && query.TryGetValue(key, out var queryValue)) { return queryValue.ToString(); } return null; } private static string LookupFormValue(string key, HttpRequest httpRequest) { if (httpRequest.HasFormContentType) { var form = httpRequest.Form; if (form != null && form.TryGetValue(key, out var queryValue)) { return queryValue.ToString(); } } return null; } private static string LookupCookieValue(string key, HttpRequest httpRequest) { string cookieValue = null; if (httpRequest.Cookies?.TryGetValue(key, out cookieValue) ?? false) { return cookieValue; } return null; } private static string LookupHeaderValue(string key, HttpRequest httpRequest) { var headers = httpRequest.Headers; if (headers != null && headers.TryGetValue(key, out var headerValue)) { return headerValue.ToString(); } return null; } private static string LookupItemValue(string key, HttpRequest httpRequest) { object itemValue = null; if (httpRequest.HttpContext.Items?.TryGetValue(key, out itemValue) ?? false) { return itemValue?.ToString(); } return null; } #endif } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// RecordActionHistory ///<para>SObject Name: RecordActionHistory</para> ///<para>Custom Object: False</para> ///</summary> public class SfRecordActionHistory : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "RecordActionHistory"; } } ///<summary> /// RecordActionHistory ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Last Modified By ID /// <para>Name: LastModifiedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedById")] [Updateable(false), Createable(false)] public string LastModifiedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastModifiedBy</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedBy")] [Updateable(false), Createable(false)] public SfUser LastModifiedBy { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Parent Record ID /// <para>Name: ParentRecordId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "parentRecordId")] [Updateable(false), Createable(false)] public string ParentRecordId { get; set; } ///<summary> /// Action Definition API Name /// <para>Name: ActionDefinitionApiName</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "actionDefinitionApiName")] [Updateable(false), Createable(false)] public string ActionDefinitionApiName { get; set; } ///<summary> /// Action Definition Label /// <para>Name: ActionDefinitionLabel</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "actionDefinitionLabel")] [Updateable(false), Createable(false)] public string ActionDefinitionLabel { get; set; } ///<summary> /// Action Type /// <para>Name: ActionType</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "actionType")] [Updateable(false), Createable(false)] public string ActionType { get; set; } ///<summary> /// State /// <para>Name: State</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "state")] [Updateable(false), Createable(false)] public string State { get; set; } ///<summary> /// User ID /// <para>Name: UserId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userId")] [Updateable(false), Createable(false)] public string UserId { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: User</para> ///</summary> [JsonProperty(PropertyName = "user")] [Updateable(false), Createable(false)] public SfUser User { get; set; } ///<summary> /// RecordAction Id /// <para>Name: RecordActionId</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "recordActionId")] [Updateable(false), Createable(false)] public string RecordActionId { get; set; } ///<summary> /// Logged Time /// <para>Name: LoggedTime</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "loggedTime")] [Updateable(false), Createable(false)] public DateTimeOffset? LoggedTime { get; set; } ///<summary> /// Pinned /// <para>Name: Pinned</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "pinned")] [Updateable(false), Createable(false)] public string Pinned { get; set; } ///<summary> /// Is Mandatory /// <para>Name: IsMandatory</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isMandatory")] [Updateable(false), Createable(false)] public bool? IsMandatory { get; set; } } }
using System; using System.Collections.Generic; using Moq; using NUnit.Framework; using Umbraco.Core.Models; namespace Our.Umbraco.Fluent.ContentTypes.Tests { [TestFixture] public class When_Comparing_Property : ComparisonTestBase { private IContentType contentType; private PropertyGroup tab; private PropertyConfigurator richTextConfig; private IDataTypeDefinition dataTypeDefinition; private IDataTypeDefinition urlPropertyDefinition; private PropertyConfigurator urlConfigurator; [SetUp] public void Setup() { contentType = Mock.Of<IContentType>(); StubContentType(1, "contentType", contentType); contentType.PropertyGroups = new PropertyGroupCollection(new List<PropertyGroup>()); tab = new PropertyGroup() { Name = "tab" }; contentType.PropertyGroups.Add(tab); dataTypeDefinition = StubDataType(5, "richtext"); urlPropertyDefinition = StubDataType(6, "textstring"); AddRichTextProperty(); AddUrlProperty(); var tabConfigurator = Config .DocumentType("contentType") .Tab("tab"); richTextConfig = tabConfigurator .Property("richtext") .DisplayName("Rich text") .Description("Write rich content here") .DataType("richtext"); urlConfigurator = tabConfigurator .Property("url") .DisplayName("Url") .Description("A relevant link") .DataType("textstring") .Mandatory() .Regex("https?://[a-zA-Z0-9-.]+.[a-zA-Z]{2,}"); // TODO: Sort order } [Test] public void For_Existing_Then_Is_Not_New() { var propertyDiff = PropertyDiffgram(RichTextDiffgram); Assert.That(propertyDiff, Has.Property("IsNew").False); } [Test] public void For_Equal_Existing_Then_Is_Not_Unsafe() { var propertyDiff = PropertyDiffgram(RichTextDiffgram); Assert.That(propertyDiff, Has.Property("IsUnsafe").False); } [Test] public void For_Unknown_Then_Is_New() { tab.PropertyTypes.Clear(); var propertyDiff = PropertyDiffgram(RichTextDiffgram); Assert.That(propertyDiff, Has.Property("IsNew").True); } [Test] public void With_Different_Name_Then_Is_Unsafe() { richTextConfig.DisplayName("Fancy content"); var propertyDiff = PropertyDiffgram(RichTextDiffgram); Assert.That(propertyDiff, Has.Property("IsUnsafe").True); } [Test] public void With_Different_Description_Then_Is_Unsafe() { richTextConfig.Description("Another description"); var propertyDiff = PropertyDiffgram(RichTextDiffgram); Assert.That(propertyDiff, Has.Property("IsUnsafe").True); } [Test] public void Then_Keeps_List_Of_Comparisons() { richTextConfig .DisplayName("New Name") .Description("New description"); var diff = PropertyDiffgram(RichTextDiffgram); Assert.That( diff.Comparisons, Has.Exactly(1).With.Property("Key").EqualTo("Name").And.Property("Result").EqualTo(ComparisonResult.Modified) & Has.Exactly(1).With.Property("Key").EqualTo("Description").And.Property("Result").EqualTo(ComparisonResult.Modified) & Has.Exactly(1).With.Property("Key").EqualTo("DataType").And.Property("Result").EqualTo(ComparisonResult.Unchanged) ); } [Test] public void With_Invalid_DataType_Is_Unsafe() { richTextConfig.DataType("NotTiny"); var propertyDiff = PropertyDiffgram(RichTextDiffgram); Assert.That(propertyDiff, Has.Property("IsUnsafe").True); } [Test] public void With_Different_DataType_Is_Unsafe() { StubDataType(6, "NotTiny"); richTextConfig.DataType("NotTiny"); var propertyDiff = PropertyDiffgram(RichTextDiffgram); Assert.That(propertyDiff, Has.Property("IsUnsafe").True); } [Test] public void With_Different_Mandatory_Is_Unsafe() { urlConfigurator.Mandatory(false); var propertyDiff = PropertyDiffgram(UrlDiffgram); Assert.That(propertyDiff, Has.Property("IsUnsafe").True); } [Test] public void With_Different_Regex_Is_Unsafe() { urlConfigurator.Regex(@"\d"); var propertyDiff = PropertyDiffgram(UrlDiffgram); Assert.That(propertyDiff, Has.Property("IsUnsafe").True); } private void AddRichTextProperty() { tab.PropertyTypes.Add( new PropertyType(dataTypeDefinition) { DataTypeDefinitionId = 5, Alias = "richtext", Name = "Rich text", Description = "Write rich content here" }); } private void AddUrlProperty() { tab.PropertyTypes.Add( new PropertyType(dataTypeDefinition) { DataTypeDefinitionId = 6, Alias = "url", Name = "Url", Description = "A relevant link", Mandatory = true, ValidationRegExp = "https?://[a-zA-Z0-9-.]+.[a-zA-Z]{2,}" }); } private PropertyTypeDiffgram PropertyDiffgram(Func<Diffgram, PropertyTypeDiffgram> propertySelector) { var diffgram = Config.Compare(); var propertyTypeDiffgram = propertySelector(diffgram); return propertyTypeDiffgram; } private static PropertyTypeDiffgram RichTextDiffgram(Diffgram diffgram) { return TabDiffgram(diffgram).Properties["richtext"]; } private static PropertyTypeDiffgram UrlDiffgram(Diffgram diffgram) { return TabDiffgram(diffgram).Properties["url"]; } private static TabDiffgram TabDiffgram(Diffgram diffgram) { return diffgram.DocumentTypes["contentType"].Tabs["tab"]; } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id: ErrorLogPage.cs 703 2010-01-18 00:00:18Z jamesdriscoll@btinternet.com $")] namespace Elmah { #region Imports using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Collections.Generic; using CultureInfo = System.Globalization.CultureInfo; #endregion /// <summary> /// Renders an HTML page displaying a page of errors from the error log. /// </summary> internal sealed class ErrorLogPage : ErrorPageBase { private int _pageIndex; private int _pageSize; private int _totalCount; private List<ErrorLogEntry> _errorEntryList; private const int _defaultPageSize = 15; private const int _maximumPageSize = 100; protected override void OnLoad(EventArgs e) { // // Get the page index and size parameters within their bounds. // _pageSize = Convert.ToInt32(this.Request.QueryString["size"], CultureInfo.InvariantCulture); _pageSize = Math.Min(_maximumPageSize, Math.Max(0, _pageSize)); if (_pageSize == 0) { _pageSize = _defaultPageSize; } _pageIndex = Convert.ToInt32(this.Request.QueryString["page"], CultureInfo.InvariantCulture); _pageIndex = Math.Max(1, _pageIndex) - 1; // // Read the error records. // _errorEntryList = new List<ErrorLogEntry>(_pageSize); _totalCount = this.ErrorLog.GetErrors(_pageIndex, _pageSize, _errorEntryList); // // Set the title of the page. // this.PageTitle = string.Format("Error log for {0} on {1} (Page #{2})", this.ApplicationName, EnvironmentHelper.GetMachineName(Context), (_pageIndex + 1).ToString("N0")); base.OnLoad(e); } protected override void RenderHead(HtmlTextWriter writer) { if (writer == null) throw new ArgumentNullException("writer"); base.RenderHead(writer); // // Write a <link> tag to relate the RSS feed. // writer.AddAttribute(HtmlTextWriterAttribute.Rel, HtmlLinkType.Alternate); writer.AddAttribute(HtmlTextWriterAttribute.Type, "application/rss+xml"); writer.AddAttribute(HtmlTextWriterAttribute.Title, "RSS"); writer.AddAttribute(HtmlTextWriterAttribute.Href, this.BasePageName + "/rss"); writer.RenderBeginTag(HtmlTextWriterTag.Link); writer.RenderEndTag(); writer.WriteLine(); // // If on the first page, then enable auto-refresh every minute // by issuing the following markup: // // <meta http-equiv="refresh" content="60"> // if (_pageIndex == 0) { writer.AddAttribute("http-equiv", "refresh"); writer.AddAttribute("content", "60"); writer.RenderBeginTag(HtmlTextWriterTag.Meta); writer.RenderEndTag(); writer.WriteLine(); } } protected override void RenderContents(HtmlTextWriter writer) { if (writer == null) throw new ArgumentNullException("writer"); // // Write out the page title and speed bar in the body. // RenderTitle(writer); SpeedBar.Render(writer, SpeedBar.RssFeed.Format(BasePageName), SpeedBar.RssDigestFeed.Format(BasePageName), SpeedBar.DownloadLog.Format(BasePageName), SpeedBar.Help, SpeedBar.About.Format(BasePageName)); if (_errorEntryList.Count != 0) { // // Write error number range displayed on this page and the // total available in the log, followed by stock // page sizes. // writer.RenderBeginTag(HtmlTextWriterTag.P); RenderStats(writer); RenderStockPageSizes(writer); writer.RenderEndTag(); // </p> writer.WriteLine(); // // Write out the main table to display the errors. // RenderErrors(writer); // // Write out page navigation links. // RenderPageNavigators(writer); } else { // // No errors found in the log, so display a corresponding // message. // RenderNoErrors(writer); } base.RenderContents(writer); } private void RenderPageNavigators(HtmlTextWriter writer) { Debug.Assert(writer != null); // // If not on the last page then render a link to the next page. // writer.RenderBeginTag(HtmlTextWriterTag.P); int nextPageIndex = _pageIndex + 1; bool moreErrors = nextPageIndex * _pageSize < _totalCount; if (moreErrors) RenderLinkToPage(writer, HtmlLinkType.Next, "Next errors", nextPageIndex); // // If not on the first page then render a link to the firs page. // if (_pageIndex > 0 && _totalCount > 0) { if (moreErrors) writer.Write("; "); RenderLinkToPage(writer, HtmlLinkType.Start, "Back to first page", 0); } writer.RenderEndTag(); // </p> writer.WriteLine(); } private void RenderStockPageSizes(HtmlTextWriter writer) { Debug.Assert(writer != null); // // Write out a set of stock page size choices. Note that // selecting a stock page size re-starts the log // display from the first page to get the right paging. // writer.Write("Start with "); int[] stockSizes = new int[] { 10, 15, 20, 25, 30, 50, 100 }; for (int stockSizeIndex = 0; stockSizeIndex < stockSizes.Length; stockSizeIndex++) { int stockSize = stockSizes[stockSizeIndex]; if (stockSizeIndex > 0) writer.Write(stockSizeIndex + 1 < stockSizes.Length ? ", " : " or "); RenderLinkToPage(writer, HtmlLinkType.Start, stockSize.ToString(), 0, stockSize); } writer.Write(" errors per page."); } private void RenderStats(HtmlTextWriter writer) { Debug.Assert(writer != null); int firstErrorNumber = _pageIndex * _pageSize + 1; int lastErrorNumber = firstErrorNumber + _errorEntryList.Count - 1; int totalPages = (int) Math.Ceiling((double) _totalCount / _pageSize); writer.Write("Errors {0} to {1} of total {2} (page {3} of {4}). ", firstErrorNumber.ToString("N0"), lastErrorNumber.ToString("N0"), _totalCount.ToString("N0"), (_pageIndex + 1).ToString("N0"), totalPages.ToString("N0")); } private void RenderTitle(HtmlTextWriter writer) { Debug.Assert(writer != null); // // If the application name matches the APPL_MD_PATH then its // of the form /LM/W3SVC/.../<name>. In this case, use only the // <name> part to reduce the noise. The full application name is // still made available through a tooltip. // string simpleName = this.ApplicationName; if (string.Compare(simpleName, this.Request.ServerVariables["APPL_MD_PATH"], true, CultureInfo.InvariantCulture) == 0) { int lastSlashIndex = simpleName.LastIndexOf('/'); if (lastSlashIndex > 0) simpleName = simpleName.Substring(lastSlashIndex + 1); } writer.AddAttribute(HtmlTextWriterAttribute.Id, "PageTitle"); writer.RenderBeginTag(HtmlTextWriterTag.H1); writer.Write("Error Log for "); writer.AddAttribute(HtmlTextWriterAttribute.Id, "ApplicationName"); writer.AddAttribute(HtmlTextWriterAttribute.Title, this.Server.HtmlEncode(this.ApplicationName)); writer.RenderBeginTag(HtmlTextWriterTag.Span); Server.HtmlEncode(simpleName, writer); writer.Write(" on "); Server.HtmlEncode(EnvironmentHelper.GetMachineName(Context), writer); writer.RenderEndTag(); // </span> writer.RenderEndTag(); // </h1> writer.WriteLine(); } private void RenderNoErrors(HtmlTextWriter writer) { Debug.Assert(writer != null); writer.RenderBeginTag(HtmlTextWriterTag.P); writer.Write("No errors found. "); // // It is possible that there are no error at the requested // page in the log (especially if it is not the first page). // However, if there are error in the log // if (_pageIndex > 0 && _totalCount > 0) { RenderLinkToPage(writer, HtmlLinkType.Start, "Go to first page", 0); writer.Write(". "); } writer.RenderEndTag(); writer.WriteLine(); } private void RenderErrors(HtmlTextWriter writer) { Debug.Assert(writer != null); // // Create a table to display error information in each row. // Table table = new Table(); table.ID = "ErrorLog"; table.CellSpacing = 0; // // Create the table row for headings. // TableRow headRow = new TableRow(); headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Host", "host-col")); headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Code", "code-col")); headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Type", "type-col")); headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Error", "error-col")); headRow.Cells.Add(FormatCell(new TableHeaderCell(), "User", "user-col")); headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Date", "date-col")); headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Time", "time-col")); table.Rows.Add(headRow); // // Generate a table body row for each error. // for (int errorIndex = 0; errorIndex < _errorEntryList.Count; errorIndex++) { ErrorLogEntry errorEntry = (ErrorLogEntry) _errorEntryList[errorIndex]; Error error = errorEntry.Error; TableRow bodyRow = new TableRow(); bodyRow.CssClass = errorIndex % 2 == 0 ? "even-row" : "odd-row"; // // Format host and status code cells. // bodyRow.Cells.Add(FormatCell(new TableCell(), error.HostName, "host-col")); bodyRow.Cells.Add(FormatCell(new TableCell(), error.StatusCode.ToString(), "code-col", HttpWorkerRequest.GetStatusDescription(error.StatusCode) ?? string.Empty)); bodyRow.Cells.Add(FormatCell(new TableCell(), ErrorDisplay.HumaneExceptionErrorType(error), "type-col", error.Type)); // // Format the message cell, which contains the message // text and a details link pointing to the page where // all error details can be viewed. // TableCell messageCell = new TableCell(); messageCell.CssClass = "error-col"; Label messageLabel = new Label(); messageLabel.Text = this.Server.HtmlEncode(error.Message); HyperLink detailsLink = new HyperLink(); detailsLink.NavigateUrl = BasePageName + "/detail?id=" + HttpUtility.UrlEncode(errorEntry.Id); detailsLink.Text = "Details&hellip;"; messageCell.Controls.Add(messageLabel); messageCell.Controls.Add(new LiteralControl(" ")); messageCell.Controls.Add(detailsLink); bodyRow.Cells.Add(messageCell); // // Format the user, date and time cells. // bodyRow.Cells.Add(FormatCell(new TableCell(), error.User, "user-col")); bodyRow.Cells.Add(FormatCell(new TableCell(), error.Time.ToShortDateString(), "date-col", error.Time.ToLongDateString())); bodyRow.Cells.Add(FormatCell(new TableCell(), error.Time.ToShortTimeString(), "time-col", error.Time.ToLongTimeString())); // // Finally, add the row to the table. // table.Rows.Add(bodyRow); } table.RenderControl(writer); } private TableCell FormatCell(TableCell cell, string contents, string cssClassName) { return FormatCell(cell, contents, cssClassName, string.Empty); } private TableCell FormatCell(TableCell cell, string contents, string cssClassName, string toolTip) { Debug.Assert(cell != null); Debug.AssertStringNotEmpty(cssClassName); cell.Wrap = false; cell.CssClass = cssClassName; if (contents.Length == 0) { cell.Text = "&nbsp;"; } else { string encodedContents = this.Server.HtmlEncode(contents); if (toolTip.Length == 0) { cell.Text = encodedContents; } else { Label label = new Label(); label.ToolTip = toolTip; label.Text = encodedContents; cell.Controls.Add(label); } } return cell; } private void RenderLinkToPage(HtmlTextWriter writer, string type, string text, int pageIndex) { RenderLinkToPage(writer, type, text, pageIndex, _pageSize); } private void RenderLinkToPage(HtmlTextWriter writer, string type, string text, int pageIndex, int pageSize) { Debug.Assert(writer != null); Debug.Assert(text != null); Debug.Assert(pageIndex >= 0); Debug.Assert(pageSize >= 0); string href = string.Format("{0}?page={1}&size={2}", BasePageName, (pageIndex + 1).ToString(CultureInfo.InvariantCulture), pageSize.ToString(CultureInfo.InvariantCulture)); writer.AddAttribute(HtmlTextWriterAttribute.Href, href); if (type != null && type.Length > 0) writer.AddAttribute(HtmlTextWriterAttribute.Rel, type); writer.RenderBeginTag(HtmlTextWriterTag.A); this.Server.HtmlEncode(text, writer); writer.RenderEndTag(); } } }
using System.Drawing; using System; namespace GuiLabs.Editor.CSharp { public static class Icons { public static Image GetIconForType(ClassType type, string modifier) { switch (type) { case ClassType.Class: return GetIconForClass(modifier); case ClassType.Enum: return GetIconForEnum(modifier); case ClassType.Interface: return GetIconForInterface(modifier); case ClassType.Struct: return GetIconForStruct(modifier); case ClassType.Delegate: return GetIconForDelegate(modifier); case ClassType.Module: default: return GetIconForClass(modifier); } } public static Image GetIconForType(Type reflectionType) { if (reflectionType.IsClass) { return Icons.TypeClass; } else if (reflectionType.IsValueType) { return Icons.TypeStruct; } else if (reflectionType.IsInterface) { return Icons.TypeInterface; } else if (reflectionType.IsEnum) { return Icons.TypeEnum; } else { return Icons.TypeDelegate; } } public static Image MethodPrivate = Resources.MethodPrivate; public static Image MethodProtected = Resources.MethodProtected; public static Image MethodInternal = Resources.MethodInternal; public static Image MethodPublic = Resources.MethodPublic; public static Image GetIconForMethod(string modifier) { switch (modifier) { case "private": return MethodPrivate; case "internal": return MethodInternal; case "public": return MethodPublic; default: return MethodProtected; } } public static Image PropertyPrivate = Resources.PropertyPrivate; public static Image PropertyProtected = Resources.PropertyProtected; public static Image PropertyInternal = Resources.PropertyInternal; public static Image PropertyPublic = Resources.PropertyPublic; public static Image GetIconForProperty(string modifier) { switch (modifier) { case "private": return PropertyPrivate; case "internal": return PropertyInternal; case "public": return PropertyPublic; default: return PropertyProtected; } } public static Image FieldPrivate = Resources.FieldPrivate; public static Image FieldProtected = Resources.FieldProtected; public static Image FieldInternal = Resources.FieldInternal; public static Image FieldPublic = Resources.FieldPublic; public static Image GetIconForField(string modifier) { switch (modifier) { case "private": return FieldPrivate; case "internal": return FieldInternal; case "public": return FieldPublic; default: return FieldProtected; } } public static Image EventPrivate = Resources.EventPrivate; public static Image EventProtected = Resources.EventProtected; public static Image EventInternal = Resources.EventInternal; public static Image EventPublic = Resources.EventPublic; public static Image GetIconForEvent(string modifier) { switch (modifier) { case "private": return EventPrivate; case "internal": return EventInternal; case "public": return EventPublic; default: return EventProtected; } } public static Image TypeClassPrivate = Resources.TypeClassPrivate; public static Image TypeClassProtected = Resources.TypeClassProtected; public static Image TypeClassInternal = Resources.TypeClassInternal; public static Image TypeClass = Resources.TypeClass; public static Image GetIconForClass(string modifier) { switch (modifier) { case "private": return TypeClassPrivate; case "internal": return TypeClassInternal; case "public": return TypeClass; default: return TypeClassProtected; } } public static Image TypeStructPrivate = Resources.TypeStructPrivate; public static Image TypeStructProtected = Resources.TypeStructProtected; public static Image TypeStructInternal = Resources.TypeStructInternal; public static Image TypeStruct = Resources.TypeStruct; public static Image GetIconForStruct(string modifier) { switch (modifier) { case "private": return TypeStructPrivate; case "internal": return TypeStructInternal; case "public": return TypeStruct; default: return TypeStructProtected; } } public static Image TypeInterfacePrivate = Resources.TypeInterfacePrivate; public static Image TypeInterfaceProtected = Resources.TypeInterfaceProtected; public static Image TypeInterfaceInternal = Resources.TypeInterfaceInternal; public static Image TypeInterface = Resources.TypeInterface; public static Image GetIconForInterface(string modifier) { switch (modifier) { case "private": return TypeInterfacePrivate; case "internal": return TypeInterfaceInternal; case "public": return TypeInterface; default: return TypeInterfaceProtected; } } public static Image TypeEnumPrivate = Resources.TypeEnumPrivate; public static Image TypeEnumProtected = Resources.TypeEnumProtected; public static Image TypeEnumInternal = Resources.TypeEnumInternal; public static Image TypeEnum = Resources.TypeEnum; public static Image GetIconForEnum(string modifier) { switch (modifier) { case "private": return TypeEnumPrivate; case "internal": return TypeEnumInternal; case "public": return TypeEnum; default: return TypeEnumProtected; } } public static Image TypeDelegatePrivate = Resources.TypeDelegatePrivate; public static Image TypeDelegateProtected = Resources.TypeDelegateProtected; public static Image TypeDelegateInternal = Resources.TypeDelegateInternal; public static Image TypeDelegate = Resources.TypeDelegate; public static Image GetIconForDelegate(string modifier) { switch (modifier) { case "private": return TypeDelegatePrivate; case "internal": return TypeDelegateInternal; case "public": return TypeDelegate; default: return TypeDelegateProtected; } } public static Image Variable = Resources.Variable; public static Image Parameter = Resources.Parameter; public static Image CodeSnippet = Resources.CodeSnippet; public static Image Keyword = Resources.Keyword; public static Image Namespace = Resources.Namespace; } }
using System; using System.Text; using System.Runtime.InteropServices; namespace Packet { public enum HeroClass { FIGHTER = 0, MAGICIAN = 1, ARCHER = 2, THIEF = 3, PRIEST = 4, MONK = 5, NUM = 6, } public enum Type { LOGIN_REQUEST = 0, LOGIN_RESPONSE = 1, ALLOC_HERO = 2, MATCH_START = 3, MATCH_END = 4, GAME_DATA = 5, SKILL_DATA = 6, CHANGE_HERO_STATE = 7, SELECT_HERO = 8, VALID_SKILLS = 9, SKILL_RANGE_REQUEST = 10, SKILL_RANGE_RESPONSE = 11, SKILL_SHOT = 12, MOVE_HERO = 13, ACT_HERO = 14, DEAD_HERO = 15, TURN_END = 16, UPDATE_TURN = 17, REJECT = 18, HERO_STATE = 19, HERO_REMOVE_STATE = 20, EFFECT_RESPONSE = 21, REGISTER_ACCOUNT_REQUEST = 22, REGISTER_ACCOUNT_RESPONSE = 23, REQUEST_MATCH = 24, CANCEL_MATCH = 25, ENTER_LOBBY = 26, HERO_DATA = 27, PICK_TURN = 28, PICK = 29, PICK_DATA = 30, PICK_END = 31, SURRENDER = 32, TYPE_NUM = 33, } public enum StateType { STATE_IRON = 0, STATE_POISON = 1, STATE_ICE = 2, STATE_BURN = 3, STATE_BUFF = 4, STATE_TAUNT = 5, STATE_SACRIFICE = 6, STATE_PRAY = 7, } public enum SkillType { FIGHTER_ATTACK = 0, FIGHTER_CHARGE = 1, FIGHTER_HARD = 2, FIGHTER_IRON = 3, MAGICIAN_ICE_ARROW = 4, MAGICIAN_FIRE_BLAST = 5, MAGICIAN_THUNDER_STORM = 6, MAGICIAN_POLYMORPH = 7, ARCHER_ATTACK = 8, ARCHER_BACK_ATTACK = 9, ARCHER_PENETRATE_SHOT = 10, ARCHER_SNIPE = 11, THIEF_ATTACK = 12, THIEF_BACK_STEP = 13, THIEF_POISON = 14, THIEF_TAUNT = 15, PRIEST_HEAL = 16, PRIEST_ATTACK = 17, PRIEST_BUFF = 18, PRIEST_REMOVE_MAGIC = 19, MONK_ATTACK = 20, MONK_SACRIFICE = 21, MONK_PRAY = 22, MONK_KICK = 23, } public enum LoginResult { FAILED = 0, SUCCESS = 1, } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class Header { [MarshalAs(UnmanagedType.U1)] public byte type; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] public string foo; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class LoginRequest : Header { [MarshalAs(UnmanagedType.U1)] public sbyte idLength; [MarshalAs(UnmanagedType.U1)] public sbyte passwordLength; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public char[] id; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public char[] password; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class LoginResponse : Header { [MarshalAs(UnmanagedType.U1)] public byte result; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class AllocHero : Header { [MarshalAs(UnmanagedType.U1)] public sbyte allocNum; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public sbyte[] x= new sbyte[4]; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public sbyte[] y= new sbyte[4]; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class MatchStart : Header { [MarshalAs(UnmanagedType.U1)] public sbyte turn; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class GameData : Header { [MarshalAs(UnmanagedType.U1)] public sbyte turn; [MarshalAs(UnmanagedType.U1)] public sbyte classNum; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public byte[] classes= new byte[4]; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public sbyte[] hp= new sbyte[4]; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public sbyte[] act= new sbyte[4]; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public sbyte[] x= new sbyte[4]; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public sbyte[] y= new sbyte[4]; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class SkillData : Header { [MarshalAs(UnmanagedType.U1)] public sbyte turn; [MarshalAs(UnmanagedType.U1)] public sbyte heroIdx; [MarshalAs(UnmanagedType.U1)] public sbyte skillNum; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public byte[] skillType= new byte[4]; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public sbyte[] skillLevel= new sbyte[4]; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class MoveHero : Header { [MarshalAs(UnmanagedType.U1)] public sbyte idx; [MarshalAs(UnmanagedType.U1)] public sbyte x; [MarshalAs(UnmanagedType.U1)] public sbyte y; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class ChangeHeroState : Header { [MarshalAs(UnmanagedType.U1)] public sbyte turn; [MarshalAs(UnmanagedType.U1)] public sbyte idx; [MarshalAs(UnmanagedType.U1)] public sbyte maxHp; [MarshalAs(UnmanagedType.U1)] public sbyte hp; [MarshalAs(UnmanagedType.U1)] public sbyte maxAct; [MarshalAs(UnmanagedType.U1)] public sbyte act; [MarshalAs(UnmanagedType.U1)] public sbyte x; [MarshalAs(UnmanagedType.U1)] public sbyte y; [MarshalAs(UnmanagedType.U1)] public sbyte isMove; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class TurnEnd : Header { [MarshalAs(UnmanagedType.U1)] public sbyte turn; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class UpdateTurn : Header { [MarshalAs(UnmanagedType.U1)] public sbyte nowTurn; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class SelectHero : Header { [MarshalAs(UnmanagedType.U1)] public sbyte idx; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class ValidSkills : Header { [MarshalAs(UnmanagedType.U1)] public sbyte num; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)] public sbyte[] idx= new sbyte[6]; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class SkillRangeRequest : Header { [MarshalAs(UnmanagedType.U1)] public sbyte heroIdx; [MarshalAs(UnmanagedType.U1)] public sbyte skillIdx; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class SkillRangeResponse : Header { [MarshalAs(UnmanagedType.U1)] public sbyte heroIdx; [MarshalAs(UnmanagedType.U1)] public sbyte skillIdx; [MarshalAs(UnmanagedType.U1)] public sbyte isMyField; [MarshalAs(UnmanagedType.U1)] public sbyte rangeNum; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)] public sbyte[] rangeX= new sbyte[9]; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)] public sbyte[] rangeY= new sbyte[9]; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class EffectResponse : Header { [MarshalAs(UnmanagedType.U1)] public sbyte heroIdx; [MarshalAs(UnmanagedType.U1)] public sbyte skillIdx; [MarshalAs(UnmanagedType.U1)] public sbyte effectNum; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)] public sbyte[] effectX= new sbyte[9]; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)] public sbyte[] effectY= new sbyte[9]; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class ActHero : Header { [MarshalAs(UnmanagedType.U1)] public sbyte heroIdx; [MarshalAs(UnmanagedType.U1)] public sbyte skillIdx; [MarshalAs(UnmanagedType.U1)] public sbyte x; [MarshalAs(UnmanagedType.U1)] public sbyte y; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class SkillShot : Header { [MarshalAs(UnmanagedType.U1)] public sbyte turn; [MarshalAs(UnmanagedType.U1)] public sbyte heroIdx; [MarshalAs(UnmanagedType.U1)] public sbyte skillIdx; [MarshalAs(UnmanagedType.U1)] public sbyte effectNum; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public sbyte[] effectTurn= new sbyte[8]; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public sbyte[] effectX= new sbyte[8]; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public sbyte[] effectY= new sbyte[8]; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class MatchEnd : Header { [MarshalAs(UnmanagedType.U1)] public sbyte winner; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class Reject : Header { } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class DeadHero : Header { [MarshalAs(UnmanagedType.U1)] public sbyte turn; [MarshalAs(UnmanagedType.U1)] public sbyte heroIdx; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class HeroState : Header { [MarshalAs(UnmanagedType.U1)] public byte stateType; [MarshalAs(UnmanagedType.U1)] public sbyte targetTurn; [MarshalAs(UnmanagedType.U1)] public sbyte targetIdx; [MarshalAs(UnmanagedType.U1)] public sbyte executerTurn; [MarshalAs(UnmanagedType.U1)] public sbyte executerIdx; [MarshalAs(UnmanagedType.U1)] public sbyte stateId; [MarshalAs(UnmanagedType.U1)] public sbyte damaged; [MarshalAs(UnmanagedType.U1)] public sbyte hp; [MarshalAs(UnmanagedType.U1)] public sbyte act; [MarshalAs(UnmanagedType.U1)] public sbyte attack; [MarshalAs(UnmanagedType.U1)] public sbyte defence; [MarshalAs(UnmanagedType.U1)] public sbyte duration; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class RemoveHeroState : Header { [MarshalAs(UnmanagedType.U1)] public sbyte targetTurn; [MarshalAs(UnmanagedType.U1)] public sbyte targetIdx; [MarshalAs(UnmanagedType.U1)] public sbyte stateId; [MarshalAs(UnmanagedType.U1)] public byte stateType; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class RegisterAccountRequest : Header { [MarshalAs(UnmanagedType.U1)] public sbyte idLength; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public char[] id= new char[16]; [MarshalAs(UnmanagedType.U1)] public sbyte passwordLength; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public char[] password= new char[16]; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class RegisterAccountResponse : Header { [MarshalAs(UnmanagedType.U1)] public sbyte isSuccess; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class RequestMatch : Header { } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class CancelMatch : Header { } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class EnterLobby : Header { [MarshalAs(UnmanagedType.U4)] public Int32 win; [MarshalAs(UnmanagedType.U4)] public Int32 lose; [MarshalAs(UnmanagedType.U1)] public sbyte heroNum; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class HeroData : Header { [MarshalAs(UnmanagedType.U1)] public byte heroType; [MarshalAs(UnmanagedType.U1)] public sbyte level; [MarshalAs(UnmanagedType.U1)] public sbyte hp; [MarshalAs(UnmanagedType.U1)] public sbyte act; [MarshalAs(UnmanagedType.U1)] public sbyte skillNum; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public sbyte[] skillType= new sbyte[4]; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public sbyte[] skillLevel= new sbyte[4]; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class PickTurn : Header { [MarshalAs(UnmanagedType.U1)] public sbyte pickNum; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class Pick : Header { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] public sbyte[] heroIdx= new sbyte[2]; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class PickData : Header { [MarshalAs(UnmanagedType.U1)] public sbyte turn; [MarshalAs(UnmanagedType.U1)] public sbyte heroNum; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] public byte[] heroType= new byte[2]; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class PickEnd : Header { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public sbyte[] heroIdx= new sbyte[4]; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public class Surrender : Header { } }
// 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.Text { using System.Runtime.Serialization; using System.Text; using System; using System.Diagnostics.Contracts; // A Decoder is used to decode a sequence of blocks of bytes into a // sequence of blocks of characters. Following instantiation of a decoder, // sequential blocks of bytes are converted into blocks of characters through // calls to the GetChars method. The decoder maintains state between the // conversions, allowing it to correctly decode byte sequences that span // adjacent blocks. // // Instances of specific implementations of the Decoder abstract base // class are typically obtained through calls to the GetDecoder method // of Encoding objects. // [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public abstract class Decoder { internal DecoderFallback m_fallback = null; [NonSerialized] internal DecoderFallbackBuffer m_fallbackBuffer = null; internal void SerializeDecoder(SerializationInfo info) { info.AddValue("m_fallback", this.m_fallback); } protected Decoder( ) { // We don't call default reset because default reset probably isn't good if we aren't initialized. } [System.Runtime.InteropServices.ComVisible(false)] public DecoderFallback Fallback { get { return m_fallback; } set { if (value == null) throw new ArgumentNullException(nameof(value)); Contract.EndContractBlock(); // Can't change fallback if buffer is wrong if (m_fallbackBuffer != null && m_fallbackBuffer.Remaining > 0) throw new ArgumentException( Environment.GetResourceString("Argument_FallbackBufferNotEmpty"), nameof(value)); m_fallback = value; m_fallbackBuffer = null; } } // Note: we don't test for threading here because async access to Encoders and Decoders // doesn't work anyway. [System.Runtime.InteropServices.ComVisible(false)] public DecoderFallbackBuffer FallbackBuffer { get { if (m_fallbackBuffer == null) { if (m_fallback != null) m_fallbackBuffer = m_fallback.CreateFallbackBuffer(); else m_fallbackBuffer = DecoderFallback.ReplacementFallback.CreateFallbackBuffer(); } return m_fallbackBuffer; } } internal bool InternalHasFallbackBuffer { get { return m_fallbackBuffer != null; } } // Reset the Decoder // // Normally if we call GetChars() and an error is thrown we don't change the state of the Decoder. This // would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.) // // If the caller doesn't want to try again after GetChars() throws an error, then they need to call Reset(). // // Virtual implimentation has to call GetChars with flush and a big enough buffer to clear a 0 byte string // We avoid GetMaxCharCount() because a) we can't call the base encoder and b) it might be really big. [System.Runtime.InteropServices.ComVisible(false)] public virtual void Reset() { byte[] byteTemp = Array.Empty<byte>(); char[] charTemp = new char[GetCharCount(byteTemp, 0, 0, true)]; GetChars(byteTemp, 0, 0, charTemp, 0, true); if (m_fallbackBuffer != null) m_fallbackBuffer.Reset(); } // Returns the number of characters the next call to GetChars will // produce if presented with the given range of bytes. The returned value // takes into account the state in which the decoder was left following the // last call to GetChars. The state of the decoder is not affected // by a call to this method. // public abstract int GetCharCount(byte[] bytes, int index, int count); [System.Runtime.InteropServices.ComVisible(false)] public virtual int GetCharCount(byte[] bytes, int index, int count, bool flush) { return GetCharCount(bytes, index, count); } // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implimentation) [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe int GetCharCount(byte* bytes, int count, bool flush) { // Validate input parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); byte[] arrbyte = new byte[count]; int index; for (index = 0; index < count; index++) arrbyte[index] = bytes[index]; return GetCharCount(arrbyte, 0, count); } // Decodes a range of bytes in a byte array into a range of characters // in a character array. The method decodes byteCount bytes from // bytes starting at index byteIndex, storing the resulting // characters in chars starting at index charIndex. The // decoding takes into account the state in which the decoder was left // following the last call to this method. // // An exception occurs if the character array is not large enough to // hold the complete decoding of the bytes. The GetCharCount method // can be used to determine the exact number of characters that will be // produced for a given range of bytes. Alternatively, the // GetMaxCharCount method of the Encoding that produced this // decoder can be used to determine the maximum number of characters that // will be produced for a given number of bytes, regardless of the actual // byte values. // public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex); public virtual int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex); } // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implimentation) // // WARNING WARNING WARNING // // WARNING: If this breaks it could be a security threat. Obviously we // call this internally, so you need to make sure that your pointers, counts // and indexes are correct when you call this method. // // In addition, we have internal code, which will be marked as "safe" calling // this code. However this code is dependent upon the implimentation of an // external GetChars() method, which could be overridden by a third party and // the results of which cannot be guaranteed. We use that result to copy // the char[] to our char* output buffer. If the result count was wrong, we // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow charCount either. [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { // Validate input parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Get the byte array to convert byte[] arrByte = new byte[byteCount]; int index; for (index = 0; index < byteCount; index++) arrByte[index] = bytes[index]; // Get the char array to fill char[] arrChar = new char[charCount]; // Do the work int result = GetChars(arrByte, 0, byteCount, arrChar, 0, flush); Contract.Assert(result <= charCount, "Returned more chars than we have space for"); // Copy the char array // WARNING: We MUST make sure that we don't copy too many chars. We can't // rely on result because it could be a 3rd party implimentation. We need // to make sure we never copy more than charCount chars no matter the value // of result if (result < charCount) charCount = result; // We check both result and charCount so that we don't accidentally overrun // our pointer buffer just because of an issue in GetChars for (index = 0; index < charCount; index++) chars[index] = arrChar[index]; return charCount; } // This method is used when the output buffer might not be large enough. // It will decode until it runs out of bytes, and then it will return // true if it the entire input was converted. In either case it // will also return the number of converted bytes and output characters used. // It will only throw a buffer overflow exception if the entire lenght of chars[] is // too small to store the next char. (like 0 or maybe 1 or 4 for some encodings) // We're done processing this buffer only if completed returns true. // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input bytes are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many bytes as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) [System.Runtime.InteropServices.ComVisible(false)] public virtual void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate parameters if (bytes == null || chars == null) throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)), Environment.GetResourceString("ArgumentNull_Array")); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); bytesUsed = byteCount; // Its easy to do if it won't overrun our buffer. while (bytesUsed > 0) { if (GetCharCount(bytes, byteIndex, bytesUsed, flush) <= charCount) { charsUsed = GetChars(bytes, byteIndex, bytesUsed, chars, charIndex, flush); completed = (bytesUsed == byteCount && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; bytesUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow throw new ArgumentException(Environment.GetResourceString("Argument_ConversionOverflow")); } // This is the version that uses *. // We're done processing this buffer only if completed returns true. // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input bytes are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many bytes as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate input parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Get ready to do it bytesUsed = byteCount; // Its easy to do if it won't overrun our buffer. while (bytesUsed > 0) { if (GetCharCount(bytes, bytesUsed, flush) <= charCount) { charsUsed = GetChars(bytes, bytesUsed, chars, charCount, flush); completed = (bytesUsed == byteCount && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; bytesUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow throw new ArgumentException(Environment.GetResourceString("Argument_ConversionOverflow")); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Net; using System.Text; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage.Table; using Orleans.Runtime; namespace Orleans.AzureUtils { internal class SiloInstanceTableEntry : TableEntity { public string DeploymentId { get; set; } // PartitionKey public string Address { get; set; } // RowKey public string Port { get; set; } // RowKey public string Generation { get; set; } // RowKey public string HostName { get; set; } // Mandatory public string Status { get; set; } // Mandatory public string ProxyPort { get; set; } // Optional public string RoleName { get; set; } // Optional - only for Azure role public string SiloName { get; set; } public string InstanceName { get; set; } // For backward compatability we leave the old column, untill all clients update the code to new version. public string UpdateZone { get; set; } // Optional - only for Azure role public string FaultZone { get; set; } // Optional - only for Azure role public string SuspectingSilos { get; set; } // For liveness public string SuspectingTimes { get; set; } // For liveness public string StartTime { get; set; } // Time this silo was started. For diagnostics. public string IAmAliveTime { get; set; } // Time this silo updated it was alive. For diagnostics. public string MembershipVersion { get; set; } // Special version row (for serializing table updates). // We'll have a designated row with only MembershipVersion column. internal const string TABLE_VERSION_ROW = "VersionRow"; // Row key for version row. internal const char Seperator = '-'; public static string ConstructRowKey(SiloAddress silo) { return String.Format("{0}-{1}-{2}", silo.Endpoint.Address, silo.Endpoint.Port, silo.Generation); } internal static SiloAddress UnpackRowKey(string rowKey) { var debugInfo = "UnpackRowKey"; try { #if DEBUG debugInfo = String.Format("UnpackRowKey: RowKey={0}", rowKey); Trace.TraceInformation(debugInfo); #endif int idx1 = rowKey.IndexOf(Seperator); int idx2 = rowKey.LastIndexOf(Seperator); #if DEBUG debugInfo = String.Format("UnpackRowKey: RowKey={0} Idx1={1} Idx2={2}", rowKey, idx1, idx2); #endif var addressStr = rowKey.Substring(0, idx1); var portStr = rowKey.Substring(idx1 + 1, idx2 - idx1 - 1); var genStr = rowKey.Substring(idx2 + 1); #if DEBUG debugInfo = String.Format("UnpackRowKey: RowKey={0} -> Address={1} Port={2} Generation={3}", rowKey, addressStr, portStr, genStr); Trace.TraceInformation(debugInfo); #endif IPAddress address = IPAddress.Parse(addressStr); int port = Int32.Parse(portStr); int generation = Int32.Parse(genStr); return SiloAddress.New(new IPEndPoint(address, port), generation); } catch (Exception exc) { throw new AggregateException("Error from " + debugInfo, exc); } } public override string ToString() { var sb = new StringBuilder(); if (RowKey.Equals(TABLE_VERSION_ROW)) { sb.Append("VersionRow [").Append(DeploymentId); sb.Append(" Deployment=").Append(DeploymentId); sb.Append(" MembershipVersion=").Append(MembershipVersion); sb.Append("]"); } else { sb.Append("OrleansSilo ["); sb.Append(" Deployment=").Append(DeploymentId); sb.Append(" LocalEndpoint=").Append(Address); sb.Append(" LocalPort=").Append(Port); sb.Append(" Generation=").Append(Generation); sb.Append(" Host=").Append(HostName); sb.Append(" Status=").Append(Status); sb.Append(" ProxyPort=").Append(ProxyPort); if (!string.IsNullOrEmpty(RoleName)) sb.Append(" RoleName=").Append(RoleName); sb.Append(" SiloName=").Append(SiloName); sb.Append(" UpgradeZone=").Append(UpdateZone); sb.Append(" FaultZone=").Append(FaultZone); if (!string.IsNullOrEmpty(SuspectingSilos)) sb.Append(" SuspectingSilos=").Append(SuspectingSilos); if (!string.IsNullOrEmpty(SuspectingTimes)) sb.Append(" SuspectingTimes=").Append(SuspectingTimes); sb.Append(" StartTime=").Append(StartTime); sb.Append(" IAmAliveTime=").Append(IAmAliveTime); sb.Append("]"); } return sb.ToString(); } } internal class OrleansSiloInstanceManager { public string TableName { get { return INSTANCE_TABLE_NAME; } } private const string INSTANCE_TABLE_NAME = "OrleansSiloInstances"; private readonly string INSTANCE_STATUS_CREATED = SiloStatus.Created.ToString(); //"Created"; private readonly string INSTANCE_STATUS_ACTIVE = SiloStatus.Active.ToString(); //"Active"; private readonly string INSTANCE_STATUS_DEAD = SiloStatus.Dead.ToString(); //"Dead"; private readonly AzureTableDataManager<SiloInstanceTableEntry> storage; private readonly Logger logger; internal static TimeSpan initTimeout = AzureTableDefaultPolicies.TableCreationTimeout; public string DeploymentId { get; private set; } private OrleansSiloInstanceManager(string deploymentId, string storageConnectionString) { DeploymentId = deploymentId; logger = LogManager.GetLogger(this.GetType().Name, LoggerType.Runtime); storage = new AzureTableDataManager<SiloInstanceTableEntry>( INSTANCE_TABLE_NAME, storageConnectionString, logger); } public static async Task<OrleansSiloInstanceManager> GetManager(string deploymentId, string storageConnectionString) { var instance = new OrleansSiloInstanceManager(deploymentId, storageConnectionString); try { await instance.storage.InitTableAsync() .WithTimeout(initTimeout); } catch (TimeoutException te) { string errorMsg = String.Format("Unable to create or connect to the Azure table in {0}", initTimeout); instance.logger.Error(ErrorCode.AzureTable_32, errorMsg, te); throw new OrleansException(errorMsg, te); } catch (Exception ex) { string errorMsg = String.Format("Exception trying to create or connect to the Azure table: {0}", ex.Message); instance.logger.Error(ErrorCode.AzureTable_33, errorMsg, ex); throw new OrleansException(errorMsg, ex); } return instance; } public SiloInstanceTableEntry CreateTableVersionEntry(int tableVersion) { return new SiloInstanceTableEntry { DeploymentId = DeploymentId, PartitionKey = DeploymentId, RowKey = SiloInstanceTableEntry.TABLE_VERSION_ROW, MembershipVersion = tableVersion.ToString(CultureInfo.InvariantCulture) }; } public void RegisterSiloInstance(SiloInstanceTableEntry entry) { entry.Status = INSTANCE_STATUS_CREATED; logger.Info(ErrorCode.Runtime_Error_100270, "Registering silo instance: {0}", entry.ToString()); storage.UpsertTableEntryAsync(entry) .WaitWithThrow(AzureTableDefaultPolicies.TableOperationTimeout); } public void UnregisterSiloInstance(SiloInstanceTableEntry entry) { entry.Status = INSTANCE_STATUS_DEAD; logger.Info(ErrorCode.Runtime_Error_100271, "Unregistering silo instance: {0}", entry.ToString()); storage.UpsertTableEntryAsync(entry) .WaitWithThrow(AzureTableDefaultPolicies.TableOperationTimeout); } public void ActivateSiloInstance(SiloInstanceTableEntry entry) { logger.Info(ErrorCode.Runtime_Error_100272, "Activating silo instance: {0}", entry.ToString()); entry.Status = INSTANCE_STATUS_ACTIVE; storage.UpsertTableEntryAsync(entry) .WaitWithThrow(AzureTableDefaultPolicies.TableOperationTimeout); } public async Task<IList<Uri>> FindAllGatewayProxyEndpoints() { IEnumerable<SiloInstanceTableEntry> gatewaySiloInstances = await FindAllGatewaySilos(); return gatewaySiloInstances.Select(ConvertToGatewayUri).ToList(); } /// <summary> /// Represent a silo instance entry in the gateway URI format. /// </summary> /// <param name="gateway">The input silo instance</param> /// <returns></returns> private static Uri ConvertToGatewayUri(SiloInstanceTableEntry gateway) { int proxyPort = 0; if (!string.IsNullOrEmpty(gateway.ProxyPort)) int.TryParse(gateway.ProxyPort, out proxyPort); int gen = 0; if (!string.IsNullOrEmpty(gateway.Generation)) int.TryParse(gateway.Generation, out gen); SiloAddress address = SiloAddress.New(new IPEndPoint(IPAddress.Parse(gateway.Address), proxyPort), gen); return address.ToGatewayUri(); } private async Task<IEnumerable<SiloInstanceTableEntry>> FindAllGatewaySilos() { if (logger.IsVerbose) logger.Verbose(ErrorCode.Runtime_Error_100277, "Searching for active gateway silos for deployment {0}.", this.DeploymentId); const string zeroPort = "0"; try { Expression<Func<SiloInstanceTableEntry, bool>> query = instance => instance.PartitionKey == this.DeploymentId && instance.Status == INSTANCE_STATUS_ACTIVE && instance.ProxyPort != zeroPort; var queryResults = await storage.ReadTableEntriesAndEtagsAsync(query) .WithTimeout(AzureTableDefaultPolicies.TableOperationTimeout); List<SiloInstanceTableEntry> gatewaySiloInstances = queryResults.Select(entity => entity.Item1).ToList(); logger.Info(ErrorCode.Runtime_Error_100278, "Found {0} active Gateway Silos for deployment {1}.", gatewaySiloInstances.Count, this.DeploymentId); return gatewaySiloInstances; }catch(Exception exc) { logger.Error(ErrorCode.Runtime_Error_100331, string.Format("Error searching for active gateway silos for deployment {0} ", this.DeploymentId), exc); throw; } } public async Task<string> DumpSiloInstanceTable() { var queryResults = await storage.ReadAllTableEntriesForPartitionAsync(this.DeploymentId); SiloInstanceTableEntry[] entries = queryResults.Select(entry => entry.Item1).ToArray(); var sb = new StringBuilder(); sb.Append(String.Format("Deployment {0}. Silos: ", DeploymentId)); // Loop through the results, displaying information about the entity Array.Sort(entries, (e1, e2) => { if (e1 == null) return (e2 == null) ? 0 : -1; if (e2 == null) return (e1 == null) ? 0 : 1; if (e1.SiloName == null) return (e2.SiloName == null) ? 0 : -1; if (e2.SiloName == null) return (e1.SiloName == null) ? 0 : 1; return String.CompareOrdinal(e1.SiloName, e2.SiloName); }); foreach (SiloInstanceTableEntry entry in entries) { sb.AppendLine(String.Format("[IP {0}:{1}:{2}, {3}, Instance={4}, Status={5}]", entry.Address, entry.Port, entry.Generation, entry.HostName, entry.SiloName, entry.Status)); } return sb.ToString(); } #region Silo instance table storage operations internal Task<string> MergeTableEntryAsync(SiloInstanceTableEntry data) { return storage.MergeTableEntryAsync(data, AzureStorageUtils.ANY_ETAG); // we merge this without checking eTags. } internal Task<Tuple<SiloInstanceTableEntry, string>> ReadSingleTableEntryAsync(string partitionKey, string rowKey) { return storage.ReadSingleTableEntryAsync(partitionKey, rowKey); } internal async Task<int> DeleteTableEntries(string deploymentId) { if (deploymentId == null) throw new ArgumentNullException("deploymentId"); var entries = await storage.ReadAllTableEntriesForPartitionAsync(deploymentId); var entriesList = new List<Tuple<SiloInstanceTableEntry, string>>(entries); if (entriesList.Count <= AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS) { await storage.DeleteTableEntriesAsync(entriesList); }else { List<Task> tasks = new List<Task>(); foreach (var batch in entriesList.BatchIEnumerable(AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS)) { tasks.Add(storage.DeleteTableEntriesAsync(batch)); } await Task.WhenAll(tasks); } return entriesList.Count(); } internal async Task<List<Tuple<SiloInstanceTableEntry, string>>> FindSiloEntryAndTableVersionRow(SiloAddress siloAddress) { string rowKey = SiloInstanceTableEntry.ConstructRowKey(siloAddress); Expression<Func<SiloInstanceTableEntry, bool>> query = instance => instance.PartitionKey == DeploymentId && (instance.RowKey == rowKey || instance.RowKey == SiloInstanceTableEntry.TABLE_VERSION_ROW); var queryResults = await storage.ReadTableEntriesAndEtagsAsync(query); var asList = queryResults.ToList(); if (asList.Count < 1 || asList.Count > 2) throw new KeyNotFoundException(string.Format("Could not find table version row or found too many entries. Was looking for key {0}, found = {1}", siloAddress.ToLongString(), Utils.EnumerableToString(asList))); int numTableVersionRows = asList.Count(tuple => tuple.Item1.RowKey == SiloInstanceTableEntry.TABLE_VERSION_ROW); if (numTableVersionRows < 1) throw new KeyNotFoundException(string.Format("Did not read table version row. Read = {0}", Utils.EnumerableToString(asList))); if (numTableVersionRows > 1) throw new KeyNotFoundException(string.Format("Read {0} table version rows, while was expecting only 1. Read = {1}", numTableVersionRows, Utils.EnumerableToString(asList))); return asList; } internal async Task<List<Tuple<SiloInstanceTableEntry, string>>> FindAllSiloEntries() { var queryResults = await storage.ReadAllTableEntriesForPartitionAsync(this.DeploymentId); var asList = queryResults.ToList(); if (asList.Count < 1) throw new KeyNotFoundException(string.Format("Could not find enough rows in the FindAllSiloEntries call. Found = {0}", Utils.EnumerableToString(asList))); int numTableVersionRows = asList.Count(tuple => tuple.Item1.RowKey == SiloInstanceTableEntry.TABLE_VERSION_ROW); if (numTableVersionRows < 1) throw new KeyNotFoundException(string.Format("Did not find table version row. Read = {0}", Utils.EnumerableToString(asList))); if (numTableVersionRows > 1) throw new KeyNotFoundException(string.Format("Read {0} table version rows, while was expecting only 1. Read = {1}", numTableVersionRows, Utils.EnumerableToString(asList))); return asList; } /// <summary> /// Insert (create new) row entry /// </summary> internal async Task<bool> TryCreateTableVersionEntryAsync() { try { var versionRow = await storage.ReadSingleTableEntryAsync(DeploymentId, SiloInstanceTableEntry.TABLE_VERSION_ROW); if (versionRow != null && versionRow.Item1 != null) { return false; } SiloInstanceTableEntry entry = CreateTableVersionEntry(0); await storage.CreateTableEntryAsync(entry); return true; } catch (Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if (!AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw; if (logger.IsVerbose2) logger.Verbose2("InsertSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus); if (AzureStorageUtils.IsContentionError(httpStatusCode)) return false; throw; } } /// <summary> /// Insert (create new) row entry /// </summary> /// <param name="siloEntry">Silo Entry to be written</param> /// <param name="tableVersionEntry">Version row to update</param> /// <param name="tableVersionEtag">Version row eTag</param> internal async Task<bool> InsertSiloEntryConditionally(SiloInstanceTableEntry siloEntry, SiloInstanceTableEntry tableVersionEntry, string tableVersionEtag) { try { await storage.InsertTwoTableEntriesConditionallyAsync(siloEntry, tableVersionEntry, tableVersionEtag); return true; } catch (Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if (!AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw; if (logger.IsVerbose2) logger.Verbose2("InsertSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus); if (AzureStorageUtils.IsContentionError(httpStatusCode)) return false; throw; } } /// <summary> /// Conditionally update the row for this entry, but only if the eTag matches with the current record in data store /// </summary> /// <param name="siloEntry">Silo Entry to be written</param> /// <param name="entryEtag">ETag value for the entry being updated</param> /// <param name="tableVersionEntry">Version row to update</param> /// <param name="versionEtag">ETag value for the version row</param> /// <returns></returns> internal async Task<bool> UpdateSiloEntryConditionally(SiloInstanceTableEntry siloEntry, string entryEtag, SiloInstanceTableEntry tableVersionEntry, string versionEtag) { try { await storage.UpdateTwoTableEntriesConditionallyAsync(siloEntry, entryEtag, tableVersionEntry, versionEtag); return true; } catch (Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if (!AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw; if (logger.IsVerbose2) logger.Verbose2("UpdateSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus); if (AzureStorageUtils.IsContentionError(httpStatusCode)) return false; throw; } } #endregion } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Config { using System; using System.Globalization; using System.Threading; using NLog.Config; using NLog.LayoutRenderers; using NLog.Targets; using Xunit; public class CultureInfoTests : NLogTestBase { [Fact] public void WhenInvariantCultureDefinedThenDefaultCultureIsInvariantCulture() { var configuration = XmlLoggingConfiguration.CreateFromXmlString("<nlog useInvariantCulture='true'></nlog>"); Assert.Equal(CultureInfo.InvariantCulture, configuration.DefaultCultureInfo); } [Fact] public void DifferentConfigurations_UseDifferentDefaultCulture() { var currentCulture = CultureInfo.CurrentCulture; try { // set the current thread culture to be definitely different from the InvariantCulture Thread.CurrentThread.CurrentCulture = GetCultureInfo("de-DE"); var configurationTemplate = @"<nlog useInvariantCulture='{0}'> <targets> <target name='debug' type='Debug' layout='${{message}}' /> </targets> <rules> <logger name='*' writeTo='debug'/> </rules> </nlog>"; // configuration with current culture var logFactory1 = new LogFactory(); var configuration1 = XmlLoggingConfiguration.CreateFromXmlString(string.Format(configurationTemplate, false), logFactory1); Assert.Null(configuration1.DefaultCultureInfo); logFactory1.Configuration = configuration1; // configuration with invariant culture var logFactory2 = new LogFactory(); var configuration2 = XmlLoggingConfiguration.CreateFromXmlString(string.Format(configurationTemplate, true), logFactory2); Assert.Equal(CultureInfo.InvariantCulture, configuration2.DefaultCultureInfo); logFactory2.Configuration = configuration2; Assert.NotEqual(configuration1.DefaultCultureInfo, configuration2.DefaultCultureInfo); var testNumber = 3.14; var testDate = DateTime.Now; const string formatString = "{0},{1:d}"; AssertMessageFormattedWithCulture(logFactory1, CultureInfo.CurrentCulture, formatString, testNumber, testDate); AssertMessageFormattedWithCulture(logFactory2, CultureInfo.InvariantCulture, formatString, testNumber, testDate); } finally { // restore current thread culture Thread.CurrentThread.CurrentCulture = currentCulture; } } private void AssertMessageFormattedWithCulture(LogFactory logFactory, CultureInfo culture, string formatString, params object[] parameters) { var expected = string.Format(culture, formatString, parameters); var logger = logFactory.GetLogger("test"); logger.Debug(formatString, parameters); Assert.Equal(expected, GetDebugLastMessage("debug", logFactory)); } [Fact] public void EventPropRendererCultureTest() { string cultureName = "de-DE"; string expected = "1,23"; // with decimal comma var logEventInfo = CreateLogEventInfo(cultureName); logEventInfo.Properties["ADouble"] = 1.23; var renderer = new EventPropertiesLayoutRenderer(); renderer.Item = "ADouble"; string output = renderer.Render(logEventInfo); Assert.Equal(expected, output); } [Fact] public void ProcessInfoLayoutRendererCultureTest() { string cultureName = "de-DE"; string expected = "."; // dot as date separator (01.10.2008) string output = string.Empty; var logEventInfo = CreateLogEventInfo(cultureName); if (IsLinux()) { Console.WriteLine("[SKIP] CultureInfoTests.ProcessInfoLayoutRendererCultureTest because we are running in Travis"); } else { var renderer = new ProcessInfoLayoutRenderer(); renderer.Property = ProcessInfoProperty.StartTime; renderer.Format = "d"; output = renderer.Render(logEventInfo); Assert.Contains(expected, output); Assert.DoesNotContain("/", output); Assert.DoesNotContain("-", output); } var renderer2 = new ProcessInfoLayoutRenderer(); renderer2.Property = ProcessInfoProperty.PriorityClass; renderer2.Format = "d"; output = renderer2.Render(logEventInfo); Assert.True(output.Length >= 1); Assert.True("012345678".IndexOf(output[0]) > 0); } [Fact] public void AllEventPropRendererCultureTest() { string cultureName = "de-DE"; string expected = "ADouble=1,23"; // with decimal comma var logEventInfo = CreateLogEventInfo(cultureName); logEventInfo.Properties["ADouble"] = 1.23; var renderer = new AllEventPropertiesLayoutRenderer(); string output = renderer.Render(logEventInfo); Assert.Equal(expected, output); } private static LogEventInfo CreateLogEventInfo(string cultureName) { var logEventInfo = new LogEventInfo( LogLevel.Info, "SomeName", CultureInfo.GetCultureInfo(cultureName), "SomeMessage", null); return logEventInfo; } /// <summary> /// expected: exactly the same exception message + stack trace regardless of the CurrentUICulture /// </summary> [Fact] public void ExceptionTest() { var target = new MemoryTarget { Layout = @"${exception:format=tostring}" }; var logger = new LogFactory().Setup().LoadConfiguration(builder => { builder.ForLogger().WriteTo(target); }).GetCurrentClassLogger(); try { throw new InvalidOperationException(); } catch (Exception ex) { Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US", false); Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", false); logger.Error(ex, ""); #if !NETSTANDARD Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE", false); Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE", false); #endif logger.Error(ex, ""); Assert.Equal(2, target.Logs.Count); Assert.NotNull(target.Logs[0]); Assert.NotNull(target.Logs[1]); Assert.Equal(target.Logs[0], target.Logs[1]); } } } }
/****************************************************************************** * 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.Rfc2251.RfcFilter.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using System.Collections; using System.IO; using System.Text; using Novell.Directory.Ldap.Asn1; using Novell.Directory.Ldap.Utilclass; namespace Novell.Directory.Ldap.Rfc2251 { /// <summary> /// Represents an Ldap Filter. /// This filter object can be created from a String or can be built up /// programatically by adding filter components one at a time. Existing filter /// components can be iterated though. /// Each filter component has an integer identifier defined in this class. /// The following are basic filter components: {@link #EQUALITY_MATCH}, /// {@link #GREATER_OR_EQUAL}, {@link #LESS_OR_EQUAL}, {@link #SUBSTRINGS}, /// {@link #PRESENT}, {@link #APPROX_MATCH}, {@link #EXTENSIBLE_MATCH}. /// More filters can be nested together into more complex filters with the /// following filter components: {@link #AND}, {@link #OR}, {@link #NOT} /// Substrings can have three components: /// <pre> /// Filter ::= CHOICE { /// and [0] SET OF Filter, /// or [1] SET OF Filter, /// not [2] Filter, /// equalityMatch [3] AttributeValueAssertion, /// substrings [4] SubstringFilter, /// greaterOrEqual [5] AttributeValueAssertion, /// lessOrEqual [6] AttributeValueAssertion, /// present [7] AttributeDescription, /// approxMatch [8] AttributeValueAssertion, /// extensibleMatch [9] MatchingRuleAssertion } /// </pre> /// </summary> public class RfcFilter : Asn1Choice { //************************************************************************* // Public variables for Filter //************************************************************************* /// <summary> Identifier for AND component.</summary> public const int AND = LdapSearchRequest.AND; /// <summary> Identifier for OR component.</summary> public const int OR = LdapSearchRequest.OR; /// <summary> Identifier for NOT component.</summary> public const int NOT = LdapSearchRequest.NOT; /// <summary> Identifier for EQUALITY_MATCH component.</summary> public const int EQUALITY_MATCH = LdapSearchRequest.EQUALITY_MATCH; /// <summary> Identifier for SUBSTRINGS component.</summary> public const int SUBSTRINGS = LdapSearchRequest.SUBSTRINGS; /// <summary> Identifier for GREATER_OR_EQUAL component.</summary> public const int GREATER_OR_EQUAL = LdapSearchRequest.GREATER_OR_EQUAL; /// <summary> Identifier for LESS_OR_EQUAL component.</summary> public const int LESS_OR_EQUAL = LdapSearchRequest.LESS_OR_EQUAL; /// <summary> Identifier for PRESENT component.</summary> public const int PRESENT = LdapSearchRequest.PRESENT; /// <summary> Identifier for APPROX_MATCH component.</summary> public const int APPROX_MATCH = LdapSearchRequest.APPROX_MATCH; /// <summary> Identifier for EXTENSIBLE_MATCH component.</summary> public const int EXTENSIBLE_MATCH = LdapSearchRequest.EXTENSIBLE_MATCH; /// <summary> Identifier for INITIAL component.</summary> public const int INITIAL = LdapSearchRequest.INITIAL; /// <summary> Identifier for ANY component.</summary> public const int ANY = LdapSearchRequest.ANY; /// <summary> Identifier for FINAL component.</summary> public const int FINAL = LdapSearchRequest.FINAL; //************************************************************************* // Private variables for Filter //************************************************************************* private FilterTokenizer ft; private Stack filterStack; private bool finalFound; //************************************************************************* // Constructor for Filter //************************************************************************* /// <summary> Constructs a Filter object by parsing an RFC 2254 Search Filter String.</summary> public RfcFilter(string filter) : base(null) { ChoiceValue = parse(filter); } /// <summary> Constructs a Filter object that will be built up piece by piece. </summary> public RfcFilter() : base(null) { filterStack = new Stack(); //The choice value must be set later: setChoiceValue(rootFilterTag) } //************************************************************************* // Helper methods for RFC 2254 Search Filter parsing. //************************************************************************* /// <summary> Parses an RFC 2251 filter string into an ASN.1 Ldap Filter object.</summary> private Asn1Tagged parse(string filterExpr) { if ((object) filterExpr == null || filterExpr.Equals("")) { filterExpr = new StringBuilder("(objectclass=*)").ToString(); } int idx; if ((idx = filterExpr.IndexOf('\\')) != -1) { var sb = new StringBuilder(filterExpr); var i = idx; while (i < sb.Length - 1) { var c = sb[i++]; if (c == '\\') { // found '\' (backslash) // If V2 escape, turn to a V3 escape c = sb[i]; if (c == '*' || c == '(' || c == ')' || c == '\\') { // Ldap v2 filter, convert them into hex chars sb.Remove(i, i + 1 - i); sb.Insert(i, Convert.ToString(c, 16)); i += 2; } } } filterExpr = sb.ToString(); } // missing opening and closing parentheses, must be V2, add parentheses if (filterExpr[0] != '(' && filterExpr[filterExpr.Length - 1] != ')') { filterExpr = "(" + filterExpr + ")"; } var ch = filterExpr[0]; var len = filterExpr.Length; // missing opening parenthesis ? if (ch != '(') { throw new LdapLocalException(ExceptionMessages.MISSING_LEFT_PAREN, LdapException.FILTER_ERROR); } // missing closing parenthesis ? if (filterExpr[len - 1] != ')') { throw new LdapLocalException(ExceptionMessages.MISSING_RIGHT_PAREN, LdapException.FILTER_ERROR); } // unmatched parentheses ? var parenCount = 0; for (var i = 0; i < len; i++) { if (filterExpr[i] == '(') { parenCount++; } if (filterExpr[i] == ')') { parenCount--; } } if (parenCount > 0) { throw new LdapLocalException(ExceptionMessages.MISSING_RIGHT_PAREN, LdapException.FILTER_ERROR); } if (parenCount < 0) { throw new LdapLocalException(ExceptionMessages.MISSING_LEFT_PAREN, LdapException.FILTER_ERROR); } ft = new FilterTokenizer(this, filterExpr); return parseFilter(); } /// <summary> Parses an RFC 2254 filter</summary> private Asn1Tagged parseFilter() { ft.getLeftParen(); var filter = parseFilterComp(); ft.getRightParen(); return filter; } /// <summary> RFC 2254 filter helper method. Will Parse a filter component.</summary> private Asn1Tagged parseFilterComp() { Asn1Tagged tag = null; var filterComp = ft.OpOrAttr; switch (filterComp) { case AND: case OR: tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, filterComp), parseFilterList(), false); break; case NOT: tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, filterComp), parseFilter(), true); break; default: var filterType = ft.FilterType; var value_Renamed = ft.Value; switch (filterType) { case GREATER_OR_EQUAL: case LESS_OR_EQUAL: case APPROX_MATCH: tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, filterType), new RfcAttributeValueAssertion(new RfcAttributeDescription(ft.Attr), new RfcAssertionValue(unescapeString(value_Renamed))), false); break; case EQUALITY_MATCH: if (value_Renamed.Equals("*")) { // present tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, PRESENT), new RfcAttributeDescription(ft.Attr), false); } else if (value_Renamed.IndexOf('*') != -1) { // substrings parse: // [initial], *any*, [final] into an Asn1SequenceOf var sub = new SupportClass.Tokenizer(value_Renamed, "*", true); // SupportClass.Tokenizer sub = new SupportClass.Tokenizer(value_Renamed, "*");//, true); var seq = new Asn1SequenceOf(5); var tokCnt = sub.Count; var cnt = 0; var lastTok = new StringBuilder("").ToString(); while (sub.HasMoreTokens()) { var subTok = sub.NextToken(); cnt++; if (subTok.Equals("*")) { // if previous token was '*', and since the current // token is a '*', we need to insert 'any' if (lastTok.Equals(subTok)) { // '**' seq.add( new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, ANY), new RfcLdapString(unescapeString("")), false)); } } else { // value (RfcLdapString) if (cnt == 1) { // initial seq.add( new Asn1Tagged( new Asn1Identifier(Asn1Identifier.CONTEXT, false, INITIAL), new RfcLdapString(unescapeString(subTok)), false)); } else if (cnt < tokCnt) { // any seq.add( new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, ANY), new RfcLdapString(unescapeString(subTok)), false)); } else { // final seq.add( new Asn1Tagged( new Asn1Identifier(Asn1Identifier.CONTEXT, false, FINAL), new RfcLdapString(unescapeString(subTok)), false)); } } lastTok = subTok; } tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, SUBSTRINGS), new RfcSubstringFilter(new RfcAttributeDescription(ft.Attr), seq), false); } else { // simple tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, EQUALITY_MATCH), new RfcAttributeValueAssertion(new RfcAttributeDescription(ft.Attr), new RfcAssertionValue(unescapeString(value_Renamed))), false); } break; case EXTENSIBLE_MATCH: string type = null, matchingRule = null; var dnAttributes = false; // SupportClass.Tokenizer st = new StringTokenizer(ft.Attr, ":", true); var st = new SupportClass.Tokenizer(ft.Attr, ":"); //, true); var first = true; while (st.HasMoreTokens()) { var s = st.NextToken().Trim(); if (first && !s.Equals(":")) { type = s; } // dn must be lower case to be considered dn of the Entry. else if (s.Equals("dn")) { dnAttributes = true; } else if (!s.Equals(":")) { matchingRule = s; } first = false; } tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, EXTENSIBLE_MATCH), new RfcMatchingRuleAssertion( (object) matchingRule == null ? null : new RfcMatchingRuleId(matchingRule), (object) type == null ? null : new RfcAttributeDescription(type), new RfcAssertionValue(unescapeString(value_Renamed)), dnAttributes == false ? null : new Asn1Boolean(true)), false); break; } break; } return tag; } /// <summary> Must have 1 or more Filters</summary> private Asn1SetOf parseFilterList() { var set_Renamed = new Asn1SetOf(); set_Renamed.add(parseFilter()); // must have at least 1 filter while (ft.peekChar() == '(') { // check for more filters set_Renamed.add(parseFilter()); } return set_Renamed; } /// <summary> /// Convert hex character to an integer. Return -1 if char is something /// other than a hex char. /// </summary> internal static int hex2int(char c) { return c >= '0' && c <= '9' ? c - '0' : c >= 'A' && c <= 'F' ? c - 'A' + 10 : c >= 'a' && c <= 'f' ? c - 'a' + 10 : -1; } /// <summary> /// Replace escaped hex digits with the equivalent binary representation. /// Assume either V2 or V3 escape mechanisms: /// V2: \*, \(, \), \\. /// V3: \2A, \28, \29, \5C, \00. /// </summary> /// <param name="string"> /// A part of the input filter string to be converted. /// </param> /// <returns> /// octet-string encoding of the specified string. /// </returns> private sbyte[] unescapeString(string string_Renamed) { // give octets enough space to grow var octets = new sbyte[string_Renamed.Length * 3]; // index for string and octets int iString, iOctets; // escape==true means we are in an escape sequence. var escape = false; // escStart==true means we are reading the first character of an escape. var escStart = false; int ival, length = string_Renamed.Length; sbyte[] utf8Bytes; char ch; // Character we are adding to the octet string var ca = new char[1]; // used while converting multibyte UTF-8 char var temp = (char) 0; // holds the value of the escaped sequence // loop through each character of the string and copy them into octets // converting escaped sequences when needed for (iString = 0, iOctets = 0; iString < length; iString++) { ch = string_Renamed[iString]; if (escape) { if ((ival = hex2int(ch)) < 0) { // Invalid escape value(not a hex character) throw new LdapLocalException(ExceptionMessages.INVALID_ESCAPE, new object[] {ch}, LdapException.FILTER_ERROR); } // V3 escaped: \\** if (escStart) { temp = (char) (ival << 4); // high bits of escaped char escStart = false; } else { temp |= (char) ival; // all bits of escaped char octets[iOctets++] = (sbyte) temp; escStart = escape = false; } } else if (ch == '\\') { escStart = escape = true; } else { try { // place the character into octets. if (ch >= 0x01 && ch <= 0x27 || ch >= 0x2B && ch <= 0x5B || ch >= 0x5D) { // found valid char if (ch <= 0x7f) { // char = %x01-27 / %x2b-5b / %x5d-7f octets[iOctets++] = (sbyte) ch; } else { // char > 0x7f, could be encoded in 2 or 3 bytes ca[0] = ch; var encoder = Encoding.GetEncoding("utf-8"); var ibytes = encoder.GetBytes(new string(ca)); utf8Bytes = SupportClass.ToSByteArray(ibytes); // utf8Bytes = new System.String(ca).getBytes("UTF-8"); // copy utf8 encoded character into octets Array.Copy(utf8Bytes, 0, octets, iOctets, utf8Bytes.Length); iOctets = iOctets + utf8Bytes.Length; } escape = false; } else { // found invalid character var escString = ""; ca[0] = ch; var encoder = Encoding.GetEncoding("utf-8"); var ibytes = encoder.GetBytes(new string(ca)); utf8Bytes = SupportClass.ToSByteArray(ibytes); // utf8Bytes = new System.String(ca).getBytes("UTF-8"); for (var i = 0; i < utf8Bytes.Length; i++) { var u = utf8Bytes[i]; if (u >= 0 && u < 0x10) { escString = escString + "\\0" + Convert.ToString(u & 0xff, 16); } else { escString = escString + "\\" + Convert.ToString(u & 0xff, 16); } } throw new LdapLocalException(ExceptionMessages.INVALID_CHAR_IN_FILTER, new object[] {ch, escString}, LdapException.FILTER_ERROR); } } catch (IOException ue) { throw new Exception("UTF-8 String encoding not supported by JVM", ue); } } } // Verify that any escape sequence completed if (escStart || escape) { throw new LdapLocalException(ExceptionMessages.SHORT_ESCAPE, LdapException.FILTER_ERROR); } var toReturn = new sbyte[iOctets]; // Array.Copy((System.Array)SupportClass.ToByteArray(octets), 0, (System.Array)SupportClass.ToByteArray(toReturn), 0, iOctets); Array.Copy(octets, 0, toReturn, 0, iOctets); octets = null; return toReturn; } /* ********************************************************************** * The following methods aid in building filters sequentially, * and is used by DSMLHandler: ***********************************************************************/ /// <summary> /// Called by sequential filter building methods to add to a filter /// component. /// Verifies that the specified Asn1Object can be added, then adds the /// object to the filter. /// </summary> /// <param name="current"> /// Filter component to be added to the filter /// @throws LdapLocalException Occurs when an invalid component is added, or /// when the component is out of sequence. /// </param> private void addObject(Asn1Object current) { if (filterStack == null) { filterStack = new Stack(); } if (choiceValue() == null) { //ChoiceValue is the root Asn1 node ChoiceValue = current; } else { var topOfStack = (Asn1Tagged) filterStack.Peek(); var value_Renamed = topOfStack.taggedValue(); if (value_Renamed == null) { topOfStack.TaggedValue = current; filterStack.Push(current); // filterStack.Add(current); } else if (value_Renamed is Asn1SetOf) { ((Asn1SetOf) value_Renamed).add(current); //don't add this to the stack: } else if (value_Renamed is Asn1Set) { ((Asn1Set) value_Renamed).add(current); //don't add this to the stack: } else if (value_Renamed.getIdentifier().Tag == LdapSearchRequest.NOT) { throw new LdapLocalException("Attemp to create more than one 'not' sub-filter", LdapException.FILTER_ERROR); } } var type = current.getIdentifier().Tag; if (type == AND || type == OR || type == NOT) { // filterStack.Add(current); filterStack.Push(current); } } /// <summary> /// Creates and addes a substrings filter component. /// startSubstrings must be immediatly followed by at least one /// {@link #addSubstring} method and one {@link #endSubstrings} method /// @throws Novell.Directory.Ldap.LdapLocalException /// Occurs when this component is created out of sequence. /// </summary> public virtual void startSubstrings(string attrName) { finalFound = false; var seq = new Asn1SequenceOf(5); Asn1Object current = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, SUBSTRINGS), new RfcSubstringFilter(new RfcAttributeDescription(attrName), seq), false); addObject(current); SupportClass.StackPush(filterStack, seq); } /// <summary> /// Adds a Substring component of initial, any or final substring matching. /// This method can be invoked only if startSubString was the last filter- /// building method called. A substring is not required to have an 'INITIAL' /// substring. However, when a filter contains an 'INITIAL' substring only /// one can be added, and it must be the first substring added. Any number of /// 'ANY' substrings can be added. A substring is not required to have a /// 'FINAL' substrings either. However, when a filter does contain a 'FINAL' /// substring only one can be added, and it must be the last substring added. /// </summary> /// <param name="type"> /// Substring type: INITIAL | ANY | FINAL] /// </param> /// <param name="value"> /// Value to use for matching /// @throws LdapLocalException Occurs if this method is called out of /// sequence or the type added is out of sequence. /// </param> [CLSCompliant(false)] public virtual void addSubstring(int type, sbyte[] value_Renamed) { try { var substringSeq = (Asn1SequenceOf) filterStack.Peek(); if (type != INITIAL && type != ANY && type != FINAL) { throw new LdapLocalException("Attempt to add an invalid " + "substring type", LdapException.FILTER_ERROR); } if (type == INITIAL && substringSeq.size() != 0) { throw new LdapLocalException( "Attempt to add an initial " + "substring match after the first substring", LdapException.FILTER_ERROR); } if (finalFound) { throw new LdapLocalException("Attempt to add a substring " + "match after a final substring match", LdapException.FILTER_ERROR); } if (type == FINAL) { finalFound = true; } substringSeq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, type), new RfcLdapString(value_Renamed), false)); } catch (InvalidCastException e) { throw new LdapLocalException("A call to addSubstring occured " + "without calling startSubstring", LdapException.FILTER_ERROR, e); } } /// <summary> /// Completes a SubString filter component. /// @throws LdapLocalException Occurs when this is called out of sequence, /// or the substrings filter is empty. /// </summary> public virtual void endSubstrings() { try { finalFound = false; var substringSeq = (Asn1SequenceOf) filterStack.Peek(); if (substringSeq.size() == 0) { throw new LdapLocalException("Empty substring filter", LdapException.FILTER_ERROR); } } catch (InvalidCastException e) { throw new LdapLocalException("Missmatched ending of substrings", LdapException.FILTER_ERROR, e); } filterStack.Pop(); } /// <summary> /// Creates and adds an AttributeValueAssertion to the filter. /// </summary> /// <param name="rfcType"> /// Filter type: EQUALITY_MATCH | GREATER_OR_EQUAL /// | LESS_OR_EQUAL | APPROX_MATCH ] /// </param> /// <param name="attrName"> /// Name of the attribute to be asserted /// </param> /// <param name="value"> /// Value of the attribute to be asserted /// @throws LdapLocalException /// Occurs when the filter type is not a valid attribute assertion. /// </param> [CLSCompliant(false)] public virtual void addAttributeValueAssertion(int rfcType, string attrName, sbyte[] value_Renamed) { if (filterStack != null && !(filterStack.Count == 0) && filterStack.Peek() is Asn1SequenceOf) { //If a sequenceof is on the stack then substring is left on the stack throw new LdapLocalException("Cannot insert an attribute assertion in a substring", LdapException.FILTER_ERROR); } if (rfcType != EQUALITY_MATCH && rfcType != GREATER_OR_EQUAL && rfcType != LESS_OR_EQUAL && rfcType != APPROX_MATCH) { throw new LdapLocalException("Invalid filter type for AttributeValueAssertion", LdapException.FILTER_ERROR); } Asn1Object current = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, rfcType), new RfcAttributeValueAssertion(new RfcAttributeDescription(attrName), new RfcAssertionValue(value_Renamed)), false); addObject(current); } /// <summary> /// Creates and adds a present matching to the filter. /// </summary> /// <param name="attrName"> /// Name of the attribute to check for presence. /// @throws LdapLocalException /// Occurs if addPresent is called out of sequence. /// </param> public virtual void addPresent(string attrName) { Asn1Object current = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, PRESENT), new RfcAttributeDescription(attrName), false); addObject(current); } /// <summary> /// Adds an extensible match to the filter. /// </summary> /// <param name=""> /// matchingRule /// OID or name of the matching rule to use for comparison /// </param> /// <param name="attrName"> /// Name of the attribute to match. /// </param> /// <param name="value"> /// Value of the attribute to match against. /// </param> /// <param name="useDNMatching"> /// Indicates whether DN matching should be used. /// @throws LdapLocalException /// Occurs when addExtensibleMatch is called out of sequence. /// </param> [CLSCompliant(false)] public virtual void addExtensibleMatch(string matchingRule, string attrName, sbyte[] value_Renamed, bool useDNMatching) { Asn1Object current = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, EXTENSIBLE_MATCH), new RfcMatchingRuleAssertion( (object) matchingRule == null ? null : new RfcMatchingRuleId(matchingRule), (object) attrName == null ? null : new RfcAttributeDescription(attrName), new RfcAssertionValue(value_Renamed), useDNMatching == false ? null : new Asn1Boolean(true)), false); addObject(current); } /// <summary> /// Creates and adds the Asn1Tagged value for a nestedFilter: AND, OR, or /// NOT. /// Note that a Not nested filter can only have one filter, where AND /// and OR do not /// </summary> /// <param name="rfcType"> /// Filter type: /// [AND | OR | NOT] /// @throws Novell.Directory.Ldap.LdapLocalException /// </param> public virtual void startNestedFilter(int rfcType) { Asn1Object current; if (rfcType == AND || rfcType == OR) { current = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, rfcType), new Asn1SetOf(), false); } else if (rfcType == NOT) { current = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, rfcType), null, true); } else { throw new LdapLocalException("Attempt to create a nested filter other than AND, OR or NOT", LdapException.FILTER_ERROR); } addObject(current); } /// <summary> Completes a nested filter and checks for the valid filter type.</summary> /// <param name="rfcType"> /// Type of filter to complete. /// @throws Novell.Directory.Ldap.LdapLocalException Occurs when the specified /// type differs from the current filter component. /// </param> public virtual void endNestedFilter(int rfcType) { if (rfcType == NOT) { //if this is a Not than Not should be the second thing on the stack filterStack.Pop(); } var topOfStackType = ((Asn1Object) filterStack.Peek()).getIdentifier().Tag; if (topOfStackType != rfcType) { throw new LdapLocalException("Missmatched ending of nested filter", LdapException.FILTER_ERROR); } filterStack.Pop(); } /// <summary> /// Creates an iterator over the preparsed segments of a filter. /// The first object returned by an iterator is an integer indicating the /// type of filter components. Subseqence values are returned. If a /// component is of type 'AND' or 'OR' or 'NOT' then the value /// returned is another iterator. This iterator is used by ToString. /// </summary> /// <returns> /// Iterator over filter segments /// </returns> public virtual IEnumerator getFilterIterator() { return new FilterIterator(this, (Asn1Tagged) choiceValue()); } /// <summary> Creates and returns a String representation of this filter.</summary> public virtual string filterToString() { var filter = new StringBuilder(); stringFilter(getFilterIterator(), filter); return filter.ToString(); } /// <summary> /// Uses a filterIterator to create a string representation of a filter. /// </summary> /// <param name="itr"> /// Iterator of filter components /// </param> /// <param name="filter"> /// Buffer to place a string representation of the filter /// </param> /// <seealso cref="FilterIterator"> /// </seealso> private static void stringFilter(IEnumerator itr, StringBuilder filter) { var op = -1; filter.Append('('); while (itr.MoveNext()) { var filterpart = itr.Current; if (filterpart is int) { op = (int) filterpart; switch (op) { case AND: filter.Append('&'); break; case OR: filter.Append('|'); break; case NOT: filter.Append('!'); break; case EQUALITY_MATCH: { filter.Append((string) itr.Current); filter.Append('='); var value_Renamed = (sbyte[]) itr.Current; filter.Append(byteString(value_Renamed)); break; } case GREATER_OR_EQUAL: { filter.Append((string) itr.Current); filter.Append(">="); var value_Renamed = (sbyte[]) itr.Current; filter.Append(byteString(value_Renamed)); break; } case LESS_OR_EQUAL: { filter.Append((string) itr.Current); filter.Append("<="); var value_Renamed = (sbyte[]) itr.Current; filter.Append(byteString(value_Renamed)); break; } case PRESENT: filter.Append((string) itr.Current); filter.Append("=*"); break; case APPROX_MATCH: filter.Append((string) itr.Current); filter.Append("~="); var value_Renamed2 = (sbyte[]) itr.Current; filter.Append(byteString(value_Renamed2)); break; case EXTENSIBLE_MATCH: var oid = (string) itr.Current; filter.Append((string) itr.Current); filter.Append(':'); filter.Append(oid); filter.Append(":="); filter.Append((string) itr.Current); break; case SUBSTRINGS: { filter.Append((string) itr.Current); filter.Append('='); var noStarLast = false; while (itr.MoveNext()) { op = (int) itr.Current; switch (op) { case INITIAL: filter.Append((string) itr.Current); filter.Append('*'); noStarLast = false; break; case ANY: if (noStarLast) filter.Append('*'); filter.Append((string) itr.Current); filter.Append('*'); noStarLast = false; break; case FINAL: if (noStarLast) filter.Append('*'); filter.Append((string) itr.Current); break; } } break; } } } else if (filterpart is IEnumerator) { stringFilter((IEnumerator) filterpart, filter); } } filter.Append(')'); } /// <summary> /// Convert a UTF8 encoded string, or binary data, into a String encoded for /// a string filter. /// </summary> private static string byteString(sbyte[] value_Renamed) { string toReturn = null; if (Base64.isValidUTF8(value_Renamed, true)) { try { var encoder = Encoding.GetEncoding("utf-8"); var dchar = encoder.GetChars(SupportClass.ToByteArray(value_Renamed)); toReturn = new string(dchar); // toReturn = new String(value_Renamed, "UTF-8"); } catch (IOException e) { throw new Exception("Default JVM does not support UTF-8 encoding" + e); } } else { var binary = new StringBuilder(); for (var i = 0; i < value_Renamed.Length; i++) { //TODO repair binary output //Every octet needs to be escaped if (value_Renamed[i] >= 0) { //one character hex string binary.Append("\\0"); binary.Append(Convert.ToString(value_Renamed[i], 16)); } else { //negative (eight character) hex string binary.Append("\\" + Convert.ToString(value_Renamed[i], 16).Substring(6)); } } toReturn = binary.ToString(); } return toReturn; } /// <summary> /// This inner class wrappers the Search Filter with an iterator. /// This iterator will give access to all the individual components /// preparsed. The first call to next will return an Integer identifying /// the type of filter component. Then the component values will be returned /// AND, NOT, and OR components values will be returned as Iterators. /// </summary> private class FilterIterator : IEnumerator { public void Reset() { } private void InitBlock(RfcFilter enclosingInstance) { this.enclosingInstance = enclosingInstance; } private RfcFilter enclosingInstance; /// <summary> /// Returns filter identifiers and components of a filter. /// The first object returned is an Integer identifying /// its type. /// </summary> public virtual object Current { get { object toReturn = null; if (!tagReturned) { tagReturned = true; toReturn = root.getIdentifier().Tag; } else { var asn1 = root.taggedValue(); if (asn1 is RfcLdapString) { //one value to iterate hasMore = false; toReturn = ((RfcLdapString) asn1).stringValue(); } else if (asn1 is RfcSubstringFilter) { var sub = (RfcSubstringFilter) asn1; if (index == -1) { //return attribute name index = 0; var attr = (RfcAttributeDescription) sub.get_Renamed(0); toReturn = attr.stringValue(); } else if (index % 2 == 0) { //return substring identifier var substrs = (Asn1SequenceOf) sub.get_Renamed(1); toReturn = ((Asn1Tagged) substrs.get_Renamed(index / 2)).getIdentifier().Tag; index++; } else { //return substring value var substrs = (Asn1SequenceOf) sub.get_Renamed(1); var tag = (Asn1Tagged) substrs.get_Renamed(index / 2); var value_Renamed = (RfcLdapString) tag.taggedValue(); toReturn = value_Renamed.stringValue(); index++; } if (index / 2 >= ((Asn1SequenceOf) sub.get_Renamed(1)).size()) { hasMore = false; } } else if (asn1 is RfcAttributeValueAssertion) { // components: =,>=,<=,~= var assertion = (RfcAttributeValueAssertion) asn1; if (index == -1) { toReturn = assertion.AttributeDescription; index = 1; } else if (index == 1) { toReturn = assertion.AssertionValue; index = 2; hasMore = false; } } else if (asn1 is RfcMatchingRuleAssertion) { //Extensible match var exMatch = (RfcMatchingRuleAssertion) asn1; if (index == -1) { index = 0; } toReturn = ((Asn1OctetString) ((Asn1Tagged) exMatch.get_Renamed(index++)).taggedValue()) .stringValue(); if (index > 2) { hasMore = false; } } else if (asn1 is Asn1SetOf) { //AND and OR nested components var set_Renamed = (Asn1SetOf) asn1; if (index == -1) { index = 0; } toReturn = new FilterIterator(enclosingInstance, (Asn1Tagged) set_Renamed.get_Renamed(index++)); if (index >= set_Renamed.size()) { hasMore = false; } } else if (asn1 is Asn1Tagged) { //NOT nested component. toReturn = new FilterIterator(enclosingInstance, (Asn1Tagged) asn1); hasMore = false; } } return toReturn; } } public RfcFilter Enclosing_Instance { get { return enclosingInstance; } } internal readonly Asn1Tagged root; /// <summary>indicates if the identifier for a component has been returned yet </summary> internal bool tagReturned; /// <summary>indexes the several parts a component may have </summary> internal int index = -1; private bool hasMore = true; public FilterIterator(RfcFilter enclosingInstance, Asn1Tagged root) { InitBlock(enclosingInstance); this.root = root; } public virtual bool MoveNext() { return hasMore; } public void remove() { throw new NotSupportedException("Remove is not supported on a filter iterator"); } } /// <summary> This inner class will tokenize the components of an RFC 2254 search filter.</summary> internal class FilterTokenizer { private void InitBlock(RfcFilter enclosingInstance) { this.enclosingInstance = enclosingInstance; } private RfcFilter enclosingInstance; /// <summary> /// Reads either an operator, or an attribute, whichever is /// next in the filter string. /// If the next component is an attribute, it is read and stored in the /// attr field of this class which may be retrieved with getAttr() /// and a -1 is returned. Otherwise, the int value of the operator read is /// returned. /// </summary> public virtual int OpOrAttr { get { int index; if (offset >= filterLength) { //"Unexpected end of filter", throw new LdapLocalException(ExceptionMessages.UNEXPECTED_END, LdapException.FILTER_ERROR); } int ret; int testChar = filter[offset]; if (testChar == '&') { offset++; ret = AND; } else if (testChar == '|') { offset++; ret = OR; } else if (testChar == '!') { offset++; ret = NOT; } else { if (filter.Substring(offset).StartsWith(":=")) { throw new LdapLocalException(ExceptionMessages.NO_MATCHING_RULE, LdapException.FILTER_ERROR); } if (filter.Substring(offset).StartsWith("::=") || filter.Substring(offset).StartsWith(":::=")) { throw new LdapLocalException(ExceptionMessages.NO_DN_NOR_MATCHING_RULE, LdapException.FILTER_ERROR); } // get first component of 'item' (attr or :dn or :matchingrule) var delims = "=~<>()"; var sb = new StringBuilder(); while (delims.IndexOf(filter[offset]) == -1 && filter.Substring(offset).StartsWith(":=") == false) { sb.Append(filter[offset++]); } attr = sb.ToString().Trim(); // is there an attribute name specified in the filter ? if (attr.Length == 0 || attr[0] == ';') { throw new LdapLocalException(ExceptionMessages.NO_ATTRIBUTE_NAME, LdapException.FILTER_ERROR); } for (index = 0; index < attr.Length; index++) { var atIndex = attr[index]; if ( !(char.IsLetterOrDigit(atIndex) || atIndex == '-' || atIndex == '.' || atIndex == ';' || atIndex == ':')) { if (atIndex == '\\') { throw new LdapLocalException(ExceptionMessages.INVALID_ESC_IN_DESCR, LdapException.FILTER_ERROR); } throw new LdapLocalException(ExceptionMessages.INVALID_CHAR_IN_DESCR, new object[] {atIndex}, LdapException.FILTER_ERROR); } } // is there an option specified in the filter ? index = attr.IndexOf(';'); if (index != -1 && index == attr.Length - 1) { throw new LdapLocalException(ExceptionMessages.NO_OPTION, LdapException.FILTER_ERROR); } ret = -1; } return ret; } } /// <summary> /// Reads an RFC 2251 filter type from the filter string and returns its /// int value. /// </summary> public virtual int FilterType { get { if (offset >= filterLength) { //"Unexpected end of filter", throw new LdapLocalException(ExceptionMessages.UNEXPECTED_END, LdapException.FILTER_ERROR); } int ret; if (filter.Substring(offset).StartsWith(">=")) { offset += 2; ret = GREATER_OR_EQUAL; } else if (filter.Substring(offset).StartsWith("<=")) { offset += 2; ret = LESS_OR_EQUAL; } else if (filter.Substring(offset).StartsWith("~=")) { offset += 2; ret = APPROX_MATCH; } else if (filter.Substring(offset).StartsWith(":=")) { offset += 2; ret = EXTENSIBLE_MATCH; } else if (filter[offset] == '=') { offset++; ret = EQUALITY_MATCH; } else { //"Invalid comparison operator", throw new LdapLocalException(ExceptionMessages.INVALID_FILTER_COMPARISON, LdapException.FILTER_ERROR); } return ret; } } /// <summary> Reads a value from a filter string.</summary> public virtual string Value { get { if (offset >= filterLength) { //"Unexpected end of filter", throw new LdapLocalException(ExceptionMessages.UNEXPECTED_END, LdapException.FILTER_ERROR); } var idx = filter.IndexOf(')', offset); if (idx == -1) { idx = filterLength; } var ret = filter.Substring(offset, idx - offset); offset = idx; return ret; } } /// <summary> Returns the current attribute identifier.</summary> public virtual string Attr { get { return attr; } } public RfcFilter Enclosing_Instance { get { return enclosingInstance; } } //************************************************************************* // Private variables //************************************************************************* private readonly string filter; // The filter string to parse private string attr; // Name of the attribute just parsed private int offset; // Offset pointer into the filter string private readonly int filterLength; // Length of the filter string to parse //************************************************************************* // Constructor //************************************************************************* /// <summary> Constructs a FilterTokenizer for a filter.</summary> public FilterTokenizer(RfcFilter enclosingInstance, string filter) { InitBlock(enclosingInstance); this.filter = filter; offset = 0; filterLength = filter.Length; } //************************************************************************* // Tokenizer methods //************************************************************************* /// <summary> /// Reads the current char and throws an Exception if it is not a left /// parenthesis. /// </summary> public void getLeftParen() { if (offset >= filterLength) { //"Unexpected end of filter", throw new LdapLocalException(ExceptionMessages.UNEXPECTED_END, LdapException.FILTER_ERROR); } if (filter[offset++] != '(') { //"Missing left paren", throw new LdapLocalException(ExceptionMessages.EXPECTING_LEFT_PAREN, new object[] {filter[offset -= 1]}, LdapException.FILTER_ERROR); } } /// <summary> /// Reads the current char and throws an Exception if it is not a right /// parenthesis. /// </summary> public void getRightParen() { if (offset >= filterLength) { //"Unexpected end of filter", throw new LdapLocalException(ExceptionMessages.UNEXPECTED_END, LdapException.FILTER_ERROR); } if (filter[offset++] != ')') { //"Missing right paren", throw new LdapLocalException(ExceptionMessages.EXPECTING_RIGHT_PAREN, new object[] {filter[offset - 1]}, LdapException.FILTER_ERROR); } } /// <summary> /// Return the current char without advancing the offset pointer. This is /// used by ParseFilterList when determining if there are any more /// Filters in the list. /// </summary> public char peekChar() { if (offset >= filterLength) { //"Unexpected end of filter", throw new LdapLocalException(ExceptionMessages.UNEXPECTED_END, LdapException.FILTER_ERROR); } return filter[offset]; } } } }
/* * Copyright 1999-2012 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections; using System.Collections.Generic; using System.Text; using Tup.Cobar4Net.Parser.Ast.Expression; using Tup.Cobar4Net.Parser.Ast.Expression.Misc; using Tup.Cobar4Net.Parser.Ast.Expression.Primary; using Tup.Cobar4Net.Parser.Ast.Fragment; using Tup.Cobar4Net.Parser.Ast.Fragment.Tableref; using Tup.Cobar4Net.Parser.Ast.Stmt.Dml; using Tup.Cobar4Net.Parser.Recognizer.Mysql.Lexer; namespace Tup.Cobar4Net.Parser.Recognizer.Mysql.Syntax { /// <author> /// <a href="mailto:shuo.qius@alibaba-inc.com">QIU Shuo</a> /// </author> public abstract class MySqlDmlParser : MySqlParser { protected MySqlExprParser exprParser; public MySqlDmlParser(MySqlLexer lexer, MySqlExprParser exprParser) : base(lexer) { this.exprParser = exprParser; } /// <summary>nothing has been pre-consumed</summary> /// <returns>null if there is no order by</returns> /// <exception cref="System.SqlSyntaxErrorException" /> protected internal virtual GroupBy GroupBy() { if (lexer.Token() != MySqlToken.KwGroup) { return null; } lexer.NextToken(); Match(MySqlToken.KwBy); var expr = exprParser.Expression(); var order = SortOrder.Asc; GroupBy groupBy; switch (lexer.Token()) { case MySqlToken.KwDesc: { order = SortOrder.Desc; goto case MySqlToken.KwAsc; } case MySqlToken.KwAsc: { lexer.NextToken(); goto default; } default: { break; } } switch (lexer.Token()) { case MySqlToken.KwWith: { lexer.NextToken(); MatchIdentifier("ROLLUP"); return new GroupBy(expr, order, true); } case MySqlToken.PuncComma: { break; } default: { return new GroupBy(expr, order, false); } } for (groupBy = new GroupBy().AddOrderByItem(expr, order); lexer.Token() == MySqlToken.PuncComma;) { lexer.NextToken(); order = SortOrder.Asc; expr = exprParser.Expression(); switch (lexer.Token()) { case MySqlToken.KwDesc: { order = SortOrder.Desc; goto case MySqlToken.KwAsc; } case MySqlToken.KwAsc: { lexer.NextToken(); goto default; } default: { break; } } groupBy.AddOrderByItem(expr, order); if (lexer.Token() == MySqlToken.KwWith) { lexer.NextToken(); MatchIdentifier("ROLLUP"); return groupBy.SetWithRollup(); } } return groupBy; } /// <summary>nothing has been pre-consumed</summary> /// <returns>null if there is no order by</returns> /// <exception cref="System.SqlSyntaxErrorException" /> protected internal virtual OrderBy OrderBy() { if (lexer.Token() != MySqlToken.KwOrder) { return null; } lexer.NextToken(); Match(MySqlToken.KwBy); var expr = exprParser.Expression(); var order = SortOrder.Asc; OrderBy orderBy; switch (lexer.Token()) { case MySqlToken.KwDesc: { order = SortOrder.Desc; goto case MySqlToken.KwAsc; } case MySqlToken.KwAsc: { if (lexer.NextToken() != MySqlToken.PuncComma) { return new OrderBy(expr, order); } goto case MySqlToken.PuncComma; } case MySqlToken.PuncComma: { orderBy = new OrderBy(); orderBy.AddOrderByItem(expr, order); break; } default: { return new OrderBy(expr, order); } } for (; lexer.Token() == MySqlToken.PuncComma;) { lexer.NextToken(); order = SortOrder.Asc; expr = exprParser.Expression(); switch (lexer.Token()) { case MySqlToken.KwDesc: { order = SortOrder.Desc; goto case MySqlToken.KwAsc; } case MySqlToken.KwAsc: { lexer.NextToken(); break; } } orderBy.AddOrderByItem(expr, order); } return orderBy; } /// <param name="id">never null</param> /// <exception cref="System.SqlSyntaxErrorException" /> protected virtual IList<Identifier> BuildIdList(Identifier id) { if (lexer.Token() != MySqlToken.PuncComma) { IList<Identifier> list = new List<Identifier>(1); list.Add(id); return list; } IList<Identifier> list_1 = new List<Identifier>(); list_1.Add(id); for (; lexer.Token() == MySqlToken.PuncComma;) { lexer.NextToken(); id = Identifier(); list_1.Add(id); } return list_1; } /// <summary> /// <code>(id (',' id)*)?</code> /// </summary> /// <returns> /// never null or empty. /// <see cref="System.Collections.ArrayList{E}" /> /// is possible /// </returns> /// <exception cref="System.SqlSyntaxErrorException" /> protected virtual IList<Identifier> IdList() { return BuildIdList(Identifier()); } /// <summary> /// <code>( idName (',' idName)*)? ')'</code> /// </summary> /// <returns>empty list if emtpy id list</returns> /// <exception cref="System.SqlSyntaxErrorException" /> protected virtual IList<string> IdNameList() { if (lexer.Token() != MySqlToken.Identifier) { Match(MySqlToken.PuncRightParen); return new List<string>(0); } IList<string> list; var str = lexer.GetStringValue(); if (lexer.NextToken() == MySqlToken.PuncComma) { list = new List<string>(); list.Add(str); for (; lexer.Token() == MySqlToken.PuncComma;) { lexer.NextToken(); list.Add(lexer.GetStringValue()); Match(MySqlToken.Identifier); } } else { list = new List<string>(1); list.Add(str); } Match(MySqlToken.PuncRightParen); return list; } /// <returns>never null</returns> /// <exception cref="System.SqlSyntaxErrorException" /> protected internal virtual TableReferences TableRefs() { var @ref = TableReference(); return BuildTableReferences(@ref); } /// <exception cref="System.SqlSyntaxErrorException" /> private TableReferences BuildTableReferences(TableReference @ref) { IList<TableReference> list; if (lexer.Token() == MySqlToken.PuncComma) { list = new List<TableReference>(); list.Add(@ref); for (; lexer.Token() == MySqlToken.PuncComma;) { lexer.NextToken(); @ref = TableReference(); list.Add(@ref); } } else { list = new List<TableReference>(1); list.Add(@ref); } return new TableReferences(list); } /// <exception cref="System.SqlSyntaxErrorException" /> private TableReference TableReference() { var @ref = TableFactor(); return BuildTableReference(@ref); } /// <exception cref="System.SqlSyntaxErrorException" /> private TableReference BuildTableReference(TableReference @ref) { for (;;) { IExpression on; IList<string> @using; TableReference temp; var isOut = false; var isLeft = true; switch (lexer.Token()) { case MySqlToken.KwInner: case MySqlToken.KwCross: { lexer.NextToken(); goto case MySqlToken.KwJoin; } case MySqlToken.KwJoin: { lexer.NextToken(); temp = TableFactor(); switch (lexer.Token()) { case MySqlToken.KwOn: { lexer.NextToken(); on = exprParser.Expression(); @ref = new InnerJoin(@ref, temp, on); break; } case MySqlToken.KwUsing: { lexer.NextToken(); Match(MySqlToken.PuncLeftParen); @using = IdNameList(); @ref = new InnerJoin(@ref, temp, @using); break; } default: { @ref = new InnerJoin(@ref, temp); break; } } break; } case MySqlToken.KwStraightJoin: { lexer.NextToken(); temp = TableFactor(); switch (lexer.Token()) { case MySqlToken.KwOn: { lexer.NextToken(); on = exprParser.Expression(); @ref = new StraightJoin(@ref, temp, on); break; } default: { @ref = new StraightJoin(@ref, temp); break; } } break; } case MySqlToken.KwRight: { isLeft = false; goto case MySqlToken.KwLeft; } case MySqlToken.KwLeft: { lexer.NextToken(); if (lexer.Token() == MySqlToken.KwOuter) { lexer.NextToken(); } Match(MySqlToken.KwJoin); temp = TableReference(); switch (lexer.Token()) { case MySqlToken.KwOn: { lexer.NextToken(); on = exprParser.Expression(); @ref = new OuterJoin(isLeft, @ref, temp, on); break; } case MySqlToken.KwUsing: { lexer.NextToken(); Match(MySqlToken.PuncLeftParen); @using = IdNameList(); @ref = new OuterJoin(isLeft, @ref, temp, @using); break; } default: { var condition = temp.RemoveLastConditionElement(); if (condition is IExpression) { @ref = new OuterJoin(isLeft, @ref, temp, (IExpression)condition); } else { if (condition is IList) { @ref = new OuterJoin(isLeft, @ref, temp, (IList<string>)condition); } else { throw Err("conditionExpr cannot be null for outer join"); } } break; } } break; } case MySqlToken.KwNatural: { lexer.NextToken(); switch (lexer.Token()) { case MySqlToken.KwRight: { isLeft = false; goto case MySqlToken.KwLeft; } case MySqlToken.KwLeft: { lexer.NextToken(); if (lexer.Token() == MySqlToken.KwOuter) { lexer.NextToken(); } isOut = true; goto case MySqlToken.KwJoin; } case MySqlToken.KwJoin: { lexer.NextToken(); temp = TableFactor(); @ref = new NaturalJoin(isOut, isLeft, @ref, temp); break; } default: { throw Err("unexpected token after NATURAL for natural join:" + lexer.Token()); } } break; } default: { return @ref; } } } } /// <exception cref="System.SqlSyntaxErrorException" /> private TableReference TableFactor() { string alias = null; switch (lexer.Token()) { case MySqlToken.PuncLeftParen: { lexer.NextToken(); var @ref = TrsOrQuery(); Match(MySqlToken.PuncRightParen); if (@ref is IQueryExpression) { alias = As(); return new SubqueryFactor((IQueryExpression)@ref, alias); } return (TableReferences)@ref; } case MySqlToken.Identifier: { var table = Identifier(); alias = As(); var hintList = HintList(); return new TableRefFactor(table, alias, hintList); } default: { throw Err("unexpected token for tableFactor: " + lexer.Token()); } } } /// <returns> /// never empty. upper-case if id format. /// <code>"alias1" |"`al`ias1`" | "'alias1'" | "_latin1'alias1'"</code> /// </returns> /// <exception cref="System.SqlSyntaxErrorException" /> protected virtual string As() { if (lexer.Token() == MySqlToken.KwAs) { lexer.NextToken(); } var alias = new StringBuilder(); var id = false; if (lexer.Token() == MySqlToken.Identifier) { alias.Append(lexer.GetStringValueUppercase()); id = true; lexer.NextToken(); } if (lexer.Token() == MySqlToken.LiteralChars) { if (!id || id && alias[0] == '_') { alias.Append(lexer.GetStringValue()); lexer.NextToken(); } } return alias.Length > 0 ? alias.ToString() : null; } /// <returns> /// type of /// <see cref="Tup.Cobar4Net.Parser.Ast.Expression.Misc.IQueryExpression" /> /// or /// <see cref="TableReferences" /> /// </returns> /// <exception cref="System.SqlSyntaxErrorException" /> private object TrsOrQuery() { object @ref; switch (lexer.Token()) { case MySqlToken.KwSelect: { var select = SelectPrimary(); return BuildUnionSelect(select); } case MySqlToken.PuncLeftParen: { lexer.NextToken(); @ref = TrsOrQuery(); Match(MySqlToken.PuncRightParen); if (@ref is IQueryExpression) { if (@ref is DmlSelectStatement) { IQueryExpression rst = BuildUnionSelect((DmlSelectStatement)@ref); if (rst != @ref) { return rst; } } var alias = As(); if (alias != null) { @ref = new SubqueryFactor((IQueryExpression)@ref, alias); } else { return @ref; } } // ---- build factor complete--------------- @ref = BuildTableReference((TableReference)@ref); // ---- build ref complete--------------- break; } default: { @ref = TableReference(); break; } } IList<TableReference> list; if (lexer.Token() == MySqlToken.PuncComma) { list = new List<TableReference>(); list.Add((TableReference)@ref); for (; lexer.Token() == MySqlToken.PuncComma;) { lexer.NextToken(); @ref = TableReference(); list.Add((TableReference)@ref); } return new TableReferences(list); } list = new List<TableReference>(1); list.Add((TableReference)@ref); return new TableReferences(list); } /// <returns>null if there is no hint</returns> /// <exception cref="System.SqlSyntaxErrorException" /> private IList<IndexHint> HintList() { var hint = Hint(); if (hint == null) { return null; } IList<IndexHint> list; var hint2 = Hint(); if (hint2 == null) { list = new List<IndexHint>(1); list.Add(hint); return list; } list = new List<IndexHint>(); list.Add(hint); list.Add(hint2); for (; (hint2 = Hint()) != null; list.Add(hint2)) { } return list; } /// <returns>null if there is no hint</returns> /// <exception cref="System.SqlSyntaxErrorException" /> private IndexHint Hint() { IndexHintAction _hintAction; switch (lexer.Token()) { case MySqlToken.KwUse: { _hintAction = IndexHintAction.Use; break; } case MySqlToken.KwIgnore: { _hintAction = IndexHintAction.Ignore; break; } case MySqlToken.KwForce: { _hintAction = IndexHintAction.Force; break; } default: { return null; } } IndexHintType _hintType; switch (lexer.NextToken()) { case MySqlToken.KwIndex: { _hintType = IndexHintType.Index; break; } case MySqlToken.KwKey: { _hintType = IndexHintType.Key; break; } default: { throw Err("must be INDEX or KEY for hint _hintType, not " + lexer.Token()); } } var scope = IndexHintScope.All; if (lexer.NextToken() == MySqlToken.KwFor) { switch (lexer.NextToken()) { case MySqlToken.KwJoin: { lexer.NextToken(); scope = IndexHintScope.Join; break; } case MySqlToken.KwOrder: { lexer.NextToken(); Match(MySqlToken.KwBy); scope = IndexHintScope.OrderBy; break; } case MySqlToken.KwGroup: { lexer.NextToken(); Match(MySqlToken.KwBy); scope = IndexHintScope.GroupBy; break; } default: { throw Err("must be JOIN or ORDER or GROUP for hint _hintScope, not " + lexer.Token()); } } } Match(MySqlToken.PuncLeftParen); var indexList = IdNameList(); return new IndexHint(_hintAction, _hintType, scope, indexList); } /// <returns>argument itself if there is no union</returns> /// <exception cref="System.SqlSyntaxErrorException" /> protected virtual DmlQueryStatement BuildUnionSelect(DmlSelectStatement select) { if (lexer.Token() != MySqlToken.KwUnion) { return select; } var union = new DmlSelectUnionStatement(select); for (; lexer.Token() == MySqlToken.KwUnion;) { lexer.NextToken(); var isAll = false; switch (lexer.Token()) { case MySqlToken.KwAll: { isAll = true; goto case MySqlToken.KwDistinct; } case MySqlToken.KwDistinct: { lexer.NextToken(); break; } } select = SelectPrimary(); union.AddSelect(select, isAll); } union.SetOrderBy(OrderBy()).SetLimit(Limit()); return union; } /// <exception cref="System.SqlSyntaxErrorException" /> protected virtual DmlSelectStatement SelectPrimary() { switch (lexer.Token()) { case MySqlToken.KwSelect: { return Select(); } case MySqlToken.PuncLeftParen: { lexer.NextToken(); var select = SelectPrimary(); Match(MySqlToken.PuncRightParen); return select; } default: { throw Err("unexpected token: " + lexer.Token()); } } } /// <summary> /// first token is /// <see cref="MySqlToken.KwSelect">SELECT</see> /// which has been scanned /// but not yet consumed /// </summary> /// <exception cref="System.SqlSyntaxErrorException" /> public virtual DmlSelectStatement Select() { return new MySqlDmlSelectParser(lexer, exprParser).Select(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Xml; using System.Collections; #if (!STANDALONEBUILD) using Microsoft.Internal.Performance; #endif using Microsoft.Build.BuildEngine.Shared; using error = Microsoft.Build.BuildEngine.Shared.ErrorUtilities; namespace Microsoft.Build.BuildEngine { /// <summary> /// This class represents a collection of persisted &lt;Target&gt;'s. Each /// MSBuild project has exactly one TargetCollection, which includes /// all the imported Targets as well as the ones in the main project file. /// </summary> /// <owner>rgoel</owner> public class TargetCollection : IEnumerable, ICollection { #region Member Data // This is the hashtable of Targets (indexed by name) contained in this collection. Hashtable targetTable = null; Project parentProject = null; #endregion #region Constructors /// <summary> /// Creates an instance of this class for the given project. /// </summary> /// <owner>RGoel</owner> /// <param name="parentProject"></param> internal TargetCollection ( Project parentProject ) { error.VerifyThrow(parentProject != null, "Must pass in valid parent project object."); this.targetTable = new Hashtable(StringComparer.OrdinalIgnoreCase); this.parentProject = parentProject; } #endregion #region Properties /// <summary> /// Read-only accessor for parent project object. /// </summary> /// <value></value> /// <owner>RGoel</owner> internal Project ParentProject { get { return this.parentProject; } } /// <summary> /// Read-only property which returns the number of Targets contained /// in our collection. /// </summary> /// <owner>RGoel</owner> public int Count { get { error.VerifyThrow(this.targetTable != null, "Hashtable not initialized!"); return this.targetTable.Count; } } /// <summary> /// This ICollection property tells whether this object is thread-safe. /// </summary> /// <owner>RGoel</owner> public bool IsSynchronized { get { return this.targetTable.IsSynchronized; } } /// <summary> /// This ICollection property returns the object to be used to synchronize /// access to the class. /// </summary> /// <owner>RGoel</owner> public object SyncRoot { get { return this.targetTable.SyncRoot; } } /// <summary> /// Gets the target with the given name, case-insensitively. /// Note that this also defines the .BuildItem() accessor automagically. /// </summary> /// <owner>RGoel</owner> /// <param name="index"></param> /// <returns>The target with the given name.</returns> public Target this[string index] { get { error.VerifyThrow(this.targetTable != null, "Hashtable not initialized!"); return (Target)targetTable[index]; } } #endregion #region Methods /// <summary> /// This ICollection method copies the contents of this collection to an /// array. /// </summary> /// <owner>RGoel</owner> public void CopyTo ( Array array, int index ) { error.VerifyThrow(this.targetTable != null, "Hashtable not initialized!"); this.targetTable.Values.CopyTo(array, index); } /// <summary> /// This IEnumerable method returns an IEnumerator object, which allows /// the caller to enumerate through the Target objects contained in /// this TargetCollection. /// </summary> /// <owner>RGoel</owner> public IEnumerator GetEnumerator ( ) { error.VerifyThrow(this.targetTable != null, "Hashtable not initialized!"); return this.targetTable.Values.GetEnumerator(); } /// <summary> /// Adds a new Target to our collection. This method does nothing /// to manipulate the project's XML content. /// If a target with the same name already exists, it is replaced by /// the new one. /// </summary> /// <param name="newTarget">target to add</param> internal void AddOverrideTarget(Target newTarget) { error.VerifyThrow(this.targetTable != null, "Hashtable not initialized!"); // if a target with this name already exists, override it // if it doesn't exist, just add it targetTable[newTarget.Name] = newTarget; } /// <summary> /// Adds a new &lt;Target&gt; element to the project file, at the very end. /// </summary> /// <param name="targetName"></param> /// <returns>The new Target object.</returns> public Target AddNewTarget ( string targetName ) { error.VerifyThrow(this.parentProject != null, "Need parent project."); // Create the XML for the new <Target> node and append it to the very end of the main project file. XmlElement projectElement = this.parentProject.ProjectElement; XmlElement newTargetElement = projectElement.OwnerDocument.CreateElement(XMakeElements.target, XMakeAttributes.defaultXmlNamespace); newTargetElement.SetAttribute(XMakeAttributes.name, targetName); projectElement.AppendChild(newTargetElement); // Create a new Target object, and add it to our hash table. Target newTarget = new Target(newTargetElement, this.parentProject, false); this.targetTable[targetName] = newTarget; // The project file has been modified and needs to be saved and re-evaluated. // Also though, adding/removing a target requires us to re-walk all the XML // in order to re-compute out the "first logical target" as well as re-compute // the target overriding rules. this.parentProject.MarkProjectAsDirtyForReprocessXml(); return newTarget; } /// <summary> /// Removes a target from the project, and removes the corresponding &lt;Target&gt; element /// from the project's XML. /// </summary> /// <param name="targetToRemove"></param> /// <owner>RGoel</owner> public void RemoveTarget ( Target targetToRemove ) { error.VerifyThrowArgumentNull(targetToRemove, nameof(targetToRemove)); // Confirm that it's not an imported target. error.VerifyThrowInvalidOperation(!targetToRemove.IsImported, "CannotModifyImportedProjects"); // Confirm that the target belongs to this project. error.VerifyThrowInvalidOperation(targetToRemove.ParentProject == this.parentProject, "IncorrectObjectAssociation", "Target", "Project"); // Remove the Xml for the <Target> from the <Project>. this.parentProject.ProjectElement.RemoveChild(targetToRemove.TargetElement); // Remove the target from our hashtable, if it exists. It might not exist, and that's okay. // The reason it might not exist is because of target overriding, and the fact that // our hashtable only stores the *last* target of a given name. if ((Target)this.targetTable[targetToRemove.Name] == targetToRemove) { this.targetTable.Remove(targetToRemove.Name); } // Dissociate the target from the parent project. targetToRemove.ParentProject = null; // The project file has been modified and needs to be saved and re-evaluated. // Also though, adding/removing a target requires us to re-walk all the XML // in order to re-compute the "first logical target" as well as re-compute // the target overriding rules. this.parentProject.MarkProjectAsDirtyForReprocessXml(); } /// <summary> /// Checks if a target with given name already exists /// </summary> /// <param name="targetName">name of the target we're looking for</param> /// <returns>true if the target already exists</returns> public bool Exists ( string targetName ) { error.VerifyThrow(this.targetTable != null, "Hashtable not initialized!"); return targetTable.ContainsKey(targetName); } /// <summary> /// Removes all Targets from our collection. This method does nothing /// to manipulate the project's XML content. /// </summary> /// <owner>RGoel</owner> internal void Clear ( ) { error.VerifyThrow(this.targetTable != null, "Hashtable not initialized!"); this.targetTable.Clear(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using Signum.Engine.Maps; using Signum.Engine.DynamicQuery; using System.Reflection; using Signum.Entities.SMS; using Signum.Entities; using Signum.Utilities; using Signum.Utilities.Reflection; using Signum.Engine.Operations; using Signum.Engine.Processes; using Signum.Entities.Processes; using System.Linq.Expressions; using Signum.Entities.Basics; using System.Text.RegularExpressions; using Signum.Engine.Basics; using System.Threading.Tasks; using System.Globalization; using Signum.Engine.Mailing; using Signum.Engine.Templating; using Signum.Entities.DynamicQuery; using System.Text; using System.Threading; namespace Signum.Engine.SMS { public static class SMSLogic { public static SMSTemplateMessageEmbedded? GetCultureMessage(this SMSTemplateEntity template, CultureInfo ci) { return template.Messages.SingleOrDefault(tm => tm.CultureInfo.ToCultureInfo() == ci); } [AutoExpressionField] public static IQueryable<SMSMessageEntity> SMSMessages(this ISMSOwnerEntity e) => As.Expression(() => Database.Query<SMSMessageEntity>().Where(m => m.Referred.Is(e))); [AutoExpressionField] public static IQueryable<SMSMessageEntity> SMSMessages(this SMSSendPackageEntity e) => As.Expression(() => Database.Query<SMSMessageEntity>().Where(a => a.SendPackage.Is(e))); [AutoExpressionField] public static IQueryable<SMSMessageEntity> SMSMessages(this SMSUpdatePackageEntity e) => As.Expression(() => Database.Query<SMSMessageEntity>().Where(a => a.UpdatePackage.Is(e))); static Func<SMSConfigurationEmbedded> getConfiguration = null!; public static SMSConfigurationEmbedded Configuration { get { return getConfiguration(); } } public static ISMSProvider? Provider { get; set; } public static ISMSProvider GetProvider() => Provider ?? throw new InvalidOperationException("No ISMSProvider set"); public static ResetLazy<Dictionary<Lite<SMSTemplateEntity>, SMSTemplateEntity>> SMSTemplatesLazy = null!; public static ResetLazy<Dictionary<object, List<SMSTemplateEntity>>> SMSTemplatesByQueryName = null!; public static void AssertStarted(SchemaBuilder sb) { sb.AssertDefined(ReflectionTools.GetMethodInfo(() => Start(null!, null!, null!))); } public static void Start(SchemaBuilder sb, ISMSProvider? provider, Func<SMSConfigurationEmbedded> getConfiguration) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { CultureInfoLogic.AssertStarted(sb); sb.Schema.SchemaCompleted += () => Schema_SchemaCompleted(sb); SMSLogic.getConfiguration = getConfiguration; SMSLogic.Provider = provider; sb.Include<SMSMessageEntity>() .WithQuery(() => m => new { Entity = m, m.Id, m.From, m.DestinationNumber, m.State, m.SendDate, m.Template, m.Referred, m.Exception, }); sb.Include<SMSTemplateEntity>() .WithQuery(() => t => new { Entity = t, t.Id, t.Name, t.IsActive, t.From, t.Query, t.Model, }); sb.Schema.EntityEvents<SMSTemplateEntity>().PreSaving += new PreSavingEventHandler<SMSTemplateEntity>(EmailTemplate_PreSaving); sb.Schema.EntityEvents<SMSTemplateEntity>().Retrieved += SMSTemplateLogic_Retrieved; sb.Schema.Table<SMSModelEntity>().PreDeleteSqlSync += e => Administrator.UnsafeDeletePreCommand(Database.Query<SMSTemplateEntity>() .Where(a => a.Model.Is(e))); SMSTemplatesLazy = sb.GlobalLazy(() => Database.Query<SMSTemplateEntity>().ToDictionary(et => et.ToLite()) , new InvalidateWith(typeof(SMSTemplateEntity))); SMSTemplatesByQueryName = sb.GlobalLazy(() => { return SMSTemplatesLazy.Value.Values.Where(q=>q.Query!=null).SelectCatch(et => KeyValuePair.Create(et.Query!.ToQueryName(), et)).GroupToDictionary(); }, new InvalidateWith(typeof(SMSTemplateEntity))); SMSMessageGraph.Register(); SMSTemplateGraph.Register(); Validator.PropertyValidator<SMSTemplateEntity>(et => et.Messages).StaticPropertyValidation += (t, pi) => { var dc = SMSLogic.Configuration?.DefaultCulture; if (dc != null && !t.Messages.Any(m => m.CultureInfo.Is(dc))) return SMSTemplateMessage.ThereMustBeAMessageFor0.NiceToString().FormatWith(dc.EnglishName); return null; }; sb.AddUniqueIndex((SMSTemplateEntity t) => new { t.Model }, where: t => t.Model != null && t.IsActive == true); ExceptionLogic.DeleteLogs += ExceptionLogic_DeleteLogs; ExceptionLogic.DeleteLogs += ExceptionLogic_DeletePackages; } } public static void ExceptionLogic_DeletePackages(DeleteLogParametersEmbedded parameters, StringBuilder sb, CancellationToken token) { Database.Query<SMSSendPackageEntity>().Where(pack => !Database.Query<ProcessEntity>().Any(pr => pr.Data == pack) && !pack.SMSMessages().Any()) .UnsafeDeleteChunksLog(parameters, sb, token); Database.Query<SMSUpdatePackageEntity>().Where(pack => !Database.Query<ProcessEntity>().Any(pr => pr.Data == pack) && !pack.SMSMessages().Any()) .UnsafeDeleteChunksLog(parameters, sb, token); } public static void ExceptionLogic_DeleteLogs(DeleteLogParametersEmbedded parameters, StringBuilder sb, CancellationToken token) { void Remove(DateTime? dateLimit, bool withExceptions) { if (dateLimit == null) return; var query = Database.Query<SMSMessageEntity>().Where(o => o.SendDate != null && o.SendDate < dateLimit); if (withExceptions) query = query.Where(a => a.Exception != null); query.UnsafeDeleteChunksLog(parameters, sb, token); } Remove(parameters.GetDateLimitDelete(typeof(SMSMessageEntity).ToTypeEntity()), withExceptions: false); Remove(parameters.GetDateLimitDeleteWithExceptions(typeof(SMSMessageEntity).ToTypeEntity()), withExceptions: true); } public static HashSet<Type> GetAllTypes() { return TypeLogic.TypeToEntity .Where(kvp => typeof(ISMSOwnerEntity).IsAssignableFrom(kvp.Key)) .Select(kvp => kvp.Key) .ToHashSet(); } public static void SMSTemplateLogic_Retrieved(SMSTemplateEntity smsTemplate, PostRetrievingContext ctx) { if (smsTemplate.Query == null) return; using (smsTemplate.DisableAuthorization ? ExecutionMode.Global() : null) { object queryName = QueryLogic.ToQueryName(smsTemplate.Query!.Key); QueryDescription description = QueryLogic.Queries.QueryDescription(queryName); using (smsTemplate.DisableAuthorization ? ExecutionMode.Global() : null) smsTemplate.ParseData(description); } } static void EmailTemplate_PreSaving(SMSTemplateEntity smsTemplate, PreSavingContext ctx) { if (smsTemplate.Query == null) return; using (smsTemplate.DisableAuthorization ? ExecutionMode.Global() : null) { var queryName = QueryLogic.ToQueryName(smsTemplate.Query!.Key); QueryDescription qd = QueryLogic.Queries.QueryDescription(queryName); List<QueryToken> list = new List<QueryToken>(); foreach (var message in smsTemplate.Messages) { message.Message = TextTemplateParser.Parse(message.Message, qd, smsTemplate.Model?.ToType()).ToString(); } } } static string CheckLength(string result, SMSTemplateEntity template) { if (template.RemoveNoSMSCharacters) { result = SMSCharacters.RemoveNoSMSCharacters(result); } int remainingLength = SMSCharacters.RemainingLength(result); if (remainingLength < 0) { switch (template.MessageLengthExceeded) { case MessageLengthExceeded.NotAllowed: throw new ApplicationException(SMSCharactersMessage.TheTextForTheSMSMessageExceedsTheLengthLimit.NiceToString()); case MessageLengthExceeded.Allowed: break; case MessageLengthExceeded.TextPruning: return result.RemoveEnd(Math.Abs(remainingLength)); } } return result; } public static void SendSMS(SMSMessageEntity message) { if (!message.DestinationNumber.Contains(',')) { SendOneMessage(message); } else { var numbers = message.DestinationNumber.Split(',').Select(n => n.Trim()).Distinct(); message.DestinationNumber = numbers.FirstEx(); SendOneMessage(message); foreach (var number in numbers.Skip(1)) { SendOneMessage(new SMSMessageEntity { DestinationNumber = number, Certified = message.Certified, EditableMessage = message.EditableMessage, From = message.From, Message = message.Message, Referred = message.Referred, State = SMSMessageState.Created, Template = message.Template, SendPackage = message.SendPackage, UpdatePackage = message.UpdatePackage, UpdatePackageProcessed = message.UpdatePackageProcessed, }); } } } private static void SendOneMessage(SMSMessageEntity message) { using (OperationLogic.AllowSave<SMSMessageEntity>()) { try { message.MessageID = GetProvider().SMSSendAndGetTicket(message); message.SendDate = TimeZoneManager.Now.TrimToSeconds(); message.State = SMSMessageState.Sent; message.Save(); } catch (Exception e) { var ex = e.LogException(); using (Transaction tr = Transaction.ForceNew()) { message.Exception = ex.ToLite(); message.State = SMSMessageState.SendFailed; message.Save(); tr.Commit(); } throw; } } } public static void SendAsyncSMS(SMSMessageEntity message) { Task.Factory.StartNew(() => { SendSMS(message); }); } public static List<SMSMessageEntity> CreateAndSendMultipleSMSMessages(MultipleSMSModel template, List<string> phones) { var messages = new List<SMSMessageEntity>(); var IDs = GetProvider().SMSMultipleSendAction(template, phones); var sendDate = TimeZoneManager.Now.TrimToSeconds(); for (int i = 0; i < phones.Count; i++) { var message = new SMSMessageEntity { Message = template.Message, From = template.From }; message.SendDate = sendDate; //message.SendState = SendState.Sent; message.DestinationNumber = phones[i]; message.MessageID = IDs[i]; message.Save(); messages.Add(message); } return messages; } public static SMSMessageEntity CreateSMSMessage(Lite<SMSTemplateEntity> template, Entity? entity, ISMSModel? model, CultureInfo? forceCulture) { var t = SMSLogic.SMSTemplatesLazy.Value.GetOrThrow(template); var defaultCulture = SMSLogic.Configuration.DefaultCulture.ToCultureInfo(); if (t.Query != null) { var qd = QueryLogic.Queries.QueryDescription(t.Query.ToQueryName()); List<QueryToken> tokens = new List<QueryToken>(); t.ParseData(qd); tokens.Add(t.To!.Token); var parsedNodes = t.Messages.ToDictionary( tm => tm.CultureInfo.ToCultureInfo(), tm => TextTemplateParser.Parse(tm.Message, qd, t.Model?.ToType()) ); parsedNodes.Values.ToList().ForEach(n => n.FillQueryTokens(tokens)); var columns = tokens.Distinct().Select(qt => new Column(qt, null)).ToList(); var filters = model != null ? model.GetFilters(qd) : new List<Filter> { new FilterCondition(QueryUtils.Parse("Entity", qd, 0), FilterOperation.EqualTo, entity!.ToLite()) }; var table = QueryLogic.Queries.ExecuteQuery(new QueryRequest { QueryName = qd.QueryName, Columns = columns, Pagination = model?.GetPagination() ?? new Pagination.All(), Filters = filters, Orders = model?.GetOrders(qd) ?? new List<Order>(), }); var columnTokens = table.Columns.ToDictionary(a => a.Column.Token); var ownerData = (SMSOwnerData)table.Rows[0][columnTokens.GetOrThrow(t.To!.Token)]!; var ci = forceCulture ?? ownerData.CultureInfo?.ToCultureInfo() ?? defaultCulture; var node = parsedNodes.TryGetC(ci) ?? parsedNodes.GetOrThrow(defaultCulture); return new SMSMessageEntity { Template = t.ToLite(), Message = node.Print(new TextTemplateParameters(entity, ci, columnTokens, table.Rows) { Model = model }), From = t.From, EditableMessage = t.EditableMessage, State = SMSMessageState.Created, Referred = ownerData.Owner, DestinationNumber = ownerData.TelephoneNumber, Certified = t.Certified }; } else { var ci = (forceCulture ?? defaultCulture).ToCultureInfoEntity(); return new SMSMessageEntity { Template = t.ToLite(), Message = t.Messages.Where(m=> m.CultureInfo.Is(ci)).SingleEx().Message, From = t.From, EditableMessage = t.EditableMessage, State = SMSMessageState.Created, Certified = t.Certified }; } } private static void Schema_SchemaCompleted(SchemaBuilder sb) { var types = sb.Schema.Tables.Keys.Where(t => typeof(ISMSOwnerEntity).IsAssignableFrom(t)); foreach (var type in types) giRegisterSMSMessagesExpression.GetInvoker(type)(sb); } static GenericInvoker<Action<SchemaBuilder>> giRegisterSMSMessagesExpression = new GenericInvoker<Action<SchemaBuilder>>(sb => RegisterSMSMessagesExpression<ISMSOwnerEntity>(sb)); private static void RegisterSMSMessagesExpression<T>(SchemaBuilder sb) where T : ISMSOwnerEntity { QueryLogic.Expressions.Register((T a) => a.SMSMessages(), () => typeof(SMSMessageEntity).NicePluralName()); } } public class SMSMessageGraph : Graph<SMSMessageEntity, SMSMessageState> { public static void Register() { GetState = m => m.State; new ConstructFrom<SMSTemplateEntity>(SMSMessageOperation.CreateSMSFromTemplate) { CanConstruct = t => !t.IsActive ? SMSCharactersMessage.TheTemplateMustBeActiveToConstructSMSMessages.NiceToString() : null, ToStates = { SMSMessageState.Created }, Construct = (t, args) => { return SMSLogic.CreateSMSMessage(t.ToLite(), args.TryGetArgC<Lite<Entity>>()?.RetrieveAndRemember(), args.TryGetArgC<ISMSModel>(), args.TryGetArgC<CultureInfo>()); } }.Register(); new Execute(SMSMessageOperation.Send) { CanBeNew = true, CanBeModified = true, FromStates = { SMSMessageState.Created }, ToStates = { SMSMessageState.Sent }, Execute = (m, _) => { try { SMSLogic.SendSMS(m); } catch (Exception e) { var ex = e.LogException(); using (Transaction tr = Transaction.ForceNew()) { m.Exception = ex.ToLite(); m.Save(); tr.Commit(); } throw; } } }.Register(); new Graph<SMSMessageEntity>.Execute(SMSMessageOperation.UpdateStatus) { CanExecute = m => m.State != SMSMessageState.Created ? null : SMSCharactersMessage.StatusCanNotBeUpdatedForNonSentMessages.NiceToString(), Execute = (sms, args) => { var func = args.TryGetArgC<Func<SMSMessageEntity, SMSMessageState>>(); if (func == null) func = SMSLogic.GetProvider().SMSUpdateStatusAction; sms.State = func(sms); if (sms.UpdatePackage != null) sms.UpdatePackageProcessed = true; } }.Register(); } } public class SMSTemplateGraph : Graph<SMSTemplateEntity> { public static void Register() { new Construct(SMSTemplateOperation.Create) { Construct = _ => new SMSTemplateEntity { Messages = { new SMSTemplateMessageEmbedded { CultureInfo = SMSLogic.Configuration.DefaultCulture } } }, }.Register(); new Execute(SMSTemplateOperation.Save) { CanBeModified = true, CanBeNew = true, Execute = (t, _) => { } }.Register(); } } public interface ISMSProvider { string SMSSendAndGetTicket(SMSMessageEntity message); List<string> SMSMultipleSendAction(MultipleSMSModel template, List<string> phones); SMSMessageState SMSUpdateStatusAction(SMSMessageEntity message); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using System.Threading.Tests; using Xunit; namespace System.Threading.ThreadPools.Tests { public partial class ThreadPoolTests { private const int UnexpectedTimeoutMilliseconds = ThreadTestHelpers.UnexpectedTimeoutMilliseconds; private const int ExpectedTimeoutMilliseconds = ThreadTestHelpers.ExpectedTimeoutMilliseconds; private const int MaxPossibleThreadCount = 0x7fff; static ThreadPoolTests() { // Run the following tests before any others if (!PlatformDetection.IsNetNative) { ConcurrentInitializeTest(); } } // Tests concurrent calls to ThreadPool.SetMinThreads [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "ThreadPool.SetMinThreads is not supported on UapAot.")] public static void ConcurrentInitializeTest() { int processorCount = Environment.ProcessorCount; var countdownEvent = new CountdownEvent(processorCount); Action threadMain = () => { countdownEvent.Signal(); countdownEvent.Wait(ThreadTestHelpers.UnexpectedTimeoutMilliseconds); Assert.True(ThreadPool.SetMinThreads(processorCount, processorCount)); }; var waitForThreadArray = new Action[processorCount]; for (int i = 0; i < processorCount; ++i) { var t = ThreadTestHelpers.CreateGuardedThread(out waitForThreadArray[i], threadMain); t.IsBackground = true; t.Start(); } foreach (Action waitForThread in waitForThreadArray) { waitForThread(); } } [Fact] public static void GetMinMaxThreadsTest() { int minw, minc; ThreadPool.GetMinThreads(out minw, out minc); Assert.True(minw >= 0); Assert.True(minc >= 0); int maxw, maxc; ThreadPool.GetMaxThreads(out maxw, out maxc); Assert.True(minw <= maxw); Assert.True(minc <= maxc); } [Fact] public static void GetAvailableThreadsTest() { int w, c; ThreadPool.GetAvailableThreads(out w, out c); Assert.True(w >= 0); Assert.True(c >= 0); int maxw, maxc; ThreadPool.GetMaxThreads(out maxw, out maxc); Assert.True(w <= maxw); Assert.True(c <= maxc); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "ThreadPool.SetMinThreads and SetMaxThreads are not supported on UapAot.")] public static void SetMinMaxThreadsTest() { int minw, minc, maxw, maxc; ThreadPool.GetMinThreads(out minw, out minc); ThreadPool.GetMaxThreads(out maxw, out maxc); Action resetThreadCounts = () => { Assert.True(ThreadPool.SetMaxThreads(maxw, maxc)); VerifyMaxThreads(maxw, maxc); Assert.True(ThreadPool.SetMinThreads(minw, minc)); VerifyMinThreads(minw, minc); }; try { int mint = Environment.ProcessorCount * 2; int maxt = mint + 1; ThreadPool.SetMinThreads(mint, mint); ThreadPool.SetMaxThreads(maxt, maxt); Assert.False(ThreadPool.SetMinThreads(maxt + 1, mint)); Assert.False(ThreadPool.SetMinThreads(mint, maxt + 1)); Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount, mint)); Assert.False(ThreadPool.SetMinThreads(mint, MaxPossibleThreadCount)); Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount + 1, mint)); Assert.False(ThreadPool.SetMinThreads(mint, MaxPossibleThreadCount + 1)); Assert.False(ThreadPool.SetMinThreads(-1, mint)); Assert.False(ThreadPool.SetMinThreads(mint, -1)); Assert.False(ThreadPool.SetMaxThreads(mint - 1, maxt)); Assert.False(ThreadPool.SetMaxThreads(maxt, mint - 1)); VerifyMinThreads(mint, mint); VerifyMaxThreads(maxt, maxt); Assert.True(ThreadPool.SetMaxThreads(MaxPossibleThreadCount, MaxPossibleThreadCount)); VerifyMaxThreads(MaxPossibleThreadCount, MaxPossibleThreadCount); Assert.True(ThreadPool.SetMaxThreads(MaxPossibleThreadCount + 1, MaxPossibleThreadCount + 1)); VerifyMaxThreads(MaxPossibleThreadCount, MaxPossibleThreadCount); Assert.True(ThreadPool.SetMaxThreads(-1, -1)); VerifyMaxThreads(MaxPossibleThreadCount, MaxPossibleThreadCount); Assert.True(ThreadPool.SetMinThreads(MaxPossibleThreadCount, MaxPossibleThreadCount)); VerifyMinThreads(MaxPossibleThreadCount, MaxPossibleThreadCount); Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount + 1, MaxPossibleThreadCount)); Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount, MaxPossibleThreadCount + 1)); Assert.False(ThreadPool.SetMinThreads(-1, MaxPossibleThreadCount)); Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount, -1)); VerifyMinThreads(MaxPossibleThreadCount, MaxPossibleThreadCount); Assert.True(ThreadPool.SetMinThreads(0, 0)); VerifyMinThreads(0, 0); Assert.True(ThreadPool.SetMaxThreads(1, 1)); VerifyMaxThreads(1, 1); Assert.True(ThreadPool.SetMinThreads(1, 1)); VerifyMinThreads(1, 1); } finally { resetThreadCounts(); } } [Fact] // Desktop framework doesn't check for this and instead, hits an assertion failure [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "ThreadPool.SetMinThreads and SetMaxThreads are not supported on UapAot.")] public static void SetMinMaxThreadsTest_ChangedInDotNetCore() { int minw, minc, maxw, maxc; ThreadPool.GetMinThreads(out minw, out minc); ThreadPool.GetMaxThreads(out maxw, out maxc); Action resetThreadCounts = () => { Assert.True(ThreadPool.SetMaxThreads(maxw, maxc)); VerifyMaxThreads(maxw, maxc); Assert.True(ThreadPool.SetMinThreads(minw, minc)); VerifyMinThreads(minw, minc); }; try { Assert.True(ThreadPool.SetMinThreads(0, 0)); VerifyMinThreads(0, 0); Assert.False(ThreadPool.SetMaxThreads(0, 0)); VerifyMaxThreads(maxw, maxc); } finally { resetThreadCounts(); } } private static void VerifyMinThreads(int expectedMinw, int expectedMinc) { int minw, minc; ThreadPool.GetMinThreads(out minw, out minc); Assert.Equal(expectedMinw, minw); Assert.Equal(expectedMinc, minc); } private static void VerifyMaxThreads(int expectedMaxw, int expectedMaxc) { int maxw, maxc; ThreadPool.GetMaxThreads(out maxw, out maxc); Assert.Equal(expectedMaxw, maxw); Assert.Equal(expectedMaxc, maxc); } [Fact] public static void QueueRegisterPositiveAndFlowTest() { var asyncLocal = new AsyncLocal<int>(); asyncLocal.Value = 1; var obj = new object(); var registerWaitEvent = new AutoResetEvent(false); var threadDone = new AutoResetEvent(false); RegisteredWaitHandle registeredWaitHandle = null; Exception backgroundEx = null; int backgroundAsyncLocalValue = 0; Action<bool, Action> commonBackgroundTest = (isRegisteredWaitCallback, test) => { try { if (isRegisteredWaitCallback) { RegisteredWaitHandle toUnregister = registeredWaitHandle; registeredWaitHandle = null; Assert.True(toUnregister.Unregister(threadDone)); } test(); backgroundAsyncLocalValue = asyncLocal.Value; } catch (Exception ex) { backgroundEx = ex; } finally { if (!isRegisteredWaitCallback) { threadDone.Set(); } } }; Action<bool> waitForBackgroundWork = isWaitForRegisteredWaitCallback => { if (isWaitForRegisteredWaitCallback) { registerWaitEvent.Set(); } threadDone.CheckedWait(); if (backgroundEx != null) { throw new AggregateException(backgroundEx); } }; ThreadPool.QueueUserWorkItem( state => { commonBackgroundTest(false, () => { Assert.Same(obj, state); }); }, obj); waitForBackgroundWork(false); Assert.Equal(1, backgroundAsyncLocalValue); ThreadPool.UnsafeQueueUserWorkItem( state => { commonBackgroundTest(false, () => { Assert.Same(obj, state); }); }, obj); waitForBackgroundWork(false); Assert.Equal(0, backgroundAsyncLocalValue); registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject( registerWaitEvent, (state, timedOut) => { commonBackgroundTest(true, () => { Assert.Same(obj, state); Assert.False(timedOut); }); }, obj, UnexpectedTimeoutMilliseconds, false); waitForBackgroundWork(true); Assert.Equal(1, backgroundAsyncLocalValue); registeredWaitHandle = ThreadPool.UnsafeRegisterWaitForSingleObject( registerWaitEvent, (state, timedOut) => { commonBackgroundTest(true, () => { Assert.Same(obj, state); Assert.False(timedOut); }); }, obj, UnexpectedTimeoutMilliseconds, false); waitForBackgroundWork(true); Assert.Equal(0, backgroundAsyncLocalValue); } [Fact] public static void QueueRegisterNegativeTest() { Assert.Throws<ArgumentNullException>(() => ThreadPool.QueueUserWorkItem(null)); Assert.Throws<ArgumentNullException>(() => ThreadPool.UnsafeQueueUserWorkItem(null, null)); WaitHandle waitHandle = new ManualResetEvent(true); WaitOrTimerCallback callback = (state, timedOut) => { }; Assert.Throws<ArgumentNullException>(() => ThreadPool.RegisterWaitForSingleObject(null, callback, null, 0, true)); Assert.Throws<ArgumentNullException>(() => ThreadPool.RegisterWaitForSingleObject(waitHandle, null, null, 0, true)); Assert.Throws<ArgumentOutOfRangeException>(() => ThreadPool.RegisterWaitForSingleObject(waitHandle, callback, null, -2, true)); Assert.Throws<ArgumentOutOfRangeException>(() => ThreadPool.RegisterWaitForSingleObject(waitHandle, callback, null, (long)-2, true)); Assert.Throws<ArgumentOutOfRangeException>(() => ThreadPool.RegisterWaitForSingleObject(waitHandle, callback, null, TimeSpan.FromMilliseconds(-2), true)); Assert.Throws<ArgumentOutOfRangeException>(() => ThreadPool.RegisterWaitForSingleObject( waitHandle, callback, null, TimeSpan.FromMilliseconds((double)int.MaxValue + 1), true)); } } }
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 WooAuth.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
/* * Copyright (c) 2006, Brendan Grant (grantb@dahat.com) * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * All original and modified versions of this source code must include the * above copyright notice, this list of conditions and the following * disclaimer. * * This code may not be used with or within any modules or code that is * licensed in any way that that compels or requires users or modifiers * to release their source code or changes as a requirement for * the use, modification or distribution of binary, object or source code * based on the licensed source code. (ex: Cannot be used with GPL code.) * * The name of Brendan Grant may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY BRENDAN GRANT ``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 BRENDAN GRANT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using Microsoft.Win32; namespace BrendanGrant.Helpers.FileAssociation { /// <summary> /// Specifies values that control some aspects of the Shell's handling of the file types linked to a ProgID. /// </summary> [Flags] public enum EditFlags : uint { /// <summary> /// No flags exist /// </summary> None = 0x0000000, /// <summary> /// Exclude the file class. /// </summary> Exclude = 0x00000001, /// <summary> /// Show file classes, such as folders, that aren't associated with a file name extension. /// </summary> Show = 0x00000002, /// <summary> /// The file class has a file name extension. /// </summary> HasExtension = 0x00000004, /// <summary> /// The registry entries associated with this file class cannot be edited. New entries cannot be added and existing entries cannot be modified or deleted. /// </summary> NoEdit = 0x00000008, /// <summary> /// The registry entries associated with this file class cannot be deleted. /// </summary> NoRemove = 0x00000010, /// <summary> /// No new verbs can be added to the file class. /// </summary> NoNewVerb = 0x00000020, /// <summary> /// Canonical verbs such as open and print cannot be modified or deleted. /// </summary> NoEditVerb = 0x00000040, /// <summary> /// Canonical verbs such as open and print cannot be deleted. /// </summary> NoRemoveVerb = 0x00000080, /// <summary> /// The description of the file class cannot be modified or deleted. /// </summary> NoEditDesc = 0x00000100, /// <summary> /// The icon assigned to the file class cannot be modified or deleted. /// </summary> NoEditIcon = 0x00000200, /// <summary> /// The default verb cannot be modified. /// </summary> NoEditDflt = 0x00000400, /// <summary> /// The commands associated with verbs cannot be modified. /// </summary> NoEditVerbCmd = 0x00000800, /// <summary> /// Verbs cannot be modified or deleted. /// </summary> NoEditVerbExe = 0x00001000, /// <summary> /// The Dynamic Data Exchange (DDE)-related entries cannot be modified or deleted. /// </summary> NoDDE = 0x00002000, /// <summary> /// The content-type and default-extension entries cannot be modified or deleted. /// </summary> NoEditMIME = 0x00008000, /// <summary> /// The file class's open verb can be safely invoked for downloaded files. Note that this flag may create a security risk, because downloaded files could contain malicious content. To reduce this risk, consider methods to scan downloaded files before opening. /// </summary> OpenIsSafe = 0x00010000, /// <summary> /// Do not allow the Never ask me check box to be enabled. The user can override this attribute through the File Type dialog box. This flag also affects ShellExecute, download dialogs, and any application making use of the AssocIsDangerous function. /// </summary> AlwaysUnsafe = 0x00020000, /// <summary> /// Always show the file class's file name extension, even if the user has selected the Hide Extensions option. /// </summary> AlwaysShowExtension = 0x00040000, /// <summary> /// Don't add members of this file class to the Recent Documents folder. /// </summary> NoRecentDocuments = 0x00100000 } /// <summary> /// Provides instance of ProgramaticID that can be referenced by multiple different extensions. /// </summary> public class ProgramAssociationInfo { private RegistryWrapper registryWrapper = new RegistryWrapper(); /// <summary> /// Actual name of Programmatic Identifier /// </summary> protected string progId; /// <summary> /// Gets or sets a value that determines if the file's extension will always be displayed. /// </summary> public bool AlwaysShowExtension { get { return GetAlwaysShowExt(); } set { SetAlwaysShowExt(value); } } /// <summary> /// Gets or sets a value that determines what the friendly name of the file is. /// </summary> public string Description { get { return GetDescription(); } set { SetDescription(value); } } /// <summary> /// Gets or sets a value that determines numerous shell options for extension as well as limitations on how extension properties can be edited by programs that honor <see cref="EditFlags"/> /// </summary> public EditFlags EditFlags { get { return GetEditFlags(); } set { SetEditFlags(value); } } /// <summary> /// Gets or sets a value that determines the default icon for the file type. /// </summary> public ProgramIcon DefaultIcon { get { return GetDefaultIcon(); } set { SetDefaultIcon(value); } } /// <summary> /// Gets or sets an array of <see cref="ProgramVerb"/> that define the verbs supported by this ProgID /// </summary> public ProgramVerb[] Verbs { get { return GetVerbs(); } set { SetVerbs(value); } } /// <summary> /// Gets a value that is the name of the Programatic Identifier /// </summary> public string ProgID { get { return progId; } } /// <summary> /// Gets a value that determines of a registry key exists with this Programatic Identifier /// </summary> public bool Exists { get { RegistryKey root = RegistryWrapper.ClassesRoot; try { if (this.progId == string.Empty) return false; RegistryKey key = root.OpenSubKey(this.progId); if (key == null) return false; } catch (Exception ex) { Console.WriteLine(ex.ToString()); return false; } return true; } } #region Public Functions - Creators /// <summary> /// Creates program id within registry. /// </summary> public void Create() { if (this.Exists) return; RegistryKey root = RegistryWrapper.ClassesRoot; root.CreateSubKey(this.progId); } /// <summary> /// Creates actual Programmatic Identifier key in registry that is used by other extensions. /// </summary> /// <param name="verb">Single <see cref="ProgramVerb"/> that contains supported verb.</param> /// <returns><see cref="ProgramAssociationInfo"/> instance referring to specified extension.</returns> public ProgramAssociationInfo Create(ProgramVerb verb) { return Create(string.Empty, EditFlags.None, new ProgramVerb[] { verb }); } /// <summary> /// Creates actual Programmatic Identifier key in registry that is used by other extensions. /// </summary> /// <param name="verbs">Array of <see cref="ProgramVerb"/> that contains supported verbs.</param> /// <returns><see cref="ProgramAssociationInfo"/> instance referring to specified extension.</returns> public ProgramAssociationInfo Create(ProgramVerb[] verbs) { return Create(string.Empty, EditFlags.None, verbs); } /// <summary> /// Creates actual Programmatic Identifier key in registry that is used by other extensions. /// </summary> /// <param name="description">Friendly description of file type.</param> /// <param name="verb">Single <see cref="ProgramVerb"/> that contains supported verbs.</param> /// <returns><see cref="ProgramAssociationInfo"/> instance referring to specified extension.</returns> public ProgramAssociationInfo Create(string description, ProgramVerb verb) { return Create(description, EditFlags.None, new ProgramVerb[] { verb }); } /// <summary> /// Creates actual Programmatic Identifier key in registry that is used by other extensions. /// </summary> /// <param name="description">Friendly description of file type.</param> /// <param name="verbs">Array of <see cref="ProgramVerb"/> that contains supported verbs.</param> /// <returns><see cref="ProgramAssociationInfo"/> instance referring to specified extension.</returns> public ProgramAssociationInfo Create(string description, ProgramVerb[] verbs) { return Create(description, EditFlags.None, verbs); } /// <summary> /// Creates actual Programmatic Identifier key in registry that is used by other extensions. /// </summary> /// <param name="description">Friendly description of file type.</param> /// <param name="editFlags"><see cref="EditFlags"/> for program file type.</param> /// <param name="verb">Single <see cref="ProgramVerb"/> that contains supported verbs.</param> /// <returns><see cref="ProgramAssociationInfo"/> instance referring to specified extension.</returns> public ProgramAssociationInfo Create(string description, EditFlags editFlags, ProgramVerb verb) { return Create(description, editFlags, new ProgramVerb[] { verb }); } /// <summary> /// Creates actual Programmatic Identifier key in registry that is used by other extensions. /// </summary> /// <param name="description">Friendly description of file type.</param> /// <param name="editFlags"><see cref="EditFlags"/> for program file type.</param> /// <param name="verbs">Array of <see cref="ProgramVerb"/> that contains supported verbs.</param> /// <returns><see cref="ProgramAssociationInfo"/> instance referring to specified extension.</returns> public ProgramAssociationInfo Create(string description, EditFlags editFlags, ProgramVerb[] verbs) { if (this.Exists) { this.Delete(); } this.Create(); if (description != string.Empty) this.Description = description; if (editFlags != EditFlags.None) this.EditFlags = editFlags; this.Verbs = verbs; return this; } #endregion #region Private Functions - Property backend /// <summary> /// Gets a value that determines if the file's extension will always be displayed. /// </summary> /// <returns>Value that specifies if the file's extension is always displayed.</returns> protected bool GetAlwaysShowExt() { if (!this.Exists) throw new Exception("Extension does not exist"); RegistryKey root = RegistryWrapper.ClassesRoot; RegistryKey key = root.OpenSubKey(this.progId); object o = key.GetValue("AlwaysShowExt", "ThisValueShouldNotExist"); if (o.ToString() == "ThisValueShouldNotExist") { return false; } return true; } /// <summary> /// Sets a value that determines if the file's extension will always be shown. /// </summary> /// <param name="value">Value that specifies if the file's extension should be always displayed.</param> protected void SetAlwaysShowExt(bool value) { if (!this.Exists) throw new Exception("Extension does not exist"); if (value) { registryWrapper.Write(this.progId, "AlwaysShowExt", string.Empty); } else { registryWrapper.Delete(this.progId, "AlwaysShowExt"); } ShellNotification.NotifyOfChange(); } /// <summary> /// Gets a value that determines what the friendly name of the file is. /// </summary> /// <returns>Friendly description of file type.</returns> protected string GetDescription() { if (!this.Exists) throw new Exception("Extension does not exist"); object val = registryWrapper.Read(this.progId, string.Empty); if (val == null) return string.Empty; return val.ToString(); } /// <summary> /// Sets a value that determines what the friendly name of the file is. /// </summary> /// <param name="description">Friendly description of file type.</param> protected void SetDescription(string description) { if (!this.Exists) throw new Exception("Extension does not exist"); registryWrapper.Write(this.progId, string.Empty, description); ShellNotification.NotifyOfChange(); } /// <summary> /// Gets a value that determines numerous shell options for extension as well as limitations on how extension properties can be edited by programs that honor <see cref="EditFlags"/> /// </summary> /// <returns><see cref="EditFlags"/> for program file type.</returns> protected EditFlags GetEditFlags() { if (!this.Exists) throw new Exception("Extension does not exist"); object val = registryWrapper.Read(this.progId, "EditFlags"); if (val == null) { return EditFlags.None; } if (val is byte[]) { int num; if (TryGetInt(val as byte[], out num)) { val = num; } else { return EditFlags.None; } } try { return (EditFlags)Convert.ToUInt32(val); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return EditFlags.None; } /// <summary> /// Sets a value that determines numerous shell options for extension as well as limitations on how extension properties can be edited by programs that honor <see cref="EditFlags"/> /// </summary> /// <param name="flags"><see cref="EditFlags"/> for program file type.</param> protected void SetEditFlags(EditFlags flags) { if (!this.Exists) throw new Exception("Extension does not exist"); //registryWrapper.Write(info.progId, "EditFlags", (uint)flags); registryWrapper.Write(this.progId, "EditFlags", flags); ShellNotification.NotifyOfChange(); } /// <summary> /// /// </summary> /// <returns></returns> protected ProgramIcon GetDefaultIcon() { if (!this.Exists) throw new Exception("Extension does not exist"); object val = registryWrapper.Read(this.progId + "\\DefaultIcon", ""); if (val == null) return ProgramIcon.None; return ProgramIcon.Parse(val.ToString()); } /// <summary> /// /// </summary> /// <param name="icon"></param> protected void SetDefaultIcon(ProgramIcon icon) { if (!this.Exists) throw new Exception("Extension does not exist"); if (icon != ProgramIcon.None) { registryWrapper.Write(this.progId, "DefaultIcon", icon.ToString()); ShellNotification.NotifyOfChange(); } } /// <summary> /// Gets an array of <see cref="ProgramVerb"/> that define the verbs supported by this ProgID. /// </summary> /// <returns>Array of <see cref="ProgramVerb"/> that contains supported verbs.</returns> protected ProgramVerb[] GetVerbs() { if (!this.Exists) throw new Exception("Extension does not exist"); RegistryKey root = RegistryWrapper.ClassesRoot; RegistryKey key = root.OpenSubKey(this.progId); List<ProgramVerb> verbs = new List<ProgramVerb>(); key = key.OpenSubKey("shell", false); if (key != null) { string[] keyNames = key.GetSubKeyNames(); foreach (string s in keyNames) { RegistryKey verb = key.OpenSubKey(s); if (verb == null) continue; verb = verb.OpenSubKey("command"); if (verb == null) continue; string command = (string)verb.GetValue("", "", RegistryValueOptions.DoNotExpandEnvironmentNames); verbs.Add(new ProgramVerb(s, command)); } key.Close(); } root.Close(); return verbs.ToArray(); } /// <summary> /// Sets an array of <see cref="ProgramVerb"/> that define the verbs supported by this ProgID /// </summary> /// <param name="verbs">Array of <see cref="ProgramVerb"/> that contains verbs to be set.</param> protected void SetVerbs(ProgramVerb[] verbs) { if (!this.Exists) throw new Exception("Extension does not exist"); RegistryKey root = RegistryWrapper.ClassesRoot; RegistryKey key = root.OpenSubKey(this.progId, true); RegistryKey tmpKey = key.OpenSubKey("shell", true); if (tmpKey != null) { key.DeleteSubKeyTree("shell"); } tmpKey = key.CreateSubKey("shell"); foreach (ProgramVerb verb in verbs) { RegistryKey newVerb = tmpKey.CreateSubKey(verb.Name.ToLower()); RegistryKey command = newVerb.CreateSubKey("command"); command.SetValue(string.Empty, verb.Command, RegistryValueKind.ExpandString); command.Close(); newVerb.Close(); } ShellNotification.NotifyOfChange(); } #endregion #region Add/Remove Single Verb /// <summary> /// Adds single <see cref="ProgramVerb"/> that define the verb supported by this ProgID. /// </summary> /// <param name="verb">Single <see cref="ProgramVerb"/> that contains supported verb.</param> protected void AddVerbInternal(ProgramVerb verb) { RegistryKey root = RegistryWrapper.ClassesRoot; RegistryKey key = root.OpenSubKey(this.progId).OpenSubKey("shell", true); if (key == null) { key = root.OpenSubKey(this.progId, true).CreateSubKey("shell"); } RegistryKey tmpkey = key.OpenSubKey(verb.Name, true); if (tmpkey == null) { tmpkey = key.CreateSubKey(verb.Name); } key = tmpkey; tmpkey = key.OpenSubKey("command", true); if (tmpkey == null) { tmpkey = key.CreateSubKey("command"); } tmpkey.SetValue(string.Empty, verb.Command, RegistryValueKind.ExpandString); tmpkey.Close(); key.Close(); root.Close(); ShellNotification.NotifyOfChange(); } /// <summary> /// Removes single <see cref="ProgramVerb"/> that define the verb supported by this ProgID. /// </summary> /// <param name="name">Name of verb to remove</param> protected void RemoveVerbInternal(string name) { RegistryKey root = RegistryWrapper.ClassesRoot; RegistryKey key = root.OpenSubKey(this.progId); key = key.OpenSubKey("shell", true); if (key == null) throw new RegistryException("Shell key not found"); string[] subkeynames = key.GetSubKeyNames(); foreach (string s in subkeynames) { if (s == name) { key.DeleteSubKeyTree(name); break; } } key.Close(); root.Close(); ShellNotification.NotifyOfChange(); } #endregion /// <summary> /// Deletes the current prog id. /// </summary> public void Delete() { if (!this.Exists) { throw new Exception("Key not found."); } RegistryKey root = RegistryWrapper.ClassesRoot; root.DeleteSubKeyTree(this.progId); } /// <summary> /// Adds single <see cref="ProgramVerb"/> that define the verb supported by this ProgID. /// </summary> /// <param name="verb">Single <see cref="ProgramVerb"/> that contains supported verb.</param> public void AddVerb(ProgramVerb verb) { AddVerbInternal(verb); } /// <summary> /// Removes single <see cref="ProgramVerb"/> that define the verb supported by this ProgID. /// </summary> /// <param name="verb">Single <see cref="ProgramVerb"/> that contains supported verb.</param> public void RemoveVerb(ProgramVerb verb) { if (verb == null) throw new NullReferenceException(); RemoveVerb(verb.Name); } /// <summary> /// Removes single <see cref="ProgramVerb"/> that define the verb supported by this ProgID. /// </summary> /// <param name="name">Name of verb to remove.</param> public void RemoveVerb(string name) { RemoveVerbInternal(name); } /// <summary> /// Initializes a new instance of the <see cref="ProgramAssociationInfo"/> class, which acts as a wrapper for a Programmatic Identifier within the registry. /// </summary> /// <param name="progId">Name of program id to interface with.</param> public ProgramAssociationInfo(string progId) { this.progId = progId; } /// <summary> /// Attempts to convert the value within the input byte array into an integer. /// </summary> /// <param name="arr">Byte array containing number.</param> /// <param name="val">Converted integer if successful.</param> /// <returns>True on success, false on failure.</returns> bool TryGetInt(byte[] arr, out int val) { try { if (arr.Length == 0) { val = -1; return false; } else if (arr.Length == 1) { val = arr[0]; } else { val = BitConverter.ToInt32(arr, 0); } return true; } catch { } val = 0; return false; } } }
using System; using System.IO; using System.Net; using System.Threading; using NUnit.Framework; using ServiceStack.Common.Utils; using ServiceStack.Common.Web; using ServiceStack.Service; using ServiceStack.ServiceClient.Web; using ServiceStack.Text; using ServiceStack.WebHost.Endpoints.Tests.Support.Host; using ServiceStack.WebHost.Endpoints.Tests.Support.Services; namespace ServiceStack.WebHost.Endpoints.Tests { [TestFixture] public class FileUploadTests { public const string ListeningOn = "http://localhost:8082/"; ExampleAppHostHttpListener appHost; [TestFixtureSetUp] public void TextFixtureSetUp() { try { appHost = new ExampleAppHostHttpListener(); appHost.Init(); appHost.Start(ListeningOn); } catch (Exception ex) { throw ex; } } [Test] [Ignore("Helps debugging when you need to find out WTF is going on")] public void Run_for_30secs() { Thread.Sleep(30000); } [TestFixtureTearDown] public void TestFixtureTearDown() { if (appHost != null) appHost.Dispose(); appHost = null; } public void AssertResponse<T>(HttpWebResponse response, Action<T> customAssert) { var contentType = response.ContentType; AssertResponse(response, contentType); var contents = new StreamReader(response.GetResponseStream()).ReadToEnd(); var result = DeserializeResult<T>(response, contents, contentType); customAssert(result); } private static T DeserializeResult<T>(WebResponse response, string contents, string contentType) { T result; switch (contentType) { case ContentType.Xml: result = XmlSerializer.DeserializeFromString<T>(contents); break; case ContentType.Json: case ContentType.Json + ContentType.Utf8Suffix: result = JsonSerializer.DeserializeFromString<T>(contents); break; case ContentType.Jsv: result = TypeSerializer.DeserializeFromString<T>(contents); break; default: throw new NotSupportedException(response.ContentType); } return result; } public void AssertResponse(HttpWebResponse response, string contentType) { var statusCode = (int)response.StatusCode; Assert.That(statusCode, Is.LessThan(400)); Assert.That(response.ContentType.StartsWith(contentType)); } [Test] public void Can_POST_upload_file() { var uploadFile = new FileInfo("~/TestExistingDir/upload.html".MapProjectPath()); var webRequest = (HttpWebRequest)WebRequest.Create(ListeningOn + "/fileuploads"); webRequest.Accept = ContentType.Json; var webResponse = webRequest.UploadFile(uploadFile, MimeTypes.GetMimeType(uploadFile.Name)); AssertResponse<FileUploadResponse>((HttpWebResponse)webResponse, r => { var expectedContents = new StreamReader(uploadFile.OpenRead()).ReadToEnd(); Assert.That(r.FileName, Is.EqualTo(uploadFile.Name)); Assert.That(r.ContentLength, Is.EqualTo(uploadFile.Length)); Assert.That(r.ContentType, Is.EqualTo(MimeTypes.GetMimeType(uploadFile.Name))); Assert.That(r.Contents, Is.EqualTo(expectedContents)); }); } [Test] public void Can_POST_upload_file_using_ServiceClient() { IServiceClient client = new JsonServiceClient(ListeningOn); var uploadFile = new FileInfo("~/TestExistingDir/upload.html".MapProjectPath()); var response = client.PostFile<FileUploadResponse>( ListeningOn + "/fileuploads", uploadFile, MimeTypes.GetMimeType(uploadFile.Name)); var expectedContents = new StreamReader(uploadFile.OpenRead()).ReadToEnd(); Assert.That(response.FileName, Is.EqualTo(uploadFile.Name)); Assert.That(response.ContentLength, Is.EqualTo(uploadFile.Length)); Assert.That(response.ContentType, Is.EqualTo(MimeTypes.GetMimeType(uploadFile.Name))); Assert.That(response.Contents, Is.EqualTo(expectedContents)); } [Test] public void Can_POST_upload_file_using_ServiceClient_with_request() { IServiceClient client = new JsonServiceClient(ListeningOn); var uploadFile = new FileInfo("~/TestExistingDir/upload.html".MapProjectPath()); var request = new FileUpload{CustomerId = 123, CustomerName = "Foo"}; var response = client.PostFileWithRequest<FileUploadResponse>(ListeningOn + "/fileuploads", uploadFile, request); var expectedContents = new StreamReader(uploadFile.OpenRead()).ReadToEnd(); Assert.That(response.FileName, Is.EqualTo(uploadFile.Name)); Assert.That(response.ContentLength, Is.EqualTo(uploadFile.Length)); Assert.That(response.Contents, Is.EqualTo(expectedContents)); Assert.That(response.CustomerName, Is.EqualTo("Foo")); Assert.That(response.CustomerId, Is.EqualTo(123)); } [Test] public void Can_handle_error_on_POST_upload_file_using_ServiceClient() { IServiceClient client = new JsonServiceClient(ListeningOn); var uploadFile = new FileInfo("~/TestExistingDir/upload.html".MapProjectPath()); try { client.PostFile<FileUploadResponse>( ListeningOn + "/fileuploads/ThrowError", uploadFile, MimeTypes.GetMimeType(uploadFile.Name)); Assert.Fail("Upload Service should've thrown an error"); } catch (Exception ex) { var webEx = ex as WebServiceException; var response = (FileUploadResponse)webEx.ResponseDto; Assert.That(response.ResponseStatus.ErrorCode, Is.EqualTo(typeof(NotSupportedException).Name)); Assert.That(response.ResponseStatus.Message, Is.EqualTo("ThrowError")); } } [Test] public void Can_GET_upload_file() { var uploadedFile = new FileInfo("~/TestExistingDir/upload.html".MapProjectPath()); var webRequest = (HttpWebRequest)WebRequest.Create(ListeningOn + "/fileuploads/TestExistingDir/upload.html"); var expectedContents = new StreamReader(uploadedFile.OpenRead()).ReadToEnd(); var webResponse = webRequest.GetResponse(); var actualContents = new StreamReader(webResponse.GetResponseStream()).ReadToEnd(); Assert.That(webResponse.ContentType, Is.EqualTo(MimeTypes.GetMimeType(uploadedFile.Name))); Assert.That(actualContents, Is.EqualTo(expectedContents)); } [Test] public void Can_POST_upload_file_and_apply_filter_using_ServiceClient() { try { var client = new JsonServiceClient(ListeningOn); var uploadFile = new FileInfo("~/TestExistingDir/upload.html".MapProjectPath()); bool isFilterCalled = false; ServiceClientBase.HttpWebRequestFilter = request => { isFilterCalled = true; }; var response = client.PostFile<FileUploadResponse>( ListeningOn + "/fileuploads", uploadFile, MimeTypes.GetMimeType(uploadFile.Name)); var expectedContents = new StreamReader(uploadFile.OpenRead()).ReadToEnd(); Assert.That(isFilterCalled); Assert.That(response.FileName, Is.EqualTo(uploadFile.Name)); Assert.That(response.ContentLength, Is.EqualTo(uploadFile.Length)); Assert.That(response.ContentType, Is.EqualTo(MimeTypes.GetMimeType(uploadFile.Name))); Assert.That(response.Contents, Is.EqualTo(expectedContents)); } finally { ServiceClientBase.HttpWebRequestFilter = null; //reset this to not cause side-effects } } [Test] public void Can_POST_upload_stream_using_ServiceClient() { try { var client = new JsonServiceClient(ListeningOn); using (var fileStream = new FileInfo("~/TestExistingDir/upload.html".MapProjectPath()).OpenRead()) { var fileName = "upload.html"; bool isFilterCalled = false; ServiceClientBase.HttpWebRequestFilter = request => { isFilterCalled = true; }; var response = client.PostFile<FileUploadResponse>( ListeningOn + "/fileuploads", fileStream, fileName, MimeTypes.GetMimeType(fileName)); fileStream.Position = 0; var expectedContents = new StreamReader(fileStream).ReadToEnd(); Assert.That(isFilterCalled); Assert.That(response.FileName, Is.EqualTo(fileName)); Assert.That(response.ContentLength, Is.EqualTo(fileStream.Length)); Assert.That(response.ContentType, Is.EqualTo(MimeTypes.GetMimeType(fileName))); Assert.That(response.Contents, Is.EqualTo(expectedContents)); } } finally { ServiceClientBase.HttpWebRequestFilter = null; //reset this to not cause side-effects } } } }
using System; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Text; namespace MSDNMagazine.Shell { /// <summary> /// /// </summary> /// [Guid("FB2EC55F-FB7B-432a-A54E-EDB524B951A6")] public class ShellView : MSDNMagazine.Shell.HelperItems.IShellView { internal ShellFolder m_mc = null; internal Form m_form = null; public MSDNMagazine.Shell.HelperItems.IShellBrowser m_shell = null; internal MSDNMagazine.Shell.HelperItems.FOLDERSETTINGS m_folderSettings = new MSDNMagazine.Shell.HelperItems.FOLDERSETTINGS(); private IntPtr m_hhook = IntPtr.Zero; private MSDNMagazine.Shell.HelperItems.HookStuff.HookProc h = null; private bool m_fired = false; public ShellView( ShellFolder m ) { this.m_mc = m; this.h = new MSDNMagazine.Shell.HelperItems.HookStuff.HookProc( this.OnDialogMsg ); } void MSDNMagazine.Shell.HelperItems.IShellView.GetWindow( out IntPtr phwnd) { phwnd = this.m_form.Handle; } void MSDNMagazine.Shell.HelperItems.IShellView.ContextSensitiveHelp( bool fEnterMode) { } long MSDNMagazine.Shell.HelperItems.IShellView.TranslateAcceleratorA( IntPtr pmsg) { return 1; } void MSDNMagazine.Shell.HelperItems.IShellView.EnableModeless( bool fEnable) { } void MSDNMagazine.Shell.HelperItems.IShellView.UIActivate( uint uState) { if ( uState == 0 ) //destroy this.m_form.Close(); } void MSDNMagazine.Shell.HelperItems.IShellView.Refresh() { } private long OnDialogMsg( int nCode, uint wParam, int lParam ) { IntPtr p = new IntPtr(lParam); MSDNMagazine.Shell.HelperItems.CWPRETSTRUCT m = (MSDNMagazine.Shell.HelperItems.CWPRETSTRUCT) Marshal.PtrToStructure( p, typeof(MSDNMagazine.Shell.HelperItems.CWPRETSTRUCT) ); bool handled = false; if( m.message == 0x004E && handled == false ) //WM_NOTIFY { MSDNMagazine.Shell.HelperItems.NMHDR n = (MSDNMagazine.Shell.HelperItems.NMHDR) Marshal.PtrToStructure( new IntPtr(m.lParam), typeof(MSDNMagazine.Shell.HelperItems.NMHDR) ); if ( n.code == 0xFFFFFDA2 ) // the special common dialog notifier { handled = true; if ( this.m_mc.OnAction != null ) { if ( !m_fired ) { this.m_mc.OnAction( this.GetActionType() ); m_fired = true; } } } } if ( m.message == 0x00F3 && handled == false ) // BN_SETSTATE { if ( m.wParam != 0 ) { int id = MSDNMagazine.Shell.HelperItems.HookStuff.GetDlgCtrlID( m.hwnd ); if ( id == 1 ) { handled = true; if ( this.m_mc.OnAction != null ) { if ( !m_fired ) { this.m_mc.OnAction( this.GetActionType() ); m_fired = true; } } } } } uint specialCode = MSDNMagazine.Shell.HelperItems.HookStuff.RegisterWindowMessage("WM_OBJECTSEL"); if ( m.message == specialCode && m.lParam == 0x25 && handled == false ) //WM_OBJECTSEL { handled = true; if ( this.m_mc.OnAction != null ) { this.m_mc.OnAction( this.GetActionType() ); m_fired = true; } } return MSDNMagazine.Shell.HelperItems.HookStuff.CallNextHookEx( this.m_hhook, nCode, wParam, lParam ); } private ShellActionType GetActionType() { string text = this.m_mc.ParentWindowText; if ( text.ToLower().IndexOf("open") != -1 ) return ShellActionType.Open; if ( text.ToLower().IndexOf("save") != -1 ) return ShellActionType.Save; return ShellActionType.Unknown; } void MSDNMagazine.Shell.HelperItems.IShellView.CreateViewWindow( IntPtr psvPrevious, ref MSDNMagazine.Shell.HelperItems.FOLDERSETTINGS pfs, MSDNMagazine.Shell.HelperItems.IShellBrowser psb, ref MSDNMagazine.Shell.HelperItems.RECT prcView, ref IntPtr phWnd) { this.m_folderSettings.ViewMode = pfs.ViewMode; this.m_folderSettings.fFlags = pfs.fFlags; this.m_form = this.m_mc.m_form; IntPtr hwnd = IntPtr.Zero; this.m_shell = psb; this.m_shell.GetWindow(out hwnd); ShellFolder.SetParent(m_form.Handle, hwnd); phWnd = m_form.Handle; int w = prcView.right - prcView.left; int h = prcView.bottom - prcView.top; ShellFolder.SetWindowLong( m_form.Handle, -16, 0x40000000 ); ShellFolder.SetWindowPos( m_form.Handle, 0, 0, 0, w, h, 0x0017 ); m_form.Location = new System.Drawing.Point(prcView.left, prcView.top); m_form.Size = new System.Drawing.Size(prcView.right - prcView.left, prcView.bottom - prcView.top); m_form.Show(); MSDNMagazine.Shell.HelperItems.HookStuff.SetFocus( hwnd ); // CWPRETSTRUCT this.m_hhook = MSDNMagazine.Shell.HelperItems.HookStuff.SetWindowsHookEx( 12, this.h, IntPtr.Zero, MSDNMagazine.Shell.HelperItems.HookStuff.GetCurrentThreadId() ); } void MSDNMagazine.Shell.HelperItems.IShellView.DestroyViewWindow() { this.m_form.Close(); bool b = MSDNMagazine.Shell.HelperItems.HookStuff.UnhookWindowsHookEx(this.m_hhook); } void MSDNMagazine.Shell.HelperItems.IShellView.GetCurrentInfo( ref MSDNMagazine.Shell.HelperItems.FOLDERSETTINGS pfs) { pfs = this.m_folderSettings; } void MSDNMagazine.Shell.HelperItems.IShellView.AddPropertySheetPages( long dwReserved, ref IntPtr pfnPtr, int lparam) { pfnPtr = IntPtr.Zero; } void MSDNMagazine.Shell.HelperItems.IShellView.SaveViewState() { } void MSDNMagazine.Shell.HelperItems.IShellView.SelectItem( IntPtr pidlItem, uint uFlags) { } long MSDNMagazine.Shell.HelperItems.IShellView.GetItemObject( uint uItem, ref Guid riid, ref IntPtr ppv) { ppv = IntPtr.Zero; if ( riid == typeof(MMC.IDataObject).GUID && (uItem == 1 || uItem == 2) ) { if ( uItem == 1 ) this.m_mc.m_mdo = new MMC.MyDataObject(255, this.m_mc.m_pidlData); if ( uItem == 2 ) this.m_mc.m_mdo = new MMC.MyDataObject(0, this.m_mc.m_pidlData); ppv = Marshal.GetComInterfaceForObject( this.m_mc.m_mdo, typeof(MMC.IDataObject) ); return 0; } Marshal.QueryInterface( Marshal.GetIUnknownForObject(this), ref riid, out ppv ); if ( ppv.ToInt32() == 0 ) Marshal.QueryInterface( Marshal.GetIUnknownForObject(this.m_mc), ref riid, out ppv ); if ( ppv.ToInt32() == 0 ) return 0x80004002L; return 0; } } }
using System; using System.IO; using System.Net; using System.Xml; using System.Reflection; using System.Windows.Forms; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using SharpVectors.Xml; using SharpVectors.Dom; using SharpVectors.Dom.Css; using SharpVectors.Dom.Svg; using SharpVectors.Dom.Events; namespace SharpVectors.Renderers.Gdi { /// <summary> /// Renders a Svg image to GDI+ /// </summary> public sealed class GdiGraphicsRenderer : ISvgRenderer, IDisposable { #region Private Fields /// <summary> /// A counter that tracks the next hit color. /// </summary> private int counter; /// <summary> /// Maps a 'hit color' to a graphics node. /// </summary> /// <remarks> /// The 'hit color' is an integer identifier that identifies the /// graphics node that drew it. When 'hit colors' are drawn onto /// a bitmap (ie. <see cref="idMapRaster">idMapRaster</see> the 'hit color' /// of each pixel with the help of <see cref="graphicsNodes" /// >graphicsNodes</see> can identify for a given x, y coordinate the /// relevant graphics node a mouse event should be dispatched to. /// </remarks> private Dictionary<Color, SvgElement> graphicsNodes = new Dictionary<Color, SvgElement>(); /// <summary> /// The bitmap containing the rendered Svg image. /// </summary> private Bitmap rasterImage; /// <summary> /// A secondary back-buffer used for invalidation repaints. The invalidRect will /// be bitblt to the rasterImage front buffer /// </summary> private Bitmap invalidatedRasterImage; /// <summary> /// A bitmap image that consists of 'hit color' instead of visual /// color. A 'hit color' is an integer identifier that identifies /// the graphics node that drew it. A 'hit color' can therefore /// identify the graphics node that corresponds an x-y coordinates. /// </summary> private Bitmap idMapRaster; /// <summary> /// The renderer's <see cref="GraphicsWrapper">GraphicsWrapper</see> /// object. /// </summary> private GdiGraphicsWrapper graphics; /// <summary> /// The renderer's back color. /// </summary> private Color backColor; /// <summary> /// The renderer's <see cref="SvgWindow">SvgWindow</see> object. /// </summary> private ISvgWindow window; /// <summary> /// /// </summary> private float currentDownX; private float currentDownY; private IEventTarget currentTarget; private IEventTarget currentDownTarget; private GdiRenderingHelper _svgRenderer; private SvgRectF invalidRect = SvgRectF.Empty; #endregion #region Constructors and Destructor /// <summary> /// Initializes a new instance of the GdiRenderer class. /// </summary> public GdiGraphicsRenderer() { counter = 0; _svgRenderer = new GdiRenderingHelper(this); backColor = Color.White; } ~GdiGraphicsRenderer() { this.Dispose(false); } #endregion #region Public Properties /// <summary> /// Gets a bitmap image of the a rendered Svg document. /// </summary> public Bitmap RasterImage { get { return rasterImage; } } /// <summary> /// Gets the image map of the rendered Svg document. This /// is a picture of how the renderer will map the (x,y) positions /// of mouse events to objects. You can display this raster /// to help in debugging of hit testing. /// </summary> public Bitmap IdMapRaster { get { return idMapRaster; } } /// <summary> /// Gets or sets the <see cref="Window">Window</see> of the /// renderer. /// </summary> /// <value> /// The <see cref="Window">Window</see> of the renderer. /// </value> public ISvgWindow Window { get { return window; } set { window = value; } } /// <summary> /// Gets or sets the back color of the renderer. /// </summary> /// <value> /// The back color of the renderer. /// </value> public Color BackColor { get { return backColor; } set { backColor = value; } } /// <summary> /// Gets or sets the <see cref="GraphicsWrapper">GraphicsWrapper</see> /// object associated with this renderer. /// </summary> /// <value> /// The <see cref="GraphicsWrapper">GraphicsWrapper</see> object /// associated with this renderer. /// </value> public GdiGraphicsWrapper GraphicsWrapper { get { return graphics; } set { graphics = value; } } /// <summary> /// Gets or sets the <see cref="Graphics">Graphics</see> object /// associated with this renderer. /// </summary> /// <value> /// The <see cref="Graphics">Graphics</see> object associated /// with this renderer. /// </value> public Graphics Graphics { get { return graphics.Graphics; } set { graphics.Graphics = value; } } #endregion #region Public Methods public void InvalidateRect(SvgRectF rect) { if (invalidRect == SvgRectF.Empty) invalidRect = rect; else invalidRect.Intersect(rect); } /// <summary> /// Renders the <see cref="SvgElement">SvgElement</see>. /// </summary> /// <param name="node"> /// The <see cref="SvgElement">SvgElement</see> node to be /// rendered /// </param> /// <returns> /// The bitmap on which the rendering was performed. /// </returns> public void Render(ISvgElement node) { SvgRectF updatedRect; if (invalidRect != SvgRectF.Empty) updatedRect = new SvgRectF(invalidRect.X, invalidRect.Y, invalidRect.Width, invalidRect.Height); else updatedRect = SvgRectF.Empty; RendererBeforeRender(); if (graphics != null && graphics.Graphics != null) { _svgRenderer.Render(node); } RendererAfterRender(); if (onRender != null) OnRender(updatedRect); } /// <summary> /// Renders the <see cref="SvgDocument">SvgDocument</see>. /// </summary> /// <param name="node"> /// The <see cref="SvgDocument">SvgDocument</see> node to be /// rendered /// </param> /// <returns> /// The bitmap on which the rendering was performed. /// </returns> public void Render(ISvgDocument node) { SvgRectF updatedRect; if (invalidRect != SvgRectF.Empty) updatedRect = new SvgRectF(invalidRect.X, invalidRect.Y, invalidRect.Width, invalidRect.Height); else updatedRect = SvgRectF.Empty; RendererBeforeRender(); if (graphics != null && graphics.Graphics != null) { _svgRenderer.Render(node); } RendererAfterRender(); if (onRender != null) OnRender(updatedRect); } public void RenderChildren(ISvgElement node) { _svgRenderer.RenderChildren(node); } public void ClearMap() { graphicsNodes.Clear(); } /// <summary> /// The invalidated region /// </summary> public SvgRectF InvalidRect { get { return invalidRect; } set { invalidRect = value; } } public ISvgRect GetRenderedBounds(ISvgElement element, float margin) { SvgTransformableElement transElement = element as SvgTransformableElement; if (transElement != null) { SvgRectF rect = this.GetElementBounds(transElement, margin); return new SvgRect(rect.X, rect.Y, rect.Width, rect.Height); } return null; } #endregion #region Event handlers private RenderEvent onRender; public RenderEvent OnRender { get { return onRender; } set { onRender = value; } } /// <summary> /// Processes mouse events. /// </summary> /// <param name="type"> /// A string describing the type of mouse event that occured. /// </param> /// <param name="e"> /// The <see cref="MouseEventArgs">MouseEventArgs</see> that contains /// the event data. /// </param> public void OnMouseEvent(string type, MouseEventArgs e) { if (idMapRaster != null) { try { Color pixel = idMapRaster.GetPixel(e.X, e.Y); SvgElement grElement = GetElementFromColor(pixel); if (grElement != null) { IEventTarget target; if (grElement.ElementInstance != null) target = grElement.ElementInstance as IEventTarget; else target = grElement as IEventTarget; if (target != null) { switch (type) { case "mousemove": { if (currentTarget == target) { target.DispatchEvent(new MouseEvent( EventType.MouseMove, true, false, null, // todo: put view here 0, // todo: put detail here e.X, e.Y, e.X, e.Y, false, false, false, false, 0, null, false)); } else { if (currentTarget != null) { currentTarget.DispatchEvent(new MouseEvent( EventType.MouseOut, true, false, null, // todo: put view here 0, // todo: put detail here e.X, e.Y, e.X, e.Y, false, false, false, false, 0, null, false)); } target.DispatchEvent(new MouseEvent( EventType.MouseOver, true, false, null, // todo: put view here 0, // todo: put detail here e.X, e.Y, e.X, e.Y, false, false, false, false, 0, null, false)); } break; } case "mousedown": target.DispatchEvent(new MouseEvent( EventType.MouseDown, true, false, null, // todo: put view here 0, // todo: put detail here e.X, e.Y, e.X, e.Y, false, false, false, false, 0, null, false)); currentDownTarget = target; currentDownX = e.X; currentDownY = e.Y; break; case "mouseup": target.DispatchEvent(new MouseEvent( EventType.MouseUp, true, false, null, // todo: put view here 0, // todo: put detail here e.X, e.Y, e.X, e.Y, false, false, false, false, 0, null, false)); if (/*currentDownTarget == target &&*/ Math.Abs(currentDownX - e.X) < 5 && Math.Abs(currentDownY - e.Y) < 5) { target.DispatchEvent(new MouseEvent( EventType.Click, true, false, null, // todo: put view here 0, // todo: put detail here e.X, e.Y, e.X, e.Y, false, false, false, false, 0, null, false)); } currentDownTarget = null; currentDownX = 0; currentDownY = 0; break; } currentTarget = target; } else { // jr patch if (currentTarget != null && type == "mousemove") { currentTarget.DispatchEvent(new MouseEvent( EventType.MouseOut, true, false, null, // todo: put view here 0, // todo: put detail here e.X, e.Y, e.X, e.Y, false, false, false, false, 0, null, false)); } currentTarget = null; } } else { // jr patch if (currentTarget != null && type == "mousemove") { currentTarget.DispatchEvent(new MouseEvent( EventType.MouseOut, true, false, null, // todo: put view here 0, // todo: put detail here e.X, e.Y, e.X, e.Y, false, false, false, false, 0, null, false)); } currentTarget = null; } } catch { } } } #endregion #region Miscellaneous Methods /// <summary> /// Allocate a hit color for the specified graphics node. /// </summary> /// <param name="grNode"> /// The <see cref="GraphicsNode">GraphicsNode</see> object for which to /// allocate a new hit color. /// </param> /// <returns> /// The hit color for the <see cref="GraphicsNode">GraphicsNode</see> /// object. /// </returns> internal Color GetNextColor(SvgElement element) { // TODO: [newhoggy] It looks like there is a potential memory leak here. // We only ever add to the graphicsNodes map, never remove // from it, so it will grow every time this function is called. // The counter is used to generate IDs in the range [0,2^24-1] // The 24 bits of the counter are interpreted as follows: // [red 7 bits | green 7 bits | blue 7 bits |shuffle term 3 bits] // The shuffle term is used to define how the remaining high // bit is set on each color. The colors are generated in the // range [0,127] (7 bits) instead of [0,255]. Then the shuffle term // is used to adjust them into the range [0,255]. // This algorithm has the feature that consecutive ids generate // visually distinct colors. int id = counter++; // Zero should be the first color. int shuffleTerm = id & 7; int r = 0x7f & (id >> 17); int g = 0x7f & (id >> 10); int b = 0x7f & (id >> 3); switch (shuffleTerm) { case 0: break; case 1: b |= 0x80; break; case 2: g |= 0x80; break; case 3: g |= 0x80; b |= 0x80; break; case 4: r |= 0x80; break; case 5: r |= 0x80; b |= 0x80; break; case 6: r |= 0x80; g |= 0x80; break; case 7: r |= 0x80; g |= 0x80; b |= 0x80; break; } Color color = Color.FromArgb(r, g, b); graphicsNodes.Add(color, element); return color; } internal void RemoveColor(Color color, SvgElement element) { if (!color.IsEmpty) { graphicsNodes[color] = null; graphicsNodes.Remove(color); } } /// <summary> /// Gets the <see cref="GraphicsNode">GraphicsNode</see> object that /// corresponds to the given hit color. /// </summary> /// <param name="color"> /// The hit color for which to get the corresponding /// <see cref="GraphicsNode">GraphicsNode</see> object. /// </param> /// <remarks> /// Returns <c>null</c> if a corresponding /// <see cref="GraphicsNode">GraphicsNode</see> object cannot be /// found for the given hit color. /// </remarks> /// <returns> /// The <see cref="GraphicsNode">GraphicsNode</see> object that /// corresponds to the given hit color /// </returns> private SvgElement GetElementFromColor(Color color) { if (color.A == 0) { return null; } else { if (graphicsNodes.ContainsKey(color)) { return graphicsNodes[color]; } return null; } } /// <summary> /// TODO: This method is not used. /// </summary> /// <param name="color"> /// </param> /// <returns> /// </returns> private static int ColorToId(Color color) { int r = color.R; int g = color.G; int b = color.B; int shuffleTerm = 0; if (0 != (r & 0x80)) { shuffleTerm |= 4; r &= 0x7f; } if (0 != (g & 0x80)) { shuffleTerm |= 2; g &= 0x7f; } if (0 != (b & 0x80)) { shuffleTerm |= 1; b &= 0x7f; } return (r << 17) + (g << 10) + (b << 3) + shuffleTerm; } private SvgRectF GetElementBounds(SvgTransformableElement element, float margin) { SvgRenderingHint hint = element.RenderingHint; if (hint == SvgRenderingHint.Shape || hint == SvgRenderingHint.Text) { GraphicsPath gp = GdiRendering.CreatePath(element); ISvgMatrix svgMatrix = element.GetScreenCTM(); Matrix matrix = new Matrix((float)svgMatrix.A, (float)svgMatrix.B, (float)svgMatrix.C, (float)svgMatrix.D, (float)svgMatrix.E, (float)svgMatrix.F); SvgRectF bounds = SvgConverter.ToRect(gp.GetBounds(matrix)); bounds = SvgRectF.Inflate(bounds, margin, margin); return bounds; } SvgUseElement useElement = element as SvgUseElement; if (useElement != null) { SvgTransformableElement refEl = useElement.ReferencedElement as SvgTransformableElement; if (refEl == null) return SvgRectF.Empty; XmlElement refElParent = (XmlElement)refEl.ParentNode; element.OwnerDocument.Static = true; useElement.CopyToReferencedElement(refEl); element.AppendChild(refEl); SvgRectF bbox = this.GetElementBounds(refEl, margin); element.RemoveChild(refEl); useElement.RestoreReferencedElement(refEl); refElParent.AppendChild(refEl); element.OwnerDocument.Static = false; return bbox; } SvgRectF union = SvgRectF.Empty; SvgTransformableElement transformChild; foreach (XmlNode childNode in element.ChildNodes) { if (childNode is SvgDefsElement) continue; if (childNode is ISvgTransformable) { transformChild = (SvgTransformableElement)childNode; SvgRectF bbox = this.GetElementBounds(transformChild, margin); if (bbox != SvgRectF.Empty) { if (union == SvgRectF.Empty) union = bbox; else union = SvgRectF.Union(union, bbox); } } } return union; } #endregion #region Private Methods /// <summary> /// BeforeRender - Make sure we have a Graphics object to render to. /// If we don't have one, then create one to match the SvgWindow's /// physical dimensions. /// </summary> private void RendererBeforeRender() { // Testing for null here allows "advanced" developers to create their own Graphics object for rendering if (graphics == null) { // Get the current SVGWindow's width and height int innerWidth = (int)window.InnerWidth; int innerHeight = (int)window.InnerHeight; // Make sure we have an actual area to render to if (innerWidth > 0 && innerHeight > 0) { // See if we already have a rasterImage that matches the current SVGWindow dimensions if (rasterImage == null || rasterImage.Width != innerWidth || rasterImage.Height != innerHeight) { // Nope, so create one if (rasterImage != null) { rasterImage.Dispose(); rasterImage = null; } rasterImage = new Bitmap(innerWidth, innerHeight); } // Maybe we are only repainting an invalidated section if (invalidRect != SvgRectF.Empty) { // TODO: Worry about pan... if (invalidRect.X < 0) invalidRect.X = 0; if (invalidRect.Y < 0) invalidRect.Y = 0; if (invalidRect.Right > innerWidth) invalidRect.Width = innerWidth - invalidRect.X; if (invalidRect.Bottom > innerHeight) invalidRect.Height = innerHeight - invalidRect.Y; if (invalidatedRasterImage == null || invalidatedRasterImage.Width < invalidRect.Right || invalidatedRasterImage.Height < invalidRect.Bottom) { // Nope, so create one if (invalidatedRasterImage != null) { invalidatedRasterImage.Dispose(); invalidatedRasterImage = null; } invalidatedRasterImage = new Bitmap((int)invalidRect.Right, (int)invalidRect.Bottom); } // Make a GraphicsWrapper object from the regionRasterImage and clear it to the background color graphics = GdiGraphicsWrapper.FromImage(invalidatedRasterImage, false); graphics.Clear(backColor); } else { // Make a GraphicsWrapper object from the rasterImage and clear it to the background color graphics = GdiGraphicsWrapper.FromImage(rasterImage, false); graphics.Clear(backColor); } } } } /// <summary> /// AfterRender - Dispose of Graphics object created for rendering. /// </summary> private void RendererAfterRender() { if (graphics != null) { // Check if we only invalidated a rect if (invalidRect != SvgRectF.Empty) { // We actually drew everything on invalidatedRasterImage and now we // need to copy that to rasterImage Graphics tempGraphics = Graphics.FromImage(rasterImage); tempGraphics.DrawImage(invalidatedRasterImage, invalidRect.X, invalidRect.Y, GdiConverter.ToRectangle(invalidRect), GraphicsUnit.Pixel); tempGraphics.Dispose(); tempGraphics = null; // If we currently have an idMapRaster here, then we need to create // a temporary graphics object to draw the invalidated portion from // our main graphics window onto it. if (idMapRaster != null) { tempGraphics = Graphics.FromImage(idMapRaster); tempGraphics.DrawImage(graphics.IdMapRaster, invalidRect.X, invalidRect.Y, GdiConverter.ToRectangle(invalidRect), GraphicsUnit.Pixel); tempGraphics.Dispose(); tempGraphics = null; } else { idMapRaster = graphics.IdMapRaster; } // We have updated the invalid region invalidRect = SvgRectF.Empty; } else { if (idMapRaster != null && idMapRaster != graphics.IdMapRaster) idMapRaster.Dispose(); idMapRaster = graphics.IdMapRaster; } graphics.Dispose(); graphics = null; } } #endregion #region IDisposable Members public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (idMapRaster != null) idMapRaster.Dispose(); if (invalidatedRasterImage != null) invalidatedRasterImage.Dispose(); if (rasterImage != null) rasterImage.Dispose(); if (graphics != null) graphics.Dispose(); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Microsoft.Research.AbstractDomains.Expressions; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; namespace Microsoft.Research.AbstractDomains { /// <summary> /// NormalizedExpressions are mathematical expressions to be used as array limits. /// They have a limited form *on purpose* /// /// NormalizedExpression ::= Constant | Var | Var + Constant /// </summary> [ContractVerification(true)] [ContractClass(typeof(NormalizedExpressionContracts<>))] abstract public class NormalizedExpression<Variable> { abstract public bool IsConstant(out int value); abstract public bool IsVariable(out Variable var); abstract public bool IsAddition(out Variable var, out int value); abstract public NormalizedExpression<Variable> PlusOne(); abstract public NormalizedExpression<Variable> MinusOne(); abstract public Expression Convert<Expression>(IExpressionEncoder<Variable, Expression> encoder); virtual public bool TryPrettyPrint<T>(IFactory<T> factory, out T result) { Contract.Requires(factory != null); result = default(T); return false; } [Pure] static public NormalizedExpression<Variable> For(int value) { Contract.Ensures(Contract.Result<NormalizedExpression<Variable>>() != null); return new ConstantExpression(value); } [Pure] static public NormalizedExpression<Variable> For(Variable var) { Contract.Ensures(Contract.Result<NormalizedExpression<Variable>>() != null); return new VariableExpression(var); } [Pure] static public NormalizedExpression<Variable> For(Variable var, int value) { Contract.Ensures(Contract.Result<NormalizedExpression<Variable>>() != null); return value == 0 ? For(var) : new Addition(var, value); } [Pure] static public bool TryConvertFrom<Expression>( Expression exp, IExpressionDecoder<Variable, Expression> decoder, out NormalizedExpression<Variable> result) { Contract.Requires(exp != null); if (decoder == null) { result = default(NormalizedExpression<Variable>); return false; } var reader = new TryConvertRead<Expression>(decoder); return reader.TryConvert(exp, out result); } [Pure] static public bool TryConvertFrom<Expression>( Expression exp, ExpressionManagerWithEncoder<Variable, Expression> expManager, out NormalizedExpression<Variable> result) { Contract.Requires(exp != null); Contract.Requires(expManager != null); if (TryConvertFrom(exp, expManager.Decoder, out result)) { return true; } //if (expManager.Encoder != null) { Polynomial<Variable, Expression> normalized; if (Polynomial<Variable, Expression>.TryToPolynomialForm(exp, expManager.Decoder, out normalized)) { return TryConvertFrom(normalized.ToPureExpression(expManager.Encoder), expManager.Decoder, out result); } } result = default(NormalizedExpression<Variable>); return false; } internal class ConstantExpression : NormalizedExpression<Variable> { private readonly int value; public ConstantExpression(int value) { this.value = value; } public override bool IsAddition(out Variable var, out int value) { var = default(Variable); value = default(int); return false; } public override bool IsConstant(out int value) { value = this.value; return true; } public override bool IsVariable(out Variable var) { var = default(Variable); return false; } public override NormalizedExpression<Variable> PlusOne() { return new ConstantExpression(value + 1); } public override NormalizedExpression<Variable> MinusOne() { return new ConstantExpression(value - 1); } override public bool TryPrettyPrint<T>(IFactory<T> factory, out T result) { result = factory.Constant(value); return true; } public override Expression Convert<Expression>(IExpressionEncoder<Variable, Expression> encoder) { return encoder.ConstantFor(value); } public override string ToString() { return value.ToString(); } public override int GetHashCode() { return value; } public override bool Equals(object obj) { var that = obj as ConstantExpression; if (that == null) return false; return value == that.value; } } internal class VariableExpression : NormalizedExpression<Variable> { private readonly Variable var; public VariableExpression(Variable var) { this.var = var; } public override bool IsAddition(out Variable var, out int value) { var = default(Variable); value = default(int); return false; } public override bool IsVariable(out Variable var) { var = this.var; return true; } public override bool IsConstant(out int value) { value = default(int); return false; } public override NormalizedExpression<Variable> PlusOne() { return new Addition(var, 1); } public override NormalizedExpression<Variable> MinusOne() { return new Addition(var, -1); } override public bool TryPrettyPrint<T>(IFactory<T> factory, out T result) { result = factory.Variable(var); return result != null; } public override Expression Convert<Expression>(IExpressionEncoder<Variable, Expression> encoder) { return encoder.VariableFor(var); } public override string ToString() { return var.ToString(); } public override int GetHashCode() { return var.GetHashCode(); } public override bool Equals(object obj) { var that = obj as VariableExpression; if (that == null) return false; return var.Equals(that.var); } } internal class Addition : NormalizedExpression<Variable> { private readonly Variable var; private readonly int value; public Addition(Variable var, int value) { this.var = var; this.value = value; } public override bool IsAddition(out Variable var, out int value) { var = this.var; value = this.value; return true; } public override bool IsConstant(out int value) { value = default(int); return false; } public override bool IsVariable(out Variable var) { var = default(Variable); return false; } public override NormalizedExpression<Variable> PlusOne() { return For(var, value + 1); } public override NormalizedExpression<Variable> MinusOne() { return For(var, value - 1); } override public bool TryPrettyPrint<T>(IFactory<T> factory, out T result) { result = factory.Add(factory.Variable(var), factory.Constant(value)); return true; } public override Expression Convert<Expression>(IExpressionEncoder<Variable, Expression> encoder) { return encoder.CompoundExpressionFor(ExpressionType.Int32, ExpressionOperator.Addition, encoder.VariableFor(var), encoder.ConstantFor(value)); } public override string ToString() { return string.Format("{0} {1} {2}", var.ToString(), value > 0 ? "+" : "", value.ToString()); } public override int GetHashCode() { return value + var.GetHashCode(); } public override bool Equals(object obj) { var that = obj as Addition; if (that == null) return false; return value == that.value && that.var.Equals(var); } } private class TryConvertRead<Expression> : GenericExpressionVisitor<Void, Boolean, Variable, Expression> { private NormalizedExpression<Variable> result; public TryConvertRead(IExpressionDecoder<Variable, Expression> decoder) : base(decoder) { Contract.Requires(decoder != null); result = default(NormalizedExpression<Variable>); } //[SuppressMessage("Microsoft.Contracts", "Ensures-22-42", Justification="Depends on overriding")] public sealed override bool Visit(Expression exp, Void data) { Contract.Ensures(!Contract.Result<bool>() || result != null); result = default(NormalizedExpression<Variable>); return base.Visit(exp, data); } public bool TryConvert(Expression exp, out NormalizedExpression<Variable> result) { Contract.Requires(exp != null); Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out result) != null); Contract.Ensures(this.result == Contract.ValueAtReturn(out result)); if (this.Visit(exp, Void.Value)) { Contract.Assert(this.result != null); result = this.result; return true; } this.result = result = default(NormalizedExpression<Variable>); return false; } public override bool VisitAddition(Expression left, Expression right, Expression original, Void data) { NormalizedExpression<Variable> leftNorm, rightNorm; if (this.TryConvert(left, out leftNorm)) { Contract.Assert(leftNorm != null); if (this.TryConvert(right, out rightNorm)) { Contract.Assert(rightNorm != null); // All the cases. We declare all the variables here, // so to leverage the definite assignment analysis of // the compiler to check we are doing everything right int leftConst, rightCont; Variable leftVar, rightVar; if (leftNorm.IsConstant(out leftConst)) { // K + K if (rightNorm.IsConstant(out rightCont)) { result = NormalizedExpression<Variable>.For(leftConst + rightCont); // Can overflow, we do not care has it may be the concrete semantics return true; } // K + V if (rightNorm.IsVariable(out rightVar)) { result = NormalizedExpression<Variable>.For(rightVar, leftConst); return true; } } else if (leftNorm.IsVariable(out leftVar)) { // V + K if (rightNorm.IsConstant(out rightCont)) { result = NormalizedExpression<Variable>.For(leftVar, rightCont); return true; } } } } return Default(data); } public override bool VisitConstant(Expression left, Void data) { Int32 value; if (this.Decoder.TryValueOf<Int32>(left, ExpressionType.Int32, out value)) { result = NormalizedExpression<Variable>.For(value); return true; } return false; } public override bool VisitConvertToInt32(Expression left, Expression original, Void data) { return this.Visit(left, data); } public override bool VisitSubtraction(Expression left, Expression right, Expression original, Void data) { NormalizedExpression<Variable> leftNorm, rightNorm; if (this.TryConvert(left, out leftNorm)) { Contract.Assert(leftNorm != null); if (this.TryConvert(right, out rightNorm)) { Contract.Assert(rightNorm != null); // All the cases. We declare all the variables here, // so to leverage the definite assignment analysis of // the compiler to check we are doing everything right int leftConst, rightConst; Variable leftVar; if (rightNorm.IsConstant(out rightConst) && rightConst != Int32.MinValue) { // K - K if (leftNorm.IsConstant(out leftConst)) { result = NormalizedExpression<Variable>.For(leftConst - rightConst); // Can overflow, we do not care has it may be the concrete semantics return true; } // V - K if (leftNorm.IsVariable(out leftVar)) { result = NormalizedExpression<Variable>.For(leftVar, -rightConst); return true; } } } } return Default(data); } public override bool VisitVariable(Variable variable, Expression original, Void data) { result = NormalizedExpression<Variable>.For(variable); return true; } protected override bool Default(Void data) { result = default(NormalizedExpression<Variable>); return false; } public override string ToString() { return result == null ? "null" : result.ToString(); } } } [ContractClassFor(typeof(NormalizedExpression<>))] internal abstract class NormalizedExpressionContracts<Variable> : NormalizedExpression<Variable> { public override NormalizedExpression<Variable> PlusOne() { Contract.Ensures(Contract.Result<NormalizedExpression<Variable>>() != null); return default(NormalizedExpression<Variable>); } public override NormalizedExpression<Variable> MinusOne() { Contract.Ensures(Contract.Result<NormalizedExpression<Variable>>() != null); return default(NormalizedExpression<Variable>); } public override Expression Convert<Expression>(IExpressionEncoder<Variable, Expression> encoder) { Contract.Requires(encoder != null); return default(Expression); } abstract public override bool IsConstant(out int value); abstract public override bool IsVariable(out Variable var); abstract public override bool IsAddition(out Variable var, out int value); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// base class for TweenChains and TweenFlows /// </summary> public class AbstractGoTweenCollection : AbstractGoTween { protected List<TweenFlowItem> _tweenFlows = new List<TweenFlowItem>(); /// <summary> /// data class that wraps an AbstractTween and its start time for the timeline /// </summary> protected class TweenFlowItem { public float startTime; public float endTime { get { return startTime + duration; } } public float duration; public AbstractGoTween tween; public TweenFlowItem( float startTime, AbstractGoTween tween ) { this.tween = tween; this.startTime = startTime; this.duration = tween.totalDuration; } public TweenFlowItem( float startTime, float duration ) { this.duration = duration; this.startTime = startTime; } } public AbstractGoTweenCollection( GoTweenCollectionConfig config ) { // allow events by default allowEvents = true; // setup callback bools _didInit = false; _didBegin = false; // flag the onIterationStart event to fire. // as long as goTo is not called on this tween, the onIterationStart event will fire _fireIterationStart = true; // copy the TweenConfig info over id = config.id; loopType = config.loopType; iterations = config.iterations; updateType = config.propertyUpdateType; timeScale = 1; state = GoTweenState.Paused; _onInit = config.onInitHandler; _onBegin = config.onBeginHandler; _onIterationStart = config.onIterationStartHandler; _onUpdate = config.onUpdateHandler; _onIterationEnd = config.onIterationEndHandler; _onComplete = config.onCompleteHandler; Go.addTween( this ); } #region AbstractTween overrides /// <summary> /// returns a list of all Tweens with the given target in the collection /// technically, this should be marked as internal /// </summary> public List<GoTween> tweensWithTarget( object target ) { List<GoTween> list = new List<GoTween>(); foreach( var flowItem in _tweenFlows ) { // skip TweenFlowItems with no target if( flowItem.tween == null ) continue; // check Tweens first var tween = flowItem.tween as GoTween; if( tween != null && tween.target == target ) list.Add( tween ); // check for TweenCollections if( tween == null ) { var tweenCollection = flowItem.tween as AbstractGoTweenCollection; if( tweenCollection != null ) { var tweensInCollection = tweenCollection.tweensWithTarget( target ); if( tweensInCollection.Count > 0 ) list.AddRange( tweensInCollection ); } } } return list; } public override bool removeTweenProperty( AbstractTweenProperty property ) { foreach( var flowItem in _tweenFlows ) { // skip delay items which have no tween if( flowItem.tween == null ) continue; if( flowItem.tween.removeTweenProperty( property ) ) return true; } return false; } public override bool containsTweenProperty( AbstractTweenProperty property ) { foreach( var flowItem in _tweenFlows ) { // skip delay items which have no tween if( flowItem.tween == null ) continue; if( flowItem.tween.containsTweenProperty( property ) ) return true; } return false; } public override List<AbstractTweenProperty> allTweenProperties() { var propList = new List<AbstractTweenProperty>(); foreach( var flowItem in _tweenFlows ) { // skip delay items which have no tween if( flowItem.tween == null ) continue; propList.AddRange( flowItem.tween.allTweenProperties() ); } return propList; } /// <summary> /// we are always considered valid because our constructor adds us to Go and we start paused /// </summary> public override bool isValid() { return true; } /// <summary> /// resumes playback /// </summary> public override void play() { base.play(); foreach( var flowItem in _tweenFlows ) { if( flowItem.tween != null ) flowItem.tween.play(); } } /// <summary> /// pauses playback /// </summary> public override void pause() { base.pause(); foreach( var flowItem in _tweenFlows ) { if( flowItem.tween != null ) flowItem.tween.pause(); } } /// <summary> /// tick method. if it returns true it indicates the tween is complete /// </summary> public override bool update( float deltaTime ) { if ( !_didInit ) onInit(); if ( !_didBegin ) onBegin(); if ( _fireIterationStart ) onIterationStart(); // update the timeline and state. base.update( deltaTime ); // get the proper elapsedTime if we're doing a PingPong var convertedElapsedTime = _isLoopingBackOnPingPong ? duration - _elapsedTime : _elapsedTime; // used for iterating over flowItems below. TweenFlowItem flowItem = null; // if we iterated last frame and this flow restarts from the beginning, we now need to reset all // of the flowItem tweens to either the beginning or the end of their respective timelines // we also want to do this in the _opposite_ way that we would normally iterate on them // as the start value of a later flowItem may alter a property of an earlier flowItem. if ( _didIterateLastFrame && loopType == GoLoopType.RestartFromBeginning ) { if ( isReversed || _isLoopingBackOnPingPong ) { for ( int i = 0; i < _tweenFlows.Count; ++i ) { flowItem = _tweenFlows[i]; if ( flowItem.tween == null ) continue; var cacheAllow = flowItem.tween.allowEvents; flowItem.tween.allowEvents = false; flowItem.tween.restart(); flowItem.tween.allowEvents = cacheAllow; } } else { for ( int i = _tweenFlows.Count - 1; i >= 0; --i ) { flowItem = _tweenFlows[i]; if ( flowItem.tween == null ) continue; var cacheAllow = flowItem.tween.allowEvents; flowItem.tween.allowEvents = false; flowItem.tween.restart(); flowItem.tween.allowEvents = cacheAllow; } } } else { if ( ( isReversed && !_isLoopingBackOnPingPong ) || ( !isReversed && _isLoopingBackOnPingPong ) ) { // if we are moving the tween in reverse, we should be iterating over the flowItems in reverse // to help properties behave a bit better. for ( var i = _tweenFlows.Count - 1; i >= 0; --i ) { flowItem = _tweenFlows[i]; if ( flowItem.tween == null ) continue; // if there's been an iteration this frame and we're not done yet, we want to make sure // this tween is set to play in the right direction, and isn't set to complete/paused. if ( _didIterateLastFrame && state != GoTweenState.Complete ) { if ( !flowItem.tween.isReversed ) flowItem.tween.reverse(); flowItem.tween.play(); } if ( flowItem.tween.state == GoTweenState.Running && flowItem.endTime >= convertedElapsedTime ) { var convertedDeltaTime = Mathf.Abs( convertedElapsedTime - flowItem.startTime - flowItem.tween.totalElapsedTime ); flowItem.tween.update( convertedDeltaTime ); } } } else { for ( int i = 0; i < _tweenFlows.Count; ++i ) { flowItem = _tweenFlows[i]; if ( flowItem.tween == null ) continue; // if there's been an iteration this frame and we're not done yet, we want to make sure // this tween is set to play in the right direction, and isn't set to complete/paused. if ( _didIterateLastFrame && state != GoTweenState.Complete ) { if ( flowItem.tween.isReversed ) flowItem.tween.reverse(); flowItem.tween.play(); } if ( flowItem.tween.state == GoTweenState.Running && flowItem.startTime <= convertedElapsedTime ) { var convertedDeltaTime = convertedElapsedTime - flowItem.startTime - flowItem.tween.totalElapsedTime; flowItem.tween.update( convertedDeltaTime ); } } } } onUpdate(); if ( _fireIterationEnd ) onIterationEnd(); if ( state == GoTweenState.Complete ) { onComplete(); return true; // true if complete } return false; // false if not complete } /// <summary> /// reverses playback. if going forward it will be going backward after this and vice versa. /// </summary> public override void reverse() { base.reverse(); var convertedElapsedTime = _isLoopingBackOnPingPong ? duration - _elapsedTime : _elapsedTime; foreach ( var flowItem in _tweenFlows ) { if ( flowItem.tween == null ) continue; if ( isReversed != flowItem.tween.isReversed ) flowItem.tween.reverse(); flowItem.tween.pause(); // we selectively mark tweens for play if they will be played immediately or in the future. // update() will filter out more tweens that should not be played yet. if ( isReversed || _isLoopingBackOnPingPong ) { if ( flowItem.startTime <= convertedElapsedTime ) flowItem.tween.play(); } else { if ( flowItem.endTime >= convertedElapsedTime ) flowItem.tween.play(); } } } /// <summary> /// goes to the specified time clamping it from 0 to the total duration of the tween. if the tween is /// not playing it will be force updated to the time specified. /// </summary> public override void goTo( float time, bool skipDelay = true ) { time = Mathf.Clamp( time, 0f, totalDuration ); // provide an early out for calling goTo on the same time multiple times. if ( time == _totalElapsedTime ) return; // we don't simply call base.goTo because that would force an update within AbstractGoTweenCollection, // which forces an update on all the tweenFlowItems without putting them in the right position. // it's also possible that people will move around a tween via the goTo method, so we want to // try to make that as efficient as possible. // if we are doing a goTo at the "start" of the timeline, based on the isReversed variable, // allow the onBegin and onIterationStart callback to fire again. // we only allow the onIterationStart event callback to fire at the start of the timeline, // as doing a goTo(x) where x % duration == 0 will trigger the onIterationEnd before we // go to the start. if ( ( isReversed && time == totalDuration ) || ( !isReversed && time == 0f ) ) { _didBegin = false; _fireIterationStart = true; } else { _didBegin = true; _fireIterationStart = false; } // since we're doing a goTo, we want to stop this tween from remembering that it iterated. // this could cause issues if you caused the tween to complete an iteration and then goTo somewhere // else while still paused. _didIterateThisFrame = false; // force a time and completedIterations before we update _totalElapsedTime = time; _completedIterations = isReversed ? Mathf.CeilToInt( _totalElapsedTime / duration ) : Mathf.FloorToInt( _totalElapsedTime / duration ); // we don't want to use the Collection update function, because we don't have all of our // child tweenFlowItems setup properly. this will properly setup our iterations, // totalElapsedTime, and other useful information. base.update( 0 ); var convertedElapsedTime = _isLoopingBackOnPingPong ? duration - _elapsedTime : _elapsedTime; // we always want to process items in the future of this tween from last to first. // and items that have already occured from first to last. TweenFlowItem flowItem = null; if ( isReversed || _isLoopingBackOnPingPong ) { // flowItems in the future of the timeline for ( int i = 0; i < _tweenFlows.Count; ++i ) { flowItem = _tweenFlows[i]; if ( flowItem == null ) continue; if ( flowItem.endTime >= convertedElapsedTime ) break; changeTimeForFlowItem( flowItem, convertedElapsedTime ); } // flowItems in the past & current part of the timeline for ( int i = _tweenFlows.Count - 1; i >= 0; --i ) { flowItem = _tweenFlows[i]; if ( flowItem == null ) continue; if ( flowItem.endTime < convertedElapsedTime ) break; changeTimeForFlowItem( flowItem, convertedElapsedTime ); } } else { // flowItems in the future of the timeline for ( int i = _tweenFlows.Count - 1; i >= 0; --i ) { flowItem = _tweenFlows[i]; if ( flowItem == null ) continue; if ( flowItem.startTime <= convertedElapsedTime ) break; changeTimeForFlowItem( flowItem, convertedElapsedTime ); } // flowItems in the past & current part of the timeline for ( int i = 0; i < _tweenFlows.Count; ++i ) { flowItem = _tweenFlows[i]; if ( flowItem == null ) continue; if ( flowItem.startTime > convertedElapsedTime ) break; changeTimeForFlowItem( flowItem, convertedElapsedTime ); } } } private void changeTimeForFlowItem( TweenFlowItem flowItem, float time ) { if ( flowItem == null || flowItem.tween == null ) return; if ( flowItem.tween.isReversed != ( isReversed || _isLoopingBackOnPingPong ) ) flowItem.tween.reverse(); var convertedTime = Mathf.Clamp( time - flowItem.startTime, 0f, flowItem.endTime ); if ( flowItem.startTime <= time && flowItem.endTime >= time ) { flowItem.tween.goToAndPlay( convertedTime ); } else { flowItem.tween.goTo( convertedTime ); flowItem.tween.pause(); } } #endregion }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using PixelFormat = System.Drawing.Imaging.PixelFormat; using System.Text; using System.Windows.Forms; using System.IO; using Vector3 = Axiom.MathLib.Vector3; using Matrix3 = Axiom.MathLib.Matrix3; using Quaternion = Axiom.MathLib.Quaternion; namespace NormalBump { public partial class Form1 : Form { public Form1() { InitializeComponent(); // normalMapTextBox.Text = "C:\\Downloads\\foundationWallsNormal_map.bmp"; // bumpMapTextBox.Text = "C:\\Downloads\\foundationWallsBumpMap.bmp"; // outputMapTextBox.Text = "C:\\Downloads\\foundationsWallsCombined.bmp"; } private void normalMapOpenButton_Click(object sender, EventArgs e) { if (normalMapOpenDialog.ShowDialog() == DialogResult.OK) normalMapTextBox.Text = normalMapOpenDialog.FileName; } private void bumpMapOpenButton_Click(object sender, EventArgs e) { if (bumpMapOpenDialog.ShowDialog() == DialogResult.OK) bumpMapTextBox.Text = bumpMapOpenDialog.FileName; } private void outputMapSaveButton_Click(object sender, EventArgs e) { if (outputMapSaveDialog.ShowDialog() == DialogResult.OK) outputMapTextBox.Text = outputMapSaveDialog.FileName; } private void ShowError(string format, params Object[] list) { string s = string.Format(format, list); MessageBox.Show (s, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } private int bumpLevel(Bitmap bumpMap, int x, int y) { Color bumpColor = bumpMap.GetPixel(x, y); return bumpColor.R; } private float colorToFloat(int c) { return (float)(c - 128); } private int floatToColor(float c) { return Math.Max(0, Math.Min(255, (int)((c + 0.5f) * 128))); } public static StreamWriter logStream; private void Log(string format, params Object[] list) { string s = string.Format(format, list); logStream.Write(s); } private void generateButton_Click(object sender, EventArgs e) { Cursor previousCursor = Cursor.Current; Cursor.Current = Cursors.WaitCursor; doneLabel.Visible = false; //outputPictureBox.Visible = false; if (generateLogFile.Checked) { string p = "NormalBump.log"; FileStream f = new FileStream(p, FileMode.Create, FileAccess.Write); logStream = new StreamWriter(f); logStream.Write(string.Format("{0} Started writing to {1}\n", DateTime.Now.ToString("hh:mm:ss"), p)); } // run the algorithm Bitmap normalMap = new Bitmap(normalMapTextBox.Text); Bitmap bumpMap = new Bitmap(bumpMapTextBox.Text); if (normalMap.Width != bumpMap.Width) { ShowError("Normal Map width {0} is not the same as Bump Map width {1}", normalMap.Width, bumpMap.Width); return; } if (normalMap.Height != bumpMap.Height) { ShowError("Normal Map height {0} is not the same as Bump Map height {1}", normalMap.Height, bumpMap.Height); return; } Bitmap outputMap = (Bitmap)normalMap.Clone(); PixelFormat normalFormat = normalMap.PixelFormat; PixelFormat bumpFormat = bumpMap.PixelFormat; // This will be set by the slider float scaleFactor = (float)trackBar.Value / 100f; if (reverseBumpDirection.Checked) scaleFactor = - scaleFactor; Vector3 unitZ = new Vector3(0f, 0f, 1f); float epsilon = 0.0000001f; // Loop through the bump map pixels, computing the normals // into the output map int w = normalMap.Width; int h = normalMap.Height; for(int x=0; x < w; x++) { for(int y=0; y < h; y++) { // Fetch the normal map normal vector Color c = normalMap.GetPixel(x, y); Vector3 normal = new Vector3(colorToFloat(c.R), colorToFloat(c.G), colorToFloat(c.B)).ToNormalized(); Vector3 result = normal; // If we're at the edge, use the normal vector if (x < w - 1 && y < h - 1) { // Compute the bump normal vector int xyLevel = bumpLevel(bumpMap, x, y); float dx = scaleFactor * (bumpLevel(bumpMap, x+1, y) - xyLevel); float dy = scaleFactor * (bumpLevel(bumpMap, x, y+1) - xyLevel); float dz = 255f; Vector3 bumpNormal = new Vector3(dx, dy, dz).ToNormalized(); if (generateLogFile.Checked) Log("X {0}, Y {1}, normal {2}, bumpNormal {3}\n", x, y, normal, bumpNormal); Vector3 axis = unitZ.Cross(normal); if (axis.Length > epsilon) { float cosAngle = unitZ.Dot(normal); float angle = (float)Math.Acos(cosAngle); Quaternion q = Quaternion.FromAngleAxis(angle, axis); Matrix3 rot = q.ToRotationMatrix(); result = rot * bumpNormal; if (generateLogFile.Checked) Log(" Angle {0}, Quaternion {1}, Result {2}\n", angle, q, result); } } Color resultColor = Color.FromArgb(floatToColor(result.x), floatToColor(result.y), floatToColor(result.z)); outputMap.SetPixel(x, y, resultColor); } } if (generateLogFile.Checked) logStream.Close(); outputMap.Save(outputMapTextBox.Text); outputPictureBox.Image = outputMap; outputPictureBox.Visible = true; Cursor.Current = previousCursor; doneLabel.Visible = true; } private void maybeEnableGenerate() { generateButton.Enabled = (normalMapTextBox.Text != "" && bumpMapTextBox.Text != "" && outputMapTextBox.Text != ""); } private void trackBar_Scroll(object sender, EventArgs e) { this.scaleFactorLabel.Text = "Bump Scale Factor: " + trackBar.Value + "%"; } private void normalMapTextBox_TextChanged(object sender, EventArgs e) { maybeEnableGenerate(); } private void bumpMapTextBox_TextChanged(object sender, EventArgs e) { maybeEnableGenerate(); } private void outputMapTextBox_TextChanged(object sender, EventArgs e) { maybeEnableGenerate(); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 7/13/2009 4:47:12 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // Jiri Kadlec | 11/20/2010 | Updated the Esri string of Web Mercator Auxiliary sphere projection // Matthew K | 01/10/2010 | Removed Parameters dictionary // ******************************************************************************************************** using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Threading; using DotSpatial.Projections.AuthorityCodes; using DotSpatial.Projections.Transforms; namespace DotSpatial.Projections { /// <summary> /// Parameters based on http://trac.osgeo.org/proj/wiki/GenParms. Also, see http://home.comcast.net/~gevenden56/proj/manual.pdf /// </summary> public class ProjectionInfo : ProjDescriptor, IEsriString { #region Constants and Fields private double? _longitudeOf1st; private double? _longitudeOf2nd; private double? _scaleFactor; private string _longitudeOfCenterAlias; // stores the value of the actual parameter name that was used in the original (when the string came from WKT/Esri) private string _latitudeOfOriginAlias; private string _falseEastingAlias; private string _falseNorthingAlias; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref = "ProjectionInfo" /> class. /// </summary> public ProjectionInfo() { GeographicInfo = new GeographicInfo(); Unit = new LinearUnit(); _scaleFactor = 1; // if not specified, default to 1 AuxiliarySphereType = AuxiliarySphereType.NotSpecified; NoDefs = true; } #endregion #region Public Properties /// <summary> /// Gets or sets the athority, for example EPSG /// </summary> public string Authority { get; set; } /// <summary> /// Gets or sets the athority code. /// </summary> public int AuthorityCode { get; set; } /// <summary> /// Gets or sets the auxiliary sphere type. /// </summary> public AuxiliarySphereType AuxiliarySphereType { get; set; } /// <summary> /// The horizontal 0 point in geographic terms /// </summary> public double? CentralMeridian { get; set; } /// <summary> /// The false easting for this coordinate system /// </summary> public double? FalseEasting { get; set; } /// <summary> /// The false northing for this coordinate system /// </summary> public double? FalseNorthing { get; set; } /// <summary> /// Gets or sets a boolean indicating a geocentric latitude parameter /// </summary> public bool Geoc { get; set; } /// <summary> /// The geographic information /// </summary> public GeographicInfo GeographicInfo { get; set; } /// <summary> /// Gets or sets a boolean that indicates whether or not this /// projection is geocentric. /// </summary> public bool IsGeocentric { get; set; } /// <summary> /// True if this coordinate system is expressed only using geographic coordinates /// </summary> public bool IsLatLon { get; set; } /// <summary> /// Gets or sets a boolean indicating whether this projection applies to the /// southern coordinate system or not. /// </summary> public bool IsSouth { get; set; } /// <summary> /// True if the transform is defined. That doesn't really mean it accurately represents the named /// projection, but rather it won't throw a null exception during transformation for the lack of /// a transform definition. /// </summary> public bool IsValid { get { return Transform != null; } } /// <summary> /// The zero point in geographic terms /// </summary> public double? LatitudeOfOrigin { get; set; } /// <summary> /// The longitude of center for this coordinate system /// </summary> public double? LongitudeOfCenter { get; set; } /// <summary> /// Gets or sets the M. /// </summary> /// <value> /// The M. /// </value> public double? M { get; set; } /// <summary> /// Gets or sets the name of this projection information /// </summary> public string Name { get; set; } /// <summary> /// A boolean that indicates whether to use the /usr/share/proj/proj_def.dat defaults file (proj4 parameter "no_defs"). /// </summary> public bool NoDefs { get; set; } /// <summary> /// Gets or sets a boolean for the over-ranging flag /// </summary> public bool Over { get; set; } /// <summary> /// The scale factor for this coordinate system /// </summary> public double ScaleFactor { get { return _scaleFactor ?? 1; } set { _scaleFactor = value; } } /// <summary> /// The line of latitude where the scale information is preserved. /// </summary> public double? StandardParallel1 { get; set; } /// <summary> /// The standard parallel 2. /// </summary> public double? StandardParallel2 { get; set; } /// <summary> /// Gets or sets the transform that converts between geodetic coordinates and projected coordinates. /// </summary> public ITransform Transform { get; set; } /// <summary> /// The unit being used for measurements. /// </summary> public LinearUnit Unit { get; set; } /// <summary> /// Gets or sets the w. /// </summary> /// <value> /// The w. /// </value> public double? W { get; set; } /// <summary> /// Gets or sets the integer zone parameter if it is specified. /// </summary> public int? Zone { get; set; } // ReSharper disable InconsistentNaming /// <summary> /// Gets or sets the alpha/ azimuth. /// </summary> /// <value> /// ? Used with Oblique Mercator and possibly a few others. For our purposes this is exactly the same as azimuth /// </value> public double? alpha { get; set; } /// <summary> /// Gets or sets the BNS. /// </summary> /// <value> /// The BNS. /// </value> public int? bns { get; set; } /// <summary> /// Gets or sets the czech. /// </summary> /// <value> /// The czech. /// </value> public int? czech { get; set; } /// <summary> /// Gets or sets the guam. /// </summary> /// <value> /// The guam. /// </value> public bool? guam { get; set; } /// <summary> /// Gets or sets the h. /// </summary> /// <value> /// The h. /// </value> public double? h { get; set; } /// <summary> /// Gets or sets the lat_ts. /// </summary> /// <value> /// Latitude of true scale. /// </value> public double? lat_ts { get; set; } /// <summary> /// Gets or sets the lon_1. /// </summary> /// <value> /// The lon_1. /// </value> public double? lon_1 { get; set; } /// <summary> /// Gets or sets the lon_2. /// </summary> /// <value> /// The lon_2. /// </value> public double? lon_2 { get; set; } /// <summary> /// Gets or sets the lonc. /// </summary> /// <value> /// The lonc. /// </value> public double? lonc { get; set; } /// <summary> /// Gets or sets the m. Named mGeneral to prevent CLS conflicts. /// </summary> /// <value> /// The m. /// </value> public double? mGeneral { get; set; } /// <summary> /// Gets or sets the n. /// </summary> /// <value> /// The n. /// </value> public double? n { get; set; } /// <summary> /// Gets or sets the no_rot. /// </summary> /// <value> /// The no_rot. Seems to be used as a boolean. /// </value> public int? no_rot { get; set; } /// <summary> /// Gets or sets the no_uoff. /// </summary> /// <value> /// The no_uoff. Seems to be used as a boolean. /// </value> public int? no_uoff { get; set; } /// <summary> /// Gets or sets the rot_conv. /// </summary> /// <value> /// The rot_conv. Seems to be used as a boolean. /// </value> public int? rot_conv { get; set; } /// <summary> /// Gets or sets the to_meter. /// </summary> /// <value> /// Multiplier to convert map units to 1.0m /// </value> public double? to_meter { get; set; } // ReSharper restore InconsistentNaming #endregion #region Public Methods /// <summary> /// Gets the lon_1 parameter in radians /// </summary> /// <returns> /// The get lam 1. /// </returns> public double Lam1 { get { if (StandardParallel1 != null) { return StandardParallel1.Value * GeographicInfo.Unit.Radians; } return 0; } } /// <summary> /// Gets the lon_2 parameter in radians /// </summary> /// <returns> /// The get lam 2. /// </returns> public double Lam2 { get { if (StandardParallel2 != null) { return StandardParallel2.Value * GeographicInfo.Unit.Radians; } return 0; } } /// <summary> /// Gets the lat_1 parameter multiplied by radians /// </summary> /// <returns> /// The get phi 1. /// </returns> public double Phi1 { get { if (StandardParallel1 != null) { return StandardParallel1.Value * GeographicInfo.Unit.Radians; } return 0; } } /// <summary> /// Gets the lat_2 parameter multiplied by radians /// </summary> /// <returns> /// The get phi 2. /// </returns> public double Phi2 { get { if (StandardParallel2 != null) { return StandardParallel2.Value * GeographicInfo.Unit.Radians; } return 0; } } /// <summary> /// Sets the lambda 0, or central meridian in radial coordinates /// </summary> /// <param name="value"> /// The value of Lambda 0 in radians /// </param> public double Lam0 { get { if (CentralMeridian != null) { return CentralMeridian.Value * GeographicInfo.Unit.Radians; } return 0; } set { CentralMeridian = value / GeographicInfo.Unit.Radians; } } /// <summary> /// Sets the phi 0 or latitude of origin in radial coordinates /// </summary> /// <param name="value"> /// </param> public double Phi0 { get { if (LatitudeOfOrigin != null) { return LatitudeOfOrigin.Value * GeographicInfo.Unit.Radians; } return 0; } set { LatitudeOfOrigin = value / GeographicInfo.Unit.Radians; } } /// <summary> /// Expresses the entire projection as the Esri well known text format that can be found in .prj files /// </summary> /// <returns> /// The generated string /// </returns> public string ToEsriString() { Spheroid tempSpheroid = new Spheroid(Proj4Ellipsoid.WGS_1984); // changed by JK to fix the web mercator auxiliary sphere Esri string if (Name == "WGS_1984_Web_Mercator_Auxiliary_Sphere") { tempSpheroid = GeographicInfo.Datum.Spheroid; GeographicInfo.Datum.Spheroid = new Spheroid(Proj4Ellipsoid.WGS_1984); } // if (_auxiliarySphereType != AuxiliarySphereType.NotSpecified) // { // tempSpheroid = _geographicInfo.Datum.Spheroid; // _geographicInfo.Datum.Spheroid = new Spheroid(Proj4Ellipsoid.WGS_1984); // } string result = string.Empty; if (!IsLatLon) { result += String.Format(@"PROJCS[""{0}"",", Name); } result += GeographicInfo.ToEsriString(); if (IsLatLon) { return result; } result += ", "; if (Transform != null) { // Since we can have semi-colon delimited names for aliases, we have to output just one in the WKT. Issue #297 var name = Transform.Name.Contains(";") ? Transform.Name.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)[0] : Transform.Name; result += String.Format(@"PROJECTION[""{0}""],", name); } if (FalseEasting != null) { string alias = _falseEastingAlias ?? "False_Easting"; result += @"PARAMETER[""" + alias + @"""," + Convert.ToString(FalseEasting / Unit.Meters, CultureInfo.InvariantCulture) + "],"; } if (FalseNorthing != null) { string alias = _falseNorthingAlias ?? "False_Northing"; result += @"PARAMETER[""" + alias + @"""," + Convert.ToString(FalseNorthing / Unit.Meters, CultureInfo.InvariantCulture) + "],"; } if (CentralMeridian != null && CentralMeridianValid()) { result += @"PARAMETER[""Central_Meridian""," + Convert.ToString(CentralMeridian, CultureInfo.InvariantCulture) + "],"; } if (StandardParallel1 != null) { result += @"PARAMETER[""Standard_Parallel_1""," + Convert.ToString(StandardParallel1, CultureInfo.InvariantCulture) + "],"; } if (StandardParallel2 != null) { result += @"PARAMETER[""Standard_Parallel_2""," + Convert.ToString(StandardParallel2, CultureInfo.InvariantCulture) + "],"; } if (_scaleFactor != null) { result += @"PARAMETER[""Scale_Factor""," + Convert.ToString(_scaleFactor, CultureInfo.InvariantCulture) + "],"; } if (alpha != null) { result += @"PARAMETER[""Azimuth""," + Convert.ToString(alpha, CultureInfo.InvariantCulture) + "],"; } if (LongitudeOfCenter != null) { string alias = _longitudeOfCenterAlias ?? "Longitude_Of_Center"; result += @"PARAMETER[""" + alias + @"""," + Convert.ToString(LongitudeOfCenter, CultureInfo.InvariantCulture) + "],"; } if (_longitudeOf1st != null) { result += @"PARAMETER[""Longitude_Of_1st""," + Convert.ToString(_longitudeOf1st, CultureInfo.InvariantCulture) + "],"; } if (_longitudeOf2nd != null) { result += @"PARAMETER[""Longitude_Of_2nd""," + Convert.ToString(_longitudeOf2nd, CultureInfo.InvariantCulture) + "],"; } if (LatitudeOfOrigin != null) { string alias = _latitudeOfOriginAlias ?? "Latitude_Of_Origin"; result += @"PARAMETER[""" + alias + @"""," + Convert.ToString(LatitudeOfOrigin, CultureInfo.InvariantCulture) + "],"; } // changed by JK to fix the web mercator auxiliary sphere Esri string if (Name == "WGS_1984_Web_Mercator_Auxiliary_Sphere") { result += @"PARAMETER[""Auxiliary_Sphere_Type""," + ((int)AuxiliarySphereType) + ".0],"; } result += Unit.ToEsriString() + "]"; // changed by JK to fix the web mercator auxiliary sphere Esri string if (Name == "WGS_1984_Web_Mercator_Auxiliary_Sphere") { GeographicInfo.Datum.Spheroid = new Spheroid(Proj4Ellipsoid.WGS_1984); GeographicInfo.Datum.Spheroid = tempSpheroid; } return result; } /// <summary> /// Using the specified code, this will attempt to look up the related reference information /// from the appropriate pcs code. /// </summary> /// <param name="epsgCode"> /// The epsg Code. /// </param> /// <exception cref="ArgumentOutOfRangeException">Throws when there is no projection for given epsg code</exception> public static ProjectionInfo FromEpsgCode(int epsgCode) { return FromAuthorityCode("EPSG", epsgCode); } /// <summary> /// Using the specified code, this will attempt to look up the related reference information from the appropriate authority code. /// </summary> /// <param name="authority"> The authority. </param> /// <param name="code"> The code. </param> /// <returns>ProjectionInfo</returns> /// <exception cref="ArgumentOutOfRangeException">Throws when there is no projection for given authority and code</exception> public static ProjectionInfo FromAuthorityCode(string authority, int code) { var pi = AuthorityCodeHandler.Instance[string.Format("{0}:{1}", authority, code)]; if (pi != null) { // we need to copy the projection information because the Authority Codes implementation returns its one and only // in memory copy of the ProjectionInfo. Passing it to the caller might introduce unintended results. var info = FromProj4String(pi.ToProj4String()); info.Name = pi.Name; info.NoDefs = true; info.Authority = authority; info.AuthorityCode = code; return info; } throw new ArgumentOutOfRangeException("authority", ProjectionMessages.AuthorityCodeNotFound); } /// <summary> /// Parses the entire projection from an Esri string. In some cases, this will have /// default projection information since only geographic information is obtained. /// </summary> /// <param name="esriString"> /// The Esri string to parse /// </param> public static ProjectionInfo FromEsriString(string esriString) { if (String.IsNullOrWhiteSpace(esriString)) { // Return a default 'empty' projection return new ProjectionInfo(); } //special case for Krovak Projection //todo use a lookup table instead of hard coding the projection here if (esriString.Contains("Krovak")) return KnownCoordinateSystems.Projected.NationalGrids.SJTSKKrovakEastNorth; var info = new ProjectionInfo(); info.NoDefs = true; if (!info.TryParseEsriString(esriString)) { throw new InvalidEsriFormatException(esriString); } return info; } /// <summary> /// Creates a new projection and automatically reads in the proj4 string /// </summary> /// <param name="proj4String">The proj4String to read in while defining the projection</param> /// <returns></returns> public static ProjectionInfo FromProj4String(string proj4String) { return FromProj4String(proj4String, null, -1); } /// <summary> /// Creates a new projection and automatically reads in the proj4 string /// </summary> /// <param name="proj4String"> /// The proj4String to read in while defining the projection /// </param> /// <param name="authority">[Optional] Authority, for example "EPSG"</param> /// <param name="authorityCode">[Optional] Authority code, for example 4326</param> public static ProjectionInfo FromProj4String(string proj4String, string authority = null, int authorityCode = -1) { var info = new ProjectionInfo(); info.ParseProj4String(proj4String); if (!string.IsNullOrWhiteSpace(authority)) info.Authority = authority; if (authorityCode > 0) info.AuthorityCode = authorityCode; return info; } /// <summary> /// Open a given prj fileName /// </summary> /// <param name="prjFilename"> /// </param> public static ProjectionInfo Open(string prjFilename) { string prj = File.ReadAllText(prjFilename); return FromEsriString(prj); } /// <summary> /// Gets a boolean that is true if the Esri WKT string created by the projections matches. /// There are multiple ways to write the same projection, but the output Esri WKT string /// should be a good indicator of whether or not they are the same. /// </summary> /// <param name="other"> /// The other projection to compare with. /// </param> /// <returns> /// Boolean, true if the projections are the same. /// </returns> public bool Equals(ProjectionInfo other) { if (other == null) { return false; } return ToEsriString().Equals(other.ToEsriString()) || ToProj4String().Equals(other.ToProj4String()); } /// <summary> /// If this is a geographic coordinate system, this will show decimal degrees. Otherwise, /// this will show the linear unit units. /// </summary> /// <param name="quantity"> /// The quantity. /// </param> /// <returns> /// The get unit text. /// </returns> public string GetUnitText(double quantity) { if (Geoc || IsLatLon) { if (Math.Abs(quantity) < 1) { return "of a decimal degree"; } return quantity == 1 ? "decimal degree" : "decimal degrees"; } if (Math.Abs(quantity) < 1) { return "of a " + Unit.Name; } if (Math.Abs(quantity) == 1) { return Unit.Name; } if (Math.Abs(quantity) > 1) { // The following are frequently followed by specifications, so adding s doesn't work if (Unit.Name.Contains("Foot") || Unit.Name.Contains("foot")) { return Unit.Name .Replace("Foot", "Feet") .Replace("foot", "Feet"); } if (Unit.Name.Contains("Yard") || Unit.Name.Contains("yard")) { return Unit.Name .Replace("Yard", "Yards") .Replace("yard", "Yards"); } if (Unit.Name.Contains("Chain") || Unit.Name.Contains("chain")) { return Unit.Name .Replace("Chain", "Chains") .Replace("chain", "Chains"); } if (Unit.Name.Contains("Link") || Unit.Name.Contains("link")) { return Unit.Name .Replace("Link", "Links") .Replace("link", "Links"); } return Unit.Name + "s"; } return Unit.Name; } /// <summary> /// Exports this projection info by saving it to a *.prj file. /// </summary> /// <param name="prjFilename"> /// The prj file to save to /// </param> public void SaveAs(string prjFilename) { if (File.Exists(prjFilename)) { File.Delete(prjFilename); } using (StreamWriter sw = File.CreateText(prjFilename)) { sw.WriteLine(ToEsriString()); } } /// <summary> /// Returns a representaion of this object as a Proj4 string. /// </summary> /// <returns> /// The to proj 4 string. /// </returns> public string ToProj4String() { //enforce invariant culture CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; var result = new StringBuilder(); Append(result, "x_0", FalseEasting); Append(result, "y_0", FalseNorthing); if (_scaleFactor != 1) { Append(result, "k_0", _scaleFactor); } Append(result, "lat_0", LatitudeOfOrigin); Append(result, "lon_0", CentralMeridian); Append(result, "lat_1", StandardParallel1); Append(result, "lat_2", StandardParallel2); if (Over) { result.Append(" +over"); } if (Geoc) { result.Append(" +geoc"); } Append(result, "alpha", alpha); Append(result, "lonc", LongitudeOfCenter); Append(result, "zone", Zone); if (IsLatLon) { Append(result, "proj", "longlat"); } else { if (Transform != null) { Append(result, "proj", Transform.Proj4Name); } // skips over to_meter if this is geographic or defaults to 1 if (Unit.Meters != 1) { // we don't create +units=m or +units=f instead we use. Append(result, "to_meter", Unit.Meters); } } result.Append(GeographicInfo.ToProj4String()); if (IsSouth) { result.Append(" +south"); } if (NoDefs) { result.Append(" +no_defs"); } //reset the culture info Thread.CurrentThread.CurrentCulture = originalCulture; return result.ToString(); } /// <summary> /// This overrides ToString to get the Esri name of the projection. /// </summary> /// <returns> /// The to string. /// </returns> public override string ToString() { if (!string.IsNullOrEmpty(Name)) { return Name; } if (Transform != null && !string.IsNullOrEmpty(Transform.Name)) { return Transform.Name; } if (IsLatLon) { if (GeographicInfo == null || string.IsNullOrEmpty(GeographicInfo.Name)) { return "LatLon"; } return GeographicInfo.Name; } return ToProj4String(); } #endregion #region Methods private bool CentralMeridianValid() { // CentralMeridian (lam0) is calculated for these coordinate system, but IS NOT part of their Esri WKTs return Transform.Name.ToLower() != "hotine_oblique_mercator_azimuth_natural_origin" && Transform.Name.ToLower() != "hotine_oblique_mercator_azimuth_center"; } private static void Append(StringBuilder result, string name, object value) { if (value == null) return; // The round-trip ("R") format specifier guarantees that a numeric value that is converted to a string will be parsed back into the same numeric value. // This format is supported only for the Single, Double, and BigInteger types. if (value is double) { value = ((double)value).ToString("R", CultureInfo.InvariantCulture); } else if (value is float) { value = ((float)value).ToString("R", CultureInfo.InvariantCulture); } result.AppendFormat(CultureInfo.InvariantCulture, " +{0}={1}", name, value); } private static double? GetParameter(string name, string esriString) { if (String.IsNullOrEmpty(name) || String.IsNullOrEmpty(esriString)) return null; double? result = null; int iStart = esriString.IndexOf(@"PARAMETER[""" + name + "\"", StringComparison.InvariantCultureIgnoreCase); if (iStart >= 0) { iStart += 13 + name.Length; int iEnd = esriString.IndexOf(']', iStart); string tst = esriString.Substring(iStart, iEnd - iStart); result = double.Parse(tst, CultureInfo.InvariantCulture); } return result; } private static double? GetParameter(IEnumerable<string> parameterNames, ref string alias, string esriString) { if (parameterNames == null || String.IsNullOrEmpty(esriString)) return null; // Return the first result that returns a value foreach (string parameterName in parameterNames) { var result = GetParameter(parameterName, esriString); if (result != null) { alias = parameterName; return result; } } return null; } /// <summary> /// Attempts to parse known parameters from the set of proj4 parameters /// </summary> private void ParseProj4String(string proj4String) { if (string.IsNullOrEmpty(proj4String)) { return; } // If it has a zone, and the projection is tmerc, it actually needs the utm initialization var tmercIsUtm = proj4String.Contains("zone="); if (tmercIsUtm) { ScaleFactor = 0.9996; // Default scale factor for utm // This also needed to write correct Esri String from given projection } string[] sections = proj4String.Split('+'); foreach (string str in sections) { string s = str.Trim(); if (string.IsNullOrEmpty(s)) { continue; } // single token commands if (s == "no_defs") { NoDefs = true; continue; } if (s == "over") { Over = true; continue; } if (s == "geoc") { Geoc = GeographicInfo.Datum.Spheroid.EccentricitySquared() != 0; continue; } if (s == "south") { IsSouth = true; continue; } if (s == "R_A") { //+R_A tells PROJ.4 to use a spherical radius that //gives a sphere with the same surface area as the original ellipsoid. I //imagine I added this while trying to get the results to match PCI's GCTP //based implementation though the history isn't clear on the details. //the R_A parameter indicates that an authalic auxiliary sphere should be used. //from http://pdl.perl.org/?docs=Transform/Proj4&title=PDL::Transform::Proj4#r_a AuxiliarySphereType = AuxiliarySphereType.Authalic; continue; } if (s == "to") { // some "+to" parameters exist... e.g., DutchRD. but I'm not sure what to do with them. // they seem to specify a second projection Trace.WriteLine( String.Format("ProjectionInfo.ParseProj4String: command 'to' not supported and the portion of the string after 'to' will not be processed in '{0}'", proj4String)); break; } // parameters string[] set = s.Split('='); if (set.Length != 2) { Trace.WriteLine( String.Format("ProjectionInfo.ParseProj4String: command '{0}' not understood in '{1}'", s, proj4String)); continue; } string name = set[0].Trim(); string value = set[1].Trim(); switch (name) { case "lonc": LongitudeOfCenter = double.Parse(value, CultureInfo.InvariantCulture); break; case "alpha": alpha = double.Parse(value, CultureInfo.InvariantCulture); break; case "x_0": FalseEasting = double.Parse(value, CultureInfo.InvariantCulture); break; case "y_0": FalseNorthing = double.Parse(value, CultureInfo.InvariantCulture); break; case "k": case "k_0": _scaleFactor = double.Parse(value, CultureInfo.InvariantCulture); break; case "lat_0": LatitudeOfOrigin = double.Parse(value, CultureInfo.InvariantCulture); break; case "lat_1": StandardParallel1 = double.Parse(value, CultureInfo.InvariantCulture); break; case "lat_2": StandardParallel2 = double.Parse(value, CultureInfo.InvariantCulture); break; case "lon_0": CentralMeridian = double.Parse(value, CultureInfo.InvariantCulture); break; case "lat_ts": StandardParallel1 = double.Parse(value, CultureInfo.InvariantCulture); break; case "zone": Zone = int.Parse(value, CultureInfo.InvariantCulture); break; case "proj": if (value == "longlat") { IsLatLon = true; } Transform = tmercIsUtm ? new UniversalTransverseMercator() : TransformManager.DefaultTransformManager.GetProj4(value); break; case "to_meter": Unit.Meters = double.Parse(value, CultureInfo.InvariantCulture); if (Unit.Meters == .3048) { Unit.Name = "Foot"; // International Foot } else if (Unit.Meters > .3048 && Unit.Meters < .305) { Unit.Name = "Foot_US"; } break; case "units": if (value == "m") { // do nothing, since the default is meter anyway. } else if (value == "ft" || value == "f") { Unit.Name = "Foot"; Unit.Meters = .3048; } else if (value == "us-ft") { Unit.Name = "Foot_US"; Unit.Meters = .304800609601219; } break; case "pm": GeographicInfo.Meridian.pm = value; //// added by Jiri Kadlec - pm should also specify the CentralMeridian //if (value != null) //{ // CentralMeridian = GeographicInfo.Meridian.Longitude; //} break; case "datum": // Even though th ellipsoid is set by its known definition, we permit overriding it with a specifically defined ellps parameter GeographicInfo.Datum = new Datum(value); break; case "nadgrids": GeographicInfo.Datum.NadGrids = value.Split(','); if (value != "@null") { GeographicInfo.Datum.DatumType = DatumType.GridShift; } break; case "towgs84": GeographicInfo.Datum.InitializeToWgs84(value.Split(',')); break; case "ellps": // Even though th ellipsoid is set by its known definition, we permit overriding it with a specifically defined ellps parameter // generally ellps will not be used in the same string as a,b,rf,R. GeographicInfo.Datum.Spheroid = new Spheroid(value); break; case "a": case "R": GeographicInfo.Datum.Spheroid.EquatorialRadius = double.Parse(value, CultureInfo.InvariantCulture); GeographicInfo.Datum.Spheroid.KnownEllipsoid = Proj4Ellipsoid.Custom; // This will provide same spheroid on export to Proj4 string break; case "b": GeographicInfo.Datum.Spheroid.PolarRadius = double.Parse(value, CultureInfo.InvariantCulture); GeographicInfo.Datum.Spheroid.KnownEllipsoid = Proj4Ellipsoid.Custom; // This will provide same spheroid on export to Proj4 string break; case "rf": Debug.Assert(GeographicInfo.Datum.Spheroid.EquatorialRadius > 0, "a must appear before rf"); GeographicInfo.Datum.Spheroid.InverseFlattening = double.Parse( value, CultureInfo.InvariantCulture); break; default: Trace.WriteLine(string.Format("Unrecognized parameter skipped {0}.", name)); break; } } if (Transform != null) { Transform.Init(this); } } /// <summary> /// This will try to read the string, but if the validation fails, then it will return false, /// rather than throwing an exception. /// </summary> /// <param name="esriString"> /// The string to test and define this projection if possible. /// </param> /// <returns> /// Boolean, true if at least the GEOGCS tag was found. /// </returns> public bool TryParseEsriString(string esriString) { if (esriString == null) { return false; } if (!esriString.Contains("GEOGCS")) { return false; } if (esriString.Contains("PROJCS") == false) { GeographicInfo.ParseEsriString(esriString); IsLatLon = true; Transform = new LongLat(); Transform.Init(this); return true; } int iStart = esriString.IndexOf(@""",", StringComparison.Ordinal); Name = esriString.Substring(8, iStart - 8); int iEnd = esriString.IndexOf("PARAMETER", StringComparison.Ordinal); string gcs; if (iEnd != -1) { gcs = esriString.Substring(iStart + 1, iEnd - (iStart + 2)); } else { // an odd Esri projection string that doesn't have PARAMETER gcs = esriString.Substring(iStart + 1); } GeographicInfo.ParseEsriString(gcs); FalseEasting = GetParameter(new string[] { "False_Easting", "Easting_At_False_Origin" }, ref _falseEastingAlias, esriString); FalseNorthing = GetParameter(new string[] { "False_Northing", "Northing_At_False_Origin" }, ref _falseNorthingAlias, esriString); CentralMeridian = GetParameter("Central_Meridian", esriString); // Esri seems to indicate that these should be treated the same, but they aren't here... http://support.esri.com/en/knowledgebase/techarticles/detail/39992 // CentralMeridian = GetParameter(new string[] { "Longitude_Of_Center", "Central_Meridian", "Longitude_Of_Origin" }, ref LongitudeOfCenterAlias, esriString); LongitudeOfCenter = GetParameter("Longitude_Of_Center", esriString); StandardParallel1 = GetParameter("Standard_Parallel_1", esriString); StandardParallel2 = GetParameter("Standard_Parallel_2", esriString); _scaleFactor = GetParameter("Scale_Factor", esriString); alpha = GetParameter("Azimuth", esriString); _longitudeOf1st = GetParameter("Longitude_Of_1st", esriString); _longitudeOf2nd = GetParameter("Longitude_Of_2nd", esriString); LatitudeOfOrigin = GetParameter(new[] { "Latitude_Of_Origin", "Latitude_Of_Center", "Central_Parallel" }, ref _latitudeOfOriginAlias, esriString); iStart = esriString.LastIndexOf("UNIT", StringComparison.Ordinal); string unit = esriString.Substring(iStart, esriString.Length - iStart); Unit.ParseEsriString(unit); if (esriString.Contains("PROJECTION")) { iStart = esriString.IndexOf("PROJECTION", StringComparison.Ordinal) + 12; iEnd = esriString.IndexOf("]", iStart, StringComparison.Ordinal) - 1; string projection = esriString.Substring(iStart, iEnd - iStart); Transform = TransformManager.DefaultTransformManager.GetProjection(projection); Transform.Init(this); } double? auxType = GetParameter("Auxiliary_Sphere_Type", esriString); if (auxType != null) { // While the Esri implementation sort of tip-toes around the datum transform, // we simply ensure that the spheroid becomes properly spherical based on the // parameters we have here. (The sphereoid will be read as WGS84). AuxiliarySphereType = (AuxiliarySphereType)auxType; if (AuxiliarySphereType == AuxiliarySphereType.SemimajorAxis) { // added by Jiri to properly re-initialize the 'web mercator auxiliary sphere' transform Transform = KnownCoordinateSystems.Projected.World.WebMercator.Transform; } else if (AuxiliarySphereType == AuxiliarySphereType.SemiminorAxis) { double r = GeographicInfo.Datum.Spheroid.PolarRadius; GeographicInfo.Datum.Spheroid = new Spheroid(r); } else if (AuxiliarySphereType == AuxiliarySphereType.Authalic || AuxiliarySphereType == AuxiliarySphereType.AuthalicWithConvertedLatitudes) { double a = GeographicInfo.Datum.Spheroid.EquatorialRadius; double b = GeographicInfo.Datum.Spheroid.PolarRadius; double r = Math.Sqrt( (a * a + a * b * b / (Math.Sqrt(a * a - b * b) * Math.Log((a + Math.Sqrt(a * a - b * b)) / b, Math.E))) / 2); GeographicInfo.Datum.Spheroid = new Spheroid(r); } } if (FalseEasting != null) { FalseEasting = FalseEasting * Unit.Meters; } if (FalseNorthing != null) { FalseNorthing = FalseNorthing * Unit.Meters; } return true; } #endregion #region IEsriString Members /// <summary> /// Re-sets the parameters of this projection info by parsing the esri projection string /// </summary> /// <param name="esriString">The projection information string in Esri WKT format</param> public void ParseEsriString(string esriString) { TryParseEsriString(esriString); } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.Compute; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute { /// <summary> /// The Compute Management API includes operations for managing the dns /// servers for your subscription. /// </summary> internal partial class DNSServerOperations : IServiceOperations<ComputeManagementClient>, Microsoft.WindowsAzure.Management.Compute.IDNSServerOperations { /// <summary> /// Initializes a new instance of the DNSServerOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DNSServerOperations(ComputeManagementClient client) { this._client = client; } private ComputeManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Compute.ComputeManagementClient. /// </summary> public ComputeManagementClient Client { get { return this._client; } } /// <summary> /// Add a definition for a DNS server to an existing deployment. VM's /// in this deployment will be programmed to use this DNS server for /// all DNS resolutions /// </summary> /// <param name='serviceName'> /// Required. The name of the service. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Add DNS Server operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async System.Threading.Tasks.Task<OperationStatusResponse> AddDNSServerAsync(string serviceName, string deploymentName, DNSAddParameters parameters, CancellationToken cancellationToken) { ComputeManagementClient client = this.Client; bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "AddDNSServerAsync", tracingParameters); } try { if (shouldTrace) { client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId)); } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse response = await client.DnsServer.BeginAddingDNSServerAsync(serviceName, deploymentName, parameters, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { Tracing.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.ErrorCode = result.Error.Code; ex.ErrorMessage = result.Error.Message; if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } } return result; } finally { if (client != null && shouldTrace) { client.Dispose(); } } } /// <summary> /// Add a definition for a DNS server to an existing deployment. VM's /// in this deployment will be programmed to use this DNS server for /// all DNS resolutions /// </summary> /// <param name='serviceName'> /// Required. The name of the service. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Add DNS Server operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async System.Threading.Tasks.Task<OperationStatusResponse> BeginAddingDNSServerAsync(string serviceName, string deploymentName, DNSAddParameters parameters, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (deploymentName == null) { throw new ArgumentNullException("deploymentName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "BeginAddingDNSServerAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/hostedservices/" + serviceName.Trim() + "/deployments/" + deploymentName.Trim() + "/dnsservers"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement dnsServerElement = new XElement(XName.Get("DnsServer", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(dnsServerElement); if (parameters.Name != null) { XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); nameElement.Value = parameters.Name; dnsServerElement.Add(nameElement); } if (parameters.Address != null) { XElement addressElement = new XElement(XName.Get("Address", "http://schemas.microsoft.com/windowsazure")); addressElement.Value = parameters.Address; dnsServerElement.Add(addressElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; result = new OperationStatusResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Deletes a definition for an existing DNS server from the deployment /// </summary> /// <param name='serviceName'> /// Required. The name of the service. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <param name='dnsServerName'> /// Required. The name of the dns server. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async System.Threading.Tasks.Task<OperationStatusResponse> BeginDeletingDNSServerAsync(string serviceName, string deploymentName, string dnsServerName, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (deploymentName == null) { throw new ArgumentNullException("deploymentName"); } if (dnsServerName == null) { throw new ArgumentNullException("dnsServerName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("dnsServerName", dnsServerName); Tracing.Enter(invocationId, this, "BeginDeletingDNSServerAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/hostedservices/" + serviceName.Trim() + "/deployments/" + deploymentName.Trim() + "/dnsservers/" + dnsServerName.Trim(); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; result = new OperationStatusResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Updates a definition for an existing DNS server. Updates to address /// is the only change allowed. DNS server name cannot be changed /// </summary> /// <param name='serviceName'> /// Required. The name of the service. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <param name='dnsServerName'> /// Required. The name of the dns server. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Update DNS Server operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async System.Threading.Tasks.Task<OperationStatusResponse> BeginUpdatingDNSServerAsync(string serviceName, string deploymentName, string dnsServerName, DNSUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (deploymentName == null) { throw new ArgumentNullException("deploymentName"); } if (dnsServerName == null) { throw new ArgumentNullException("dnsServerName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("dnsServerName", dnsServerName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "BeginUpdatingDNSServerAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/hostedservices/" + serviceName.Trim() + "/deployments/" + deploymentName.Trim() + "/dnsservers/" + dnsServerName.Trim(); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement dnsServerElement = new XElement(XName.Get("DnsServer", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(dnsServerElement); if (parameters.Name != null) { XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); nameElement.Value = parameters.Name; dnsServerElement.Add(nameElement); } if (parameters.Address != null) { XElement addressElement = new XElement(XName.Get("Address", "http://schemas.microsoft.com/windowsazure")); addressElement.Value = parameters.Address; dnsServerElement.Add(addressElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; result = new OperationStatusResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Deletes a definition for an existing DNS server from the deployment /// </summary> /// <param name='serviceName'> /// Required. The name of the service. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <param name='dnsServerName'> /// Required. The name of the dns server. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async System.Threading.Tasks.Task<OperationStatusResponse> DeleteDNSServerAsync(string serviceName, string deploymentName, string dnsServerName, CancellationToken cancellationToken) { ComputeManagementClient client = this.Client; bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("dnsServerName", dnsServerName); Tracing.Enter(invocationId, this, "DeleteDNSServerAsync", tracingParameters); } try { if (shouldTrace) { client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId)); } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse response = await client.DnsServer.BeginDeletingDNSServerAsync(serviceName, deploymentName, dnsServerName, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { Tracing.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.ErrorCode = result.Error.Code; ex.ErrorMessage = result.Error.Message; if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } } return result; } finally { if (client != null && shouldTrace) { client.Dispose(); } } } /// <summary> /// Updates a definition for an existing DNS server. Updates to address /// is the only change allowed. DNS server name cannot be changed /// </summary> /// <param name='serviceName'> /// Required. The name of the service. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <param name='dnsServerName'> /// Required. The name of the dns server. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Update DNS Server operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async System.Threading.Tasks.Task<OperationStatusResponse> UpdateDNSServerAsync(string serviceName, string deploymentName, string dnsServerName, DNSUpdateParameters parameters, CancellationToken cancellationToken) { ComputeManagementClient client = this.Client; bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("dnsServerName", dnsServerName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "UpdateDNSServerAsync", tracingParameters); } try { if (shouldTrace) { client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId)); } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse response = await client.DnsServer.BeginUpdatingDNSServerAsync(serviceName, deploymentName, dnsServerName, parameters, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { Tracing.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.ErrorCode = result.Error.Code; ex.ErrorMessage = result.Error.Message; if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } } return result; } finally { if (client != null && shouldTrace) { client.Dispose(); } } } } }
using System.Reflection; using System.Windows; using System.Windows.Input; using System.Windows.Interactivity; namespace Prism.Interactivity { /// <summary> /// Trigger action that executes a command when invoked. /// It also maintains the Enabled state of the target control based on the CanExecute method of the command. /// </summary> public class InvokeCommandAction : TriggerAction<UIElement> { private ExecutableCommandBehavior _commandBehavior; /// <summary> /// Dependency property identifying if the associated element should automaticlaly be enabled or disabled based on the result of the Command's CanExecute /// </summary> public static readonly DependencyProperty AutoEnableProperty = DependencyProperty.Register("AutoEnable", typeof(bool), typeof(InvokeCommandAction), new PropertyMetadata(true, (d, e) => ((InvokeCommandAction)d).OnAllowDisableChanged((bool)e.NewValue))); /// <summary> /// Gets or sets whther or not the associated element will automatically be enabled or disabled based on the result of the commands CanExecute /// </summary> public bool AutoEnable { get { return (bool)GetValue(AutoEnableProperty); } set { SetValue(AutoEnableProperty, value); } } private void OnAllowDisableChanged(bool newValue) { var behavior = GetOrCreateBehavior(); if (behavior != null) behavior.AutoEnable = newValue; } /// <summary> /// Dependency property identifying the command to execute when invoked. /// </summary> public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(InvokeCommandAction), new PropertyMetadata(null, (d, e) => ((InvokeCommandAction)d).OnCommandChanged((ICommand)e.NewValue))); /// <summary> /// Gets or sets the command to execute when invoked. /// </summary> public ICommand Command { get { return GetValue(CommandProperty) as ICommand; } set { SetValue(CommandProperty, value); } } private void OnCommandChanged(ICommand newValue) { var behavior = GetOrCreateBehavior(); if (behavior != null) behavior.Command = newValue; } /// <summary> /// Dependency property identifying the command parameter to supply on command execution. /// </summary> public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), typeof(InvokeCommandAction), new PropertyMetadata(null, (d, e) => ((InvokeCommandAction)d).OnCommandParameterChanged(e.NewValue))); /// <summary> /// Gets or sets the command parameter to supply on command execution. /// </summary> public object CommandParameter { get { return GetValue(CommandParameterProperty); } set { SetValue(CommandParameterProperty, value); } } private void OnCommandParameterChanged(object newValue) { var behavior = GetOrCreateBehavior(); if (behavior != null) behavior.CommandParameter = newValue; } /// <summary> /// Dependency property identifying the TriggerParameterPath to be parsed to identify the child property of the trigger parameter to be used as the command parameter. /// </summary> public static readonly DependencyProperty TriggerParameterPathProperty = DependencyProperty.Register("TriggerParameterPath", typeof(string), typeof(InvokeCommandAction), new PropertyMetadata(null, (d, e) => { })); /// <summary> /// Gets or sets the TriggerParameterPath value. /// </summary> public string TriggerParameterPath { get { return GetValue(TriggerParameterPathProperty) as string; } set { SetValue(TriggerParameterPathProperty, value); } } /// <summary> /// Public wrapper of the Invoke method. /// </summary> public void InvokeAction(object parameter) { Invoke(parameter); } /// <summary> /// Executes the command /// </summary> /// <param name="parameter">This parameter is passed to the command; the CommandParameter specified in the CommandParameterProperty is used for command invocation if not null.</param> protected override void Invoke(object parameter) { if (!string.IsNullOrEmpty(TriggerParameterPath)) { //Walk the ParameterPath for nested properties. var propertyPathParts = TriggerParameterPath.Split('.'); object propertyValue = parameter; foreach (var propertyPathPart in propertyPathParts) { var propInfo = propertyValue.GetType().GetTypeInfo().GetDeclaredProperty(propertyPathPart); propertyValue = propInfo.GetValue(propertyValue); } parameter = propertyValue; } var behavior = GetOrCreateBehavior(); if (behavior != null) { behavior.ExecuteCommand(parameter); } } /// <summary> /// Sets the Command and CommandParameter properties to null. /// </summary> protected override void OnDetaching() { base.OnDetaching(); Command = null; CommandParameter = null; _commandBehavior = null; } /// <summary> /// This method is called after the behavior is attached. /// It updates the command behavior's Command and CommandParameter properties if necessary. /// </summary> protected override void OnAttached() { base.OnAttached(); // In case this action is attached to a target object after the Command and/or CommandParameter properties are set, // the command behavior would be created without a value for these properties. // To cover this scenario, the Command and CommandParameter properties of the behavior are updated here. var behavior = GetOrCreateBehavior(); behavior.AutoEnable = AutoEnable; if (behavior.Command != Command) behavior.Command = Command; if (behavior.CommandParameter != CommandParameter) behavior.CommandParameter = CommandParameter; } private ExecutableCommandBehavior GetOrCreateBehavior() { // In case this method is called prior to this action being attached, // the CommandBehavior would always keep a null target object (which isn't changeable afterwards). // Therefore, in that case the behavior shouldn't be created and this method should return null. if (_commandBehavior == null && AssociatedObject != null) { _commandBehavior = new ExecutableCommandBehavior(AssociatedObject); } return _commandBehavior; } /// <summary> /// A CommandBehavior that exposes a public ExecuteCommand method. It provides the functionality to invoke commands and update Enabled state of the target control. /// It is not possible to make the <see cref="InvokeCommandAction"/> inherit from <see cref="CommandBehaviorBase{T}"/>, since the <see cref="InvokeCommandAction"/> /// must already inherit from <see cref="TriggerAction{T}"/>, so we chose to follow the aggregation approach. /// </summary> private class ExecutableCommandBehavior : CommandBehaviorBase<UIElement> { /// <summary> /// Constructor specifying the target object. /// </summary> /// <param name="target">The target object the behavior is attached to.</param> public ExecutableCommandBehavior(UIElement target) : base(target) { } /// <summary> /// Executes the command, if it's set. /// </summary> public new void ExecuteCommand(object parameter) { base.ExecuteCommand(parameter); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Xunit; namespace System.Collections.Immutable.Tests { public partial class ImmutableSortedSetBuilderTest : ImmutablesTestBase { [Fact] public void CreateBuilder() { ImmutableSortedSet<string>.Builder builder = ImmutableSortedSet.CreateBuilder<string>(); Assert.NotNull(builder); builder = ImmutableSortedSet.CreateBuilder<string>(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer); } [Fact] public void ToBuilder() { var builder = ImmutableSortedSet<int>.Empty.ToBuilder(); Assert.True(builder.Add(3)); Assert.True(builder.Add(5)); Assert.False(builder.Add(5)); Assert.Equal(2, builder.Count); Assert.True(builder.Contains(3)); Assert.True(builder.Contains(5)); Assert.False(builder.Contains(7)); var set = builder.ToImmutable(); Assert.Equal(builder.Count, set.Count); Assert.True(builder.Add(8)); Assert.Equal(3, builder.Count); Assert.Equal(2, set.Count); Assert.True(builder.Contains(8)); Assert.False(set.Contains(8)); } [Fact] public void BuilderFromSet() { var set = ImmutableSortedSet<int>.Empty.Add(1); var builder = set.ToBuilder(); Assert.True(builder.Contains(1)); Assert.True(builder.Add(3)); Assert.True(builder.Add(5)); Assert.False(builder.Add(5)); Assert.Equal(3, builder.Count); Assert.True(builder.Contains(3)); Assert.True(builder.Contains(5)); Assert.False(builder.Contains(7)); var set2 = builder.ToImmutable(); Assert.Equal(builder.Count, set2.Count); Assert.True(set2.Contains(1)); Assert.True(builder.Add(8)); Assert.Equal(4, builder.Count); Assert.Equal(3, set2.Count); Assert.True(builder.Contains(8)); Assert.False(set.Contains(8)); Assert.False(set2.Contains(8)); } [Fact] public void EnumerateBuilderWhileMutating() { var builder = ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 10)).ToBuilder(); Assert.Equal(Enumerable.Range(1, 10), builder); var enumerator = builder.GetEnumerator(); Assert.True(enumerator.MoveNext()); builder.Add(11); // Verify that a new enumerator will succeed. Assert.Equal(Enumerable.Range(1, 11), builder); // Try enumerating further with the previous enumerable now that we've changed the collection. Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); enumerator.Reset(); enumerator.MoveNext(); // resetting should fix the problem. // Verify that by obtaining a new enumerator, we can enumerate all the contents. Assert.Equal(Enumerable.Range(1, 11), builder); } [Fact] public void BuilderReusesUnchangedImmutableInstances() { var collection = ImmutableSortedSet<int>.Empty.Add(1); var builder = collection.ToBuilder(); Assert.Same(collection, builder.ToImmutable()); // no changes at all. builder.Add(2); var newImmutable = builder.ToImmutable(); Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance. Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance. } [Fact] public void GetEnumeratorTest() { var builder = ImmutableSortedSet.Create("a", "B").WithComparer(StringComparer.Ordinal).ToBuilder(); IEnumerable<string> enumerable = builder; using (var enumerator = enumerable.GetEnumerator()) { Assert.True(enumerator.MoveNext()); Assert.Equal("B", enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal("a", enumerator.Current); Assert.False(enumerator.MoveNext()); } } [Fact] public void MaxMin() { var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder(); Assert.Equal(1, builder.Min); Assert.Equal(3, builder.Max); } [Fact] public void Clear() { var set = ImmutableSortedSet<int>.Empty.Add(1); var builder = set.ToBuilder(); builder.Clear(); Assert.Equal(0, builder.Count); } [Fact] public void KeyComparer() { var builder = ImmutableSortedSet.Create("a", "B").ToBuilder(); Assert.Same(Comparer<string>.Default, builder.KeyComparer); Assert.True(builder.Contains("a")); Assert.False(builder.Contains("A")); builder.KeyComparer = StringComparer.OrdinalIgnoreCase; Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer); Assert.Equal(2, builder.Count); Assert.True(builder.Contains("a")); Assert.True(builder.Contains("A")); var set = builder.ToImmutable(); Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer); } [Fact] public void KeyComparerCollisions() { var builder = ImmutableSortedSet.Create("a", "A").ToBuilder(); builder.KeyComparer = StringComparer.OrdinalIgnoreCase; Assert.Equal(1, builder.Count); Assert.True(builder.Contains("a")); var set = builder.ToImmutable(); Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer); Assert.Equal(1, set.Count); Assert.True(set.Contains("a")); } [Fact] public void KeyComparerEmptyCollection() { var builder = ImmutableSortedSet.Create<string>().ToBuilder(); Assert.Same(Comparer<string>.Default, builder.KeyComparer); builder.KeyComparer = StringComparer.OrdinalIgnoreCase; Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer); var set = builder.ToImmutable(); Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer); } [Fact] public void UnionWith() { var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.UnionWith(null)); builder.UnionWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 1, 2, 3, 4 }, builder); } [Fact] public void ExceptWith() { var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.ExceptWith(null)); builder.ExceptWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 1 }, builder); } [Fact] public void SymmetricExceptWith() { var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.SymmetricExceptWith(null)); builder.SymmetricExceptWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 1, 4 }, builder); } [Fact] public void IntersectWith() { var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IntersectWith(null)); builder.IntersectWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 2, 3 }, builder); } [Fact] public void IsProperSubsetOf() { var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IsProperSubsetOf(null)); Assert.False(builder.IsProperSubsetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsProperSubsetOf(Enumerable.Range(1, 5))); } [Fact] public void IsProperSupersetOf() { var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IsProperSupersetOf(null)); Assert.False(builder.IsProperSupersetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsProperSupersetOf(Enumerable.Range(1, 2))); } [Fact] public void IsSubsetOf() { var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IsSubsetOf(null)); Assert.False(builder.IsSubsetOf(Enumerable.Range(1, 2))); Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 5))); } [Fact] public void IsSupersetOf() { var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IsSupersetOf(null)); Assert.False(builder.IsSupersetOf(Enumerable.Range(1, 4))); Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 2))); } [Fact] public void Overlaps() { var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.Overlaps(null)); Assert.True(builder.Overlaps(Enumerable.Range(3, 2))); Assert.False(builder.Overlaps(Enumerable.Range(4, 3))); } [Fact] public void Remove() { var builder = ImmutableSortedSet.Create("a").ToBuilder(); Assert.False(builder.Remove("b")); Assert.True(builder.Remove("a")); } [Fact] public void Reverse() { var builder = ImmutableSortedSet.Create("a", "b").ToBuilder(); Assert.Equal(new[] { "b", "a" }, builder.Reverse()); } [Fact] public void SetEquals() { var builder = ImmutableSortedSet.Create("a").ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.SetEquals(null)); Assert.False(builder.SetEquals(new[] { "b" })); Assert.True(builder.SetEquals(new[] { "a" })); Assert.True(builder.SetEquals(builder)); } [Fact] public void ICollectionOfTMethods() { ICollection<string> builder = ImmutableSortedSet.Create("a").ToBuilder(); builder.Add("b"); Assert.True(builder.Contains("b")); var array = new string[3]; builder.CopyTo(array, 1); Assert.Equal(new[] { null, "a", "b" }, array); Assert.False(builder.IsReadOnly); Assert.Equal(new[] { "a", "b" }, builder.ToArray()); // tests enumerator } [Fact] public void ICollectionMethods() { ICollection builder = ImmutableSortedSet.Create("a").ToBuilder(); var array = new string[builder.Count + 1]; builder.CopyTo(array, 1); Assert.Equal(new[] { null, "a" }, array); Assert.False(builder.IsSynchronized); Assert.NotNull(builder.SyncRoot); Assert.Same(builder.SyncRoot, builder.SyncRoot); } [Fact] public void Indexer() { var builder = ImmutableSortedSet.Create(1, 3, 2).ToBuilder(); Assert.Equal(1, builder[0]); Assert.Equal(2, builder[1]); Assert.Equal(3, builder[2]); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder[-1]); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder[3]); } [Fact] public void NullHandling() { var builder = ImmutableSortedSet<string>.Empty.ToBuilder(); Assert.True(builder.Add(null)); Assert.False(builder.Add(null)); Assert.True(builder.Contains(null)); Assert.True(builder.Remove(null)); builder.UnionWith(new[] { null, "a" }); Assert.True(builder.IsSupersetOf(new[] { null, "a" })); Assert.True(builder.IsSubsetOf(new[] { null, "a" })); Assert.True(builder.IsProperSupersetOf(new[] { default(string) })); Assert.True(builder.IsProperSubsetOf(new[] { null, "a", "b" })); builder.IntersectWith(new[] { default(string) }); Assert.Equal(1, builder.Count); builder.ExceptWith(new[] { default(string) }); Assert.False(builder.Remove(null)); } [Fact] public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSortedSet.CreateBuilder<string>()); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableSortedSet.CreateBuilder<int>()); ImmutableSortedSet<int>.Builder builder = ImmutableSortedSet.CreateBuilder<int>(); builder.Add(1); builder.Add(2); builder.Add(3); DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(builder); PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden); int[] items = itemProperty.GetValue(info.Instance) as int[]; Assert.Equal(builder, items); } [Fact] public static void TestDebuggerAttributes_Null() { Type proxyType = DebuggerAttributes.GetProxyType(ImmutableSortedSet.CreateBuilder<int>()); TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object)null)); Assert.IsType<ArgumentNullException>(tie.InnerException); } [Fact] public void ToImmutableSortedSet() { ImmutableSortedSet<int>.Builder builder = ImmutableSortedSet.CreateBuilder<int>(); builder.Add(1); builder.Add(5); builder.Add(10); var set = builder.ToImmutableSortedSet(); Assert.Equal(1, builder[0]); Assert.Equal(5, builder[1]); Assert.Equal(10, builder[2]); builder.Remove(10); Assert.False(builder.Contains(10)); Assert.True(set.Contains(10)); builder.Clear(); Assert.True(builder.ToImmutableSortedSet().IsEmpty); Assert.False(set.IsEmpty); ImmutableSortedSet<int>.Builder nullBuilder = null; AssertExtensions.Throws<ArgumentNullException>("builder", () => nullBuilder.ToImmutableSortedSet()); } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Xml.Serialization; using Rock.Conversion; namespace Rock.Logging.Defaults { /// <summary> /// Represents a single logging data point. /// </summary> [Serializable] [XmlRoot(Namespace = XmlNamespace)] [DataContract(Namespace = XmlNamespace)] [KnownType(typeof(LogEntry))] public class LogEntry : ILogEntry { /// <summary> /// The namespace that should be used for xml documents that describe a log entry. /// </summary> public const string XmlNamespace = "http://rockframework.org/logging"; /// <summary> /// Initializes a new instance of the <see cref="LogEntry"/> class. /// </summary> public LogEntry() : this(null, null, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="LogEntry"/> class. /// </summary> /// <param name="message">The log entry's message.</param> /// <example> /// <code> /// LogEntry entry = new LogEntry("Some message"); /// </code> /// </example> public LogEntry(string message) : this(message, null, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="LogEntry"/> class. /// </summary> /// <param name="message">The log entry's message.</param> /// <param name="exception">The log entry's exception.</param> /// <param name="exceptionContext">Contextual information about the exception. This value /// should give a developer additional information to help debug or fix the issue.</param> /// <example> /// <code> /// ILogger logger = LoggerFactory.GetInstance(); /// /// public void ProcessLoan(int loanNumber) /// { /// try /// { /// DoSomething(loanNumber); /// } /// catch (Exception ex) /// { /// if (logger.IsErrorEnabled()) /// { /// LogEntry entry = new LogEntry("Error doing something", ex); /// entry.ExtendedProperties.Add("LoanNumber", loanNumber); /// logger.Error(entry); /// } /// } /// } /// </code> /// </example> public LogEntry( string message, Exception exception, string exceptionContext = null) : this(message, null, exception, exceptionContext) { } /// <summary> /// Initializes a new instance of the LogEntry class. /// </summary> /// <param name="message">The message.</param> /// <param name="extendedProperties">The extended properties as an anonymous type.</param> /// <example> /// <code> /// LogEntry entry = new LogEntry("Hello, world!", new { Foo = "abc", Bar = 123}); /// </code> /// </example> public LogEntry(string message, object extendedProperties) : this( message, (IDictionary<string, string>)extendedProperties.ToDictionaryOfStringToString(), null, null) { } /// <summary> /// Initializes a new instance of the LogEntry class. /// </summary> /// <param name="message">The message.</param> /// <param name="extendedProperties">The extended properties as anonymous type.</param> /// <param name="exception">The exception.</param> /// <param name="exceptionContext">Contextual information about the exception. This value /// should give a developer additional information to help debug or fix the issue.</param> /// <example> /// <code> /// ILogger logger = LoggerFactory.GetInstance(); /// /// public void ProcessLoan(int loanNumber) /// { /// try /// { /// DoSomething(loanNumber); /// } /// catch (Exception ex) /// { /// if (logger.IsErrorEnabled()) /// { /// LogEntry entry = new LogEntry("Error doing something", new { LoanNumber = loanNumber }, ex); /// logger.Error(entry); /// } /// } /// } /// </code> /// </example> public LogEntry( string message, object extendedProperties, Exception exception, string exceptionContext = null) : this( message, (IDictionary<string, string>)extendedProperties.ToDictionaryOfStringToString(), exception, exceptionContext) { } /// <summary> /// Initializes a new instance of the LogEntry class. /// </summary> /// <param name="message">The message.</param> /// <param name="extendedProperties">The extended properties.</param> /// <example> /// <code> /// IDictionary&lt;string, string&gt; extendedProperties = /// new Dictionary&lt;string, string&gt;(); /// extendedProperties.Add("Foo", "abc"); /// extendedProperties.Add("Bar", "123"); /// LogEntry entry = new LogEntry("Hello, world!", extendedProperties); /// </code> /// </example> public LogEntry(string message, IDictionary<string, string> extendedProperties) : this(message, extendedProperties, null, null) { } /// <summary> /// Initializes a new instance of the LogEntry class. /// </summary> /// <param name="message">The message.</param> /// <param name="extendedProperties">The extended properties.</param> /// <param name="exception">The exception.</param> /// <param name="exceptionContext">Contextual information about the exception. This value /// should give a developer additional information to help debug or fix the issue.</param> /// <example> /// <code> /// ILogger logger = LoggerFactory.GetInstance(); /// /// public void ProcessLoan(int loanNumber) /// { /// try /// { /// DoSomething(loanNumber); /// } /// catch (Exception ex) /// { /// if (logger.IsErrorEnabled()) /// { /// IDictionary&lt;string, string&gt; extendedProperties = /// new Dictionary&lt;string, string&gt;(); /// extendedProperties.Add("LoanNumber", loanNumber.ToString()); /// LogEntry entry = new LogEntry("Error doing something", extendedProperties, ex); /// logger.Error(entry); /// } /// } /// } /// </code> /// </example> public LogEntry( string message, IDictionary<string, string> extendedProperties, Exception exception, string exceptionContext = null) { Message = message; ExtendedProperties = new LogEntryExtendedProperties(extendedProperties); this.SetException(exception, exceptionContext); MachineName = System.Environment.MachineName; ApplicationUserId = System.Environment.UserName; CreateTime = DateTime.UtcNow; UniqueId = Guid.NewGuid().ToString(); } /// <summary> /// Gets or sets the message that needs to be logged. /// </summary> [DataMember] public string Message { get; set; } /// <summary> /// Gets or sets the application id. /// </summary> [DataMember] public string ApplicationId { get; set; } /// <summary> /// The ID of the account that is running the application. By default, this is set to <see cref="System.Environment.UserName"/>. /// </summary> [DataMember] public string ApplicationUserId { get; set; } /// <summary> /// Gets or sets the time when the entry was created. This is automatically set when a new LogEntry is initialized. /// </summary> [DataMember] public DateTime CreateTime { get; set; } /// <summary> /// Gets or sets the environment (e.g. Test or Prod) in which the log entry was created. /// </summary> [DataMember] public string Environment { get; set; } /// <summary> /// Gets or sets the name of the machine name the log entry was created on. /// </summary> [DataMember] public string MachineName { get; set; } /// <summary> /// Gets or sets the log level of the log entry (e.g. Debug or Error). /// </summary> [DataMember] public LogLevel Level { get; set; } /// <summary> /// Gets or sets the details of an exception. /// </summary> [DataMember] public string ExceptionDetails { get; set; } /// <summary> /// Gets or sets arbitrary contextual information related to a thrown exception. This value /// should give a developer additional information to help debug or fix the issue. /// </summary> [DataMember] public string ExceptionContext { get; set; } /// <summary> /// Gets or sets the type of the exception. While the value of this property can be /// arbitrary, when <see cref="SetExceptionExtensionMethod.SetException"/> is called, /// its value will be set to the full name of the type of the exception. /// </summary> /// <remarks> /// When this log entry is processed (e.g. a web service), this value of this property /// can be used for a variety of purposes, such as tagging/labelling or indexing. /// </remarks> [DataMember] public string ExceptionType { get; set; } /// <summary> /// Gets or sets the extended properties. This property is used to add any additional /// information into the log entry. /// </summary> [DataMember] public LogEntryExtendedProperties ExtendedProperties { get; set; } /// <summary> /// Gets or sets an arbitrary unique identifier for the log entry. Its default value is /// a string representation of a new GUID. This value allows a log entry to be identified /// on the client-side. For example, a link to this log entry can be generated, client-side, /// before the log entry is added to a database. It is assumed that a database will index /// this value. /// </summary> [DataMember] public string UniqueId { get; set; } /// <summary> /// Gets a hash of this instance of <see cref="LogEntry"/> for the purpose of /// throttling log entries. If the value returned from this log entry is equal /// to the value from another log entry, then they are considered duplicates. /// Depending on the throttling configuration of a logger, duplicate log etries /// may or may not be sent its log providers. /// </summary> /// <returns>A hash code to be used for throttling purposes.</returns> public virtual int GetThrottlingHashCode() { unchecked { // TODO: determine exactly which properties should be included in the throttling hash code. var key = Level.GetHashCode(); key = (key * 397) ^ (Message != null ? Message.GetHashCode() : 0); key = (key * 397) ^ (ExceptionType != null ? ExceptionType.GetHashCode() : 0); key = (key * 397) ^ (ExceptionDetails != null ? ExceptionDetails.GetHashCode() : 0); key = (key * 397) ^ (MachineName != null ? MachineName.GetHashCode() : 0); key = (key * 397) ^ (Environment != null ? Environment.GetHashCode() : 0); return key; } } } }
#region Using directives using SimpleFramework.Xml.Transform; using SimpleFramework.Xml; using System; #endregion package SimpleFramework.Xml.transform; public class TransformerTest : TestCase { private static class BlankMatcher : Matcher { public Transform Match(Class type) { return null; } } private Transformer transformer; public void SetUp() { this.transformer = new Transformer(new BlankMatcher()); } public void TestInteger() { Object value = transformer.Read("1", Integer.class); String text = transformer.Write(value, Integer.class); AssertEquals(value, new Integer(1)); AssertEquals(text, "1"); } public void TestString() { Object value = transformer.Read("some text", String.class); String text = transformer.Write(value, String.class); AssertEquals("some text", value); AssertEquals("some text", text); } public void TestCharacter() { Object value = transformer.Read("c", Character.class); String text = transformer.Write(value, Character.class); AssertEquals(value, new Character('c')); AssertEquals(text, "c"); } public void TestInvalidCharacter() { bool success = false; try { transformer.Read("too long", Character.class); }catch(InvalidFormatException e) { e.printStackTrace(); success = true; } assertTrue(success); } public void TestFloat() { Object value = transformer.Read("1.12", Float.class); String text = transformer.Write(value, Float.class); AssertEquals(value, new Float(1.12)); AssertEquals(text, "1.12"); } public void TestDouble() { Object value = transformer.Read("12.33", Double.class); String text = transformer.Write(value, Double.class); AssertEquals(value, new Double(12.33)); AssertEquals(text, "12.33"); } public void TestBoolean() { Object value = transformer.Read("true", Boolean.class); String text = transformer.Write(value, Boolean.class); AssertEquals(value, Boolean.TRUE); AssertEquals(text, "true"); } public void TestLong() { Object value = transformer.Read("1234567", Long.class); String text = transformer.Write(value, Long.class); AssertEquals(value, new Long(1234567)); AssertEquals(text, "1234567"); } public void TestShort() { Object value = transformer.Read("12", Short.class); String text = transformer.Write(value, Short.class); AssertEquals(value, new Short((short)12)); AssertEquals(text, "12"); } public void TestPrimitiveIntegerArray() { Object value = transformer.Read("1, 2, 3, 4, 5", int[].class); String text = transformer.Write(value, int[].class); assertTrue(value instanceof int[]); int[] array = (int[])value; AssertEquals(array.length, 5); AssertEquals(array[0], 1); AssertEquals(array[1], 2); AssertEquals(array[2], 3); AssertEquals(array[3], 4); AssertEquals(array[4], 5); AssertEquals(text, "1, 2, 3, 4, 5"); } public void TestPrimitiveLongArray() { Object value = transformer.Read("1, 2, 3, 4, 5", long[].class); String text = transformer.Write(value, long[].class); assertTrue(value instanceof long[]); long[] array = (long[])value; AssertEquals(array.length, 5); AssertEquals(array[0], 1); AssertEquals(array[1], 2); AssertEquals(array[2], 3); AssertEquals(array[3], 4); AssertEquals(array[4], 5); AssertEquals(text, "1, 2, 3, 4, 5"); } public void TestPrimitiveShortArray() { Object value = transformer.Read("1, 2, 3, 4, 5", short[].class); String text = transformer.Write(value, short[].class); assertTrue(value instanceof short[]); short[] array = (short[])value; AssertEquals(array.length, 5); AssertEquals(array[0], 1); AssertEquals(array[1], 2); AssertEquals(array[2], 3); AssertEquals(array[3], 4); AssertEquals(array[4], 5); AssertEquals(text, "1, 2, 3, 4, 5"); } public void TestPrimitiveByteArray() { Object value = transformer.Read("1, 2, 3, 4, 5", byte[].class); String text = transformer.Write(value, byte[].class); assertTrue(value instanceof byte[]); byte[] array = (byte[])value; AssertEquals(array.length, 5); AssertEquals(array[0], 1); AssertEquals(array[1], 2); AssertEquals(array[2], 3); AssertEquals(array[3], 4); AssertEquals(array[4], 5); AssertEquals(text, "1, 2, 3, 4, 5"); } public void TestPrimitiveFloatArray() { Object value = transformer.Read("1.0, 2.0, 3.0, 4.0, 5.0", float[].class); String text = transformer.Write(value, float[].class); assertTrue(value instanceof float[]); float[] array = (float[])value; AssertEquals(array.length, 5); AssertEquals(array[0], 1.0f); AssertEquals(array[1], 2.0f); AssertEquals(array[2], 3.0f); AssertEquals(array[3], 4.0f); AssertEquals(array[4], 5.0f); AssertEquals(text, "1.0, 2.0, 3.0, 4.0, 5.0"); } public void TestPrimitiveDoubleArray() { Object value = transformer.Read("1, 2, 3, 4, 5", double[].class); String text = transformer.Write(value, double[].class); assertTrue(value instanceof double[]); double[] array = (double[])value; AssertEquals(array.length, 5); AssertEquals(array[0], 1.0d); AssertEquals(array[1], 2.0d); AssertEquals(array[2], 3.0d); AssertEquals(array[3], 4.0d); AssertEquals(array[4], 5.0d); AssertEquals(text, "1.0, 2.0, 3.0, 4.0, 5.0"); } public void TestPrimitiveCharacterArray() { Object value = transformer.Read("hello world", char[].class); String text = transformer.Write(value, char[].class); assertTrue(value instanceof char[]); char[] array = (char[])value; AssertEquals(array.length, 11); AssertEquals(array[0], 'h'); AssertEquals(array[1], 'e'); AssertEquals(array[2], 'l'); AssertEquals(array[3], 'l'); AssertEquals(array[4], 'o'); AssertEquals(array[5], ' '); AssertEquals(array[6], 'w'); AssertEquals(array[7], 'o'); AssertEquals(array[8], 'r'); AssertEquals(array[9], 'l'); AssertEquals(array[10], 'd'); AssertEquals(text, "hello world"); } // Java Language types public void TestIntegerArray() { Object value = transformer.Read("1, 2, 3, 4, 5", Integer[].class); String text = transformer.Write(value, Integer[].class); assertTrue(value instanceof Integer[]); Integer[] array = (Integer[])value; AssertEquals(array.length, 5); AssertEquals(array[0], new Integer(1)); AssertEquals(array[1], new Integer(2)); AssertEquals(array[2], new Integer(3)); AssertEquals(array[3], new Integer(4)); AssertEquals(array[4], new Integer(5)); AssertEquals(text, "1, 2, 3, 4, 5"); } public void TestBooleanArray() { Object value = transformer.Read("true, false, false, false, true", Boolean[].class); String text = transformer.Write(value, Boolean[].class); assertTrue(value instanceof Boolean[]); Boolean[] array = (Boolean[])value; AssertEquals(array.length, 5); AssertEquals(array[0], Boolean.TRUE); AssertEquals(array[1], Boolean.FALSE); AssertEquals(array[2], Boolean.FALSE); AssertEquals(array[3], Boolean.FALSE); AssertEquals(array[4], Boolean.TRUE); AssertEquals(text, "true, false, false, false, true"); } public void TestLongArray() { Object value = transformer.Read("1, 2, 3, 4, 5", Long[].class); String text = transformer.Write(value, Long[].class); assertTrue(value instanceof Long[]); Long[] array = (Long[])value; AssertEquals(array.length, 5); AssertEquals(array[0], new Long(1)); AssertEquals(array[1], new Long(2)); AssertEquals(array[2], new Long(3)); AssertEquals(array[3], new Long(4)); AssertEquals(array[4], new Long(5)); AssertEquals(text, "1, 2, 3, 4, 5"); } public void TestShortArray() { Object value = transformer.Read("1, 2, 3, 4, 5", Short[].class); String text = transformer.Write(value, Short[].class); assertTrue(value instanceof Short[]); Short[] array = (Short[])value; AssertEquals(array.length, 5); AssertEquals(array[0], new Short((short)1)); AssertEquals(array[1], new Short((short)2)); AssertEquals(array[2], new Short((short)3)); AssertEquals(array[3], new Short((short)4)); AssertEquals(array[4], new Short((short)5)); AssertEquals(text, "1, 2, 3, 4, 5"); } public void TestByteArray() { Object value = transformer.Read("1, 2, 3, 4, 5", Byte[].class); String text = transformer.Write(value, Byte[].class); assertTrue(value instanceof Byte[]); Byte[] array = (Byte[])value; AssertEquals(array.length, 5); AssertEquals(array[0], new Byte((byte)1)); AssertEquals(array[1], new Byte((byte)2)); AssertEquals(array[2], new Byte((byte)3)); AssertEquals(array[3], new Byte((byte)4)); AssertEquals(array[4], new Byte((byte)5)); AssertEquals(text, "1, 2, 3, 4, 5"); } public void TestFloatArray() { Object value = transformer.Read("1.0, 2.0, 3.0, 4.0, 5.0", Float[].class); String text = transformer.Write(value, Float[].class); assertTrue(value instanceof Float[]); Float[] array = (Float[])value; AssertEquals(array.length, 5); AssertEquals(array[0], new Float(1.0f)); AssertEquals(array[1], new Float(2.0f)); AssertEquals(array[2], new Float(3.0f)); AssertEquals(array[3], new Float(4.0f)); AssertEquals(array[4], new Float(5.0f)); AssertEquals(text, "1.0, 2.0, 3.0, 4.0, 5.0"); } public void TestDoubleArray() { Object value = transformer.Read("1, 2, 3, 4, 5", Double[].class); String text = transformer.Write(value, Double[].class); assertTrue(value instanceof Double[]); Double[] array = (Double[])value; AssertEquals(array.length, 5); AssertEquals(array[0], new Double(1.0d)); AssertEquals(array[1], new Double(2.0d)); AssertEquals(array[2], new Double(3.0d)); AssertEquals(array[3], new Double(4.0d)); AssertEquals(array[4], new Double(5.0d)); AssertEquals(text, "1.0, 2.0, 3.0, 4.0, 5.0"); } public void TestCharacterArray() { Object value = transformer.Read("hello world", Character[].class); String text = transformer.Write(value, Character[].class); assertTrue(value instanceof Character[]); Character[] array = (Character[])value; AssertEquals(array.length, 11); AssertEquals(array[0], new Character('h')); AssertEquals(array[1], new Character('e')); AssertEquals(array[2], new Character('l')); AssertEquals(array[3], new Character('l')); AssertEquals(array[4], new Character('o')); AssertEquals(array[5], new Character(' ')); AssertEquals(array[6], new Character('w')); AssertEquals(array[7], new Character('o')); AssertEquals(array[8], new Character('r')); AssertEquals(array[9], new Character('l')); AssertEquals(array[10], new Character('d')); AssertEquals(text, "hello world"); } } }
namespace Microsoft.Protocols.TestSuites.Common { using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using Microsoft.Protocols.TestTools; /// <summary> /// A class that implements ROP parsing and supports ROP buffer transmission between client and server. /// </summary> public class OxcropsClient { #region private Fields /// <summary> /// Length of RPC_HEADER_EXT /// </summary> private static readonly int RPCHEADEREXTLEN = Marshal.SizeOf(typeof(RPC_HEADER_EXT)); /// <summary> /// Status of connection. /// </summary> private bool isConnected; /// <summary> /// An instance of ITestSite /// </summary> private ITestSite site; /// <summary> /// RPC session context handle used by a client when issuing RPC calls against a server. /// </summary> private IntPtr cxh; /// <summary> /// The user name /// </summary> private string userName; /// <summary> /// The user DN /// </summary> private string userDN; /// <summary> /// User password /// </summary> private string userPassword; /// <summary> /// Domain name /// </summary> private string domainName; /// <summary> /// Original server name /// </summary> private string originalServerName; /// <summary> /// Reserved rop id hash table /// </summary> private Hashtable reservedRopIdsHT = null; /// <summary> /// Server name for logon public folder /// </summary> private string publicFolderServer = null; /// <summary> /// Server name for logon private mailbox /// </summary> private string privateMailboxServer = null; /// <summary> /// Proxy name for logon public folder /// </summary> private string publicFolderProxyServer = null; /// <summary> /// Proxy name for logon private mailbox /// </summary> private string privateMailboxProxyServer = null; /// <summary> /// Mail store url for private mailbox /// </summary> private string privateMailStoreUrl = null; /// <summary> /// Mail store url for public folder /// </summary> private string publicFolderUrl = null; /// <summary> /// RpcAdapter instance /// </summary> private RpcAdapter rpcAdapter; /// <summary> /// MapiHttpAdapter instance /// </summary> private MapiHttpAdapter mapiHttpAdapter; #endregion /// <summary> /// Initializes a new instance of the OxcropsClient class. /// </summary> public OxcropsClient() { } /// <summary> /// Initializes a new instance of the OxcropsClient class. /// </summary> /// <param name="mapiContext">The Mapi Context</param> public OxcropsClient(MapiContext mapiContext) { if (mapiContext == null) { throw new ArgumentNullException("mapiContext should not be null"); } this.RegisterROPDeserializer(); this.MapiContext = mapiContext; this.site = mapiContext.TestSite; switch (mapiContext.TransportSequence.ToLower()) { case "mapi_http": this.mapiHttpAdapter = new MapiHttpAdapter(this.site); break; case "ncacn_ip_tcp": case "ncacn_http": this.rpcAdapter = new RpcAdapter(this.site); break; default: this.site.Assert.Fail("TransportSeq \"{0}\" is not supported by the test suite."); break; } } /// <summary> /// Gets or sets mapi context /// </summary> public MapiContext MapiContext { get; set; } /// <summary> /// Gets or sets the RPC Context Pointer. /// </summary> public IntPtr CXH { get { return this.cxh; } set { this.cxh = value; } } /// <summary> /// Gets or sets a value indicating whether the status of connection is connected. /// </summary> public bool IsConnected { get { return this.isConnected; } set { this.isConnected = value; } } /// <summary> /// Check RopId whether in Reserved RopIds array /// </summary> /// <param name="ropId">The RopId will be checked</param> /// <returns>If the RopId is a reserved RopId, return true, else return false</returns> public bool IsReservedRopId(byte ropId) { if (this.reservedRopIdsHT == null) { this.reservedRopIdsHT = new Hashtable(); // Reserved RopId array byte[] reservedRopIds = { 0x00, 0x28, 0x3C, 0x3D, 0x62, 0x65, 0x6A, 0x71, 0x7C, 0x7D, 0x85, 0x87, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 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, 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 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, 0xFA, 0xFB, 0xFC, 0xFD, 0x52, 0x83, 0x84, 0x88 }; for (int i = 0; i < reservedRopIds.Length; i++) { this.reservedRopIdsHT.Add(reservedRopIds[i], "ROPID" + i.ToString()); } } // Check ropId whether in Reserved RopIds hashtable return this.reservedRopIdsHT.ContainsKey(ropId); } /// <summary> /// Connect to the server for running ROP commands. /// </summary> /// <param name="server">Server to connect.</param> /// <param name="connectionType">the type of connection</param> /// <param name="userDN">UserDN used to connect server</param> /// <param name="domain">Domain name</param> /// <param name="userName">User name used to logon</param> /// <param name="password">User Password</param> /// <returns>Result of connecting.</returns> public bool Connect(string server, ConnectionType connectionType, string userDN, string domain, string userName, string password) { this.privateMailboxServer = null; this.privateMailboxProxyServer = null; this.publicFolderServer = null; this.publicFolderProxyServer = null; this.privateMailStoreUrl = null; this.publicFolderUrl = null; this.userName = userName; this.userDN = userDN; this.userPassword = password; this.domainName = domain; this.originalServerName = server; if ((this.MapiContext.AutoRedirect == true) && (Common.GetConfigurationPropertyValue("UseAutodiscover", this.site).ToLower() == "true")) { string requestURL = Common.GetConfigurationPropertyValue("AutoDiscoverUrlFormat", this.site); requestURL = Regex.Replace(requestURL, @"\[ServerName\]", this.originalServerName, RegexOptions.IgnoreCase); string publicFolderMailbox = Common.GetConfigurationPropertyValue("PublicFolderMailbox", this.site); AutoDiscoverProperties autoDiscoverProperties = AutoDiscover.GetAutoDiscoverProperties(this.site, this.originalServerName, this.userName, this.domainName, requestURL, this.MapiContext.TransportSequence.ToLower(), publicFolderMailbox); this.privateMailboxServer = autoDiscoverProperties.PrivateMailboxServer; this.privateMailboxProxyServer = autoDiscoverProperties.PrivateMailboxProxy; this.publicFolderServer = autoDiscoverProperties.PublicMailboxServer; this.publicFolderProxyServer = autoDiscoverProperties.PublicMailboxProxy; this.privateMailStoreUrl = autoDiscoverProperties.PrivateMailStoreUrl; this.publicFolderUrl = autoDiscoverProperties.PublicMailStoreUrl; } else { if (this.MapiContext.TransportSequence.ToLower() == "mapi_http") { this.site.Assert.Fail("When the value of TransportSeq is set to mapi_http, the value of UseAutodiscover must be set to true."); } else { this.publicFolderServer = server; this.privateMailboxServer = server; } } bool ret = false; switch (this.MapiContext.TransportSequence.ToLower()) { case "mapi_http": if (connectionType == ConnectionType.PrivateMailboxServer) { ret = this.MapiConnect(this.privateMailStoreUrl, userDN, domain, userName, password); } else { ret = this.MapiConnect(this.publicFolderUrl, userDN, domain, userName, password); } break; case "ncacn_ip_tcp": case "ncacn_http": if (connectionType == ConnectionType.PrivateMailboxServer) { ret = this.RpcConnect(this.privateMailboxServer, userDN, domain, userName, password, this.privateMailboxProxyServer); } else { ret = this.RpcConnect(this.publicFolderServer, userDN, domain, userName, password, this.publicFolderProxyServer); } break; default: this.site.Assert.Fail("TransportSeq \"{0}\" is not supported by the test suite."); break; } return ret; } /// <summary> /// Disconnect from the server. /// </summary> /// <returns>Result of disconnecting.</returns> public bool Disconnect() { uint ret = 0; this.privateMailboxServer = null; this.privateMailboxProxyServer = null; this.publicFolderServer = null; this.publicFolderProxyServer = null; this.privateMailStoreUrl = null; this.publicFolderUrl = null; if (this.IsConnected) { switch (this.MapiContext.TransportSequence.ToLower()) { case "mapi_http": ret = this.mapiHttpAdapter.Disconnect(); break; case "ncacn_ip_tcp": case "ncacn_http": ret = this.rpcAdapter.Disconnect(ref this.cxh); break; default: this.site.Assert.Fail("TransportSeq \"{0}\" is not supported by the test suite."); break; } if (ret == 0) { this.IsConnected = false; } else { return false; } } return true; } /// <summary> /// Send ROP request to the server. /// </summary> /// <param name="requestROPs">ROP request objects.</param> /// <param name="requestSOHTable">ROP request server object handle table.</param> /// <param name="responseROPs">ROP response objects.</param> /// <param name="responseSOHTable">ROP response server object handle table.</param> /// <param name="rgbRopOut">The response payload bytes.</param> /// <param name="pcbOut">The maximum size of the rgbOut buffer to place Response in.</param> /// <param name="mailBoxUserName">Autodiscover find the mailbox according to this username.</param> /// <returns>0 indicates success, other values indicate failure. </returns> public uint RopCall( List<ISerializable> requestROPs, List<uint> requestSOHTable, ref List<IDeserializable> responseROPs, ref List<List<uint>> responseSOHTable, ref byte[] rgbRopOut, uint pcbOut, string mailBoxUserName = null) { // Log the rop requests if (requestROPs != null) { foreach (ISerializable requestROP in requestROPs) { byte[] ropData = requestROP.Serialize(); this.site.Log.Add(LogEntryKind.Comment, "Request: {0}", requestROP.GetType().Name); this.site.Log.Add(LogEntryKind.Comment, Common.FormatBinaryDate(ropData)); } } // Construct request buffer byte[] rgbIn = this.BuildRequestBuffer(requestROPs, requestSOHTable); uint ret = 0; switch (this.MapiContext.TransportSequence.ToLower()) { case "mapi_http": ret = this.mapiHttpAdapter.Execute(rgbIn, pcbOut, out rgbRopOut); break; case "ncacn_ip_tcp": case "ncacn_http": ret = this.rpcAdapter.RpcExt2(ref this.cxh, rgbIn, out rgbRopOut, ref pcbOut); break; default: this.site.Assert.Fail("TransportSeq \"{0}\" is not supported by the test suite."); break; } RPC_HEADER_EXT[] rpcHeaderExts; byte[][] rops; uint[][] serverHandleObjectsTables; if (ret == OxcRpcErrorCode.ECNone) { this.ParseResponseBuffer(rgbRopOut, out rpcHeaderExts, out rops, out serverHandleObjectsTables); // Deserialize rops if (rops != null) { foreach (byte[] rop in rops) { List<IDeserializable> ropResponses = new List<IDeserializable>(); RopDeserializer.Deserialize(rop, ref ropResponses); foreach (IDeserializable ropResponse in ropResponses) { responseROPs.Add(ropResponse); Type type = ropResponse.GetType(); this.site.Log.Add(LogEntryKind.Comment, "Response: {0}", type.Name); } this.site.Log.Add(LogEntryKind.Comment, Common.FormatBinaryDate(rop)); } } // Deserialize serverHandleObjectsTables if (serverHandleObjectsTables != null) { foreach (uint[] serverHandleObjectsTable in serverHandleObjectsTables) { List<uint> serverHandleObjectList = new List<uint>(); foreach (uint serverHandleObject in serverHandleObjectsTable) { serverHandleObjectList.Add(serverHandleObject); } responseSOHTable.Add(serverHandleObjectList); } } // The return value 0x478 means that the client needs to reconnect server with server name in response if (this.MapiContext.AutoRedirect && rops.Length > 0 && rops[0][0] == 0xfe && ((RopLogonResponse)responseROPs[0]).ReturnValue == 0x478) { // Reconnect server with returned server name string serverName = Encoding.ASCII.GetString(((RopLogonResponse)responseROPs[0]).ServerName); serverName = serverName.Substring(serverName.LastIndexOf("=") + 1); responseROPs.Clear(); responseSOHTable.Clear(); bool disconnectReturnValue = this.Disconnect(); this.site.Assert.IsTrue(disconnectReturnValue, "Disconnect should be successful here."); string rpcProxyOptions = null; if (string.Compare(this.MapiContext.TransportSequence, "ncacn_http", true) == 0) { rpcProxyOptions = "RpcProxy=" + this.originalServerName + "." + this.domainName; bool connectionReturnValue = this.RpcConnect(serverName, this.userDN, this.domainName, this.userName, this.userPassword, rpcProxyOptions); this.site.Assert.IsTrue(connectionReturnValue, "RpcConnect_Internal should be successful here."); } else if (string.Compare(this.MapiContext.TransportSequence, "mapi_http", true) == 0) { if (mailBoxUserName == null) { mailBoxUserName = Common.GetConfigurationPropertyValue("AdminUserName", this.site); if (mailBoxUserName == null || mailBoxUserName == "") { this.site.Assert.Fail(@"There must be ""AdminUserName"" configure item in the ptfconfig file."); } } string requestURL = Common.GetConfigurationPropertyValue("AutoDiscoverUrlFormat", this.site); requestURL = Regex.Replace(requestURL, @"\[ServerName\]", this.originalServerName, RegexOptions.IgnoreCase); string publicFolderMailbox = Common.GetConfigurationPropertyValue("PublicFolderMailbox", this.site); AutoDiscoverProperties autoDiscoverProperties = AutoDiscover.GetAutoDiscoverProperties(this.site, this.originalServerName, mailBoxUserName, this.domainName, requestURL, this.MapiContext.TransportSequence.ToLower(), publicFolderMailbox); this.privateMailboxServer = autoDiscoverProperties.PrivateMailboxServer; this.privateMailboxProxyServer = autoDiscoverProperties.PrivateMailboxProxy; this.publicFolderServer = autoDiscoverProperties.PublicMailboxServer; this.publicFolderProxyServer = autoDiscoverProperties.PublicMailboxProxy; this.privateMailStoreUrl = autoDiscoverProperties.PrivateMailStoreUrl; this.publicFolderUrl = autoDiscoverProperties.PublicMailStoreUrl; bool connectionReturnValue = this.MapiConnect(this.privateMailStoreUrl, this.userDN, this.domainName, this.userName, this.userPassword); this.site.Assert.IsTrue(connectionReturnValue, "RpcConnect_Internal should be successful here."); } ret = this.RopCall( requestROPs, requestSOHTable, ref responseROPs, ref responseSOHTable, ref rgbRopOut, 0x10008); } } return ret; } /// <summary> /// The method to send NotificationWait request to the server. /// </summary> /// <param name="requestBody">The NotificationWait request body.</param> /// <returns>Return the NotificationWait response body.</returns> public NotificationWaitSuccessResponseBody MAPINotificationWaitCall(IRequestBody requestBody) { return this.mapiHttpAdapter.NotificationWaitCall(requestBody); } #region Register ROPs' deserializer /// <summary> /// Register ROPs' deserializer /// </summary> public void RegisterROPDeserializer() { RopDeserializer.Init(); // Logon ROPs response register this.RegisterLogonROPDeserializer(); // Fast Transfer ROPs response register this.RegisterFastTransferROPDeserializer(); // Folder ROPs response register this.RegisterFolderROPDeserializer(); // Incremental Change Synchronization ROPs response register this.RegisterIncrementalChangeSynchronizationROPDeserializer(); // Message ROPs response register this.RegisterMessageROPDeserializer(); // Notification ROPs response register this.RegisterNotificationROPDeserializer(); // Other ROPs response register this.RegisterOtherROPDeserializer(); // Permission ROPs response register this.RegisterPermissionROPDeserializer(); // Property ROPs this.RegisterPropertyROPDeserializer(); // Rule ROPs response register this.RegisterRuleROPDeserializer(); // Stream ROPs response register this.RegisterStreamROPDeserializer(); // Table ROPs response register this.RegisterTableROPDeserializer(); // Transport ROPs response register this.RegisterTransportROPDeserializer(); } /// <summary> /// Register Logon ROPs' deserializer /// </summary> private void RegisterLogonROPDeserializer() { #region Logon ROPs response register RopDeserializer.Register(Convert.ToInt32(RopId.RopGetOwningServers), new RopGetOwningServersResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetPerUserGuid), new RopGetPerUserGuidResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetPerUserLongTermIds), new RopGetPerUserLongTermIdsResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetReceiveFolder), new RopGetReceiveFolderResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetReceiveFolderTable), new RopGetReceiveFolderTableResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetStoreState), new RopGetStoreStateResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopIdFromLongTermId), new RopIdFromLongTermIdResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopLogon), new RopLogonResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopLongTermIdFromId), new RopLongTermIdFromIdResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopOpenAttachment), new RopOpenAttachmentResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopPublicFolderIsGhosted), new RopPublicFolderIsGhostedResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopReadPerUserInformation), new RopReadPerUserInformationResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSetReceiveFolder), new RopSetReceiveFolderResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopWritePerUserInformation), new RopWritePerUserInformationResponse()); #endregion } /// <summary> /// Register Fast Transfer ROPs' deserializer /// </summary> private void RegisterFastTransferROPDeserializer() { #region Fast Transfer ROPs response register RopDeserializer.Register(Convert.ToInt32(RopId.RopFastTransferDestinationConfigure), new RopFastTransferDestinationConfigureResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopFastTransferDestinationPutBuffer), new RopFastTransferDestinationPutBufferResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopFastTransferSourceCopyFolder), new RopFastTransferSourceCopyFolderResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopFastTransferSourceCopyMessages), new RopFastTransferSourceCopyMessagesResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopFastTransferSourceCopyProperties), new RopFastTransferSourceCopyPropertiesResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopFastTransferSourceCopyTo), new RopFastTransferSourceCopyToResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopFastTransferSourceGetBuffer), new RopFastTransferSourceGetBufferResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopTellVersion), new RopTellVersionResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopFastTransferDestinationPutBufferExtended), new RopFastTransferDestinationPutBufferExtendedResponse()); #endregion } /// <summary> /// Register Folder ROPs' deserializer /// </summary> private void RegisterFolderROPDeserializer() { #region Folder ROPs response register RopDeserializer.Register(Convert.ToInt32(RopId.RopCopyFolder), new RopCopyFolderResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopCreateFolder), new RopCreateFolderResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopDeleteFolder), new RopDeleteFolderResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopDeleteMessages), new RopDeleteMessagesResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopEmptyFolder), new RopEmptyFolderResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetContentsTable), new RopGetContentsTableResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetHierarchyTable), new RopGetHierarchyTableResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetSearchCriteria), new RopGetSearchCriteriaResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopHardDeleteMessages), new RopHardDeleteMessagesResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopHardDeleteMessagesAndSubfolders), new RopHardDeleteMessagesAndSubfoldersResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopMoveCopyMessages), new RopMoveCopyMessagesResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopMoveFolder), new RopMoveFolderResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopOpenFolder), new RopOpenFolderResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSetSearchCriteria), new RopSetSearchCriteriaResponse()); #endregion } /// <summary> /// Register Incremental Change Synchronization ROPs' deserializer /// </summary> private void RegisterIncrementalChangeSynchronizationROPDeserializer() { #region Incremental Change Synchronization ROPs response register RopDeserializer.Register(Convert.ToInt32(RopId.RopGetLocalReplicaIds), new RopGetLocalReplicaIdsResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSetLocalReplicaMidsetDeleted), new RopSetLocalReplicaMidsetDeletedResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSynchronizationConfigure), new RopSynchronizationConfigureResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSynchronizationGetTransferState), new RopSynchronizationGetTransferStateResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSynchronizationImportDeletes), new RopSynchronizationImportDeletesResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSynchronizationImportHierarchyChange), new RopSynchronizationImportHierarchyChangeResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSynchronizationImportMessageChange), new RopSynchronizationImportMessageChangeResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSynchronizationImportMessageMove), new RopSynchronizationImportMessageMoveResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSynchronizationImportReadStateChanges), new RopSynchronizationImportReadStateChangesResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSynchronizationOpenCollector), new RopSynchronizationOpenCollectorResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSynchronizationUploadStateStreamBegin), new RopSynchronizationUploadStateStreamBeginResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSynchronizationUploadStateStreamContinue), new RopSynchronizationUploadStateStreamContinueResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSynchronizationUploadStateStreamEnd), new RopSynchronizationUploadStateStreamEndResponse()); #endregion } /// <summary> /// Register Message ROPs' deserializer /// </summary> private void RegisterMessageROPDeserializer() { #region Message ROPs response register RopDeserializer.Register(Convert.ToInt32(RopId.RopCreateAttachment), new RopCreateAttachmentResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopCreateMessage), new RopCreateMessageResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopDeleteAttachment), new RopDeleteAttachmentResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetAttachmentTable), new RopGetAttachmentTableResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetMessageStatus), new RopGetMessageStatusResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopModifyRecipients), new RopModifyRecipientsResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopOpenEmbeddedMessage), new RopOpenEmbeddedMessageResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopOpenMessage), new RopOpenMessageResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopReadRecipients), new RopReadRecipientsResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopReloadCachedInformation), new RopReloadCachedInformationResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopRemoveAllRecipients), new RopRemoveAllRecipientsResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSaveChangesAttachment), new RopSaveChangesAttachmentResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSaveChangesMessage), new RopSaveChangesMessageResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSetMessageReadFlag), new RopSetMessageReadFlagResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSetMessageStatus), new RopSetMessageStatusResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSetReadFlags), new RopSetReadFlagsResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetValidAttachments), new RopGetValidAttachmentsResponse()); #endregion } /// <summary> /// Register Notification ROPs' deserializer /// </summary> private void RegisterNotificationROPDeserializer() { #region Notification ROPs response register RopDeserializer.Register(Convert.ToInt32(RopId.RopNotify), new RopNotifyResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopPending), new RopPendingResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopRegisterNotification), new RopRegisterNotificationResponse()); #endregion } /// <summary> /// Register other ROPs' deserializer /// </summary> private void RegisterOtherROPDeserializer() { #region Other ROPs response register RopDeserializer.Register(Convert.ToInt32(RopId.RopBackoff), new RopBackoffResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopBufferTooSmall), new RopBufferTooSmallResponse()); #endregion } /// <summary> /// Register Permission ROPs' deserializer /// </summary> private void RegisterPermissionROPDeserializer() { #region Permission ROPs response register RopDeserializer.Register(Convert.ToInt32(RopId.RopGetPermissionsTable), new RopGetPermissionsTableResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopModifyPermissions), new RopModifyPermissionsResponse()); #endregion } /// <summary> /// Register Property ROPs' deserializer /// </summary> private void RegisterPropertyROPDeserializer() { #region Property ROPs RopDeserializer.Register(Convert.ToInt32(RopId.RopOpenAttachment), new RopOpenAttachmentResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopCopyProperties), new RopCopyPropertiesResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopCopyTo), new RopCopyToResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopDeleteProperties), new RopDeletePropertiesResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopDeletePropertiesNoReplicate), new RopDeletePropertiesNoReplicateResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetNamesFromPropertyIds), new RopGetNamesFromPropertyIdsResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetPropertiesAll), new RopGetPropertiesAllResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetPropertiesList), new RopGetPropertiesListResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetPropertiesSpecific), new RopGetPropertiesSpecificResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetPropertyIdsFromNames), new RopGetPropertyIdsFromNamesResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopProgress), new RopProgressResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopQueryNamedProperties), new RopQueryNamedPropertiesResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSetProperties), new RopSetPropertiesResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSetPropertiesNoReplicate), new RopSetPropertiesNoReplicateResponse()); #endregion } /// <summary> /// Register Rule ROPs' deserializer /// </summary> private void RegisterRuleROPDeserializer() { #region Rule ROPs response register RopDeserializer.Register(Convert.ToInt32(RopId.RopGetRulesTable), new RopGetRulesTableResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopModifyRules), new RopModifyRulesResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopUpdateDeferredActionMessages), new RopUpdateDeferredActionMessagesResponse()); #endregion } /// <summary> /// Register Stream ROPs' deserializer /// </summary> private void RegisterStreamROPDeserializer() { #region Stream ROPs response register RopDeserializer.Register(Convert.ToInt32(RopId.RopCommitStream), new RopCommitStreamResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopCopyToStream), new RopCopyToStreamResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetStreamSize), new RopGetStreamSizeResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopLockRegionStream), new RopLockRegionStreamResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopOpenStream), new RopOpenStreamResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopReadStream), new RopReadStreamResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSeekStream), new RopSeekStreamResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSetStreamSize), new RopSetStreamSizeResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopUnlockRegionStream), new RopUnlockRegionStreamResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopWriteStream), new RopWriteStreamResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopCloneStream), new RopCloneStreamResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopWriteAndCommitStream), new RopWriteAndCommitStreamResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopWriteStreamExtended), new RopWriteStreamExtendedResponse()); #endregion } /// <summary> /// Register Table ROPs' deserializer /// </summary> private void RegisterTableROPDeserializer() { #region Table ROPs response register RopDeserializer.Register(Convert.ToInt32(RopId.RopAbort), new RopAbortResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopCollapseRow), new RopCollapseRowResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopCreateBookmark), new RopCreateBookmarkResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopExpandRow), new RopExpandRowResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopFindRow), new RopFindRowResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopFreeBookmark), new RopFreeBookmarkResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetCollapseState), new RopGetCollapseStateResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetStatus), new RopGetStatusResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopQueryColumnsAll), new RopQueryColumnsAllResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopQueryPosition), new RopQueryPositionResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopQueryRows), new RopQueryRowsResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopResetTable), new RopResetTableResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopRestrict), new RopRestrictResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSeekRow), new RopSeekRowResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSeekRowBookmark), new RopSeekRowBookmarkResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSeekRowFractional), new RopSeekRowFractionalResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSetCollapseState), new RopSetCollapseStateResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSetColumns), new RopSetColumnsResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSortTable), new RopSortTableResponse()); #endregion } /// <summary> /// Register Transport ROPs' deserializer /// </summary> private void RegisterTransportROPDeserializer() { #region Transport ROPs response register RopDeserializer.Register(Convert.ToInt32(RopId.RopAbortSubmit), new RopAbortSubmitResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetAddressTypes), new RopGetAddressTypesResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopGetTransportFolder), new RopGetTransportFolderResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopOptionsData), new RopOptionsDataResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSetSpooler), new RopSetSpoolerResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSpoolerLockMessage), new RopSpoolerLockMessageResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopSubmitMessage), new RopSubmitMessageResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopTransportNewMail), new RopTransportNewMailResponse()); RopDeserializer.Register(Convert.ToInt32(RopId.RopTransportSend), new RopTransportSendResponse()); #endregion } #endregion /// <summary> /// The method parses response buffer. /// </summary> /// <param name="rgbOut">The ROP response payload.</param> /// <param name="rpcHeaderExts">RPC header ext.</param> /// <param name="rops">ROPs in response.</param> /// <param name="serverHandleObjectsTables">Server handle objects tables</param> private void ParseResponseBuffer(byte[] rgbOut, out RPC_HEADER_EXT[] rpcHeaderExts, out byte[][] rops, out uint[][] serverHandleObjectsTables) { List<RPC_HEADER_EXT> rpcHeaderExtList = new List<RPC_HEADER_EXT>(); List<byte[]> ropList = new List<byte[]>(); List<uint[]> serverHandleObjectList = new List<uint[]>(); IntPtr ptr = IntPtr.Zero; int index = 0; bool end = false; do { // Parse rpc header ext RPC_HEADER_EXT rpcHeaderExt; ptr = Marshal.AllocHGlobal(RPCHEADEREXTLEN); try { Marshal.Copy(rgbOut, index, ptr, RPCHEADEREXTLEN); rpcHeaderExt = (RPC_HEADER_EXT)Marshal.PtrToStructure(ptr, typeof(RPC_HEADER_EXT)); rpcHeaderExtList.Add(rpcHeaderExt); index += RPCHEADEREXTLEN; end = (rpcHeaderExt.Flags & (ushort)RpcHeaderExtFlags.Last) == (ushort)RpcHeaderExtFlags.Last; } finally { Marshal.FreeHGlobal(ptr); } #region start parse payload // Parse ropSize ushort ropSize = BitConverter.ToUInt16(rgbOut, index); index += sizeof(ushort); if ((ropSize - sizeof(ushort)) > 0) { // Parse rop byte[] rop = new byte[ropSize - sizeof(ushort)]; Array.Copy(rgbOut, index, rop, 0, ropSize - sizeof(ushort)); ropList.Add(rop); index += ropSize - sizeof(ushort); } // Parse server handle objects table this.site.Assert.IsTrue((rpcHeaderExt.Size - ropSize) % sizeof(uint) == 0, "Server object handle should be uint32 array"); int count = (rpcHeaderExt.Size - ropSize) / sizeof(uint); if (count > 0) { uint[] sohs = new uint[count]; for (int k = 0; k < count; k++) { sohs[k] = BitConverter.ToUInt32(rgbOut, index); index += sizeof(uint); } serverHandleObjectList.Add(sohs); } #endregion } while (!end); rpcHeaderExts = rpcHeaderExtList.ToArray(); rops = ropList.ToArray(); serverHandleObjectsTables = serverHandleObjectList.ToArray(); } /// <summary> /// Create ROPs request buffer. /// </summary> /// <param name="requestROPs">ROPs in request.</param> /// <param name="requestSOHTable">Server object handles table.</param> /// <returns>The ROPs request buffer.</returns> private byte[] BuildRequestBuffer(List<ISerializable> requestROPs, List<uint> requestSOHTable) { // Definition for PayloadLen which indicates the length of the field that represents the length of payload. int payloadLen = 0x2; if (requestROPs != null) { foreach (ISerializable requestROP in requestROPs) { payloadLen += requestROP.Size(); } } ushort ropSize = (ushort)payloadLen; if (requestSOHTable != null) { payloadLen += requestSOHTable.Count * sizeof(uint); } byte[] requestBuffer = new byte[RPCHEADEREXTLEN + payloadLen]; int index = 0; // Construct RPC header ext buffer RPC_HEADER_EXT rpcHeaderExt = new RPC_HEADER_EXT { // There is only one version of the header at this time so this value MUST be set to 0x00. Version = 0x00, // Last (0x04) indicates that no other RPC_HEADER_EXT follows the data of the current RPC_HEADER_EXT. Flags = (ushort)RpcHeaderExtFlags.Last, Size = (ushort)payloadLen }; rpcHeaderExt.SizeActual = rpcHeaderExt.Size; IntPtr ptr = Marshal.AllocHGlobal(RPCHEADEREXTLEN); try { Marshal.StructureToPtr(rpcHeaderExt, ptr, true); Marshal.Copy(ptr, requestBuffer, index, RPCHEADEREXTLEN); index += RPCHEADEREXTLEN; } finally { Marshal.FreeHGlobal(ptr); } // RopSize's type is ushort. So the offset will be 2. Array.Copy(BitConverter.GetBytes(ropSize), 0, requestBuffer, index, 2); index += 2; if (requestROPs != null) { foreach (ISerializable requestROP in requestROPs) { Array.Copy(requestROP.Serialize(), 0, requestBuffer, index, requestROP.Size()); index += requestROP.Size(); } } if (requestSOHTable != null) { foreach (uint serverHandle in requestSOHTable) { Array.Copy(BitConverter.GetBytes(serverHandle), 0, requestBuffer, index, sizeof(uint)); index += sizeof(uint); } } // Compress and obfuscate request buffer as configured. requestBuffer = Common.CompressAndObfuscateRequest(requestBuffer, this.site); return requestBuffer; } /// <summary> /// Internal use connect to the server for RPC calling. /// </summary> /// <param name="mailStoreUrl">The mail store url used to connect with the server.</param> /// <param name="userDN">User DN used to connect server</param> /// <param name="domain">Domain name</param> /// <param name="userName">User name used to logon.</param> /// <param name="password">User Password.</param> /// <returns>If client connects server successfully, it returns true, otherwise return false.</returns> private bool MapiConnect(string mailStoreUrl, string userDN, string domain, string userName, string password) { uint returnValue = this.mapiHttpAdapter.Connect(mailStoreUrl, domain, userName, userDN, password); if (0 == returnValue) { this.isConnected = true; return true; } else { return false; } } /// <summary> /// Internal use connect to the server for RPC calling. /// This method is defined as a direct way to connect to server with specific parameters. /// </summary> /// <param name="server">Server to connect.</param> /// <param name="userDN">UserDN used to connect server</param> /// <param name="domain">Domain name</param> /// <param name="userName">User name used to logon</param> /// <param name="password">User Password</param> /// <param name="rpcProxyOptions">Rpc proxy parameter</param> /// <returns>Result of connecting.</returns> private bool RpcConnect(string server, string userDN, string domain, string userName, string password, string rpcProxyOptions) { string userSpn = Regex.Replace(this.MapiContext.SpnFormat, @"\[ServerName\]", this.originalServerName, RegexOptions.IgnoreCase); this.cxh = this.rpcAdapter.Connect(server, domain, userName, userDN, password, userSpn, this.MapiContext, rpcProxyOptions); if (this.cxh != IntPtr.Zero) { this.IsConnected = true; return true; } else { return false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Rocket.API; using Rocket.Unturned; using Rocket.Core; using UnityEngine; using Rocket.Unturned.Plugins; using SDG; using Rocket.Core.Plugins; using Rocket.Core.Logging; using Rocket.Unturned.Chat; using Rocket.Unturned.Events; using Steamworks; using SDG.Unturned; using Rocket.API.Serialisation; using Rocket.Unturned.Player; using fr34kyn01535.Uconomy; using Rocket.API.Collections; namespace Remastered.DeathMessages { public class PlayerDeath : RocketPlugin<DMC2> { public static PlayerDeath Instance; public static UnturnedPlayer murderer3; public override TranslationList DefaultTranslations { get { return new TranslationList() { }; } } protected override void Load() { Instance = this; Rocket.Core.Logging.Logger.Log("Death Messages Remastered has been loaded!"); #region Event UnturnedPlayerEvents.OnPlayerDeath += UnturnedPlayerEvents_OnPlayerDeath; UnturnedPlayerEvents.OnPlayerUpdateHealth += UnturnedPlayerEvents_OnPlayerUpdateHealth; #endregion Rocket.Core.Logging.Logger.LogWarning("--"); if (Configuration.Instance.suicidemsg) { Rocket.Core.Logging.Logger.LogWarning("Suicide messages are enabled!"); } else { Rocket.Core.Logging.Logger.LogError("Suicide messages are disabled!"); } if (Configuration.Instance.healthwarningmsg) { Rocket.Core.Logging.Logger.LogWarning("Health warning messages are enabled!"); } else { Rocket.Core.Logging.Logger.LogError("Health warning messages are disabled!"); } if (Configuration.Instance.ExperienceEnabled) { Rocket.Core.Logging.Logger.LogWarning("Experience is enabled!"); } else { Rocket.Core.Logging.Logger.LogError("Experience is disabled!"); } if (Configuration.Instance.ZombieMessagesEnabled) { Rocket.Core.Logging.Logger.LogWarning("Zombie Death Messages are enabled!"); } else { Rocket.Core.Logging.Logger.LogError("Zombie Death Messages are disabled!"); } Rocket.Core.Logging.Logger.LogWarning("--"); } private void UnturnedPlayerEvents_OnPlayerDeath(UnturnedPlayer player, EDeathCause cause, ELimb limb, CSteamID murderer) { murderer3 = UnturnedPlayer.FromCSteamID(murderer); string Part = "???"; if (Configuration.Instance.ZombieMessagesEnabled && cause.ToString() == "ZOMBIE") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.zombie + " ", UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (Configuration.Instance.ShowDistance = true && cause.ToString() == "GUN") { if (limb == ELimb.SKULL) { UnturnedChat.Say(player.CharacterName + ", " + Configuration.Instance.headshotgun + ", " + Rocket.Unturned.Player.UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "[\u2719" + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "]" + ", " + Configuration.Instance.usinga + " " + Rocket.Unturned.Player.UnturnedPlayer.FromCSteamID(murderer).Player.equipment.asset.itemName.ToString() + " from " + Math.Round((double)Vector3.Distance(player.Position, murderer3.Position)).ToString() + "m!", UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); if (Configuration.Instance.UconomyEnabled) { UnturnedChat.Say(murderer, "You recieved" + " " + Configuration.Instance.Head + " " + Uconomy.Instance.Configuration.Instance.MoneyName + " " + "for getting a Headshot!", Color.green); } } else if (limb == ELimb.SPINE) { UnturnedChat.Say(UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "[\u2719" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "]" + ", " + Configuration.Instance.gun + ", " + player.CharacterName + ", " + Configuration.Instance.usinga + " " + UnturnedPlayer.FromCSteamID(murderer).Player.equipment.asset.itemName.ToString() + " from " + Math.Round((double)Vector3.Distance(player.Position, murderer3.Position)).ToString() + "m!", UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); if (Configuration.Instance.UconomyEnabled) { UnturnedChat.Say(murderer, "You recieved" + " " + Configuration.Instance.Body + " " + Uconomy.Instance.Configuration.Instance.MoneyName + " " + "for getting a body shot!", Color.green); } } else if (limb == ELimb.RIGHT_ARM || limb == ELimb.LEFT_ARM || limb == ELimb.LEFT_HAND || limb == ELimb.RIGHT_HAND) { UnturnedChat.Say(UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "HP:" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "%" + ", " + Configuration.Instance.gun + ", " + player.CharacterName + ", " + Configuration.Instance.usinga + " " + UnturnedPlayer.FromCSteamID(murderer).Player.equipment.asset.itemName.ToString() + " from " + Math.Round((double)Vector3.Distance(player.Position, murderer3.Position)).ToString() + "m!", UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); if (Configuration.Instance.UconomyEnabled) { UnturnedChat.Say(murderer, "You recieved" + " " + Configuration.Instance.Arm + " " + Uconomy.Instance.Configuration.Instance.MoneyName + " " + "for getting an arm shot!", Color.green); } } else if (limb == ELimb.RIGHT_LEG || limb == ELimb.LEFT_LEG || limb == ELimb.LEFT_FOOT || limb == ELimb.RIGHT_FOOT) { UnturnedChat.Say(UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "HP:" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "%" + ", " + Configuration.Instance.gun + ", " + player.CharacterName + ", " + Configuration.Instance.usinga + " " + UnturnedPlayer.FromCSteamID(murderer).Player.equipment.asset.itemName.ToString() + " from " + Math.Round((double)Vector3.Distance(player.Position, murderer3.Position)).ToString() + "m!", UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); if (Configuration.Instance.UconomyEnabled) { UnturnedChat.Say(murderer, "You recieved" + " " + Configuration.Instance.Leg + " " + Uconomy.Instance.Configuration.Instance.MoneyName + " " + "for getting a leg shot!", Color.green); } } else UnturnedChat.Say(UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "HP:" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "%" + ", " + Configuration.Instance.gun + ", " + player.CharacterName + ", " + Configuration.Instance.usinga + " " + Rocket.Unturned.Player.UnturnedPlayer.FromCSteamID(murderer).Player.equipment.asset.itemName.ToString() + " from " + Math.Round((double)Vector3.Distance(player.Position, murderer3.Position)).ToString() + "m!", UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "GUN") { if (limb == ELimb.SKULL) { UnturnedChat.Say(player.CharacterName + ", " + Configuration.Instance.headshotgun + ", " + Rocket.Unturned.Player.UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "HP:" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "%" + ", " + Configuration.Instance.usinga + " " + Rocket.Unturned.Player.UnturnedPlayer.FromCSteamID(murderer).Player.equipment.asset.itemName.ToString() + " from " + Math.Round((double)Vector3.Distance(player.Position, murderer3.Position)).ToString() + "m!", UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); if (Configuration.Instance.UconomyEnabled) { UnturnedChat.Say(murderer, "You recieved" + " " + Configuration.Instance.Head + " " + Uconomy.Instance.Configuration.Instance.MoneyName + " " + "for getting a Headshot!", Color.green); } } else if (limb == ELimb.SPINE) { UnturnedChat.Say(UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "HP:" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "%" + ", " + Configuration.Instance.gun + ", " + player.CharacterName + ", " + Configuration.Instance.usinga + " " + UnturnedPlayer.FromCSteamID(murderer).Player.equipment.asset.itemName.ToString() + " from " + Math.Round((double)Vector3.Distance(player.Position, murderer3.Position)).ToString() + "m!", UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); if (Configuration.Instance.UconomyEnabled) { UnturnedChat.Say(murderer, "You recieved" + " " + Configuration.Instance.Body + " " + Uconomy.Instance.Configuration.Instance.MoneyName + " " + "for getting a body shot!", Color.green); } } else if (limb == ELimb.RIGHT_ARM || limb == ELimb.LEFT_ARM || limb == ELimb.LEFT_HAND || limb == ELimb.RIGHT_HAND) { UnturnedChat.Say(UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "HP:" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "%" + ", " + Configuration.Instance.gun + ", " + player.CharacterName + ", " + Configuration.Instance.usinga + " " + UnturnedPlayer.FromCSteamID(murderer).Player.equipment.asset.itemName.ToString() + " from " + Math.Round((double)Vector3.Distance(player.Position, murderer3.Position)).ToString() + "m!", UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); if (Configuration.Instance.UconomyEnabled) { UnturnedChat.Say(murderer, "You recieved" + " " + Configuration.Instance.Arm + " " + Uconomy.Instance.Configuration.Instance.MoneyName + " " + "for getting an arm shot!", Color.green); } } else if (limb == ELimb.RIGHT_LEG || limb == ELimb.LEFT_LEG || limb == ELimb.LEFT_FOOT || limb == ELimb.RIGHT_FOOT) { UnturnedChat.Say(UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "HP:" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "%" + ", " + Configuration.Instance.gun + ", " + player.CharacterName + ", " + Configuration.Instance.usinga + " " + UnturnedPlayer.FromCSteamID(murderer).Player.equipment.asset.itemName.ToString() + " from " + Math.Round((double)Vector3.Distance(player.Position, murderer3.Position)).ToString() + "m!", UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); if (Configuration.Instance.UconomyEnabled) { UnturnedChat.Say(murderer, "You recieved" + " " + Configuration.Instance.Leg + " " + Uconomy.Instance.Configuration.Instance.MoneyName + " " + "for getting a leg shot!", Color.green); } } else UnturnedChat.Say(UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "HP:" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "%" + ", " + Configuration.Instance.gun + ", " + player.CharacterName + ", " + Configuration.Instance.usinga + " " + Rocket.Unturned.Player.UnturnedPlayer.FromCSteamID(murderer).Player.equipment.asset.itemName.ToString() + " from " + Math.Round((double)Vector3.Distance(player.Position, murderer3.Position)).ToString() + "m!", UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "MELEE") { if (limb == ELimb.SKULL) { UnturnedChat.Say(player.CharacterName + ", " + Configuration.Instance.headchop + ", " + UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "HP:" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "%" + ", " + Configuration.Instance.usinga + " " + Rocket.Unturned.Player.UnturnedPlayer.FromCSteamID(murderer).Player.equipment.asset.itemName.ToString() + " " + "!", UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); if (Configuration.Instance.UconomyEnabled) { UnturnedChat.Say(murderer, "You recieved" + " " + Configuration.Instance.Head + " " + Uconomy.Instance.Configuration.Instance.MoneyName + " " + "for getting a head chop!", Color.yellow); } } else if (limb == ELimb.SPINE) { UnturnedChat.Say(UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "HP:" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "%" + ", " + Configuration.Instance.melee + ", " + player.CharacterName + ", " + Configuration.Instance.melee2 + " " + Configuration.Instance.usinga + " " + Rocket.Unturned.Player.UnturnedPlayer.FromCSteamID(murderer).Player.equipment.asset.itemName.ToString(), UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); if (Configuration.Instance.UconomyEnabled) { UnturnedChat.Say(murderer, "You recieved" + " " + Configuration.Instance.Body + " " + Uconomy.Instance.Configuration.Instance.MoneyName + " " + "for getting a body kill!", Color.green); } } else if (limb == ELimb.RIGHT_ARM || limb == ELimb.LEFT_ARM || limb == ELimb.LEFT_HAND || limb == ELimb.RIGHT_HAND) { UnturnedChat.Say(UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "HP:" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "%" + ", " + Configuration.Instance.melee + ", " + player.CharacterName + ", " + Configuration.Instance.melee2 + " " + Configuration.Instance.usinga + " " + Rocket.Unturned.Player.UnturnedPlayer.FromCSteamID(murderer).Player.equipment.asset.itemName.ToString(), UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); if (Configuration.Instance.UconomyEnabled) { UnturnedChat.Say(murderer, "You recieved" + " " + Configuration.Instance.Arm + " " + Uconomy.Instance.Configuration.Instance.MoneyName + " " + "for getting an arm kill!", Color.green); } } else if (limb == ELimb.RIGHT_LEG || limb == ELimb.LEFT_LEG || limb == ELimb.LEFT_FOOT || limb == ELimb.RIGHT_FOOT) { UnturnedChat.Say(UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "HP:" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "%" + ", " + Configuration.Instance.melee + ", " + player.CharacterName + ", " + Configuration.Instance.melee2 + " " + Configuration.Instance.usinga + " " + Rocket.Unturned.Player.UnturnedPlayer.FromCSteamID(murderer).Player.equipment.asset.itemName.ToString(), UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); if (Configuration.Instance.UconomyEnabled) { UnturnedChat.Say(murderer, "You recieved" + " " + Configuration.Instance.Leg + " " + Uconomy.Instance.Configuration.Instance.MoneyName + " " + "for getting a leg kill!", Color.green); } } else UnturnedChat.Say(UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "HP:" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "%" + ", " + Configuration.Instance.melee + ", " + player.CharacterName + ", " + Configuration.Instance.melee2 + " " + Configuration.Instance.usinga + " " + Rocket.Unturned.Player.UnturnedPlayer.FromCSteamID(murderer).Player.equipment.asset.itemName.ToString(), UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "PUNCH") { if (limb == ELimb.SKULL) { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.headpunch + ", " + Rocket.Unturned.Player.UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "HP:" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "%" + "!", UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); if (Configuration.Instance.UconomyEnabled) { UnturnedChat.Say(murderer, "You recieved" + " " + Configuration.Instance.Head + " " + Uconomy.Instance.Configuration.Instance.MoneyName + " " + "for getting a head punch kill!", Color.green); } } else if (limb == ELimb.SPINE) { UnturnedChat.Say(UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "HP:" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "%" + ", " + Configuration.Instance.punch + " " + player.CharacterName + ", " + Configuration.Instance.punch2, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); if (Configuration.Instance.UconomyEnabled) { UnturnedChat.Say(murderer, "You recieved" + " " + Configuration.Instance.Body + " " + Uconomy.Instance.Configuration.Instance.MoneyName + " " + "for getting a body punch kill!", Color.green); } } else if (limb == ELimb.RIGHT_ARM || limb == ELimb.LEFT_ARM || limb == ELimb.LEFT_HAND || limb == ELimb.RIGHT_HAND) { UnturnedChat.Say(UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "HP:" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "%" + ", " + Configuration.Instance.punch + " " + player.CharacterName + ", " + Configuration.Instance.punch2, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); if (Configuration.Instance.UconomyEnabled) { UnturnedChat.Say(murderer, "You recieved" + " " + Configuration.Instance.Arm + " " + Uconomy.Instance.Configuration.Instance.MoneyName + " " + "for getting an arm punch kill!", Color.green); } } else if (limb == ELimb.RIGHT_LEG || limb == ELimb.LEFT_LEG || limb == ELimb.LEFT_FOOT || limb == ELimb.RIGHT_FOOT) { UnturnedChat.Say(UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "HP:" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "%" + ", " + Configuration.Instance.punch + " " + player.CharacterName + ", " + Configuration.Instance.punch2, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); if (Configuration.Instance.UconomyEnabled) { UnturnedChat.Say(murderer, "You recieved" + " " + Configuration.Instance.Leg + " " + Uconomy.Instance.Configuration.Instance.MoneyName + " " + "for getting a leg punch kill!", Color.green); } } else UnturnedChat.Say(UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "HP:" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "%" + ", " + Configuration.Instance.punch + " " + player.CharacterName + ", " + Configuration.Instance.punch2, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "SHRED") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.shred, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "ROADKILL") { UnturnedChat.Say(UnturnedPlayer.FromCSteamID(murderer).CharacterName + ", " + "HP:" + " " + UnturnedPlayer.FromCSteamID(murderer).Health.ToString() + "%" + ", " + Configuration.Instance.roadkill + " " + player.CharacterName + ", " + Configuration.Instance.usinga + " " + Rocket.Unturned.Player.UnturnedPlayer.FromCSteamID(murderer).CurrentVehicle.asset.vehicleName.ToString() + "!", UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); if (Configuration.Instance.UconomyEnabled) { UnturnedChat.Say(murderer, "You recieved" + " " + Configuration.Instance.Roadkill + " " + Uconomy.Instance.Configuration.Instance.MoneyName + " " + "for roadkill!", Color.green); } } else if (cause.ToString() == "SPARK") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.spark, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "VEHICLE") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.vehicle, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "FOOD") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.food, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "WATER") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.water, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "INFECTION") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.infection, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "BLEEDING") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.bleeding, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "LANDMINE") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.landmine, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "BREATH") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.breath, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "GRENADE") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.grenade, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "FREEZING") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.freezing, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "SENTRY") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.sentry, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "CHARGE") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.charge, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "MISSILE") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.missile, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "BONES") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.bones, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "SPLASH") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.splash, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "ACID") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.acid, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "SPIT") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.spit, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "BURNING") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.fire, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "BURNER") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.fire, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "BOULDER") { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.boulder, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } else if (cause.ToString() == "SUICIDE" && Configuration.Instance.suicidemsg) { UnturnedChat.Say(player.CharacterName + " " + Configuration.Instance.suicide, UnturnedChat.GetColorFromName(Configuration.Instance.messagecolour, Color.red)); } bool suicided = cause.ToString() == "SUICIDE"; if (limb == ELimb.SKULL && !suicided) { Part = ("head"); } else if (limb == ELimb.SPINE) { Part = ("body"); } else if (limb == ELimb.LEFT_ARM || limb == ELimb.RIGHT_ARM || limb == ELimb.LEFT_HAND || limb == ELimb.RIGHT_HAND) { Part = ("arm"); } else if (limb == ELimb.LEFT_LEG || limb == ELimb.RIGHT_LEG || limb == ELimb.LEFT_FOOT || limb == ELimb.RIGHT_FOOT) { Part = ("leg"); } if (Configuration.Instance.UconomyEnabled) { try { { { int value = 0; if (Part == "head") { value = Configuration.Instance.Head; } else if (Part == "body") { value = Configuration.Instance.Body; } else if (Part == "arm") { value = Configuration.Instance.Arm; } else if (Part == "leg") { value = Configuration.Instance.Leg; } else if (cause.ToString() == "ROADKILL") { value = Configuration.Instance.Roadkill; } else { Rocket.Core.Logging.Logger.LogWarning(""); } Uconomy.Instance.Database.IncreaseBalance(murderer3.CSteamID.ToString(), value); }; } } catch (Exception e) { Rocket.Core.Logging.Logger.LogError(e.Message); } } if (Configuration.Instance.ExperienceEnabled) { try { uint num1 = 0u; if (Part == "head") { num1 = Configuration.Instance.ExpHead; } else if (Part == "body") { num1 = Configuration.Instance.ExpBody; } else if (Part == "arm") { num1 = Configuration.Instance.ExpArm; } else if (Part == "leg") { num1 = Configuration.Instance.ExpLeg; } else { num1 = 0; } UnturnedPlayer exp = murderer3; exp.Experience = +num1; } catch (Exception e) { Rocket.Core.Logging.Logger.LogError(e.Message); } } } protected override void Unload() { UnturnedPlayerEvents.OnPlayerDeath -= UnturnedPlayerEvents_OnPlayerDeath; UnturnedPlayerEvents.OnPlayerUpdateHealth -= UnturnedPlayerEvents_OnPlayerUpdateHealth; } public void UnturnedPlayerEvents_OnPlayerUpdateHealth(UnturnedPlayer player, byte health) { if (this.Configuration.Instance.healthwarningmsg) { if (health == 25) { UnturnedChat.Say(player, Configuration.Instance.warning1, Color.yellow); UnturnedChat.Say(player, Configuration.Instance.warning2, Color.yellow); } } } } }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Grpc.Core; using Grpc.Core.Internal; using Grpc.Core.Profiling; using Grpc.Core.Utils; using NUnit.Framework; namespace Grpc.Core.Tests { public class ClientServerTest { const string Host = "127.0.0.1"; MockServiceHelper helper; Server server; Channel channel; [SetUp] public void Init() { helper = new MockServiceHelper(Host); server = helper.GetServer(); server.Start(); channel = helper.GetChannel(); } [TearDown] public void Cleanup() { channel.ShutdownAsync().Wait(); server.ShutdownAsync().Wait(); } [Test] public async Task UnaryCall() { helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { return Task.FromResult(request); }); Assert.AreEqual("ABC", Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "ABC")); Assert.AreEqual("ABC", await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "ABC")); Assert.AreEqual("ABC", await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "ABC").ConfigureAwait(false)); } [Test] public void UnaryCall_ServerHandlerThrows() { helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { throw new Exception("This was thrown on purpose by a test"); }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unknown, ex.Status.StatusCode); var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unknown, ex2.Status.StatusCode); } [Test] public void UnaryCall_ServerHandlerThrowsRpcException() { helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { throw new RpcException(new Status(StatusCode.Unauthenticated, "")); }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode); Assert.AreEqual(0, ex.Trailers.Count); var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode); Assert.AreEqual(0, ex.Trailers.Count); } [Test] public void UnaryCall_ServerHandlerThrowsRpcExceptionWithTrailers() { helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { var trailers = new Metadata { {"xyz", "xyz-value"} }; throw new RpcException(new Status(StatusCode.Unauthenticated, ""), trailers); }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode); Assert.AreEqual(1, ex.Trailers.Count); Assert.AreEqual("xyz", ex.Trailers[0].Key); Assert.AreEqual("xyz-value", ex.Trailers[0].Value); var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode); Assert.AreEqual(1, ex2.Trailers.Count); Assert.AreEqual("xyz", ex2.Trailers[0].Key); Assert.AreEqual("xyz-value", ex2.Trailers[0].Value); } [Test] public void UnaryCall_ServerHandlerSetsStatus() { helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { context.Status = new Status(StatusCode.Unauthenticated, ""); return Task.FromResult(""); }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode); Assert.AreEqual(0, ex.Trailers.Count); var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode); Assert.AreEqual(0, ex2.Trailers.Count); } [Test] public void UnaryCall_StatusDebugErrorStringNotTransmittedFromServer() { helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { context.Status = new Status(StatusCode.Unauthenticated, "", new CoreErrorDetailException("this DebugErrorString value should not be transmitted to the client")); return Task.FromResult(""); }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode); StringAssert.Contains("Error received from peer", ex.Status.DebugException.Message, "Is \"Error received from peer\" still a valid substring to search for in the client-generated error message from C-core?"); Assert.AreEqual(0, ex.Trailers.Count); var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode); StringAssert.Contains("Error received from peer", ex2.Status.DebugException.Message, "Is \"Error received from peer\" still a valid substring to search for in the client-generated error message from C-core?"); Assert.AreEqual(0, ex2.Trailers.Count); } [Test] public void UnaryCall_ServerHandlerSetsStatusAndTrailers() { helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { context.Status = new Status(StatusCode.Unauthenticated, ""); context.ResponseTrailers.Add("xyz", "xyz-value"); return Task.FromResult(""); }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode); Assert.AreEqual(1, ex.Trailers.Count); Assert.AreEqual("xyz", ex.Trailers[0].Key); Assert.AreEqual("xyz-value", ex.Trailers[0].Value); var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode); Assert.AreEqual(1, ex2.Trailers.Count); Assert.AreEqual("xyz", ex2.Trailers[0].Key); Assert.AreEqual("xyz-value", ex2.Trailers[0].Value); } [Test] public async Task ClientStreamingCall() { helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) => { string result = ""; await requestStream.ForEachAsync((request) => { result += request; return TaskUtils.CompletedTask; }); await Task.Delay(100); return result; }); { var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall()); await call.RequestStream.WriteAllAsync(new string[] { "A", "B", "C" }); Assert.AreEqual("ABC", await call); Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); Assert.IsNotNull(call.GetTrailers()); } { var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall()); await call.RequestStream.WriteAllAsync(new string[] { "A", "B", "C" }); Assert.AreEqual("ABC", await call.ConfigureAwait(false)); Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); Assert.IsNotNull(call.GetTrailers()); } } [Test] public async Task ServerStreamingCall() { helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) => { await responseStream.WriteAllAsync(request.Split(new []{' '})); context.ResponseTrailers.Add("xyz", ""); }); var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), "A B C"); CollectionAssert.AreEqual(new string[] { "A", "B", "C" }, await call.ResponseStream.ToListAsync()); Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); Assert.AreEqual("xyz", call.GetTrailers()[0].Key); } [Test] public async Task ServerStreamingCall_EndOfStreamIsIdempotent() { helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>((request, responseStream, context) => TaskUtils.CompletedTask); var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), ""); Assert.IsFalse(await call.ResponseStream.MoveNext()); Assert.IsFalse(await call.ResponseStream.MoveNext()); } [Test] public void ServerStreamingCall_ErrorCanBeAwaitedTwice() { helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>((request, responseStream, context) => { context.Status = new Status(StatusCode.InvalidArgument, ""); return TaskUtils.CompletedTask; }); var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), ""); var ex = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseStream.MoveNext()); Assert.AreEqual(StatusCode.InvalidArgument, ex.Status.StatusCode); // attempting MoveNext again should result in throwing the same exception. var ex2 = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseStream.MoveNext()); Assert.AreEqual(StatusCode.InvalidArgument, ex2.Status.StatusCode); } [Test] public void ServerStreamingCall_TrailersFromMultipleSourcesGetConcatenated() { helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>((request, responseStream, context) => { context.ResponseTrailers.Add("xyz", "xyz-value"); throw new RpcException(new Status(StatusCode.InvalidArgument, ""), new Metadata { {"abc", "abc-value"} }); }); var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), ""); var ex = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseStream.MoveNext()); Assert.AreEqual(StatusCode.InvalidArgument, ex.Status.StatusCode); Assert.AreEqual(2, call.GetTrailers().Count); Assert.AreEqual(2, ex.Trailers.Count); Assert.AreEqual("xyz", ex.Trailers[0].Key); Assert.AreEqual("xyz-value", ex.Trailers[0].Value); Assert.AreEqual("abc", ex.Trailers[1].Key); Assert.AreEqual("abc-value", ex.Trailers[1].Value); } [Test] public async Task DuplexStreamingCall() { helper.DuplexStreamingHandler = new DuplexStreamingServerMethod<string, string>(async (requestStream, responseStream, context) => { while (await requestStream.MoveNext()) { await responseStream.WriteAsync(requestStream.Current); } context.ResponseTrailers.Add("xyz", "xyz-value"); }); var call = Calls.AsyncDuplexStreamingCall(helper.CreateDuplexStreamingCall()); await call.RequestStream.WriteAllAsync(new string[] { "A", "B", "C" }); CollectionAssert.AreEqual(new string[] { "A", "B", "C" }, await call.ResponseStream.ToListAsync()); Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); Assert.AreEqual("xyz-value", call.GetTrailers()[0].Value); } [Test] public async Task AsyncUnaryCall_EchoMetadata() { helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { foreach (Metadata.Entry metadataEntry in context.RequestHeaders) { if (metadataEntry.Key != "user-agent") { context.ResponseTrailers.Add(metadataEntry); } } return Task.FromResult(""); }); var headers = new Metadata { { "ascii-header", "abcdefg" }, { "binary-header-bin", new byte[] { 1, 2, 3, 0, 0xff } } }; var call = Calls.AsyncUnaryCall(helper.CreateUnaryCall(new CallOptions(headers: headers)), "ABC"); await call; Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); var trailers = call.GetTrailers(); Assert.AreEqual(2, trailers.Count); Assert.AreEqual(headers[0].Key, trailers[0].Key); Assert.AreEqual(headers[0].Value, trailers[0].Value); Assert.AreEqual(headers[1].Key, trailers[1].Key); CollectionAssert.AreEqual(headers[1].ValueBytes, trailers[1].ValueBytes); } [Test] public void UnknownMethodHandler() { var nonexistentMethod = new Method<string, string>( MethodType.Unary, MockServiceHelper.ServiceName, "NonExistentMethod", Marshallers.StringMarshaller, Marshallers.StringMarshaller); var callDetails = new CallInvocationDetails<string, string>(channel, nonexistentMethod, new CallOptions()); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(callDetails, "abc")); Assert.AreEqual(StatusCode.Unimplemented, ex.Status.StatusCode); } [Test] public void StatusDetailIsUtf8() { // some japanese and chinese characters var nonAsciiString = "\u30a1\u30a2\u30a3 \u62b5\u6297\u662f\u5f92\u52b3\u7684"; helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { context.Status = new Status(StatusCode.Unknown, nonAsciiString); return Task.FromResult(""); }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unknown, ex.Status.StatusCode); Assert.AreEqual(nonAsciiString, ex.Status.Detail); } [Test] public void ServerCallContext_PeerInfoPresent() { helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { return Task.FromResult(context.Peer); }); string peer = Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"); Assert.IsTrue(peer.Contains(Host)); } [Test] public void ServerCallContext_HostAndMethodPresent() { helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { Assert.IsTrue(context.Host.Contains(Host)); Assert.AreEqual("/tests.Test/Unary", context.Method); return Task.FromResult("PASS"); }); Assert.AreEqual("PASS", Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); } [Test] public void ServerCallContext_AuthContextNotPopulated() { helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { Assert.IsFalse(context.AuthContext.IsPeerAuthenticated); // 1) security_level: TSI_SECURITY_NONE // 2) transport_security_type: 'insecure' Assert.AreEqual(2, context.AuthContext.Properties.Count()); return Task.FromResult("PASS"); }); Assert.AreEqual("PASS", Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Linq.Expressions.Tests { public class ReferenceNotEqual : ReferenceEqualityTests { [Theory] [PerCompilationType(nameof(ReferenceObjectsData))] public void FalseOnSame(object item, bool useInterpreter) { Expression exp = Expression.ReferenceNotEqual( Expression.Constant(item, item.GetType()), Expression.Constant(item, item.GetType()) ); Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(ReferenceTypesData))] public void FalseOnBothNull(Type type, bool useInterpreter) { Expression exp = Expression.ReferenceNotEqual( Expression.Constant(null, type), Expression.Constant(null, type) ); Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(ReferenceObjectsData))] public void TrueIfLeftNull(object item, bool useInterpreter) { Expression exp = Expression.ReferenceNotEqual( Expression.Constant(null, item.GetType()), Expression.Constant(item, item.GetType()) ); Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(ReferenceObjectsData))] public void TrueIfRightNull(object item, bool useInterpreter) { Expression exp = Expression.ReferenceNotEqual( Expression.Constant(item, item.GetType()), Expression.Constant(null, item.GetType()) ); Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(DifferentObjects))] public void TrueIfDifferentObjectsAsObject(object x, object y, bool useInterpreter) { Expression exp = Expression.ReferenceNotEqual( Expression.Constant(x, typeof(object)), Expression.Constant(y, typeof(object)) ); Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(DifferentObjects))] public void TrueIfDifferentObjectsOwnType(object x, object y, bool useInterpreter) { Expression exp = Expression.ReferenceNotEqual( Expression.Constant(x), Expression.Constant(y) ); Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Theory] [MemberData(nameof(LeftValueType))] [MemberData(nameof(RightValueType))] [MemberData(nameof(BothValueType))] public void ThrowsOnValueTypeArguments(object x, object y) { Expression xExp = Expression.Constant(x); Expression yExp = Expression.Constant(y); Assert.Throws<InvalidOperationException>(() => Expression.ReferenceNotEqual(xExp, yExp)); } [Theory] [MemberData(nameof(UnassignablePairs))] public void ThrowsOnUnassignablePairs(object x, object y) { Expression xExp = Expression.Constant(x); Expression yExp = Expression.Constant(y); Assert.Throws<InvalidOperationException>(() => Expression.ReferenceNotEqual(xExp, yExp)); } [Theory] [PerCompilationType(nameof(ComparableValuesData))] public void FalseOnSameViaInterface(object item, bool useInterpreter) { Expression exp = Expression.ReferenceNotEqual( Expression.Constant(item, typeof(IComparable)), Expression.Constant(item, typeof(IComparable)) ); Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(DifferentComparableValues))] public void TrueOnDifferentViaInterface(object x, object y, bool useInterpreter) { Expression exp = Expression.ReferenceNotEqual( Expression.Constant(x, typeof(IComparable)), Expression.Constant(y, typeof(IComparable)) ); Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(ComparableReferenceTypesData))] public void FalseOnSameLeftViaInterface(object item, bool useInterpreter) { Expression exp = Expression.ReferenceNotEqual( Expression.Constant(item, typeof(IComparable)), Expression.Constant(item) ); Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(ComparableReferenceTypesData))] public void FalseOnSameRightViaInterface(object item, bool useInterpreter) { Expression exp = Expression.ReferenceNotEqual( Expression.Constant(item), Expression.Constant(item, typeof(IComparable)) ); Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Fact] public void CannotReduce() { Expression exp = Expression.ReferenceNotEqual(Expression.Constant(""), Expression.Constant("")); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public void ThrowsOnLeftNull() { Assert.Throws<ArgumentNullException>("left", () => Expression.ReferenceNotEqual(null, Expression.Constant(""))); } [Fact] public void ThrowsOnRightNull() { Assert.Throws<ArgumentNullException>("right", () => Expression.ReferenceNotEqual(Expression.Constant(""), null)); } [Fact] public static void ThrowsOnLeftUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<string>), "WriteOnly"); Assert.Throws<ArgumentException>("left", () => Expression.ReferenceNotEqual(value, Expression.Constant(""))); } [Fact] public static void ThrowsOnRightUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<string>), "WriteOnly"); Assert.Throws<ArgumentException>("right", () => Expression.ReferenceNotEqual(Expression.Constant(""), value)); } [Fact] public void Update() { Expression e1 = Expression.Constant("bar"); Expression e2 = Expression.Constant("foo"); Expression e3 = Expression.Constant("qux"); BinaryExpression ne = Expression.ReferenceNotEqual(e1, e2); Assert.Same(ne, ne.Update(e1, null, e2)); BinaryExpression ne1 = ne.Update(e1, null, e3); Assert.Equal(ExpressionType.NotEqual, ne1.NodeType); Assert.Same(e1, ne1.Left); Assert.Same(e3, ne1.Right); Assert.Null(ne1.Conversion); Assert.Null(ne1.Method); BinaryExpression ne2 = ne.Update(e3, null, e2); Assert.Equal(ExpressionType.NotEqual, ne2.NodeType); Assert.Same(e3, ne2.Left); Assert.Same(e2, ne2.Right); Assert.Null(ne2.Conversion); Assert.Null(ne2.Method); } } }
// // UserJobTile.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007-2008 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 Mono.Unix; using Gtk; using Hyena; using Hyena.Jobs; using Hyena.Gui; using Banshee.ServiceStack; namespace Banshee.Gui.Widgets { public class UserJobTile : Table { private Job job; private string [] icon_names; private string title; private string status; private Image icon; private Gdk.Pixbuf icon_pixbuf; private Label title_label; private Label status_label; private ProgressBar progress_bar; private Button cancel_button; private uint update_delay_id; private uint progress_bounce_id; Hyena.Widgets.HigMessageDialog cancel_dialog; public UserJobTile (Job job) : base (3, 2, false) { this.job = job; this.job.Updated += OnJobUpdated; BuildWidget (); UpdateFromJob (); } private void BuildWidget () { ThreadAssist.AssertInMainThread (); ColumnSpacing = 5; RowSpacing = 2; icon = new Image (); title_label = new Label (); title_label.Xalign = 0.0f; title_label.Ellipsize = Pango.EllipsizeMode.End; status_label = new Label (); status_label.Xalign = 0.0f; status_label.Ellipsize = Pango.EllipsizeMode.End; progress_bar = new ProgressBar (); progress_bar.SetSizeRequest (0, -1); progress_bar.Text = " "; progress_bar.Show (); cancel_button = new Button (new Image (Stock.Stop, IconSize.Menu)); cancel_button.Relief = ReliefStyle.None; cancel_button.ShowAll (); cancel_button.Clicked += OnCancelClicked; Attach (title_label, 0, 3, 0, 1, AttachOptions.Expand | AttachOptions.Fill, AttachOptions.Expand | AttachOptions.Fill, 0, 0); Attach (status_label, 0, 3, 1, 2, AttachOptions.Expand | AttachOptions.Fill, AttachOptions.Expand | AttachOptions.Fill, 0, 0); Attach (icon, 0, 1, 2, 3, AttachOptions.Shrink | AttachOptions.Fill, AttachOptions.Shrink | AttachOptions.Fill, 0, 0); Attach (progress_bar, 1, 2, 2, 3, AttachOptions.Expand | AttachOptions.Fill, AttachOptions.Shrink, 0, 0); Attach (cancel_button, 2, 3, 2, 3, AttachOptions.Shrink | AttachOptions.Fill, AttachOptions.Shrink | AttachOptions.Fill, 0, 0); } protected override void OnStyleUpdated () { base.OnStyleUpdated (); UpdateIcons (); } private void OnCancelClicked (object o, EventArgs args) { if (cancel_dialog != null) { return; } Window parent = null; if (ServiceManager.Contains<GtkElementsService> ()) { parent = ServiceManager.Get<GtkElementsService> ().PrimaryWindow; } cancel_dialog = new Hyena.Widgets.HigMessageDialog (parent, DialogFlags.Modal, MessageType.Question, ButtonsType.None, job.Title == null ? Catalog.GetString ("Stop Operation") : String.Format (Catalog.GetString ("Stop {0}"), job.Title), job.CancelMessage == null ? (job.Title == null ? Catalog.GetString ("This operation is still performing work. Would you like to stop it?") : String.Format (Catalog.GetString ( "The '{0}' operation is still performing work. Would you like to stop it?"), job.Title)) : job.CancelMessage); cancel_dialog.AddButton (job.Title == null ? Catalog.GetString ("Continue") : String.Format (Catalog.GetString ("Continue {0}"), job.Title), ResponseType.No, true); cancel_dialog.AddButton (Stock.Stop, ResponseType.Yes, false); cancel_dialog.DefaultResponse = ResponseType.Cancel; if (cancel_dialog.Run () == (int)ResponseType.Yes) { if (job.CanCancel) { ServiceManager.JobScheduler.Cancel (job); } } cancel_dialog.Destroy (); cancel_dialog = null; } private void SetTitle (string new_title) { if (String.IsNullOrEmpty (new_title)) { title_label.Hide (); } else { title_label.Markup = String.Format ("<small><b>{0}</b></small>", GLib.Markup.EscapeText (new_title)); title_label.Show (); } title = new_title; } private bool never_had_status = true; private void UpdateFromJob () { ThreadAssist.AssertInMainThread (); if (cancel_dialog != null && !job.CanCancel) { cancel_dialog.Respond (Gtk.ResponseType.Cancel); } if (job.IsCancelRequested) { SetTitle (Catalog.GetString ("Stopping...")); } else if (title != job.Title) { SetTitle (job.Title); } if (status != job.Status) { // If we've ever had the status in this job, don't hide it b/c that'll make // the tile change width, possibly repeatedly and annoyingly if (String.IsNullOrEmpty (job.Status) && never_had_status) { status_label.Hide (); } else { never_had_status = false; status_label.Markup = String.Format ("<small>{0}</small>", GLib.Markup.EscapeText (job.Status ?? String.Empty)); status_label.TooltipText = job.Status ?? String.Empty; status_label.Show (); } status = job.Status; } if (icon_names == null || icon_names.Length != job.IconNames.Length) { UpdateIcons (); } else { for (int i = 0; i < job.IconNames.Length; i++) { if (icon_names[i] != job.IconNames[i]) { UpdateIcons (); break; } } } cancel_button.Sensitive = job.CanCancel && !job.IsCancelRequested; if (job.Progress == 0 && progress_bounce_id > 0) { return; } progress_bar.Fraction = job.Progress; if (job.Progress == 0.0 && progress_bounce_id == 0) { progress_bounce_id = GLib.Timeout.Add (100, delegate { progress_bar.Text = " "; progress_bar.Pulse (); return true; }); } else if (job.Progress > 0.0) { if (progress_bounce_id > 0) { GLib.Source.Remove (progress_bounce_id); progress_bounce_id = 0; } progress_bar.Text = String.Format("{0}%", (int)(job.Progress * 100.0)); } } private void UpdateIcons () { icon_names = job.IconNames; if (icon_pixbuf != null) { icon_pixbuf.Dispose (); icon_pixbuf = null; } if (icon_names == null || icon_names.Length == 0) { icon.Hide (); return; } icon_pixbuf = IconThemeUtils.LoadIcon (22, icon_names); if (icon_pixbuf != null) { icon.Pixbuf = icon_pixbuf; icon.Show (); return; } try { icon_pixbuf = new Gdk.Pixbuf (icon_names[0]); } catch (GLib.GException) {} if (icon_pixbuf != null) { Gdk.Pixbuf scaled = icon_pixbuf.ScaleSimple (22, 22, Gdk.InterpType.Bilinear); icon_pixbuf.Dispose (); icon.Pixbuf = scaled; icon.Show (); } } private void OnJobUpdated (object o, EventArgs args) { if (update_delay_id == 0) { GLib.Timeout.Add (100, UpdateFromJobTimeout); } } private bool UpdateFromJobTimeout () { UpdateFromJob (); update_delay_id = 0; return false; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.IO.Compression; using System.Net; using System.Net.Security; using System.Reflection; using System.Text; using System.Web; using System.Xml; using System.Xml.Serialization; using System.Xml.Linq; using log4net; using Nwc.XmlRpc; using OpenMetaverse.StructuredData; using XMLResponseHelper = OpenSim.Framework.SynchronousRestObjectRequester.XMLResponseHelper; using OpenSim.Framework.ServiceAuth; namespace OpenSim.Framework { /// <summary> /// Miscellaneous static methods and extension methods related to the web /// </summary> public static class WebUtil { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Control the printing of certain debug messages. /// </summary> /// <remarks> /// If DebugLevel >= 3 then short notices about outgoing HTTP requests are logged. /// </remarks> public static int DebugLevel { get; set; } /// <summary> /// Request number for diagnostic purposes. /// </summary> public static int RequestNumber { get; set; } /// <summary> /// Control where OSD requests should be serialized per endpoint. /// </summary> public static bool SerializeOSDRequestsPerEndpoint { get; set; } /// <summary> /// this is the header field used to communicate the local request id /// used for performance and debugging /// </summary> public const string OSHeaderRequestID = "opensim-request-id"; /// <summary> /// Number of milliseconds a call can take before it is considered /// a "long" call for warning & debugging purposes /// </summary> public const int LongCallTime = 3000; /// <summary> /// The maximum length of any data logged because of a long request time. /// </summary> /// <remarks> /// This is to truncate any really large post data, such as an asset. In theory, the first section should /// give us useful information about the call (which agent it relates to if applicable, etc.). /// This is also used to truncate messages when using DebugLevel 5. /// </remarks> public const int MaxRequestDiagLength = 200; /// <summary> /// Dictionary of end points /// </summary> private static Dictionary<string,object> m_endpointSerializer = new Dictionary<string,object>(); private static object EndPointLock(string url) { System.Uri uri = new System.Uri(url); string endpoint = string.Format("{0}:{1}",uri.Host,uri.Port); lock (m_endpointSerializer) { object eplock = null; if (! m_endpointSerializer.TryGetValue(endpoint,out eplock)) { eplock = new object(); m_endpointSerializer.Add(endpoint,eplock); // m_log.WarnFormat("[WEB UTIL] add a new host to end point serializer {0}",endpoint); } return eplock; } } #region JSONRequest /// <summary> /// PUT JSON-encoded data to a web service that returns LLSD or /// JSON data /// </summary> public static OSDMap PutToServiceCompressed(string url, OSDMap data, int timeout) { return ServiceOSDRequest(url,data, "PUT", timeout, true, false); } public static OSDMap PutToService(string url, OSDMap data, int timeout) { return ServiceOSDRequest(url,data, "PUT", timeout, false, false); } public static OSDMap PostToService(string url, OSDMap data, int timeout, bool rpc) { return ServiceOSDRequest(url, data, "POST", timeout, false, rpc); } public static OSDMap PostToServiceCompressed(string url, OSDMap data, int timeout) { return ServiceOSDRequest(url, data, "POST", timeout, true, false); } public static OSDMap GetFromService(string url, int timeout) { return ServiceOSDRequest(url, null, "GET", timeout, false, false); } public static OSDMap ServiceOSDRequest(string url, OSDMap data, string method, int timeout, bool compressed, bool rpc) { if (SerializeOSDRequestsPerEndpoint) { lock (EndPointLock(url)) { return ServiceOSDRequestWorker(url, data, method, timeout, compressed, rpc); } } else { return ServiceOSDRequestWorker(url, data, method, timeout, compressed, rpc); } } public static void LogOutgoingDetail(Stream outputStream) { LogOutgoingDetail("", outputStream); } public static void LogOutgoingDetail(string context, Stream outputStream) { using (Stream stream = Util.Copy(outputStream)) using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { string output; if (DebugLevel == 5) { char[] chars = new char[WebUtil.MaxRequestDiagLength + 1]; // +1 so we know to add "..." only if needed int len = reader.Read(chars, 0, WebUtil.MaxRequestDiagLength + 1); output = new string(chars, 0, len); } else { output = reader.ReadToEnd(); } LogOutgoingDetail(context, output); } } public static void LogOutgoingDetail(string type, int reqnum, string output) { LogOutgoingDetail(string.Format("{0} {1}: ", type, reqnum), output); } public static void LogOutgoingDetail(string context, string output) { if (DebugLevel == 5) { if (output.Length > MaxRequestDiagLength) output = output.Substring(0, MaxRequestDiagLength) + "..."; } m_log.DebugFormat("[LOGHTTP]: {0}{1}", context, Util.BinaryToASCII(output)); } public static void LogResponseDetail(int reqnum, Stream inputStream) { LogOutgoingDetail(string.Format("RESPONSE {0}: ", reqnum), inputStream); } public static void LogResponseDetail(int reqnum, string input) { LogOutgoingDetail(string.Format("RESPONSE {0}: ", reqnum), input); } private static OSDMap ServiceOSDRequestWorker(string url, OSDMap data, string method, int timeout, bool compressed, bool rpc) { int reqnum = RequestNumber++; if (DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} JSON-RPC {1} to {2}", reqnum, method, url); string errorMessage = "unknown error"; int tickstart = Util.EnvironmentTickCount(); int tickdata = 0; string strBuffer = null; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = method; request.Timeout = timeout; request.KeepAlive = false; request.MaximumAutomaticRedirections = 10; request.ReadWriteTimeout = timeout / 4; request.Headers[OSHeaderRequestID] = reqnum.ToString(); // If there is some input, write it into the request if (data != null) { strBuffer = OSDParser.SerializeJsonString(data); if (DebugLevel >= 5) LogOutgoingDetail("SEND", reqnum, strBuffer); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strBuffer); request.ContentType = rpc ? "application/json-rpc" : "application/json"; if (compressed) { request.Headers["X-Content-Encoding"] = "gzip"; // can't set "Content-Encoding" because old OpenSims fail if they get an unrecognized Content-Encoding using (MemoryStream ms = new MemoryStream()) { using (GZipStream comp = new GZipStream(ms, CompressionMode.Compress, true)) { comp.Write(buffer, 0, buffer.Length); // We need to close the gzip stream before we write it anywhere // because apparently something important related to gzip compression // gets written on the stream upon Dispose() } byte[] buf = ms.ToArray(); request.ContentLength = buf.Length; //Count bytes to send using (Stream requestStream = request.GetRequestStream()) requestStream.Write(buf, 0, (int)buf.Length); } } else { request.ContentLength = buffer.Length; //Count bytes to send using (Stream requestStream = request.GetRequestStream()) requestStream.Write(buffer, 0, buffer.Length); //Send it } } // capture how much time was spent writing, this may seem silly // but with the number concurrent requests, this often blocks tickdata = Util.EnvironmentTickCountSubtract(tickstart); using (WebResponse response = request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { string responseStr = reader.ReadToEnd(); if (WebUtil.DebugLevel >= 5) WebUtil.LogResponseDetail(reqnum, responseStr); return CanonicalizeResults(responseStr); } } } } catch (WebException we) { errorMessage = we.Message; if (we.Status == WebExceptionStatus.ProtocolError) { using (HttpWebResponse webResponse = (HttpWebResponse)we.Response) errorMessage = String.Format("[{0}] {1}", webResponse.StatusCode, webResponse.StatusDescription); } } catch (Exception ex) { errorMessage = ex.Message; } finally { int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); if (tickdiff > LongCallTime) { m_log.InfoFormat( "[LOGHTTP]: Slow JSON-RPC request {0} {1} to {2} took {3}ms, {4}ms writing, {5}", reqnum, method, url, tickdiff, tickdata, strBuffer != null ? (strBuffer.Length > MaxRequestDiagLength ? strBuffer.Remove(MaxRequestDiagLength) : strBuffer) : ""); } else if (DebugLevel >= 4) { m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing", reqnum, tickdiff, tickdata); } } m_log.DebugFormat( "[LOGHTTP]: JSON-RPC request {0} {1} to {2} FAILED: {3}", reqnum, method, url, errorMessage); return ErrorResponseMap(errorMessage); } /// <summary> /// Since there are no consistencies in the way web requests are /// formed, we need to do a little guessing about the result format. /// Keys: /// Success|success == the success fail of the request /// _RawResult == the raw string that came back /// _Result == the OSD unpacked string /// </summary> private static OSDMap CanonicalizeResults(string response) { OSDMap result = new OSDMap(); // Default values result["Success"] = OSD.FromBoolean(true); result["success"] = OSD.FromBoolean(true); result["_RawResult"] = OSD.FromString(response); result["_Result"] = new OSDMap(); if (response.Equals("true",System.StringComparison.OrdinalIgnoreCase)) return result; if (response.Equals("false",System.StringComparison.OrdinalIgnoreCase)) { result["Success"] = OSD.FromBoolean(false); result["success"] = OSD.FromBoolean(false); return result; } try { OSD responseOSD = OSDParser.Deserialize(response); if (responseOSD.Type == OSDType.Map) { result["_Result"] = (OSDMap)responseOSD; return result; } } catch { // don't need to treat this as an error... we're just guessing anyway // m_log.DebugFormat("[WEB UTIL] couldn't decode <{0}>: {1}",response,e.Message); } return result; } #endregion JSONRequest #region FormRequest /// <summary> /// POST URL-encoded form data to a web service that returns LLSD or /// JSON data /// </summary> public static OSDMap PostToService(string url, NameValueCollection data) { return ServiceFormRequest(url,data,10000); } public static OSDMap ServiceFormRequest(string url, NameValueCollection data, int timeout) { lock (EndPointLock(url)) { return ServiceFormRequestWorker(url,data,timeout); } } private static OSDMap ServiceFormRequestWorker(string url, NameValueCollection data, int timeout) { int reqnum = RequestNumber++; string method = (data != null && data["RequestMethod"] != null) ? data["RequestMethod"] : "unknown"; if (DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} ServiceForm '{1}' to {2}", reqnum, method, url); string errorMessage = "unknown error"; int tickstart = Util.EnvironmentTickCount(); int tickdata = 0; string queryString = null; try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "POST"; request.Timeout = timeout; request.KeepAlive = false; request.MaximumAutomaticRedirections = 10; request.ReadWriteTimeout = timeout / 4; request.Headers[OSHeaderRequestID] = reqnum.ToString(); if (data != null) { queryString = BuildQueryString(data); if (DebugLevel >= 5) LogOutgoingDetail("SEND", reqnum, queryString); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(queryString); request.ContentLength = buffer.Length; request.ContentType = "application/x-www-form-urlencoded"; using (Stream requestStream = request.GetRequestStream()) requestStream.Write(buffer, 0, buffer.Length); } // capture how much time was spent writing, this may seem silly // but with the number concurrent requests, this often blocks tickdata = Util.EnvironmentTickCountSubtract(tickstart); using (WebResponse response = request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { string responseStr = reader.ReadToEnd(); if (WebUtil.DebugLevel >= 5) WebUtil.LogResponseDetail(reqnum, responseStr); OSD responseOSD = OSDParser.Deserialize(responseStr); if (responseOSD.Type == OSDType.Map) return (OSDMap)responseOSD; } } } } catch (WebException we) { errorMessage = we.Message; if (we.Status == WebExceptionStatus.ProtocolError) { using (HttpWebResponse webResponse = (HttpWebResponse)we.Response) errorMessage = String.Format("[{0}] {1}",webResponse.StatusCode,webResponse.StatusDescription); } } catch (Exception ex) { errorMessage = ex.Message; } finally { int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); if (tickdiff > LongCallTime) { m_log.InfoFormat( "[LOGHTTP]: Slow ServiceForm request {0} '{1}' to {2} took {3}ms, {4}ms writing, {5}", reqnum, method, url, tickdiff, tickdata, queryString != null ? (queryString.Length > MaxRequestDiagLength) ? queryString.Remove(MaxRequestDiagLength) : queryString : ""); } else if (DebugLevel >= 4) { m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing", reqnum, tickdiff, tickdata); } } m_log.WarnFormat("[LOGHTTP]: ServiceForm request {0} '{1}' to {2} failed: {3}", reqnum, method, url, errorMessage); return ErrorResponseMap(errorMessage); } /// <summary> /// Create a response map for an error, trying to keep /// the result formats consistent /// </summary> private static OSDMap ErrorResponseMap(string msg) { OSDMap result = new OSDMap(); result["Success"] = "False"; result["Message"] = OSD.FromString("Service request failed: " + msg); return result; } #endregion FormRequest #region Uri /// <summary> /// Combines a Uri that can contain both a base Uri and relative path /// with a second relative path fragment /// </summary> /// <param name="uri">Starting (base) Uri</param> /// <param name="fragment">Relative path fragment to append to the end /// of the Uri</param> /// <returns>The combined Uri</returns> /// <remarks>This is similar to the Uri constructor that takes a base /// Uri and the relative path, except this method can append a relative /// path fragment on to an existing relative path</remarks> public static Uri Combine(this Uri uri, string fragment) { string fragment1 = uri.Fragment; string fragment2 = fragment; if (!fragment1.EndsWith("/")) fragment1 = fragment1 + '/'; if (fragment2.StartsWith("/")) fragment2 = fragment2.Substring(1); return new Uri(uri, fragment1 + fragment2); } /// <summary> /// Combines a Uri that can contain both a base Uri and relative path /// with a second relative path fragment. If the fragment is absolute, /// it will be returned without modification /// </summary> /// <param name="uri">Starting (base) Uri</param> /// <param name="fragment">Relative path fragment to append to the end /// of the Uri, or an absolute Uri to return unmodified</param> /// <returns>The combined Uri</returns> public static Uri Combine(this Uri uri, Uri fragment) { if (fragment.IsAbsoluteUri) return fragment; string fragment1 = uri.Fragment; string fragment2 = fragment.ToString(); if (!fragment1.EndsWith("/")) fragment1 = fragment1 + '/'; if (fragment2.StartsWith("/")) fragment2 = fragment2.Substring(1); return new Uri(uri, fragment1 + fragment2); } /// <summary> /// Appends a query string to a Uri that may or may not have existing /// query parameters /// </summary> /// <param name="uri">Uri to append the query to</param> /// <param name="query">Query string to append. Can either start with ? /// or just containg key/value pairs</param> /// <returns>String representation of the Uri with the query string /// appended</returns> public static string AppendQuery(this Uri uri, string query) { if (String.IsNullOrEmpty(query)) return uri.ToString(); if (query[0] == '?' || query[0] == '&') query = query.Substring(1); string uriStr = uri.ToString(); if (uriStr.Contains("?")) return uriStr + '&' + query; else return uriStr + '?' + query; } #endregion Uri #region NameValueCollection /// <summary> /// Convert a NameValueCollection into a query string. This is the /// inverse of HttpUtility.ParseQueryString() /// </summary> /// <param name="parameters">Collection of key/value pairs to convert</param> /// <returns>A query string with URL-escaped values</returns> public static string BuildQueryString(NameValueCollection parameters) { List<string> items = new List<string>(parameters.Count); foreach (string key in parameters.Keys) { string[] values = parameters.GetValues(key); if (values != null) { foreach (string value in values) items.Add(String.Concat(key, "=", HttpUtility.UrlEncode(value ?? String.Empty))); } } return String.Join("&", items.ToArray()); } /// <summary> /// /// </summary> /// <param name="collection"></param> /// <param name="key"></param> /// <returns></returns> public static string GetOne(this NameValueCollection collection, string key) { string[] values = collection.GetValues(key); if (values != null && values.Length > 0) return values[0]; return null; } #endregion NameValueCollection #region Stream /// <summary> /// Copies the contents of one stream to another, starting at the /// current position of each stream /// </summary> /// <param name="copyFrom">The stream to copy from, at the position /// where copying should begin</param> /// <param name="copyTo">The stream to copy to, at the position where /// bytes should be written</param> /// <param name="maximumBytesToCopy">The maximum bytes to copy</param> /// <returns>The total number of bytes copied</returns> /// <remarks> /// Copying begins at the streams' current positions. The positions are /// NOT reset after copying is complete. /// NOTE!! .NET 4.0 adds the method 'Stream.CopyTo(stream, bufferSize)'. /// This function could be replaced with that method once we move /// totally to .NET 4.0. For versions before, this routine exists. /// This routine used to be named 'CopyTo' but the int parameter has /// a different meaning so this method was renamed to avoid any confusion. /// </remarks> public static int CopyStream(this Stream copyFrom, Stream copyTo, int maximumBytesToCopy) { byte[] buffer = new byte[4096]; int readBytes; int totalCopiedBytes = 0; while ((readBytes = copyFrom.Read(buffer, 0, Math.Min(4096, maximumBytesToCopy))) > 0) { int writeBytes = Math.Min(maximumBytesToCopy, readBytes); copyTo.Write(buffer, 0, writeBytes); totalCopiedBytes += writeBytes; maximumBytesToCopy -= writeBytes; } return totalCopiedBytes; } #endregion Stream public class QBasedComparer : IComparer { public int Compare(Object x, Object y) { float qx = GetQ(x); float qy = GetQ(y); return qy.CompareTo(qx); // descending order } private float GetQ(Object o) { // Example: image/png;q=0.9 float qvalue = 1F; if (o is String) { string mime = (string)o; string[] parts = mime.Split(';'); if (parts.Length > 1) { string[] kvp = parts[1].Split('='); if (kvp.Length == 2 && kvp[0] == "q") float.TryParse(kvp[1], NumberStyles.Number, CultureInfo.InvariantCulture, out qvalue); } } return qvalue; } } /// <summary> /// Takes the value of an Accept header and returns the preferred types /// ordered by q value (if it exists). /// Example input: image/jpg;q=0.7, image/png;q=0.8, image/jp2 /// Exmaple output: ["jp2", "png", "jpg"] /// NOTE: This doesn't handle the semantics of *'s... /// </summary> /// <param name="accept"></param> /// <returns></returns> public static string[] GetPreferredImageTypes(string accept) { if (string.IsNullOrEmpty(accept)) return new string[0]; string[] types = accept.Split(new char[] { ',' }); if (types.Length > 0) { List<string> list = new List<string>(types); list.RemoveAll(delegate(string s) { return !s.ToLower().StartsWith("image"); }); ArrayList tlist = new ArrayList(list); tlist.Sort(new QBasedComparer()); string[] result = new string[tlist.Count]; for (int i = 0; i < tlist.Count; i++) { string mime = (string)tlist[i]; string[] parts = mime.Split(new char[] { ';' }); string[] pair = parts[0].Split(new char[] { '/' }); if (pair.Length == 2) result[i] = pair[1].ToLower(); else // oops, we don't know what this is... result[i] = pair[0]; } return result; } return new string[0]; } } public static class AsynchronousRestObjectRequester { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Perform an asynchronous REST request. /// </summary> /// <param name="verb">GET or POST</param> /// <param name="requestUrl"></param> /// <param name="obj"></param> /// <param name="action"></param> /// <returns></returns> /// /// <exception cref="System.Net.WebException">Thrown if we encounter a /// network issue while posting the request. You'll want to make /// sure you deal with this as they're not uncommon</exception> // public static void MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, Action<TResponse> action) { MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, action, 0); } public static void MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, Action<TResponse> action, int maxConnections) { MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, action, maxConnections, null); } public static void MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, Action<TResponse> action, int maxConnections, IServiceAuth auth) { int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} AsynchronousRequestObject {1} to {2}", reqnum, verb, requestUrl); int tickstart = Util.EnvironmentTickCount(); int tickdata = 0; Type type = typeof(TRequest); WebRequest request = WebRequest.Create(requestUrl); HttpWebRequest ht = (HttpWebRequest)request; if (auth != null) auth.AddAuthorization(ht.Headers); if (maxConnections > 0 && ht.ServicePoint.ConnectionLimit < maxConnections) ht.ServicePoint.ConnectionLimit = maxConnections; TResponse deserial = default(TResponse); request.Method = verb; MemoryStream buffer = null; try { if (verb == "POST") { request.ContentType = "text/xml"; buffer = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; using (XmlWriter writer = XmlWriter.Create(buffer, settings)) { XmlSerializer serializer = new XmlSerializer(type); serializer.Serialize(writer, obj); writer.Flush(); } int length = (int)buffer.Length; request.ContentLength = length; byte[] data = buffer.ToArray(); if (WebUtil.DebugLevel >= 5) WebUtil.LogOutgoingDetail("SEND", reqnum, System.Text.Encoding.UTF8.GetString(data)); request.BeginGetRequestStream(delegate(IAsyncResult res) { using (Stream requestStream = request.EndGetRequestStream(res)) requestStream.Write(data, 0, length); // capture how much time was spent writing tickdata = Util.EnvironmentTickCountSubtract(tickstart); request.BeginGetResponse(delegate(IAsyncResult ar) { using (WebResponse response = request.EndGetResponse(ar)) { try { using (Stream respStream = response.GetResponseStream()) { deserial = XMLResponseHelper.LogAndDeserialize<TRequest, TResponse>( reqnum, respStream, response.ContentLength); } } catch (System.InvalidOperationException) { } } action(deserial); }, null); }, null); } else { request.BeginGetResponse(delegate(IAsyncResult res2) { try { // If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't // documented in MSDN using (WebResponse response = request.EndGetResponse(res2)) { try { using (Stream respStream = response.GetResponseStream()) { deserial = XMLResponseHelper.LogAndDeserialize<TRequest, TResponse>( reqnum, respStream, response.ContentLength); } } catch (System.InvalidOperationException) { } } } catch (WebException e) { if (e.Status == WebExceptionStatus.ProtocolError) { if (e.Response is HttpWebResponse) { using (HttpWebResponse httpResponse = (HttpWebResponse)e.Response) { if (httpResponse.StatusCode != HttpStatusCode.NotFound) { // We don't appear to be handling any other status codes, so log these feailures to that // people don't spend unnecessary hours hunting phantom bugs. m_log.DebugFormat( "[ASYNC REQUEST]: Request {0} {1} failed with unexpected status code {2}", verb, requestUrl, httpResponse.StatusCode); } } } } else { m_log.ErrorFormat( "[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}", verb, requestUrl, e.Status, e.Message); } } catch (Exception e) { m_log.ErrorFormat( "[ASYNC REQUEST]: Request {0} {1} failed with exception {2}{3}", verb, requestUrl, e.Message, e.StackTrace); } // m_log.DebugFormat("[ASYNC REQUEST]: Received {0}", deserial.ToString()); try { action(deserial); } catch (Exception e) { m_log.ErrorFormat( "[ASYNC REQUEST]: Request {0} {1} callback failed with exception {2}{3}", verb, requestUrl, e.Message, e.StackTrace); } }, null); } int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); if (tickdiff > WebUtil.LongCallTime) { string originalRequest = null; if (buffer != null) { originalRequest = Encoding.UTF8.GetString(buffer.ToArray()); if (originalRequest.Length > WebUtil.MaxRequestDiagLength) originalRequest = originalRequest.Remove(WebUtil.MaxRequestDiagLength); } m_log.InfoFormat( "[LOGHTTP]: Slow AsynchronousRequestObject request {0} {1} to {2} took {3}ms, {4}ms writing, {5}", reqnum, verb, requestUrl, tickdiff, tickdata, originalRequest); } else if (WebUtil.DebugLevel >= 4) { m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing", reqnum, tickdiff, tickdata); } } finally { if (buffer != null) buffer.Dispose(); } } } public static class SynchronousRestFormsRequester { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Perform a synchronous REST request. /// </summary> /// <param name="verb"></param> /// <param name="requestUrl"></param> /// <param name="obj"> </param> /// <param name="timeoutsecs"> </param> /// <returns></returns> /// /// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting /// the request. You'll want to make sure you deal with this as they're not uncommon</exception> public static string MakeRequest(string verb, string requestUrl, string obj, int timeoutsecs, IServiceAuth auth) { int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} SynchronousRestForms {1} to {2}", reqnum, verb, requestUrl); int tickstart = Util.EnvironmentTickCount(); int tickdata = 0; WebRequest request = WebRequest.Create(requestUrl); request.Method = verb; if (timeoutsecs > 0) request.Timeout = timeoutsecs * 1000; if (auth != null) auth.AddAuthorization(request.Headers); string respstring = String.Empty; using (MemoryStream buffer = new MemoryStream()) { if ((verb == "POST") || (verb == "PUT")) { request.ContentType = "application/x-www-form-urlencoded"; int length = 0; using (StreamWriter writer = new StreamWriter(buffer)) { writer.Write(obj); writer.Flush(); } length = (int)obj.Length; request.ContentLength = length; byte[] data = buffer.ToArray(); if (WebUtil.DebugLevel >= 5) WebUtil.LogOutgoingDetail("SEND", reqnum, System.Text.Encoding.UTF8.GetString(data)); Stream requestStream = null; try { requestStream = request.GetRequestStream(); requestStream.Write(data, 0, length); } catch (Exception e) { m_log.InfoFormat("[FORMS]: Error sending request to {0}: {1}. Request: {2}", requestUrl, e.Message, obj.Length > WebUtil.MaxRequestDiagLength ? obj.Remove(WebUtil.MaxRequestDiagLength) : obj); throw e; } finally { if (requestStream != null) requestStream.Dispose(); // capture how much time was spent writing tickdata = Util.EnvironmentTickCountSubtract(tickstart); } } try { using (WebResponse resp = request.GetResponse()) { if (resp.ContentLength != 0) { using (Stream respStream = resp.GetResponseStream()) using (StreamReader reader = new StreamReader(respStream)) respstring = reader.ReadToEnd(); } } } catch (Exception e) { m_log.InfoFormat("[FORMS]: Error receiving response from {0}: {1}. Request: {2}", requestUrl, e.Message, obj.Length > WebUtil.MaxRequestDiagLength ? obj.Remove(WebUtil.MaxRequestDiagLength) : obj); throw e; } } int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); if (tickdiff > WebUtil.LongCallTime) { m_log.InfoFormat( "[LOGHTTP]: Slow SynchronousRestForms request {0} {1} to {2} took {3}ms, {4}ms writing, {5}", reqnum, verb, requestUrl, tickdiff, tickdata, obj.Length > WebUtil.MaxRequestDiagLength ? obj.Remove(WebUtil.MaxRequestDiagLength) : obj); } else if (WebUtil.DebugLevel >= 4) { m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing", reqnum, tickdiff, tickdata); } if (WebUtil.DebugLevel >= 5) WebUtil.LogResponseDetail(reqnum, respstring); return respstring; } public static string MakeRequest(string verb, string requestUrl, string obj, int timeoutsecs) { return MakeRequest(verb, requestUrl, obj, timeoutsecs, null); } public static string MakeRequest(string verb, string requestUrl, string obj) { return MakeRequest(verb, requestUrl, obj, -1); } public static string MakeRequest(string verb, string requestUrl, string obj, IServiceAuth auth) { return MakeRequest(verb, requestUrl, obj, -1, auth); } } public class SynchronousRestObjectRequester { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Perform a synchronous REST request. /// </summary> /// <param name="verb"></param> /// <param name="requestUrl"></param> /// <param name="obj"></param> /// <returns> /// The response. If there was an internal exception, then the default(TResponse) is returned. /// </returns> public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj) { return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, 0); } public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, IServiceAuth auth) { return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, 0, auth); } /// <summary> /// Perform a synchronous REST request. /// </summary> /// <param name="verb"></param> /// <param name="requestUrl"></param> /// <param name="obj"></param> /// <param name="pTimeout"> /// Request timeout in milliseconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default HttpWebRequest timeout is used (100 seconds) /// </param> /// <returns> /// The response. If there was an internal exception or the request timed out, /// then the default(TResponse) is returned. /// </returns> public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout) { return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, pTimeout, 0); } public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout, IServiceAuth auth) { return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, pTimeout, 0, auth); } /// Perform a synchronous REST request. /// </summary> /// <param name="verb"></param> /// <param name="requestUrl"></param> /// <param name="obj"></param> /// <param name="pTimeout"> /// Request timeout in milliseconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default HttpWebRequest timeout is used (100 seconds) /// </param> /// <param name="maxConnections"></param> /// <returns> /// The response. If there was an internal exception or the request timed out, /// then the default(TResponse) is returned. /// </returns> public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout, int maxConnections) { return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, pTimeout, maxConnections, null); } /// <summary> /// Perform a synchronous REST request. /// </summary> /// <param name="verb"></param> /// <param name="requestUrl"></param> /// <param name="obj"></param> /// <param name="pTimeout"> /// Request timeout in milliseconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default HttpWebRequest timeout is used (100 seconds) /// </param> /// <param name="maxConnections"></param> /// <returns> /// The response. If there was an internal exception or the request timed out, /// then the default(TResponse) is returned. /// </returns> public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout, int maxConnections, IServiceAuth auth) { int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} SynchronousRestObject {1} to {2}", reqnum, verb, requestUrl); int tickstart = Util.EnvironmentTickCount(); int tickdata = 0; Type type = typeof(TRequest); TResponse deserial = default(TResponse); WebRequest request = WebRequest.Create(requestUrl); HttpWebRequest ht = (HttpWebRequest)request; if (auth != null) auth.AddAuthorization(ht.Headers); if (pTimeout != 0) ht.Timeout = pTimeout; if (maxConnections > 0 && ht.ServicePoint.ConnectionLimit < maxConnections) ht.ServicePoint.ConnectionLimit = maxConnections; request.Method = verb; MemoryStream buffer = null; try { if ((verb == "POST") || (verb == "PUT")) { request.ContentType = "text/xml"; buffer = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; using (XmlWriter writer = XmlWriter.Create(buffer, settings)) { XmlSerializer serializer = new XmlSerializer(type); serializer.Serialize(writer, obj); writer.Flush(); } int length = (int)buffer.Length; request.ContentLength = length; byte[] data = buffer.ToArray(); if (WebUtil.DebugLevel >= 5) WebUtil.LogOutgoingDetail("SEND", reqnum, System.Text.Encoding.UTF8.GetString(data)); try { using (Stream requestStream = request.GetRequestStream()) requestStream.Write(data, 0, length); } catch (Exception e) { m_log.DebugFormat( "[SynchronousRestObjectRequester]: Exception in making request {0} {1}: {2}{3}", verb, requestUrl, e.Message, e.StackTrace); return deserial; } finally { // capture how much time was spent writing tickdata = Util.EnvironmentTickCountSubtract(tickstart); } } try { using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse()) { if (resp.ContentLength != 0) { using (Stream respStream = resp.GetResponseStream()) { deserial = XMLResponseHelper.LogAndDeserialize<TRequest, TResponse>( reqnum, respStream, resp.ContentLength); } } else { m_log.DebugFormat( "[SynchronousRestObjectRequester]: Oops! no content found in response stream from {0} {1}", verb, requestUrl); } } } catch (WebException e) { using (HttpWebResponse hwr = (HttpWebResponse)e.Response) { if (hwr != null) { if (hwr.StatusCode == HttpStatusCode.NotFound) return deserial; if (hwr.StatusCode == HttpStatusCode.Unauthorized) { m_log.Error(string.Format( "[SynchronousRestObjectRequester]: Web request {0} requires authentication ", requestUrl)); return deserial; } } else m_log.Error(string.Format( "[SynchronousRestObjectRequester]: WebException for {0} {1} {2} ", verb, requestUrl, typeof(TResponse).ToString()), e); } } catch (System.InvalidOperationException) { // This is what happens when there is invalid XML m_log.DebugFormat( "[SynchronousRestObjectRequester]: Invalid XML from {0} {1} {2}", verb, requestUrl, typeof(TResponse).ToString()); } catch (Exception e) { m_log.Debug(string.Format( "[SynchronousRestObjectRequester]: Exception on response from {0} {1} ", verb, requestUrl), e); } int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); if (tickdiff > WebUtil.LongCallTime) { string originalRequest = null; if (buffer != null) { originalRequest = Encoding.UTF8.GetString(buffer.ToArray()); if (originalRequest.Length > WebUtil.MaxRequestDiagLength) originalRequest = originalRequest.Remove(WebUtil.MaxRequestDiagLength); } m_log.InfoFormat( "[LOGHTTP]: Slow SynchronousRestObject request {0} {1} to {2} took {3}ms, {4}ms writing, {5}", reqnum, verb, requestUrl, tickdiff, tickdata, originalRequest); } else if (WebUtil.DebugLevel >= 4) { m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing", reqnum, tickdiff, tickdata); } } finally { if (buffer != null) buffer.Dispose(); } return deserial; } public static class XMLResponseHelper { public static TResponse LogAndDeserialize<TRequest, TResponse>(int reqnum, Stream respStream, long contentLength) { XmlSerializer deserializer = new XmlSerializer(typeof(TResponse)); if (WebUtil.DebugLevel >= 5) { byte[] data = new byte[contentLength]; Util.ReadStream(respStream, data); WebUtil.LogResponseDetail(reqnum, System.Text.Encoding.UTF8.GetString(data)); using (MemoryStream temp = new MemoryStream(data)) return (TResponse)deserializer.Deserialize(temp); } else { return (TResponse)deserializer.Deserialize(respStream); } } } } public static class XMLRPCRequester { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public static Hashtable SendRequest(Hashtable ReqParams, string method, string url) { int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} XML-RPC '{1}' to {2}", reqnum, method, url); int tickstart = Util.EnvironmentTickCount(); string responseStr = null; try { ArrayList SendParams = new ArrayList(); SendParams.Add(ReqParams); XmlRpcRequest Req = new XmlRpcRequest(method, SendParams); if (WebUtil.DebugLevel >= 5) { string str = Req.ToString(); str = XElement.Parse(str).ToString(SaveOptions.DisableFormatting); WebUtil.LogOutgoingDetail("SEND", reqnum, str); } XmlRpcResponse Resp = Req.Send(url, 30000); try { responseStr = Resp.ToString(); responseStr = XElement.Parse(responseStr).ToString(SaveOptions.DisableFormatting); if (WebUtil.DebugLevel >= 5) WebUtil.LogResponseDetail(reqnum, responseStr); } catch (Exception e) { m_log.Error("Error parsing XML-RPC response", e); } if (Resp.IsFault) { m_log.DebugFormat( "[LOGHTTP]: XML-RPC request {0} '{1}' to {2} FAILED: FaultCode={3}, FaultMessage={4}", reqnum, method, url, Resp.FaultCode, Resp.FaultString); return null; } Hashtable RespData = (Hashtable)Resp.Value; return RespData; } finally { int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); if (tickdiff > WebUtil.LongCallTime) { m_log.InfoFormat( "[LOGHTTP]: Slow XML-RPC request {0} '{1}' to {2} took {3}ms, {4}", reqnum, method, url, tickdiff, responseStr != null ? (responseStr.Length > WebUtil.MaxRequestDiagLength ? responseStr.Remove(WebUtil.MaxRequestDiagLength) : responseStr) : ""); } else if (WebUtil.DebugLevel >= 4) { m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms", reqnum, tickdiff); } } } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using Csla; using Invoices.DataAccess; namespace Invoices.Business { /// <summary> /// ProductTypeList (read only list).<br/> /// This is a generated <see cref="ProductTypeList"/> business object. /// This class is a root collection. /// </summary> /// <remarks> /// The items of the collection are <see cref="ProductTypeInfo"/> objects. /// No cache. Updated by ProductTypeDynaItem /// </remarks> [Serializable] #if WINFORMS public partial class ProductTypeList : ReadOnlyBindingListBase<ProductTypeList, ProductTypeInfo> #else public partial class ProductTypeList : ReadOnlyListBase<ProductTypeList, ProductTypeInfo> #endif { #region Event handler properties [NotUndoable] private static bool _singleInstanceSavedHandler = true; /// <summary> /// Gets or sets a value indicating whether only a single instance should handle the Saved event. /// </summary> /// <value> /// <c>true</c> if only a single instance should handle the Saved event; otherwise, <c>false</c>. /// </value> public static bool SingleInstanceSavedHandler { get { return _singleInstanceSavedHandler; } set { _singleInstanceSavedHandler = value; } } #endregion #region Collection Business Methods /// <summary> /// Determines whether a <see cref="ProductTypeInfo"/> item is in the collection. /// </summary> /// <param name="productTypeId">The ProductTypeId of the item to search for.</param> /// <returns><c>true</c> if the ProductTypeInfo is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int productTypeId) { foreach (var productTypeInfo in this) { if (productTypeInfo.ProductTypeId == productTypeId) { return true; } } return false; } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="ProductTypeList"/> collection. /// </summary> /// <returns>A reference to the fetched <see cref="ProductTypeList"/> collection.</returns> public static ProductTypeList GetProductTypeList() { return DataPortal.Fetch<ProductTypeList>(); } /// <summary> /// Factory method. Asynchronously loads a <see cref="ProductTypeList"/> collection. /// </summary> /// <param name="callback">The completion callback method.</param> public static void GetProductTypeList(EventHandler<DataPortalResult<ProductTypeList>> callback) { DataPortal.BeginFetch<ProductTypeList>(callback); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="ProductTypeList"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public ProductTypeList() { // Use factory methods and do not use direct creation. ProductTypeDynaItemSaved.Register(this); var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = false; AllowEdit = false; AllowRemove = false; RaiseListChangedEvents = rlce; } #endregion #region Saved Event Handler /// <summary> /// Handle Saved events of <see cref="ProductTypeDynaItem"/> to update the list of <see cref="ProductTypeInfo"/> objects. /// </summary> /// <param name="sender">The sender of the event.</param> /// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param> internal void ProductTypeDynaItemSavedHandler(object sender, Csla.Core.SavedEventArgs e) { var obj = (ProductTypeDynaItem)e.NewObject; if (((ProductTypeDynaItem)sender).IsNew) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = true; Add(ProductTypeInfo.LoadInfo(obj)); RaiseListChangedEvents = rlce; IsReadOnly = true; } else if (((ProductTypeDynaItem)sender).IsDeleted) { for (int index = 0; index < this.Count; index++) { var child = this[index]; if (child.ProductTypeId == obj.ProductTypeId) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = true; this.RemoveItem(index); RaiseListChangedEvents = rlce; IsReadOnly = true; break; } } } else { for (int index = 0; index < this.Count; index++) { var child = this[index]; if (child.ProductTypeId == obj.ProductTypeId) { child.UpdatePropertiesOnSaved(obj); #if !WINFORMS var notifyCollectionChangedEventArgs = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, child, child, index); OnCollectionChanged(notifyCollectionChangedEventArgs); #else var listChangedEventArgs = new ListChangedEventArgs(ListChangedType.ItemChanged, index); OnListChanged(listChangedEventArgs); #endif break; } } } } #endregion #region Data Access /// <summary> /// Loads a <see cref="ProductTypeList"/> collection from the database. /// </summary> protected void DataPortal_Fetch() { var args = new DataPortalHookArgs(); OnFetchPre(args); using (var dalManager = DalFactoryInvoices.GetManager()) { var dal = dalManager.GetProvider<IProductTypeListDal>(); var data = dal.Fetch(); Fetch(data); } OnFetchPost(args); } /// <summary> /// Loads all <see cref="ProductTypeList"/> collection items from the given list of ProductTypeInfoDto. /// </summary> /// <param name="data">The list of <see cref="ProductTypeInfoDto"/>.</param> private void Fetch(List<ProductTypeInfoDto> data) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; foreach (var dto in data) { Add(DataPortal.FetchChild<ProductTypeInfo>(dto)); } RaiseListChangedEvents = rlce; IsReadOnly = true; } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); #endregion #region ProductTypeDynaItemSaved nested class // TODO: edit "ProductTypeList.cs", uncomment the "OnDeserialized" method and add the following line: // TODO: ProductTypeDynaItemSaved.Register(this); /// <summary> /// Nested class to manage the Saved events of <see cref="ProductTypeDynaItem"/> /// to update the list of <see cref="ProductTypeInfo"/> objects. /// </summary> private static class ProductTypeDynaItemSaved { private static List<WeakReference> _references; private static bool Found(object obj) { return _references.Any(reference => Equals(reference.Target, obj)); } /// <summary> /// Registers a ProductTypeList instance to handle Saved events. /// to update the list of <see cref="ProductTypeInfo"/> objects. /// </summary> /// <param name="obj">The ProductTypeList instance.</param> public static void Register(ProductTypeList obj) { var mustRegister = _references == null; if (mustRegister) _references = new List<WeakReference>(); if (ProductTypeList.SingleInstanceSavedHandler) _references.Clear(); if (!Found(obj)) _references.Add(new WeakReference(obj)); if (mustRegister) ProductTypeDynaItem.ProductTypeDynaItemSaved += ProductTypeDynaItemSavedHandler; } /// <summary> /// Handles Saved events of <see cref="ProductTypeDynaItem"/>. /// </summary> /// <param name="sender">The sender of the event.</param> /// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param> public static void ProductTypeDynaItemSavedHandler(object sender, Csla.Core.SavedEventArgs e) { foreach (var reference in _references) { if (reference.IsAlive) ((ProductTypeList) reference.Target).ProductTypeDynaItemSavedHandler(sender, e); } } /// <summary> /// Removes event handling and clears all registered ProductTypeList instances. /// </summary> public static void Unregister() { ProductTypeDynaItem.ProductTypeDynaItemSaved -= ProductTypeDynaItemSavedHandler; _references = null; } } #endregion } }
/*=================================\ * PlotterControl\Form_viewvect.cs * * The Coestaris licenses this file to you under the MIT license. * See the LICENSE file in the project root for more information. * * Created: 27.11.2017 14:04 * Last Edited: 27.11.2017 14:04:46 *=================================*/ using CWA; using CWA.Vectors; using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.IO; using System.Linq; using System.Threading; using System.Windows.Forms; namespace CnC_WFA { public partial class Form_ViewVect : Form { private string path; private Vector vect; private Color backcolor; private Color drawcolor; public string filename; private Thread draw_th; private int lastsi; private Bitmap bmp; private Color selColor; private bool defaultView = true; private bool isToolStrip; private bool isZoom; private bool isList; public Form_ViewVect() { InitializeComponent(); isToolStrip = true; isZoom = true; isList = false; SetIntr(); panel_zoom.Visible = false; loadingCircle1.InnerCircleRadius = 25; loadingCircle1.OuterCircleRadius = 26; loadingCircle1.NumberSpoke = 100; } public Form_ViewVect(string fn, bool ignore) { InitializeComponent(); isToolStrip = true; isZoom = true; isList = false; SetIntr(); if (!ignore) { var fi = new FileInfo(Application.ExecutablePath); GlobalOptions.Filename = fi.DirectoryName + "\\Options\\options.xml"; GlobalOptionsLogPolitics.Filename = fi.DirectoryName + "\\Options\\logPolitics.xml"; GlobalOptions.Load(); } loadingCircle1.InnerCircleRadius = 25; loadingCircle1.OuterCircleRadius = 26; loadingCircle1.NumberSpoke = 100; panel_zoom.Visible = false; Proceed(fn); FillListBox(); Rectangle resolution = Screen.PrimaryScreen.Bounds; Height = (int)vect.Header.Height + 100; Width = (int)vect.Header.Width + 40; double timesH = double.MaxValue, timesW = double.MaxValue; if (vect.Header.Height > resolution.Height - 100) timesH = (resolution.Height - 100) / vect.Header.Height; if (vect.Header.Width > resolution.Width - 40) timesW = (resolution.Width - 40) / vect.Header.Width; var minTimes = Math.Min(timesH, timesW); if (minTimes != double.MaxValue) { trackBar1.Value = (int)(minTimes * 100 - 10); if (timesH != double.MaxValue) Height = resolution.Height - 100; else Height = (int)((Height - 100) * minTimes); if (timesW != double.MaxValue) Width = resolution.Width - 40; else Width = (int)((Width - 40) * minTimes) - 50; } else { isZoom = false; SetIntr(); } } private void FillListBox() { int i = 0; listBox1.Items.Clear(); foreach (var a in vect.RawData) listBox1.Items.Add(string.Format(TB.L.Phrase["VectorViewer.ContourDiscr"], i++, a.Length)); } private void SetIntr() { toolStripMenuItem_defDisp.Image = !defaultView ? CWA_Resources.Properties.Resources.delete : CWA_Resources.Properties.Resources.ok1; contoursToolStripMenuItem.Image = !isList ? CWA_Resources.Properties.Resources.delete : CWA_Resources.Properties.Resources.ok1; infoStripToolStripMenuItem.Image = !isToolStrip ? CWA_Resources.Properties.Resources.delete : CWA_Resources.Properties.Resources.ok1; zoomToolStripMenuItem.Image = !isZoom ? CWA_Resources.Properties.Resources.delete : CWA_Resources.Properties.Resources.ok1; toolStripComboBox_dispType.Image = !defaultView ? CWA_Resources.Properties.Resources.delete : CWA_Resources.Properties.Resources.ok1; statusStrip1.Visible = isToolStrip; if (isList) { panel3.Location = new Point(276, 36); panel3.Size = new Size(Width - 304, Height - 110); panel_cont.Visible = true; if (isZoom) { panel_zoom.Visible = true; panel_zoom.Location = new Point(10, 288); } else panel_zoom.Visible = false; } else { panel_cont.Visible = false; panel3.Location = new Point(0, 24); panel3.Size = new Size(Width - 16, Height - 88); if (isZoom) { panel_zoom.Visible = true; panel_zoom.Location = new Point(4, Height - 139); } else panel_zoom.Visible = false; } } private void Proceed(string fn) { toolStripComboBox_dispType.SelectedIndex = 1; lastsi = 0; filename = fn; listBox1.Enabled = true; loadingCircle1.Visible = true; loadingCircle1.Active = true; label_status.Visible = true; label_status.Text = TB.L.Phrase["VectorViewer.Word.Loading"]; path = fn; vect = new Vector(path); toolStripStatusLabel_filename.Text = TB.L.Phrase["VectorViewer.Word.Filename"] + ": " + new FileInfo(path).Directory.Name + '\\' + path.Split('\\')[path.Split('\\').Length - 1]; toolStripStatusLabel_resolution.Text = TB.L.Phrase["VectorViewer.Word.Resolution"] + ": " + vect.Header.Width + "x" + vect.Header.Height; toolStripStatusLabel1.Text = TB.L.Phrase["VectorViewer.Word.Contours"] + ": " + vect.ContorurCount + "; " + TB.L.Phrase["VectorViewer.Word.Points"] + ": " + vect.Points.ToString(); vect.RawData = vect.RawData.ToList().OrderByDescending(p => p.Length).ToArray(); Text = $"{TB.L.Phrase["VectorViewer.Label"]} \"{new FileInfo(path).Directory.Name}{'\\'}{path.Split('\\')[path.Split('\\').Length - 1]}{'\"'}"; drawcolor = GlobalOptions.DefViewDraw; backcolor = GlobalOptions.DefViewBack; selColor = Color.Blue; label_status.Text = TB.L.Phrase["VectorViewer.Word.Drawing"]; if (new FileInfo(filename).Extension == ".prres") toolStripStatusLabel_oldprstyle.Text = TB.L.Phrase["VectorViewer.OldVectorFormat"]; else toolStripStatusLabel_oldprstyle.Text = ""; SetColorProbe(); label.Visible = false; pictureBox_main.Visible = true; if (isZoom) panel_zoom.Visible = true; draw_th = new Thread(ChangeLabelTextProcAsync); draw_th.Start(); } private void button4_Click(object sender, EventArgs e) { openFileDialog1.ShowDialog(); } private void openFileDialog1_FileOk(object sender, CancelEventArgs e) { path = openFileDialog1.FileName; Proceed(path); FillListBox(); } private void SetColorProbe() { Bitmap colorprobe_draw = new Bitmap(50, 50); Bitmap colorprobe_back = new Bitmap(50, 50); Bitmap colorprobe_sel = new Bitmap(50, 50); Rectangle rect = new Rectangle(0, 0, 50, 50); Rectangle rect1 = new Rectangle(5, 5, 40, 40); using (Graphics gr = Graphics.FromImage(colorprobe_back)) { gr.FillRectangle(Brushes.Black, rect); gr.FillRectangle(new SolidBrush(backcolor), rect1); } using (Graphics gr = Graphics.FromImage(colorprobe_draw)) { gr.FillRectangle(Brushes.Black, rect); gr.FillRectangle(new SolidBrush(drawcolor), rect1); } using (Graphics gr = Graphics.FromImage(colorprobe_sel)) { gr.FillRectangle(Brushes.Black, rect); gr.FillRectangle(new SolidBrush(selColor), rect1); } toolStripMenuItem_color.Image?.Dispose(); toolStripMenuItem_color.Image = colorprobe_draw; toolStripMenuItem_backgroundColor.Image?.Dispose(); toolStripMenuItem_backgroundColor.Image = colorprobe_back; toolStripMenuItem_selectedColor.Image?.Dispose(); toolStripMenuItem_selectedColor.Image = colorprobe_sel; } private delegate void EndOfRenderImageHandler(); private void EndOfRenderImage() { if (InvokeRequired) { EndOfRenderImageHandler d = new EndOfRenderImageHandler(EndOfRenderImage); Invoke(d, new object[] {}); } else { loadingCircle1.Visible = false; loadingCircle1.Active = false; label_status.Visible = false; float zoom = trackBar1.Value / 100f; pictureBox_main.Image?.Dispose(); pictureBox_main.Image = new Bitmap(bmp, new Size((int)(bmp.Width * zoom), (int)(bmp.Height * zoom))); } } private void ChangeLabelTextProcAsync() { if (defaultView) { bmp = vect.ToBitmap(backcolor, drawcolor); } else { bmp = new Bitmap((int)vect.Header.Width, (int)vect.Header.Height); using (Graphics gr = Graphics.FromImage(bmp)) { gr.FillRectangle(new SolidBrush(backcolor), new Rectangle(0, 0, bmp.Width, bmp.Height)); gr.DrawPath(new Pen(drawcolor), vect.GrPath); } } EndOfRenderImage(); } private void button_exit_Click(object sender, EventArgs e) { Close(); } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { if(listBox1.SelectedIndex!=-1) { Random rnd = new Random(); Color c; var bmp_ = new Bitmap((Image)bmp.Clone()); if (toolStripComboBox_dispType.SelectedIndex == 0) c = Color.FromArgb(255, rnd.Next(100, 255), rnd.Next(100, 255), rnd.Next(100, 255)); else c = drawcolor; for (var ii = 0; ii <= vect.RawData[lastsi].Length - 1; ii++) bmp_.SetPixel((int)vect.RawData[lastsi][ii].BasePoint.Y, (int)vect.RawData[lastsi][ii].BasePoint.X, c); int nowsel = listBox1.SelectedIndex; c = selColor; for (var ii = 0; ii <= vect.RawData[nowsel].Length - 1; ii++) bmp_.SetPixel((int)vect.RawData[nowsel][ii].BasePoint.Y, (int)vect.RawData[nowsel][ii].BasePoint.X, c); float zoom = trackBar1.Value / 100f; pictureBox_main.Image?.Dispose(); pictureBox_main.Image = new Bitmap(bmp_, new Size((int)(bmp_.Width * zoom), (int)(bmp_.Height * zoom))); lastsi = nowsel; } } private void Form_viewvect_DragDropEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.All; } private void statusStrip1_DragDrop(object sender, DragEventArgs e) { string[] fn = (string[])e.Data.GetData(DataFormats.FileDrop, false); if (fn[0].EndsWith(".pcv") || fn[0].EndsWith(".prres")) Proceed(fn[0]); else MessageBox.Show( TB.L.Phrase["VectorViewer.Word.WrongFileExt"], TB.L.Phrase["VectorViewer.Word.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error); FillListBox(); } private void button_redraw_Click(object sender, EventArgs e) { loadingCircle1.Visible = true; loadingCircle1.Active = true; label_status.Visible = true; draw_th?.Abort(); draw_th = new Thread(ChangeLabelTextProcAsync); SetColorProbe(); draw_th.Start(); listBox1.SelectedIndex = -1; } private void button_print_Click(object sender, EventArgs e) { Form_PrintMaster fpr = FormTranslator.Translate(new Form_PrintMaster(filename,true)); fpr.Show(); } private void toolStripMenuItem_color_Click(object sender, EventArgs e) { colorDialog1.Color = drawcolor; if (colorDialog1.ShowDialog() == DialogResult.OK) { drawcolor = colorDialog1.Color; SetColorProbe(); draw_th = new Thread(ChangeLabelTextProcAsync); draw_th.Start(); } } private void trackBar1_Scroll(object sender, EventArgs e) { float zoom = trackBar1.Value / 100f; label3.Text = zoom.ToString("0.##"); pictureBox_main.Image?.Dispose(); pictureBox_main.Image = new Bitmap(bmp, new Size((int)(bmp.Width * zoom), (int)(bmp.Height * zoom))); } private void Form_ViewVect_Load(object sender, EventArgs e) { label_zoom_min.Text = trackBar1.Minimum.ToString(); label_zoom_max.Text = trackBar1.Maximum.ToString(); float zoom = trackBar1.Value / 100f; label3.Text = zoom.ToString("0.##"); } private void toolStripMenuItem_backgroundColor_Click(object sender, EventArgs e) { colorDialog1.Color = backcolor; if (colorDialog1.ShowDialog() == DialogResult.OK) { backcolor = colorDialog1.Color; SetColorProbe(); draw_th = new Thread(ChangeLabelTextProcAsync); draw_th.Start(); } } private void toolStripMenuItem_selectedColor_Click(object sender, EventArgs e) { colorDialog1.Color = selColor; if (colorDialog1.ShowDialog() == DialogResult.OK) { selColor = colorDialog1.Color; SetColorProbe(); } } private void toolStripComboBox_dispType_Click(object sender, EventArgs e) { } private void toolStripMenuItem_resetZoom_Click(object sender, EventArgs e) { trackBar1.Value = 100; trackBar1_Scroll(null, null); } private void Form_ViewVect_Resize(object sender, EventArgs e) { SetIntr(); } private void contoursToolStripMenuItem_Click(object sender, EventArgs e) { isList = !isList; SetIntr(); } private void infoStripToolStripMenuItem_Click(object sender, EventArgs e) { isToolStrip = !isToolStrip; SetIntr(); } private void zoomToolStripMenuItem_Click(object sender, EventArgs e) { isZoom = !isZoom; SetIntr(); } private void toolStripMenuItem_defDisp_Click(object sender, EventArgs e) { defaultView = !defaultView; SetIntr(); draw_th = new Thread(ChangeLabelTextProcAsync); draw_th.Start(); } private void toolStripMenuItem_saveAs_Click(object sender, EventArgs e) { if (vect == null) { MessageBox.Show( TB.L.Phrase["VectorViewer.Word.OpenSomeVectForCont"], TB.L.Phrase["VectorViewer.Word.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if(saveFileDialog1.ShowDialog() == DialogResult.OK) { vect.Save(saveFileDialog1.FileName, (VectorFileFormat)(saveFileDialog1.FilterIndex-1)); } } private void saveFileDialog1_FileOk(object sender, CancelEventArgs e) { } } }
using De.Osthus.Ambeth.Ioc; using De.Osthus.Ambeth.Util; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading; using System; using System.IO; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Reflection; using De.Osthus.Ambeth.Config; using De.Osthus.Ambeth.Debug; using De.Osthus.Ambeth.Ioc.Annotation; using De.Osthus.Ambeth.Log; namespace De.Osthus.Ambeth.Testutil { /// <summary> /// Abstract test class easing usage of IOC containers in test scenarios. Isolated modules can be registered with the <code>TestModule</code> annotation. The test /// itself will be registered as a bean within the IOC container. Therefore it can consume any components for testing purpose and behave like a productively /// bean. /// /// In addition to registering custom modules the environment can be constructed for specific testing purpose with the <code>TestProperties</code> annotation. /// Multiple properties can be wrapped using the <code>TestPropertiesList</code> annotation. /// /// All annotations can be used on test class level as well as on test method level. In ambiguous scenarios the method annotations will gain precedence. /// </summary> [DeploymentItem(@"Ambeth.IoC.dll")] [DeploymentItem(@"Ambeth.Log.dll")] [DeploymentItem(@"Ambeth.Util.dll")] [TestClass] [TestFrameworkModule(typeof(IocModule))] [TestProperties(Name = IocConfigurationConstants.TrackDeclarationTrace, Value = "true")] [TestProperties(Name = IocConfigurationConstants.DebugModeActive, Value = "true")] [TestProperties(Name = "ambeth.log.level.De.Osthus.Ambeth.Accessor.AccessorTypeProvider", Value = "INFO")] [TestProperties(Name = "ambeth.log.level.De.Osthus.Ambeth.Bytecode.Core.BytecodeEnhancer", Value = "INFO")] [TestProperties(Name = "ambeth.log.level.De.Osthus.Ambeth.Bytecode.Visitor.ClassWriter", Value = "INFO")] [TestProperties(Name = "ambeth.log.level.De.Osthus.Ambeth.Bytecode.Visitor.LogImplementationsClassVisitor", Value = "INFO")] [TestProperties(Name = "ambeth.log.level.De.Osthus.Ambeth.Template.PropertyChangeTemplate", Value = "INFO")] public abstract class AbstractIocTest : IInitializingBean, IStartingBean, IDisposableBean { public class Assert { public static void AssertNull(Object obj) { Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNull(obj); } public static void AssertNotNull(Object obj) { Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNotNull(obj); } public static void AssertNotSame(Object notExpected, Object value) { Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsFalse(Object.ReferenceEquals(notExpected, value)); } public static void AssertSame(Object expected, Object value, String message = null) { if (message == null) { Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue(Object.ReferenceEquals(expected, value)); } else { Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue(Object.ReferenceEquals(expected, value), message); } } public static void AssertTrue(bool actual, String message = null) { if (message == null) { Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue(actual); } else { Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue(actual, message); } } public static void AssertFalse(bool actual, String message = null) { if (message == null) { Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsFalse(actual); } else { Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsFalse(actual, message); } } public static void AssertEquals<T>(T expected, T actual, String message = null) { if (message == null) { Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(expected, actual); } else { Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(expected, actual, message); } } public static void AssertNotEquals<T>(T expected, T actual, String message = null) { if (message == null) { Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreNotEqual(expected, actual); } else { Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreNotEqual(expected, actual, message); } } public static void AssertNotEquals(Object expected, Object actual, String message = null) { if (message == null) { Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreNotEqual(expected, actual); } else { Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreNotEqual(expected, actual, message); } } public static void Fail(String message) { Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Fail(message); } public static void IsInstanceOfType(Object value, Type expectedType) { Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsInstanceOfType(value, expectedType); } public static void IsNotInstanceOfType(Object value, Type expectedType) { Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNotInstanceOfType(value, expectedType); } public static void AssertArrayEquals<T>(T[] a1, T[] a2) { if (ReferenceEquals(a1, a2)) { return; } if (a1 == null || a2 == null) { Fail("One array instance is null"); return; } if (a1.Length != a2.Length) { Fail("Length is not equal: " + a1.Length + " != " + a2.Length); return; } for (int i = 0; i < a1.Length; i++) { if (!Object.Equals(a1[i], a2[i])) { Fail("Item at index " + i + " is not equal"); return; } } } } [LogInstance] public ILogger Log { private get; set; } private static bool assemblyInitRan = false; private readonly AmbethIocRunner runner; private IServiceContext beanContext; [Autowired] public IServiceContext BeanContext { protected get { return beanContext; } set { beanContext = value; FlattenHierarchyProxy.Context = beanContext; } } public Microsoft.VisualStudio.TestTools.UnitTesting.TestContext TestContext { get; set; } public AbstractIocTest() { runner = new AmbethIocRunner(GetType(), this); } /// <summary> /// Workaround to get all needed assemblies known by the AssemblyHelper. /// </summary> /// <param name="context"></param> [AssemblyInitialize] public static void RegisterAssemblies(Microsoft.VisualStudio.TestTools.UnitTesting.TestContext context) { assemblyInitRan = true; AssemblyHelper.RegisterAssemblyFromType(typeof(IProperties)); // for xsd files from Ambeth.Util } [TestInitialize] public virtual void InitAutomatically() { try { if (!assemblyInitRan) { RegisterAssemblies(null); } InitManually(GetType()); } catch (Exception e) { if (Log != null) { Log.Error(e); } throw; } } //[TestInitialize] public virtual void InitManually(Type testType) { //String stackTrace = Environment.StackTrace; //List<String> lines = new List<String>(); //StringReader reader = new StringReader(stackTrace); //while (true) //{ // String line = reader.ReadLine(); // if (line == null) // { // break; // } // lines.Add(line); //} //Regex regex = new Regex(" *(?:Microsoft|System).(.+)"); //Regex fqClassNameRegex = new Regex(@" *(?:[^ ]+ +)?([^ ]+)\.([^ \.]+)\(\) +.+"); //String fqClassNameLine = null; //for (int a = lines.Count; a-- > 0;) //{ // String line = lines[a]; // Match match = regex.Match(line); // if (match.Success) // { // continue; // } // fqClassNameLine = line; // break; //} String methodName = TestContext.TestName; AssemblyHelper.RegisterAssemblyFromType(testType); MethodInfo method = testType.GetMethod(methodName); runner.RunChild(method); BeanContext = runner.GetBeanContext(); } [TestCleanup] public void Cleanup() { if (BeanContext != null) { BeanContext.GetRoot().Dispose(); BeanContext = null; } } public virtual void AfterPropertiesSet() { // Intended blank } public virtual void AfterStarted() { // Intended blank } public virtual void Destroy() { if (Object.ReferenceEquals(FlattenHierarchyProxy.Context, BeanContext)) { FlattenHierarchyProxy.Context = null; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Nini.Config; using System; using System.Collections.Generic; using System.Reflection; using OpenSim.Framework; using OpenSim.Server.Base; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenMetaverse; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset { public class HGAssetBroker : ISharedRegionModule, IAssetService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private IImprovedAssetCache m_Cache = null; private IAssetService m_GridService; private IAssetService m_HGService; private Scene m_aScene; private string m_LocalAssetServiceURI; private bool m_Enabled = false; public Type ReplaceableInterface { get { return null; } } public string Name { get { return "HGAssetBroker"; } } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("AssetServices", ""); if (name == Name) { IConfig assetConfig = source.Configs["AssetService"]; if (assetConfig == null) { m_log.Error("[HG ASSET CONNECTOR]: AssetService missing from OpenSim.ini"); return; } string localDll = assetConfig.GetString("LocalGridAssetService", String.Empty); string HGDll = assetConfig.GetString("HypergridAssetService", String.Empty); if (localDll == String.Empty) { m_log.Error("[HG ASSET CONNECTOR]: No LocalGridAssetService named in section AssetService"); return; } if (HGDll == String.Empty) { m_log.Error("[HG ASSET CONNECTOR]: No HypergridAssetService named in section AssetService"); return; } Object[] args = new Object[] { source }; m_GridService = ServerUtils.LoadPlugin<IAssetService>(localDll, args); m_HGService = ServerUtils.LoadPlugin<IAssetService>(HGDll, args); if (m_GridService == null) { m_log.Error("[HG ASSET CONNECTOR]: Can't load local asset service"); return; } if (m_HGService == null) { m_log.Error("[HG ASSET CONNECTOR]: Can't load hypergrid asset service"); return; } m_LocalAssetServiceURI = assetConfig.GetString("AssetServerURI", string.Empty); if (m_LocalAssetServiceURI == string.Empty) { IConfig netConfig = source.Configs["Network"]; m_LocalAssetServiceURI = netConfig.GetString("asset_server_url", string.Empty); } if (m_LocalAssetServiceURI != string.Empty) m_LocalAssetServiceURI = m_LocalAssetServiceURI.Trim('/'); m_Enabled = true; m_log.Info("[HG ASSET CONNECTOR]: HG asset broker enabled"); } } } public void PostInitialise() { } public void Close() { } public void AddRegion(Scene scene) { if (!m_Enabled) return; m_aScene = scene; scene.RegisterModuleInterface<IAssetService>(this); } public void RemoveRegion(Scene scene) { } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; if (m_Cache == null) { m_Cache = scene.RequestModuleInterface<IImprovedAssetCache>(); if (!(m_Cache is ISharedRegionModule)) m_Cache = null; } m_log.InfoFormat("[HG ASSET CONNECTOR]: Enabled hypergrid asset broker for region {0}", scene.RegionInfo.RegionName); if (m_Cache != null) { m_log.InfoFormat("[HG ASSET CONNECTOR]: Enabled asset caching for region {0}", scene.RegionInfo.RegionName); } } private bool IsHG(string id) { Uri assetUri; if (Uri.TryCreate(id, UriKind.Absolute, out assetUri) && assetUri.Scheme == Uri.UriSchemeHttp) return true; return false; } public AssetBase Get(string id) { //m_log.DebugFormat("[HG ASSET CONNECTOR]: Get {0}", id); AssetBase asset = null; if (m_Cache != null) { asset = m_Cache.Get(id); if (asset != null) return asset; } if (IsHG(id)) { asset = m_HGService.Get(id); if (asset != null) { // Now store it locally // For now, let me just do it for textures and scripts if (((AssetType)asset.Type == AssetType.Texture) || ((AssetType)asset.Type == AssetType.LSLBytecode) || ((AssetType)asset.Type == AssetType.LSLText)) { m_GridService.Store(asset); } } } else asset = m_GridService.Get(id); if (asset != null) { if (m_Cache != null) m_Cache.Cache(asset); } return asset; } public AssetBase GetCached(string id) { if (m_Cache != null) return m_Cache.Get(id); return null; } public AssetMetadata GetMetadata(string id) { AssetBase asset = null; if (m_Cache != null) { if (m_Cache != null) m_Cache.Get(id); if (asset != null) return asset.Metadata; } AssetMetadata metadata; if (IsHG(id)) metadata = m_HGService.GetMetadata(id); else metadata = m_GridService.GetMetadata(id); return metadata; } public byte[] GetData(string id) { AssetBase asset = null; if (m_Cache != null) { if (m_Cache != null) m_Cache.Get(id); if (asset != null) return asset.Data; } if (IsHG(id)) asset = m_HGService.Get(id); else asset = m_GridService.Get(id); if (asset != null) { if (m_Cache != null) m_Cache.Cache(asset); return asset.Data; } return null; } public bool Get(string id, Object sender, AssetRetrieved handler) { AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset != null) { Util.FireAndForget(delegate { handler(id, sender, asset); }); return true; } if (IsHG(id)) { return m_HGService.Get(id, sender, delegate (string assetID, Object s, AssetBase a) { if (a != null && m_Cache != null) m_Cache.Cache(a); handler(assetID, s, a); }); } else { return m_GridService.Get(id, sender, delegate (string assetID, Object s, AssetBase a) { if (a != null && m_Cache != null) m_Cache.Cache(a); handler(assetID, s, a); }); } } public string Store(AssetBase asset) { bool isHG = IsHG(asset.ID); if ((m_Cache != null) && !isHG) // Don't store it in the cache if the asset is to // be sent to the other grid, because this is already // a copy of the local asset. m_Cache.Cache(asset); if (asset.Temporary || asset.Local) return asset.ID; if (IsHG(asset.ID)) return m_HGService.Store(asset); else return m_GridService.Store(asset); } public bool UpdateContent(string id, byte[] data) { AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset != null) { asset.Data = data; m_Cache.Cache(asset); } if (IsHG(id)) return m_HGService.UpdateContent(id, data); else return m_GridService.UpdateContent(id, data); } public bool Delete(string id) { if (m_Cache != null) m_Cache.Expire(id); if (IsHG(id)) return m_HGService.Delete(id); else return m_GridService.Delete(id); } #region IHyperAssetService public string GetUserAssetServer(UUID userID) { UserAccount account = m_aScene.UserAccountService.GetUserAccount(m_aScene.RegionInfo.ScopeID, userID); if (account != null && account.ServiceURLs.ContainsKey("AssetServerURI") && account.ServiceURLs["AssetServerURI"] != null) return account.ServiceURLs["AssetServerURI"].ToString(); return string.Empty; } public string GetSimAssetServer() { return m_LocalAssetServiceURI; } #endregion } }
using System; using System.Security.Cryptography; using System.Collections.Generic; using System.Text; using System.Web; namespace OAuth { public class OAuthBase { /// <summary> /// Provides a predefined set of algorithms that are supported officially by the protocol /// </summary> public enum SignatureTypes { HMACSHA1, PLAINTEXT, RSASHA1 } /// <summary> /// Provides an internal structure to sort the query parameter /// </summary> protected class QueryParameter { private string name = null; private string value = null; public QueryParameter(string name, string value) { this.name = name; this.value = value; } public string Name { get { return name; } } public string Value { get { return value; } } } /// <summary> /// Comparer class used to perform the sorting of the query parameters /// </summary> protected class QueryParameterComparer : IComparer<QueryParameter> { #region IComparer<QueryParameter> Members public int Compare(QueryParameter x, QueryParameter y) { if (x.Name == y.Name) { return string.Compare(x.Value, y.Value); } else { return string.Compare(x.Name, y.Name); } } #endregion } protected const string OAuthVersion = "1.0"; protected const string OAuthParameterPrefix = "oauth_"; public bool includeVersion = true; // // List of know and used oauth parameters' names // protected const string OAuthConsumerKeyKey = "oauth_consumer_key"; protected const string OAuthCallbackKey = "oauth_callback"; protected const string OAuthVersionKey = "oauth_version"; protected const string OAuthSignatureMethodKey = "oauth_signature_method"; protected const string OAuthSignatureKey = "oauth_signature"; protected const string OAuthTimestampKey = "oauth_timestamp"; protected const string OAuthNonceKey = "oauth_nonce"; protected const string OAuthTokenKey = "oauth_token"; protected const string OAuthTokenSecretKey = "oauth_token_secret"; protected const string HMACSHA1SignatureType = "HMAC-SHA1"; protected const string PlainTextSignatureType = "PLAINTEXT"; protected const string RSASHA1SignatureType = "RSA-SHA1"; protected Random random = new Random(); protected string unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"; /// <summary> /// Helper function to compute a hash value /// </summary> /// <param name="hashAlgorithm">The hashing algoirhtm used. If that algorithm needs some initialization, like HMAC and its derivatives, they should be initialized prior to passing it to this function</param> /// <param name="data">The data to hash</param> /// <returns>a Base64 string of the hash value</returns> private string ComputeHash(HashAlgorithm hashAlgorithm, string data) { if (hashAlgorithm == null) { throw new ArgumentNullException("hashAlgorithm"); } if (string.IsNullOrEmpty(data)) { throw new ArgumentNullException("data"); } byte[] dataBuffer = System.Text.Encoding.ASCII.GetBytes(data); byte[] hashBytes = hashAlgorithm.ComputeHash(dataBuffer); return Convert.ToBase64String(hashBytes); } /// <summary> /// Internal function to cut out all non oauth query string parameters (all parameters not begining with "oauth_") /// </summary> /// <param name="parameters">The query string part of the Url</param> /// <returns>A list of QueryParameter each containing the parameter name and value</returns> private List<QueryParameter> GetQueryParameters(string parameters) { if (parameters.StartsWith("?")) { parameters = parameters.Remove(0, 1); } List<QueryParameter> result = new List<QueryParameter>(); if (!string.IsNullOrEmpty(parameters)) { string[] p = parameters.Split('&'); foreach (string s in p) { if (!string.IsNullOrEmpty(s) && !s.StartsWith(OAuthParameterPrefix)) { if (s.IndexOf('=') > -1) { string[] temp = s.Split('='); result.Add(new QueryParameter(temp[0], temp[1])); } else { result.Add(new QueryParameter(s, string.Empty)); } } } } return result; } /// <summary> /// This is a different Url Encode implementation since the default .NET one outputs the percent encoding in lower case. /// While this is not a problem with the percent encoding spec, it is used in upper case throughout OAuth /// </summary> /// <param name="value">The value to Url encode</param> /// <returns>Returns a Url encoded string</returns> public string UrlEncode(string value) { StringBuilder result = new StringBuilder(); foreach (char symbol in value) { if (unreservedChars.IndexOf(symbol) != -1) { result.Append(symbol); } else { result.Append('%' + String.Format("{0:X2}", (int)symbol)); } } return result.ToString(); } /// <summary> /// Normalizes the request parameters according to the spec /// </summary> /// <param name="parameters">The list of parameters already sorted</param> /// <returns>a string representing the normalized parameters</returns> protected string NormalizeRequestParameters(IList<QueryParameter> parameters) { StringBuilder sb = new StringBuilder(); QueryParameter p = null; for (int i = 0; i < parameters.Count; i++) { p = parameters[i]; sb.AppendFormat("{0}={1}", p.Name, p.Value); if (i < parameters.Count - 1) { sb.Append("&"); } } return sb.ToString(); } /// <summary> /// Generate the signature base that is used to produce the signature /// </summary> /// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param> /// <param name="consumerKey">The consumer key</param> /// <param name="token">The token, if available. If not available pass null or an empty string</param> /// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param> /// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param> /// <param name="signatureType">The signature type. To use the default values use <see cref="OAuthBase.SignatureTypes">OAuthBase.SignatureTypes</see>.</param> /// <returns>The signature base</returns> public string GenerateSignatureBase(Uri url, string consumerKey, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, string signatureType, out string normalizedUrl, out string normalizedRequestParameters) { if (token == null) { token = string.Empty; } if (tokenSecret == null) { tokenSecret = string.Empty; } if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(httpMethod)) { throw new ArgumentNullException("httpMethod"); } if (string.IsNullOrEmpty(signatureType)) { throw new ArgumentNullException("signatureType"); } normalizedUrl = null; normalizedRequestParameters = null; List<QueryParameter> parameters = GetQueryParameters(url.Query); if (includeVersion) { parameters.Add(new QueryParameter(OAuthVersionKey, OAuthVersion)); } parameters.Add(new QueryParameter(OAuthNonceKey, nonce)); parameters.Add(new QueryParameter(OAuthTimestampKey, timeStamp)); parameters.Add(new QueryParameter(OAuthSignatureMethodKey, signatureType)); parameters.Add(new QueryParameter(OAuthConsumerKeyKey, consumerKey)); if (!string.IsNullOrEmpty(token)) { parameters.Add(new QueryParameter(OAuthTokenKey, token)); } parameters.Sort(new QueryParameterComparer()); normalizedUrl = string.Format("{0}://{1}", url.Scheme, url.Host); if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443))) { normalizedUrl += ":" + url.Port; } normalizedUrl += url.AbsolutePath; normalizedRequestParameters = NormalizeRequestParameters(parameters); StringBuilder signatureBase = new StringBuilder(); signatureBase.AppendFormat("{0}&", httpMethod.ToUpper()); signatureBase.AppendFormat("{0}&", UrlEncode(normalizedUrl)); signatureBase.AppendFormat("{0}", UrlEncode(normalizedRequestParameters)); return signatureBase.ToString(); } /// <summary> /// Generate the signature value based on the given signature base and hash algorithm /// </summary> /// <param name="signatureBase">The signature based as produced by the GenerateSignatureBase method or by any other means</param> /// <param name="hash">The hash algorithm used to perform the hashing. If the hashing algorithm requires initialization or a key it should be set prior to calling this method</param> /// <returns>A base64 string of the hash value</returns> public string GenerateSignatureUsingHash(string signatureBase, HashAlgorithm hash) { return ComputeHash(hash, signatureBase); } /// <summary> /// Generates a signature using the HMAC-SHA1 algorithm /// </summary> /// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param> /// <param name="consumerKey">The consumer key</param> /// <param name="consumerSecret">The consumer seceret</param> /// <param name="token">The token, if available. If not available pass null or an empty string</param> /// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param> /// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param> /// <returns>A base64 string of the hash value</returns> public string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, out string normalizedUrl, out string normalizedRequestParameters) { return GenerateSignature(url, consumerKey, consumerSecret, token, tokenSecret, httpMethod, timeStamp, nonce, SignatureTypes.HMACSHA1, out normalizedUrl, out normalizedRequestParameters); } /// <summary> /// Generates a signature using the specified signatureType /// </summary> /// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param> /// <param name="consumerKey">The consumer key</param> /// <param name="consumerSecret">The consumer seceret</param> /// <param name="token">The token, if available. If not available pass null or an empty string</param> /// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param> /// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param> /// <param name="signatureType">The type of signature to use</param> /// <returns>A base64 string of the hash value</returns> public string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, SignatureTypes signatureType, out string normalizedUrl, out string normalizedRequestParameters) { normalizedUrl = null; normalizedRequestParameters = null; switch (signatureType) { case SignatureTypes.PLAINTEXT: return HttpUtility.UrlEncode(string.Format("{0}&{1}", consumerSecret, tokenSecret)); case SignatureTypes.HMACSHA1: string signatureBase = GenerateSignatureBase(url, consumerKey, token, tokenSecret, httpMethod, timeStamp, nonce, HMACSHA1SignatureType, out normalizedUrl, out normalizedRequestParameters); HMACSHA1 hmacsha1 = new HMACSHA1(); hmacsha1.Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", UrlEncode(consumerSecret), string.IsNullOrEmpty(tokenSecret) ? "" : UrlEncode(tokenSecret))); return GenerateSignatureUsingHash(signatureBase, hmacsha1); case SignatureTypes.RSASHA1: throw new NotImplementedException(); default: throw new ArgumentException("Unknown signature type", "signatureType"); } } /// <summary> /// Generate the timestamp for the signature /// </summary> /// <returns></returns> public virtual string GenerateTimeStamp() { // Default implementation of UNIX time of the current UTC time TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalSeconds).ToString(); } /// <summary> /// Generate a nonce /// </summary> /// <returns></returns> public virtual string GenerateNonce() { // Just a simple implementation of a random number between 123400 and 9999999 return random.Next(123400, 9999999).ToString(); } } }
using UnityEngine; using System.Collections.Generic; [RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(CapsuleCollider))] [RequireComponent(typeof(Animator))] public class Pedestrian : Character { [SerializeField] float m_MovingTurnSpeed = 360; [SerializeField] float m_StationaryTurnSpeed = 180; [SerializeField] float m_JumpPower = 12f; [Range(1f, 4f)][SerializeField] float m_GravityMultiplier = 2f; [SerializeField] float m_RunCycleLegOffset = 0.2f; //specific to the character in sample assets, will need to be modified to work with others [SerializeField] float m_MoveSpeedMultiplier = 1f; [SerializeField] float m_AnimSpeedMultiplier = 1f; [SerializeField] float m_GroundCheckDistance = 0.1f; Rigidbody m_Rigidbody; Animator m_Animator; bool m_IsGrounded; float m_OrigGroundCheckDistance; const float k_Half = 0.5f; float m_TurnAmount; float m_ForwardAmount; Vector3 m_GroundNormal; float m_CapsuleHeight; Vector3 m_CapsuleCenter; CapsuleCollider m_Capsule; bool m_Crouching; Waypoint turnTarget; Waypoint lastWaypoint; bool hasPlayerAskedForMoneyToday; bool hasGivenMoney; int dayLastAskedMoney; bool isTalkingToPlayer; bool hasStoppedToTalkToPlayer; float timeStartedTalkingToPlayer; bool hasBeenRepulsed; float timeAtLastRepulsion; [Space(20.0f)] public Trigger Trigger; [Header("Pedestrian Settings:")] public bool IsVisible = true; public bool ReverseDirection; public float TurnSpeed; public float TurnToFacePlayerSpeed; public float WalkSpeed; public string WayPointGroupName; public float StopAnimatingAboveTimeScale = 800.0f; [Header("Note: Also supports wrapping over (e.g. 11pm to 2am)")] [Range(0.0f, 24.0f)] public float ActiveFromHour = 0.0f; [Range(0.0f, 24.0f)] public float ActiveToHour = 24.0f; public float MaxChanceMoneyGainedWhenBegging; public float HealthAffectsChanceFactor = 1.0f; public float MoraleAffectsChanceFactor = 1.0f; public float CleanlinessAffectsChanceFactor = 1.0f; public float[] PossibleMoniesGained; public float MoraleLostForActiveBegging; public float MoraleLostForAskingTimeOrDay; public float WalksAfterSeconds; [Header("Factors that control how repellent the player character is")] public float PoorHealthRepellenceFactor = 1.0f; public float LowMoraleRepellenceFactor = 1.0f; public float UncleanlinessRepellenceFactor = 1.0f; public float InebriationRepellenceFactor = 1.0f; public float IgnorePlayerAtRepellance; public float WalkAwayFromPlayerAtRepellance; public float TurnAroundCooloffSeconds; public float ChanceWalkAwayFromRepulsion; [ReadOnly] public bool IsInActiveHour; [ReadOnly] public float PlayerRepellence; void Start() { m_Animator = GetComponent<Animator>(); m_Rigidbody = GetComponent<Rigidbody>(); m_Capsule = GetComponent<CapsuleCollider>(); m_CapsuleHeight = m_Capsule.height; m_CapsuleCenter = m_Capsule.center; m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ; m_OrigGroundCheckDistance = m_GroundCheckDistance; transform.Rotate(new Vector3(0.0f, -90.0f, 0.0f)); // Register listeners. Trigger.RegisterOnTriggerListener(OnTrigger); Trigger.RegisterOnPlayerExitListener(OnPlayerExit); Trigger.RegisterOnCloseRequested(Reset); } public void OnTrigger() { // Stop talking to the player if already talking to them. if (isTalkingToPlayer || hasStoppedToTalkToPlayer) { Reset(); return; } // Player refuses to talk if their morale is too low. if (Main.PlayerState.RefusesToTalkToStrangersWhenDepressed && Main.PlayerState.Morale < Main.PlayerState.PoorMoraleEffectsBelowLevel) { Main.MessageBox.ShowForTime("You don't feel like talking to anyone right now"); } else { // Having low health, low morale and/or being intoxicated repels the pedestrian. if (PlayerRepellence > IgnorePlayerAtRepellance) { // Ignore player. Main.PlayerCharacter.Speak("Excuse me"); Reset(); } else { hasStoppedToTalkToPlayer = true; // Player introduces themselves. Main.PlayerCharacter.Speak("Excuse me", null, () => { Speak("Yes?", null, () => { timeStartedTalkingToPlayer = Time.time; isTalkingToPlayer = true; // Open conversation menu. if (Main.UI.CurrentTrigger == Trigger) { List<Menu.Option> options = new List<Menu.Option>(); options.Add(new Menu.Option(AskForTime, "What's the time?")); options.Add(new Menu.Option(AskForDate, "What day is it today?")); options.Add(new Menu.Option(AskForMoney, "Could you spare some change?")); //options.Add(new Menu.Option(null, "GIVE ME YOUR MONEY NOW!", 0, false)); options.Add(new Menu.Option(Reset, "Exit", 0, true, null, true)); Main.Menu.Show(options); } }); }); } } } public void AskForTime() { // Apply morale penalty for asking. Main.PlayerState.ChangeMorale(-MoraleLostForAskingTimeOrDay); Main.Menu.Hide(); Speak("It's " + Main.GameTime.GetTimeAsHumanString() + ".", null, () => { Reset(); }); } public void AskForDate() { // Apply morale penalty for asking. Main.PlayerState.ChangeMorale(-MoraleLostForAskingTimeOrDay); Main.Menu.Hide(); Speak("It's " + Main.GameTime.DayOfTheWeekAsString() + ".", null, () => { Reset(); }); } public void AskForMoney() { Main.Menu.Hide(); // Apply morale penalty for asking. Main.PlayerState.ChangeMorale(-MoraleLostForActiveBegging); // Determine chance of getting money based on health/morale/cleanliness. float chance = MaxChanceMoneyGainedWhenBegging * ( Main.PlayerState.HealthTiredness * HealthAffectsChanceFactor + Main.PlayerState.Morale * MoraleAffectsChanceFactor + Main.PlayerState.CurrentClothingCleanliness * CleanlinessAffectsChanceFactor) / 3f; // Check if we got any money. bool hasGivenMoneyToday = (hasGivenMoney && hasPlayerAskedForMoneyToday); if (!hasPlayerAskedForMoneyToday && !hasGivenMoneyToday && Random.Range(0.0f, 1.0f) < chance) { float moneyEarned = PossibleMoniesGained[Random.Range(0, PossibleMoniesGained.Length)]; hasGivenMoney = true; // Add money. Main.PlayerState.Money += moneyEarned; // Tell the user that they got money and how much. Speak("Here", null, () => { Reset(); }); Main.MessageBox.ShowForTime("$" + moneyEarned.ToString("f2") + " gained"); } else if (hasGivenMoneyToday) { Speak("I already gave you money", null, () => { Reset(); }); } else if (hasPlayerAskedForMoneyToday) { // Just ignore the player and walk away. Reset(); } else { hasGivenMoney = false; Speak("Sorry, no", null, () => { Reset(); }); } hasPlayerAskedForMoneyToday = true; dayLastAskedMoney = Main.GameTime.Day; } public void OnPlayerExit() { Reset(); } public void Reset() { isTalkingToPlayer = false; hasStoppedToTalkToPlayer = false; Main.Menu.Hide(); Trigger.ResetWithCooloff(); } new void Update() { base.Update(); // Disable the trigger while the player is doing something. if (Main.PlayerState.CurrentTrigger && Main.Splash.IsDisplayed()) { Trigger.Reset(false); ForceStopSpeaking(); } // Update player repellence, based on health, morale and inebriation. { PlayerRepellence = ((1.0f - Main.PlayerState.HealthTiredness) * PoorHealthRepellenceFactor + (1.0f - Main.PlayerState.Morale) * LowMoraleRepellenceFactor + (1.0f - Main.PlayerState.CurrentClothingCleanliness) * UncleanlinessRepellenceFactor + Main.PlayerState.Inebriation * InebriationRepellenceFactor) / 3f; } if (isTalkingToPlayer) { // If the day changes the player can ask for money again. if (Main.GameTime.Day != dayLastAskedMoney) { hasPlayerAskedForMoneyToday = false; hasGivenMoney = false; } // Walk away if the player doesn't say anything for a while. if (Main.Menu.IsDisplayed() && Time.time - timeStartedTalkingToPlayer > WalksAfterSeconds) { Reset(); } // Walk away if the player has triggered something else. if (Main.UI.CurrentTrigger != Trigger) { Reset(); } } // Determine if we're in the active hour. If from and to are flipped the period wraps (e.g. 11pm to 2am). if (Main.GameTime) { float time = Main.GameTime.TimeOfDayHours; if (ActiveFromHour < ActiveToHour) { IsInActiveHour = (time >= ActiveFromHour && time <= ActiveToHour); } else { IsInActiveHour = (time >= ActiveFromHour || time <= ActiveToHour); } } // ReActivate if we're in the active hour. if (!IsVisible && IsInActiveHour) { IsVisible = true; GetComponentInChildren<Renderer>().enabled = true; Trigger.IsEnabled = true; } } void FixedUpdate() { if (!hasStoppedToTalkToPlayer) { // Make walk animation follow gametime. If game-time is too fast for reliable navigation don't animate. if (IsVisible && Main.GameTime.TimeScale < StopAnimatingAboveTimeScale) { // Update turning if (turnTarget) { Vector3 delta = turnTarget.transform.position - transform.position; Quaternion lookRotation = Quaternion.LookRotation(delta); Quaternion rotation = Quaternion.RotateTowards(transform.rotation, lookRotation, TurnSpeed * Time.deltaTime); Vector3 eulerAngles = transform.eulerAngles; eulerAngles.y = rotation.eulerAngles.y; transform.eulerAngles = eulerAngles; } // Walk forward. m_AnimSpeedMultiplier = WalkSpeed * Time.deltaTime; m_MoveSpeedMultiplier = 1.0f; Move(transform.rotation * Vector3.forward * WalkSpeed * Time.deltaTime, false, false); } else { m_AnimSpeedMultiplier = 0.0f; m_MoveSpeedMultiplier = 0.0f; m_TurnAmount = 0.0f; // Instantly set player state. if (!IsInActiveHour) { IsVisible = false; GetComponentInChildren<Renderer>().enabled = false; Trigger.IsEnabled = false; } } } else { // Stop moving when talking to the player. //m_AnimSpeedMultiplier = 0.0f; m_MoveSpeedMultiplier = 0.0f; m_TurnAmount = 0.0f; Move(Vector3.zero, false, false); // Turn to face the player. if (turnTarget) { turnToFace(TurnToFacePlayerSpeed * Time.deltaTime); } } } void turnToFace(float maxAngle) { Vector3 delta = turnTarget.transform.position - transform.position; Quaternion lookRotation = Quaternion.LookRotation(delta); Quaternion rotation = Quaternion.RotateTowards(transform.rotation, lookRotation, maxAngle); Vector3 eulerAngles = transform.eulerAngles; eulerAngles.y = rotation.eulerAngles.y; transform.eulerAngles = eulerAngles; } public void OnTriggerEnter(Collider other) { // Actively avoid the player if they're highly repellent. PlayerRepellenceZone repellenceZone = other.GetComponent<PlayerRepellenceZone>(); if (repellenceZone && (!hasBeenRepulsed || Time.time - timeAtLastRepulsion > TurnAroundCooloffSeconds) && PlayerRepellence > WalkAwayFromPlayerAtRepellance) { hasBeenRepulsed = true; timeAtLastRepulsion = Time.time; // Change direction if they're heading towards the player. const float TOLERANCE = 0.1f; float dot = Vector3.Dot( transform.forward, (transform.position - Main.PlayerCharacter.transform.position)); bool facingEachOther = (dot < TOLERANCE); if (facingEachOther && Random.Range(0.0f, 1.0f) < ChanceWalkAwayFromRepulsion) { if (!ReverseDirection) { turnTarget = lastWaypoint.Previous; ReverseDirection = true; } else { turnTarget = lastWaypoint.Next; ReverseDirection = false; } } } // Handle waypoint. Waypoint waypoint = other.GetComponent<Waypoint>(); if (waypoint && waypoint.GroupName == WayPointGroupName) { lastWaypoint = waypoint; // Exit at point if inactive. if (waypoint.IsExitPoint && !IsInActiveHour && IsVisible) { IsVisible = false; // Switch direction if not teleporting. if (!waypoint.TeleportToNext && !waypoint.TeleportToPrevious) { transform.forward = -transform.forward; turnTarget = waypoint.Previous; } GetComponentInChildren<Renderer>().enabled = false; Trigger.IsEnabled = false; } // Teleport to the next waypoint. if (waypoint.TeleportToNext || waypoint.TeleportToPrevious) { Vector3 position = transform.position; if (!ReverseDirection && waypoint.TeleportToNext) { position.x = waypoint.Next.transform.position.x; position.z = waypoint.Next.transform.position.z; turnTarget = waypoint.Next.Next; turnToFace(360.0f); } else if (ReverseDirection && waypoint.TeleportToPrevious) { position.x = waypoint.Previous.transform.position.x; position.z = waypoint.Previous.transform.position.z; turnTarget = waypoint.Previous.Previous; turnToFace(360.0f); } transform.position = position; } // Turn towards exit route if inactive. else if (!IsInActiveHour && waypoint.Exit) { turnTarget = waypoint.Exit; } // Turn towards next waypoint. else if (waypoint.Next && !ReverseDirection) { turnTarget = waypoint.Next; } // Turn towards previous waypoint. else if (waypoint.Previous && ReverseDirection) { turnTarget = waypoint.Previous; } } } public void Move(Vector3 move, bool crouch, bool jump) { // convert the world relative moveInput vector into a local-relative // turn amount and forward amount required to head in the desired // direction. if (move.magnitude > 1f) move.Normalize(); move = transform.InverseTransformDirection(move); CheckGroundStatus(); move = Vector3.ProjectOnPlane(move, m_GroundNormal); m_TurnAmount = Mathf.Atan2(move.x, move.z); m_ForwardAmount = move.z; ApplyExtraTurnRotation(); // control and velocity handling is different when grounded and airborne: if (m_IsGrounded) { HandleGroundedMovement(crouch, jump); } else { HandleAirborneMovement(); } //ScaleCapsuleForCrouching(crouch); //PreventStandingInLowHeadroom(); // send input and other state parameters to the animator UpdateAnimator(move); } void ScaleCapsuleForCrouching(bool crouch) { if (m_IsGrounded && crouch) { if (m_Crouching) return; m_Capsule.height = m_Capsule.height / 2f; m_Capsule.center = m_Capsule.center / 2f; m_Crouching = true; } else { Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up); float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half; if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, ~0, QueryTriggerInteraction.Ignore)) { m_Crouching = true; return; } m_Capsule.height = m_CapsuleHeight; m_Capsule.center = m_CapsuleCenter; m_Crouching = false; } } void PreventStandingInLowHeadroom() { // prevent standing up in crouch-only zones if (!m_Crouching) { Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up); float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half; if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, ~0, QueryTriggerInteraction.Ignore)) { m_Crouching = true; } } } void UpdateAnimator(Vector3 move) { // update the animator parameters m_Animator.SetFloat("Forward", m_ForwardAmount, 0.1f, Time.deltaTime); m_Animator.SetFloat("Turn", m_TurnAmount, 0.1f, Time.deltaTime); m_Animator.SetBool("Crouch", m_Crouching); m_Animator.SetBool("OnGround", m_IsGrounded); if (!m_IsGrounded) { m_Animator.SetFloat("Jump", m_Rigidbody.velocity.y); } // calculate which leg is behind, so as to leave that leg trailing in the jump animation // (This code is reliant on the specific run cycle offset in our animations, // and assumes one leg passes the other at the normalized clip times of 0.0 and 0.5) float runCycle = Mathf.Repeat( m_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime + m_RunCycleLegOffset, 1); float jumpLeg = (runCycle < k_Half ? 1 : -1) * m_ForwardAmount; if (m_IsGrounded) { m_Animator.SetFloat("JumpLeg", jumpLeg); } // the anim speed multiplier allows the overall speed of walking/running to be tweaked in the inspector, // which affects the movement speed because of the root motion. if (m_IsGrounded && move.magnitude > 0) { m_Animator.speed = m_AnimSpeedMultiplier; } else { // don't use that while airborne m_Animator.speed = 1; } } void HandleAirborneMovement() { // apply extra gravity from multiplier: Vector3 extraGravityForce = (Physics.gravity * m_GravityMultiplier) - Physics.gravity; m_Rigidbody.AddForce(extraGravityForce); m_GroundCheckDistance = m_Rigidbody.velocity.y < 0 ? m_OrigGroundCheckDistance : 0.01f; } void HandleGroundedMovement(bool crouch, bool jump) { // check whether conditions are right to allow a jump: if (jump && !crouch && m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Grounded")) { // jump! m_Rigidbody.velocity = new Vector3(m_Rigidbody.velocity.x, m_JumpPower, m_Rigidbody.velocity.z); m_IsGrounded = false; m_Animator.applyRootMotion = false; m_GroundCheckDistance = 0.1f; } } void ApplyExtraTurnRotation() { // help the character turn faster (this is in addition to root rotation in the animation) float turnSpeed = Mathf.Lerp(m_StationaryTurnSpeed, m_MovingTurnSpeed, m_ForwardAmount); transform.Rotate(0, m_TurnAmount * turnSpeed * Time.deltaTime, 0); } public void OnAnimatorMove() { // we implement this function to override the default root motion. // this allows us to modify the positional speed before it's applied. if (m_IsGrounded && Time.deltaTime > 0) { Vector3 v = (m_Animator.deltaPosition * m_MoveSpeedMultiplier) / Time.deltaTime; // we preserve the existing y part of the current velocity. v.y = m_Rigidbody.velocity.y; m_Rigidbody.velocity = v; } } void CheckGroundStatus() { //RaycastHit hitInfo; #if UNITY_EDITOR // helper to visualise the ground check ray in the scene view /*Debug.DrawLine(transform.position + (Vector3.up * 0.1f), transform.position + (Vector3.up * 0.1f) + (Vector3.down * m_GroundCheckDistance));*/ #endif // 0.1f is a small offset to start the ray from inside the character // it is also good to note that the transform position in the sample assets is at the base of the character /*if (Physics.Raycast(transform.position + (Vector3.up * 0.1f), Vector3.down, out hitInfo, m_GroundCheckDistance))*/ { m_GroundNormal = Vector3.up /*hitInfo.normal*/; m_IsGrounded = true; m_Animator.applyRootMotion = true; } /*else { m_IsGrounded = false; m_GroundNormal = Vector3.up; m_Animator.applyRootMotion = false; }*/ } }
using System; using System.Globalization; using System.Xml; using Google.GData.Client; using Google.GData.Extensions; namespace Google.GData.Spreadsheets { /// <summary> /// Entry API customization class for defining entries in a Cells feed. /// </summary> public class CellEntry : AbstractEntry { /// <summary> /// Category used to label entries that contain Cell extension data. /// </summary> public static AtomCategory CELL_CATEGORY = new AtomCategory(GDataSpreadsheetsNameTable.Cell, new AtomUri(BaseNameTable.gKind)); /// <summary> /// Constructs a new CellEntry instance with the appropriate category /// to indicate that it is a cell. /// </summary> public CellEntry() { Categories.Add(CELL_CATEGORY); AddExtension(new CellElement()); } /// <summary> /// Constructs a new CellEntry instance with the provided content. /// </summary> /// <param name="inputValue">The uncalculated content of the cell.</param> public CellEntry(string inputValue) : this() { Cell = new CellElement(); Cell.InputValue = inputValue; } /// <summary> /// create a CellEntry for a given row/column /// </summary> /// <param name="row"></param> /// <param name="column"></param> [CLSCompliant(false)] public CellEntry(uint row, uint column) : this() { Cell = new CellElement(); Cell.Column = column; Cell.Row = row; } /// <summary> /// create a CellEntry for a given row/column and /// initial value /// </summary> /// <param name="row"></param> /// <param name="column"></param> /// <param name="inputValue">The uncalculated content of the cell.</param> [CLSCompliant(false)] public CellEntry(uint row, uint column, string inputValue) : this(row, column) { Cell.InputValue = inputValue; } /// <summary> /// The cell element in this cell entry /// </summary> public CellElement Cell { get { CellElement c = FindExtension(GDataSpreadsheetsNameTable.XmlCellElement, GDataSpreadsheetsNameTable.NSGSpreadsheets) as CellElement; if (c == null) { c = new CellElement(); Cell = c; } return c; } set { ReplaceExtension(GDataSpreadsheetsNameTable.XmlCellElement, GDataSpreadsheetsNameTable.NSGSpreadsheets, value); Dirty = true; } } /// <summary> /// The row the cell lies in /// </summary> [CLSCompliant(false)] public uint Row { get { return Cell.Row; } set { Cell.Row = value; Dirty = true; } } /// <summary> /// The column the cell lies in /// </summary> [CLSCompliant(false)] public uint Column { get { return Cell.Column; } set { Cell.Column = value; Dirty = true; } } /// <summary> /// The input (uncalculated) value for the cell /// </summary> public string InputValue { get { return Cell.InputValue; } set { Cell.InputValue = value; Dirty = true; } } /// <summary> /// The numeric (calculated) value for the cell /// </summary> public string NumericValue { get { return Cell.NumericValue; } set { Cell.NumericValue = value; Dirty = true; } } /// <summary> /// The numeric (calculated) value for the cell /// </summary> public string Value { get { return Cell.Value; } set { Cell.Value = value; Dirty = true; } } /// <summary> /// add the spreadsheet NS /// </summary> /// <param name="writer">The XmlWrite, where we want to add default namespaces to</param> protected override void AddOtherNamespaces(XmlWriter writer) { base.AddOtherNamespaces(writer); if (writer == null) { throw new ArgumentNullException("writer"); } string strPrefix = writer.LookupPrefix(GDataSpreadsheetsNameTable.NSGSpreadsheets); if (strPrefix == null) { writer.WriteAttributeString("xmlns", GDataSpreadsheetsNameTable.Prefix, null, GDataSpreadsheetsNameTable.NSGSpreadsheets); } } /// <summary> /// Checks if this is a namespace declaration that we already added /// </summary> /// <param name="node">XmlNode to check</param> /// <returns>True if this node should be skipped</returns> protected override bool SkipNode(XmlNode node) { if (base.SkipNode(node)) { return true; } return (node.NodeType == XmlNodeType.Attribute && node.Name.StartsWith("xmlns") && string.Compare(node.Value, GDataSpreadsheetsNameTable.NSGSpreadsheets) == 0); } #region Schema Extensions /// <summary> /// GData schema extension describing a Cell in a spreadsheet. /// </summary> public class CellElement : SimpleElement { /// <summary> /// default constructor for the Cell element /// </summary> public CellElement() : base(GDataSpreadsheetsNameTable.XmlCellElement, GDataSpreadsheetsNameTable.Prefix, GDataSpreadsheetsNameTable.NSGSpreadsheets) { Attributes.Add(GDataSpreadsheetsNameTable.XmlAttributeRow, null); Attributes.Add(GDataSpreadsheetsNameTable.XmlAttributeColumn, null); Attributes.Add(GDataSpreadsheetsNameTable.XmlAttributeInputValue, null); Attributes.Add(GDataSpreadsheetsNameTable.XmlAttributeNumericValue, null); } /// <summary> /// The row the cell lies in /// </summary> [CLSCompliant(false)] public uint Row { get { return Convert.ToUInt32(Attributes[GDataSpreadsheetsNameTable.XmlAttributeRow], CultureInfo.InvariantCulture); } set { Attributes[GDataSpreadsheetsNameTable.XmlAttributeRow] = value.ToString(); } } /// <summary> /// The column the cell lies in /// </summary> [CLSCompliant(false)] public uint Column { get { return Convert.ToUInt32(Attributes[GDataSpreadsheetsNameTable.XmlAttributeColumn], CultureInfo.InvariantCulture); } set { Attributes[GDataSpreadsheetsNameTable.XmlAttributeColumn] = value.ToString(); } } /// <summary> /// The input (uncalculated) value for the cell /// </summary> public string InputValue { get { return Attributes[GDataSpreadsheetsNameTable.XmlAttributeInputValue] as string; } set { Attributes[GDataSpreadsheetsNameTable.XmlAttributeInputValue] = value; } } /// <summary> /// The numeric (calculated) value for the cell /// </summary> public string NumericValue { get { return Attributes[GDataSpreadsheetsNameTable.XmlAttributeNumericValue] as string; } set { Attributes[GDataSpreadsheetsNameTable.XmlAttributeNumericValue] = value; } } } // class Cell #endregion } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// TemplateUpdateSummary /// </summary> [DataContract] public partial class TemplateUpdateSummary : IEquatable<TemplateUpdateSummary>, IValidatableObject { public TemplateUpdateSummary() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="TemplateUpdateSummary" /> class. /// </summary> /// <param name="BulkEnvelopeStatus">BulkEnvelopeStatus.</param> /// <param name="EnvelopeId">The envelope ID of the envelope status that failed to post..</param> /// <param name="ErrorDetails">ErrorDetails.</param> /// <param name="ListCustomFieldUpdateResults">ListCustomFieldUpdateResults.</param> /// <param name="LockInformation">LockInformation.</param> /// <param name="PurgeState">PurgeState.</param> /// <param name="RecipientUpdateResults">RecipientUpdateResults.</param> /// <param name="TabUpdateResults">TabUpdateResults.</param> /// <param name="TextCustomFieldUpdateResults">TextCustomFieldUpdateResults.</param> public TemplateUpdateSummary(BulkEnvelopeStatus BulkEnvelopeStatus = default(BulkEnvelopeStatus), string EnvelopeId = default(string), ErrorDetails ErrorDetails = default(ErrorDetails), List<ListCustomField> ListCustomFieldUpdateResults = default(List<ListCustomField>), LockInformation LockInformation = default(LockInformation), string PurgeState = default(string), List<RecipientUpdateResponse> RecipientUpdateResults = default(List<RecipientUpdateResponse>), Tabs TabUpdateResults = default(Tabs), List<TextCustomField> TextCustomFieldUpdateResults = default(List<TextCustomField>)) { this.BulkEnvelopeStatus = BulkEnvelopeStatus; this.EnvelopeId = EnvelopeId; this.ErrorDetails = ErrorDetails; this.ListCustomFieldUpdateResults = ListCustomFieldUpdateResults; this.LockInformation = LockInformation; this.PurgeState = PurgeState; this.RecipientUpdateResults = RecipientUpdateResults; this.TabUpdateResults = TabUpdateResults; this.TextCustomFieldUpdateResults = TextCustomFieldUpdateResults; } /// <summary> /// Gets or Sets BulkEnvelopeStatus /// </summary> [DataMember(Name="bulkEnvelopeStatus", EmitDefaultValue=false)] public BulkEnvelopeStatus BulkEnvelopeStatus { get; set; } /// <summary> /// The envelope ID of the envelope status that failed to post. /// </summary> /// <value>The envelope ID of the envelope status that failed to post.</value> [DataMember(Name="envelopeId", EmitDefaultValue=false)] public string EnvelopeId { get; set; } /// <summary> /// Gets or Sets ErrorDetails /// </summary> [DataMember(Name="errorDetails", EmitDefaultValue=false)] public ErrorDetails ErrorDetails { get; set; } /// <summary> /// Gets or Sets ListCustomFieldUpdateResults /// </summary> [DataMember(Name="listCustomFieldUpdateResults", EmitDefaultValue=false)] public List<ListCustomField> ListCustomFieldUpdateResults { get; set; } /// <summary> /// Gets or Sets LockInformation /// </summary> [DataMember(Name="lockInformation", EmitDefaultValue=false)] public LockInformation LockInformation { get; set; } /// <summary> /// Gets or Sets PurgeState /// </summary> [DataMember(Name="purgeState", EmitDefaultValue=false)] public string PurgeState { get; set; } /// <summary> /// Gets or Sets RecipientUpdateResults /// </summary> [DataMember(Name="recipientUpdateResults", EmitDefaultValue=false)] public List<RecipientUpdateResponse> RecipientUpdateResults { get; set; } /// <summary> /// Gets or Sets TabUpdateResults /// </summary> [DataMember(Name="tabUpdateResults", EmitDefaultValue=false)] public Tabs TabUpdateResults { get; set; } /// <summary> /// Gets or Sets TextCustomFieldUpdateResults /// </summary> [DataMember(Name="textCustomFieldUpdateResults", EmitDefaultValue=false)] public List<TextCustomField> TextCustomFieldUpdateResults { 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 TemplateUpdateSummary {\n"); sb.Append(" BulkEnvelopeStatus: ").Append(BulkEnvelopeStatus).Append("\n"); sb.Append(" EnvelopeId: ").Append(EnvelopeId).Append("\n"); sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n"); sb.Append(" ListCustomFieldUpdateResults: ").Append(ListCustomFieldUpdateResults).Append("\n"); sb.Append(" LockInformation: ").Append(LockInformation).Append("\n"); sb.Append(" PurgeState: ").Append(PurgeState).Append("\n"); sb.Append(" RecipientUpdateResults: ").Append(RecipientUpdateResults).Append("\n"); sb.Append(" TabUpdateResults: ").Append(TabUpdateResults).Append("\n"); sb.Append(" TextCustomFieldUpdateResults: ").Append(TextCustomFieldUpdateResults).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 TemplateUpdateSummary); } /// <summary> /// Returns true if TemplateUpdateSummary instances are equal /// </summary> /// <param name="other">Instance of TemplateUpdateSummary to be compared</param> /// <returns>Boolean</returns> public bool Equals(TemplateUpdateSummary other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.BulkEnvelopeStatus == other.BulkEnvelopeStatus || this.BulkEnvelopeStatus != null && this.BulkEnvelopeStatus.Equals(other.BulkEnvelopeStatus) ) && ( this.EnvelopeId == other.EnvelopeId || this.EnvelopeId != null && this.EnvelopeId.Equals(other.EnvelopeId) ) && ( this.ErrorDetails == other.ErrorDetails || this.ErrorDetails != null && this.ErrorDetails.Equals(other.ErrorDetails) ) && ( this.ListCustomFieldUpdateResults == other.ListCustomFieldUpdateResults || this.ListCustomFieldUpdateResults != null && this.ListCustomFieldUpdateResults.SequenceEqual(other.ListCustomFieldUpdateResults) ) && ( this.LockInformation == other.LockInformation || this.LockInformation != null && this.LockInformation.Equals(other.LockInformation) ) && ( this.PurgeState == other.PurgeState || this.PurgeState != null && this.PurgeState.Equals(other.PurgeState) ) && ( this.RecipientUpdateResults == other.RecipientUpdateResults || this.RecipientUpdateResults != null && this.RecipientUpdateResults.SequenceEqual(other.RecipientUpdateResults) ) && ( this.TabUpdateResults == other.TabUpdateResults || this.TabUpdateResults != null && this.TabUpdateResults.Equals(other.TabUpdateResults) ) && ( this.TextCustomFieldUpdateResults == other.TextCustomFieldUpdateResults || this.TextCustomFieldUpdateResults != null && this.TextCustomFieldUpdateResults.SequenceEqual(other.TextCustomFieldUpdateResults) ); } /// <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.BulkEnvelopeStatus != null) hash = hash * 59 + this.BulkEnvelopeStatus.GetHashCode(); if (this.EnvelopeId != null) hash = hash * 59 + this.EnvelopeId.GetHashCode(); if (this.ErrorDetails != null) hash = hash * 59 + this.ErrorDetails.GetHashCode(); if (this.ListCustomFieldUpdateResults != null) hash = hash * 59 + this.ListCustomFieldUpdateResults.GetHashCode(); if (this.LockInformation != null) hash = hash * 59 + this.LockInformation.GetHashCode(); if (this.PurgeState != null) hash = hash * 59 + this.PurgeState.GetHashCode(); if (this.RecipientUpdateResults != null) hash = hash * 59 + this.RecipientUpdateResults.GetHashCode(); if (this.TabUpdateResults != null) hash = hash * 59 + this.TabUpdateResults.GetHashCode(); if (this.TextCustomFieldUpdateResults != null) hash = hash * 59 + this.TextCustomFieldUpdateResults.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
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 xStudio.Web.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; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Xml.XPath; namespace System.Xml.Xsl.Runtime { internal class TokenInfo { public char startChar; // First element of numbering sequence for format token public int startIdx; // Start index of separator token public string formatString; // Format string for separator token public int length; // Length of separator token, or minimum length of decimal numbers for format token // Instances of this internal class must be created via CreateFormat and CreateSeparator private TokenInfo() { } [Conditional("DEBUG")] public void AssertSeparator(bool isSeparator) { Debug.Assert(isSeparator == (formatString != null), "AssertSeparator"); } // Creates a TokenInfo for a separator token. public static TokenInfo CreateSeparator(string formatString, int startIdx, int tokLen) { Debug.Assert(startIdx >= 0 && tokLen > 0); TokenInfo token = new TokenInfo(); { token.startIdx = startIdx; token.formatString = formatString; token.length = tokLen; } return token; } // Maps a token of alphanumeric characters to a numbering format ID and a // minimum length bound. Tokens specify the character(s) that begins a Unicode // numbering sequence. For example, "i" specifies lower case roman numeral // numbering. Leading "zeros" specify a minimum length to be maintained by // padding, if necessary. public static TokenInfo CreateFormat(string formatString, int startIdx, int tokLen) { Debug.Assert(startIdx >= 0 && tokLen > 0); TokenInfo token = new TokenInfo(); token.formatString = null; token.length = 1; bool useDefault = false; char ch = formatString[startIdx]; switch (ch) { case '1': case 'A': case 'I': case 'a': case 'i': break; default: // NOTE: We do not support Tamil and Ethiopic numbering systems having no zeros if (CharUtil.IsDecimalDigitOne(ch)) { break; } if (CharUtil.IsDecimalDigitOne((char)(ch + 1))) { // Leading zeros request padding. Track how much. int idx = startIdx; do { token.length++; } while (--tokLen > 0 && ch == formatString[++idx]); // Recognize the token only if the next character is "one" if (formatString[idx] == ++ch) { break; } } useDefault = true; break; } if (tokLen != 1) { // If remaining token length is not 1, do not recognize the token useDefault = true; } if (useDefault) { // Default to Arabic numbering with no zero padding token.startChar = NumberFormatter.DefaultStartChar; token.length = 1; } else { token.startChar = ch; } return token; } } internal class NumberFormatter : NumberFormatterBase { private readonly string _formatString; private readonly int _lang; private readonly string _letterValue; private readonly string _groupingSeparator; private readonly int _groupingSize; private readonly List<TokenInfo> _tokens; public const char DefaultStartChar = '1'; private static readonly TokenInfo s_defaultFormat = TokenInfo.CreateFormat("0", 0, 1); private static readonly TokenInfo s_defaultSeparator = TokenInfo.CreateSeparator(".", 0, 1); // Creates a Format object parsing format string into format tokens (alphanumeric) and separators (non-alphanumeric). public NumberFormatter(string formatString, int lang, string letterValue, string groupingSeparator, int groupingSize) { Debug.Assert(groupingSeparator.Length <= 1); _formatString = formatString; _lang = lang; _letterValue = letterValue; _groupingSeparator = groupingSeparator; _groupingSize = groupingSeparator.Length > 0 ? groupingSize : 0; if (formatString == "1" || formatString.Length == 0) { // Special case of the default format return; } _tokens = new List<TokenInfo>(); int idxStart = 0; bool isAlphaNumeric = CharUtil.IsAlphaNumeric(formatString[idxStart]); if (isAlphaNumeric) { // If the first one is alpha num add empty separator as a prefix _tokens.Add(null); } for (int idx = 0; idx <= formatString.Length; idx++) { // Loop until a switch from formatString token to separator is detected (or vice-versa) if (idx == formatString.Length || isAlphaNumeric != CharUtil.IsAlphaNumeric(formatString[idx])) { if (isAlphaNumeric) { // Just finished a format token _tokens.Add(TokenInfo.CreateFormat(formatString, idxStart, idx - idxStart)); } else { // Just finished a separator token _tokens.Add(TokenInfo.CreateSeparator(formatString, idxStart, idx - idxStart)); } // Begin parsing the next format token or separator idxStart = idx; // Flip flag from format token to separator or vice-versa isAlphaNumeric = !isAlphaNumeric; } } } /// <summary> /// Format the given xsl:number place marker /// </summary> /// <param name="val">Place marker - either a sequence of ints, or a double singleton</param> /// <returns>Formatted string</returns> public string FormatSequence(IList<XPathItem> val) { StringBuilder sb = new StringBuilder(); // If the value was supplied directly, in the 'value' attribute, check its validity if (val.Count == 1 && val[0].ValueType == typeof(double)) { double dblVal = val[0].ValueAsDouble; if (!(0.5 <= dblVal && dblVal < double.PositiveInfinity)) { // Errata E24: It is an error if the number is NaN, infinite or less than 0.5; an XSLT processor may signal // the error; if it does not signal the error, it must recover by converting the number to a string as if // by a call to the 'string' function and inserting the resulting string into the result tree. return XPathConvert.DoubleToString(dblVal); } } if (_tokens == null) { // Special case of the default format for (int idx = 0; idx < val.Count; idx++) { if (idx > 0) { sb.Append('.'); } FormatItem(sb, val[idx], DefaultStartChar, 1); } } else { int cFormats = _tokens.Count; TokenInfo prefix = _tokens[0], suffix; if (cFormats % 2 == 0) { suffix = null; } else { suffix = _tokens[--cFormats]; } TokenInfo periodicSeparator = 2 < cFormats ? _tokens[cFormats - 2] : s_defaultSeparator; TokenInfo periodicFormat = 0 < cFormats ? _tokens[cFormats - 1] : s_defaultFormat; if (prefix != null) { prefix.AssertSeparator(true); sb.Append(prefix.formatString, prefix.startIdx, prefix.length); } int valCount = val.Count; for (int i = 0; i < valCount; i++) { int formatIndex = i * 2; bool haveFormat = formatIndex < cFormats; if (i > 0) { TokenInfo thisSeparator = haveFormat ? _tokens[formatIndex + 0] : periodicSeparator; thisSeparator.AssertSeparator(true); sb.Append(thisSeparator.formatString, thisSeparator.startIdx, thisSeparator.length); } TokenInfo thisFormat = haveFormat ? _tokens[formatIndex + 1] : periodicFormat; thisFormat.AssertSeparator(false); FormatItem(sb, val[i], thisFormat.startChar, thisFormat.length); } if (suffix != null) { suffix.AssertSeparator(true); sb.Append(suffix.formatString, suffix.startIdx, suffix.length); } } return sb.ToString(); } private void FormatItem(StringBuilder sb, XPathItem item, char startChar, int length) { double dblVal; if (item.ValueType == typeof(int)) { dblVal = (double)item.ValueAsInt; } else { Debug.Assert(item.ValueType == typeof(double), "Item must be either of type int, or double"); dblVal = XsltFunctions.Round(item.ValueAsDouble); } Debug.Assert(1 <= dblVal && dblVal < double.PositiveInfinity); char zero = '0'; switch (startChar) { case '1': break; case 'A': case 'a': if (dblVal <= MaxAlphabeticValue) { ConvertToAlphabetic(sb, dblVal, startChar, 26); return; } break; case 'I': case 'i': if (dblVal <= MaxRomanValue) { ConvertToRoman(sb, dblVal, /*upperCase:*/ startChar == 'I'); return; } break; default: Debug.Assert(CharUtil.IsDecimalDigitOne(startChar), "Unexpected startChar: " + startChar); zero = (char)(startChar - 1); break; } sb.Append(ConvertToDecimal(dblVal, length, zero, _groupingSeparator, _groupingSize)); } private static string ConvertToDecimal(double val, int minLen, char zero, string groupSeparator, int groupSize) { Debug.Assert(val >= 0 && val == Math.Round(val), "ConvertToArabic operates on non-negative integer numbers only"); string str = XPathConvert.DoubleToString(val); int shift = zero - '0'; // Figure out new string length without separators int oldLen = str.Length; int newLen = Math.Max(oldLen, minLen); // Calculate length of string with separators if (groupSize != 0) { Debug.Assert(groupSeparator.Length == 1); checked { newLen += (newLen - 1) / groupSize; } } // If the new number of characters equals the old one, no changes need to be made if (newLen == oldLen && shift == 0) { return str; } // If grouping is not needed, add zero padding only if (groupSize == 0 && shift == 0) { return str.PadLeft(newLen, zero); } // Add both grouping separators and zero padding to the string representation of a number #if true unsafe { char* result = stackalloc char[newLen]; char separator = (groupSeparator.Length > 0) ? groupSeparator[0] : ' '; fixed (char* pin = str) { char* pOldEnd = pin + oldLen - 1; char* pNewEnd = result + newLen - 1; int cnt = groupSize; while (true) { // Move digit to its new location (zero if we've run out of digits) *pNewEnd-- = (pOldEnd >= pin) ? (char)(*pOldEnd-- + shift) : zero; if (pNewEnd < result) { break; } if (/*groupSize > 0 && */--cnt == 0) { // Every groupSize digits insert the separator *pNewEnd-- = separator; cnt = groupSize; Debug.Assert(pNewEnd >= result, "Separator cannot be the first character"); } } } return new string(result, 0, newLen); } #else // Safe version is about 20% slower after NGEN char[] result = new char[newLen]; char separator = (groupSeparator.Length > 0) ? groupSeparator[0] : ' '; int oldEnd = oldLen - 1; int newEnd = newLen - 1; int cnt = groupSize; while (true) { // Move digit to its new location (zero if we've run out of digits) result[newEnd--] = (oldEnd >= 0) ? (char)(str[oldEnd--] + shift) : zero; if (newEnd < 0) { break; } if (/*groupSize > 0 && */--cnt == 0) { // Every groupSize digits insert the separator result[newEnd--] = separator; cnt = groupSize; Debug.Assert(newEnd >= 0, "Separator cannot be the first character"); } } return new string(result, 0, newLen); #endif } } }
// // HttpClientHandler.cs // // Authors: // Marek Safar <marek.safar@gmail.com> // // Copyright (C) 2011 Xamarin Inc (http://www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Threading; using System.Threading.Tasks; using System.Collections.Specialized; using System.Net.Http.Headers; using System.Reflection; using System.IO; namespace System.Net.Http { public class HttpClientHandler : HttpMessageHandler { static long groupCounter; bool allowAutoRedirect; DecompressionMethods automaticDecompression; CookieContainer cookieContainer; ICredentials credentials; int maxAutomaticRedirections; long maxRequestContentBufferSize; bool preAuthenticate; IWebProxy proxy; bool useCookies; bool useDefaultCredentials; bool useProxy; ClientCertificateOption certificate; int sentRequest; string connectionGroupName; int disposed; public HttpClientHandler () { allowAutoRedirect = true; maxAutomaticRedirections = 50; maxRequestContentBufferSize = int.MaxValue; useCookies = true; useProxy = true; connectionGroupName = "HttpClientHandler" + Interlocked.Increment (ref groupCounter); } internal void EnsureModifiability () { if (sentRequest != 0) throw new InvalidOperationException ( "This instance has already started one or more requests. " + "Properties can only be modified before sending the first request."); } public bool AllowAutoRedirect { get { return allowAutoRedirect; } set { EnsureModifiability (); allowAutoRedirect = value; } } public DecompressionMethods AutomaticDecompression { get { return automaticDecompression; } set { EnsureModifiability (); automaticDecompression = value; } } public ClientCertificateOption ClientCertificateOptions { get { return certificate; } set { EnsureModifiability (); certificate = value; } } public CookieContainer CookieContainer { get { return cookieContainer ?? (cookieContainer = new CookieContainer ()); } set { EnsureModifiability (); cookieContainer = value; } } public ICredentials Credentials { get { return credentials; } set { EnsureModifiability (); credentials = value; } } public int MaxAutomaticRedirections { get { return maxAutomaticRedirections; } set { EnsureModifiability (); if (value <= 0) throw new ArgumentOutOfRangeException (); maxAutomaticRedirections = value; } } public long MaxRequestContentBufferSize { get { return maxRequestContentBufferSize; } set { EnsureModifiability (); if (value < 0) throw new ArgumentOutOfRangeException (); maxRequestContentBufferSize = value; } } public bool PreAuthenticate { get { return preAuthenticate; } set { EnsureModifiability (); preAuthenticate = value; } } public IWebProxy Proxy { get { return proxy; } set { EnsureModifiability (); if (!UseProxy) throw new InvalidOperationException (); proxy = value; } } public virtual bool SupportsAutomaticDecompression { get { return true; } } public virtual bool SupportsProxy { get { return true; } } public virtual bool SupportsRedirectConfiguration { get { return true; } } public bool UseCookies { get { return useCookies; } set { EnsureModifiability (); useCookies = value; } } public bool UseDefaultCredentials { get { return useDefaultCredentials; } set { EnsureModifiability (); useDefaultCredentials = value; } } public bool UseProxy { get { return useProxy; } set { EnsureModifiability (); useProxy = value; } } protected override void Dispose (bool disposing) { if (disposing && disposed != 1) { Interlocked.Exchange(ref disposed, 1); var closeConnectionGroupMethod = typeof(ServicePointManager).GetMethod("CloseConnectionGroup", BindingFlags.NonPublic | BindingFlags.Static); if (closeConnectionGroupMethod != null) { closeConnectionGroupMethod.Invoke(null, new object[] { connectionGroupName }); } } base.Dispose (disposing); } internal virtual HttpWebRequest CreateWebRequest (HttpRequestMessage request) { var wr = (HttpWebRequest)WebRequest.Create(request.RequestUri); wr.AllowWriteStreamBuffering = false; var throwOnErrorProperty = typeof(HttpWebRequest).GetProperty("ThrowOnError", BindingFlags.NonPublic | BindingFlags.Instance); if (throwOnErrorProperty != null) { throwOnErrorProperty.SetValue(wr, false, null); } wr.ConnectionGroupName = connectionGroupName; wr.Method = request.Method.Method; wr.ProtocolVersion = request.Version; if (wr.ProtocolVersion == HttpVersion.Version10) { wr.KeepAlive = request.Headers.ConnectionKeepAlive; } else { wr.KeepAlive = request.Headers.ConnectionClose != true; } wr.ServicePoint.Expect100Continue = request.Headers.ExpectContinue == true; if (allowAutoRedirect) { wr.AllowAutoRedirect = true; wr.MaximumAutomaticRedirections = maxAutomaticRedirections; } else { wr.AllowAutoRedirect = false; } wr.AutomaticDecompression = automaticDecompression; wr.PreAuthenticate = preAuthenticate; if (useCookies) { // It cannot be null or allowAutoRedirect won't work wr.CookieContainer = CookieContainer; } if (useDefaultCredentials) { wr.UseDefaultCredentials = true; } else { wr.Credentials = credentials; } if (useProxy) { wr.Proxy = proxy; } // Add request headers var headers = wr.Headers; var addValueMethod = typeof(WebHeaderCollection).GetMethod("AddWithoutValidate", BindingFlags.NonPublic | BindingFlags.Instance); foreach (var header in request.Headers) { foreach (var value in header.Value) { addValueMethod.Invoke(headers, new object[] { header.Key, value }); } } return wr; } HttpResponseMessage CreateResponseMessage (HttpWebResponse wr, HttpRequestMessage requestMessage, CancellationToken cancellationToken) { var response = new HttpResponseMessage (wr.StatusCode); response.RequestMessage = requestMessage; response.ReasonPhrase = wr.StatusDescription; response.Content = new StreamContent (wr.GetResponseStream (), cancellationToken); var headers = wr.Headers; for (int i = 0; i < headers.Count; ++i) { var key = headers.GetKey(i); var value = headers.GetValues (i); HttpHeaders item_headers; if (HttpHeaders.GetKnownHeaderKind (key) == Headers.HttpHeaderKind.Content) item_headers = response.Content.Headers; else item_headers = response.Headers; item_headers.TryAddWithoutValidation (key, value); } requestMessage.RequestUri = wr.ResponseUri; return response; } #if UNITY protected internal override Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, CancellationToken cancellationToken) { if (disposed != 0) throw new ObjectDisposedException (GetType ().ToString ()); Interlocked.Exchange(ref sentRequest, 1); var wrequest = CreateWebRequest (request); HttpWebResponse wresponse = null; try { using (cancellationToken.Register(l => ((HttpWebRequest)l).Abort(), wrequest)) { var content = request.Content; if (content != null) { var headers = wrequest.Headers; var addValueMethod = headers.GetType().GetMethod("AddWithoutValidate", BindingFlags.NonPublic | BindingFlags.Instance); foreach (var header in content.Headers) { foreach (var value in header.Value) { addValueMethod.Invoke(headers, new object[] { header.Key, value }); } } // // Content length has to be set because HttpWebRequest is running without buffering // var contentLength = content.Headers.ContentLength; if (contentLength != null) { wrequest.ContentLength = contentLength.Value; } else { content.LoadIntoBufferAsync(MaxRequestContentBufferSize).Await(); wrequest.ContentLength = content.Headers.ContentLength.Value; } var stream = wrequest.GetRequestStreamAsync().Await(); request.Content.CopyToAsync(stream).Await(); } else if (HttpMethod.Post.Equals(request.Method) || HttpMethod.Put.Equals(request.Method) || HttpMethod.Delete.Equals(request.Method)) { // Explicitly set this to make sure we're sending a "Content-Length: 0" header. // This fixes the issue that's been reported on the forums: // http://forums.xamarin.com/discussion/17770/length-required-error-in-http-post-since-latest-release wrequest.ContentLength = 0; } wresponse = (HttpWebResponse)wrequest.GetResponseAsync().Await(); } } catch (WebException we) { if (we.Status == WebExceptionStatus.ProtocolError) { wresponse = (HttpWebResponse)we.Response; } else if (we.Status != WebExceptionStatus.RequestCanceled) { throw; } } catch (AggregateException e) { var we = e.InnerException as WebException; if (we == null) { throw; } if (we.Status == WebExceptionStatus.ProtocolError) { wresponse = (HttpWebResponse)we.Response; } else if (we.Status != WebExceptionStatus.RequestCanceled) { throw; } } if (cancellationToken.IsCancellationRequested) { var cancelled = new TaskCompletionSource<HttpResponseMessage>(); cancelled.SetCanceled(); return cancelled.Task; } return Task.FromResult(CreateResponseMessage(wresponse, request, cancellationToken)); } #else protected async internal override Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, CancellationToken cancellationToken) { if (disposed != 0) throw new ObjectDisposedException (GetType ().ToString ()); Interlocked.Exchange(ref sentRequest, 1); var wrequest = CreateWebRequest (request); HttpWebResponse wresponse = null; try { using (cancellationToken.Register(l => ((HttpWebRequest)l).Abort(), wrequest)) { var content = request.Content; if (content != null) { var headers = wrequest.Headers; var addValueMethod = headers.GetType().GetMethod("AddWithoutValidate", BindingFlags.NonPublic | BindingFlags.Instance); foreach (var header in content.Headers) { foreach (var value in header.Value) { addValueMethod.Invoke(headers, new object[] { header.Key, value }); } } // // Content length has to be set because HttpWebRequest is running without buffering // var contentLength = content.Headers.ContentLength; if (contentLength != null) { wrequest.ContentLength = contentLength.Value; } else { await content.LoadIntoBufferAsync(MaxRequestContentBufferSize).ConfigureAwait(false); wrequest.ContentLength = content.Headers.ContentLength.Value; } var resendContentFactoryField = typeof(HttpWebRequest).GetField("ResendContentFactory", BindingFlags.NonPublic | BindingFlags.Instance); if (resendContentFactoryField != null) { resendContentFactoryField.SetValue(wrequest, new Action<Stream>(content.CopyTo)); } var stream = await wrequest.GetRequestStreamAsync().ConfigureAwait(false); await request.Content.CopyToAsync(stream).ConfigureAwait(false); } else if (HttpMethod.Post.Equals(request.Method) || HttpMethod.Put.Equals(request.Method) || HttpMethod.Delete.Equals(request.Method)) { // Explicitly set this to make sure we're sending a "Content-Length: 0" header. // This fixes the issue that's been reported on the forums: // http://forums.xamarin.com/discussion/17770/length-required-error-in-http-post-since-latest-release wrequest.ContentLength = 0; } wresponse = (HttpWebResponse)await wrequest.GetResponseAsync().ConfigureAwait(false); } } catch (WebException we) { if (we.Status == WebExceptionStatus.ProtocolError) { wresponse = (HttpWebResponse)we.Response; } else if (we.Status != WebExceptionStatus.RequestCanceled) { throw; } } catch (AggregateException e) { var we = e.InnerException as WebException; if (we == null) { throw; } if (we.Status == WebExceptionStatus.ProtocolError) { wresponse = (HttpWebResponse)we.Response; } else if (we.Status != WebExceptionStatus.RequestCanceled) { throw; } } if (cancellationToken.IsCancellationRequested) { var cancelled = new TaskCompletionSource<HttpResponseMessage>(); cancelled.SetCanceled(); return await cancelled.Task; } return CreateResponseMessage(wresponse, request, cancellationToken); } #endif } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using UnityEngine.Events; namespace UIWidgets { /// <summary> /// Splitter type. /// </summary> public enum SplitterType { Horizontal = 0, Vertical = 1, } /// <summary> /// Splitter resize event. /// </summary> [SerializeField] public class SplitterResizeEvent : UnityEvent<Splitter> { } /// <summary> /// Splitter. /// </summary> [AddComponentMenu("UI/UIWidgets/Splitter")] public class Splitter : MonoBehaviour, IInitializePotentialDragHandler, IBeginDragHandler, IEndDragHandler, IDragHandler, IPointerEnterHandler, IPointerExitHandler { /// <summary> /// The type. /// </summary> public SplitterType Type = SplitterType.Vertical; /// <summary> /// Is need to update RectTransform on Resize. /// </summary> [SerializeField] public bool UpdateRectTransforms = true; /// <summary> /// Is need to update LayoutElement on Resize. /// </summary> [SerializeField] public bool UpdateLayoutElements = true; /// <summary> /// The current camera. For Screen Space - Overlay let it empty. /// </summary> [SerializeField] public Camera CurrentCamera; /// <summary> /// The cursor texture. /// </summary> [SerializeField] public Texture2D CursorTexture; /// <summary> /// The cursor hot spot. /// </summary> [SerializeField] public Vector2 CursorHotSpot = new Vector2(16, 16); /// <summary> /// The default cursor texture. /// </summary> [SerializeField] public Texture2D DefaultCursorTexture; /// <summary> /// The default cursor hot spot. /// </summary> [SerializeField] public Vector2 DefaultCursorHotSpot; /// <summary> /// OnStartResize event. /// </summary> public SplitterResizeEvent OnStartResize = new SplitterResizeEvent(); /// <summary> /// OnEndResize event. /// </summary> public SplitterResizeEvent OnEndResize = new SplitterResizeEvent(); RectTransform rectTransform; /// <summary> /// Gets the rect transform. /// </summary> /// <value>The rect transform.</value> public RectTransform RectTransform { get { if (rectTransform==null) { rectTransform = transform as RectTransform; } return rectTransform; } } Canvas canvas; RectTransform leftTarget; RectTransform rightTarget; LayoutElement leftTargetElement; LayoutElement LeftTargetElement { get { if (leftTargetElement==null) { leftTargetElement = leftTarget.GetComponent<LayoutElement>(); if (leftTargetElement==null) { leftTargetElement = leftTarget.gameObject.AddComponent<LayoutElement>(); } } return leftTargetElement; } } LayoutElement rightTargetElement; LayoutElement RightTargetElement { get { if (rightTargetElement==null) { rightTargetElement = rightTarget.GetComponent<LayoutElement>(); if (rightTargetElement==null) { rightTargetElement = rightTarget.gameObject.AddComponent<LayoutElement>(); } } return rightTargetElement; } } Vector2 summarySize; bool processDrag; void Start() { Init(); } /// <summary> /// Raises the initialize potential drag event. /// </summary> /// <param name="eventData">Event data.</param> public void OnInitializePotentialDrag(PointerEventData eventData) { Init(); } /// <summary> /// Init this instance. /// </summary> public void Init() { canvas = Utilites.FindTopmostCanvas(transform).GetComponent<Canvas>(); } bool cursorChanged = false; protected bool IsCursorOver; /// <summary> /// Called by a BaseInputModule when an OnPointerEnter event occurs. /// </summary> /// <param name="eventData">Event data.</param> public void OnPointerEnter(PointerEventData eventData) { IsCursorOver = true; } /// <summary> /// Called by a BaseInputModule when an OnPointerExit event occurs. /// </summary> /// <param name="eventData">Event data.</param> public void OnPointerExit(PointerEventData eventData) { IsCursorOver = false; cursorChanged = false; Cursor.SetCursor(DefaultCursorTexture, DefaultCursorHotSpot, Utilites.GetCursorMode()); } void LateUpdate() { if (!IsCursorOver) { return ; } if (processDrag) { return ; } if (CursorTexture==null) { return ; } if (!Input.mousePresent) { return ; } Vector2 point; if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(RectTransform, Input.mousePosition, CurrentCamera, out point)) { return ; } var rect = RectTransform.rect; if (rect.Contains(point)) { cursorChanged = true; Cursor.SetCursor(CursorTexture, CursorHotSpot, Utilites.GetCursorMode()); } else if (cursorChanged) { cursorChanged = false; Cursor.SetCursor(DefaultCursorTexture, DefaultCursorHotSpot, Utilites.GetCursorMode()); } } /// <summary> /// Raises the begin drag event. /// </summary> /// <param name="eventData">Event data.</param> public void OnBeginDrag(PointerEventData eventData) { Vector2 point; processDrag = false; if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(RectTransform, eventData.pressPosition, eventData.pressEventCamera, out point)) { return ; } var index = transform.GetSiblingIndex(); if (index==0 || transform.parent.childCount==(index+1)) { return ; } Cursor.SetCursor(CursorTexture, CursorHotSpot, Utilites.GetCursorMode()); cursorChanged = true; processDrag = true; leftTarget = transform.parent.GetChild(index - 1) as RectTransform; LeftTargetElement.preferredWidth = leftTarget.rect.width; LeftTargetElement.preferredHeight = leftTarget.rect.height; rightTarget = transform.parent.GetChild(index + 1) as RectTransform; RightTargetElement.preferredWidth = rightTarget.rect.width; RightTargetElement.preferredHeight = rightTarget.rect.height; summarySize = new Vector2(leftTarget.rect.width + rightTarget.rect.width, leftTarget.rect.height + rightTarget.rect.height); OnStartResize.Invoke(this); } /// <summary> /// Raises the end drag event. /// </summary> /// <param name="eventData">Event data.</param> public void OnEndDrag(PointerEventData eventData) { Cursor.SetCursor(DefaultCursorTexture, DefaultCursorHotSpot, Utilites.GetCursorMode()); cursorChanged = false; processDrag = false; OnEndResize.Invoke(this); } /// <summary> /// Raises the drag event. /// </summary> /// <param name="eventData">Event data.</param> public void OnDrag(PointerEventData eventData) { if (!processDrag) { return ; } if (canvas==null) { throw new MissingComponentException(gameObject.name + " not in Canvas hierarchy."); } Vector2 p1; RectTransformUtility.ScreenPointToLocalPointInRectangle(RectTransform, eventData.position, CurrentCamera, out p1); Vector2 p2; RectTransformUtility.ScreenPointToLocalPointInRectangle(RectTransform, eventData.position - eventData.delta, CurrentCamera, out p2); var delta = p1 - p2; if (UpdateRectTransforms) { PerformUpdateRectTransforms(delta); } if (UpdateLayoutElements) { PerformUpdateLayoutElements(delta); } } bool IsHorizontal() { return SplitterType.Horizontal==Type; } void PerformUpdateRectTransforms(Vector2 delta) { if (!IsHorizontal()) { float left_width; float right_width; if (delta.x > 0) { left_width = Mathf.Min(LeftTargetElement.preferredWidth + delta.x, summarySize.x - RightTargetElement.minWidth); right_width = summarySize.x - LeftTargetElement.preferredWidth; } else { right_width = Mathf.Min(RightTargetElement.preferredWidth - delta.x, summarySize.x - LeftTargetElement.minWidth); left_width = summarySize.x - RightTargetElement.preferredWidth; } leftTarget.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, left_width); rightTarget.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, right_width); } else { float left_height; float right_height; delta.y *= -1; if (delta.y > 0) { left_height = Mathf.Min(LeftTargetElement.preferredHeight + delta.y, summarySize.y - RightTargetElement.minHeight); right_height = summarySize.y - LeftTargetElement.preferredHeight; } else { right_height = Mathf.Min(RightTargetElement.preferredHeight - delta.y, summarySize.y - LeftTargetElement.minHeight); left_height = summarySize.y - RightTargetElement.preferredHeight; } leftTarget.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, left_height); rightTarget.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, right_height); } } void PerformUpdateLayoutElements(Vector2 delta) { if (!IsHorizontal()) { if (delta.x > 0) { LeftTargetElement.preferredWidth = Mathf.Min(LeftTargetElement.preferredWidth + delta.x, summarySize.x - RightTargetElement.minWidth); RightTargetElement.preferredWidth = summarySize.x - LeftTargetElement.preferredWidth; } else { RightTargetElement.preferredWidth = Mathf.Min(RightTargetElement.preferredWidth - delta.x, summarySize.x - LeftTargetElement.minWidth); LeftTargetElement.preferredWidth = summarySize.x - RightTargetElement.preferredWidth; } } else { delta.y *= -1; if (delta.y > 0) { LeftTargetElement.preferredHeight = Mathf.Min(LeftTargetElement.preferredHeight + delta.y, summarySize.y - RightTargetElement.minHeight); RightTargetElement.preferredHeight = summarySize.y - LeftTargetElement.preferredHeight; } else { RightTargetElement.preferredHeight = Mathf.Min(RightTargetElement.preferredHeight - delta.y, summarySize.y - LeftTargetElement.minHeight); LeftTargetElement.preferredHeight = summarySize.y - RightTargetElement.preferredHeight; } } } } }
using System; using System.IO; using Ninject.Extensions.Logging; using SharpFlame.Collections; using SharpFlame.Core.Extensions; using SharpFlame.FileIO; using SharpFlame.Mapping.Objects; using SharpFlame.Maths; using SharpFlame.Core; using SharpFlame.Core.Domain; using SharpFlame.Domain; using SharpFlame.Mapping.Tiles; namespace SharpFlame.Mapping.IO.LND { public class LNDSaver: IIOSaver { private readonly ILogger logger; public LNDSaver(ILoggerFactory logFactory) { logger = logFactory.GetCurrentClassLogger(); } public Result Save(string path, Map map, bool overwrite, bool compress = false) // Compress is ignored. { var returnResult = new Result("Writing LND to \"{0}\"".Format2(path), false); logger.Info("Writing LND to \"{0}\"".Format2(path)); if ( System.IO.File.Exists(path) ) { if ( overwrite ) { System.IO.File.Delete(path); } else { returnResult.ProblemAdd("The selected file already exists."); return returnResult; } } StreamWriter File = null; try { var text = ""; var endChar = '\n'; var quote = '\"';; var a = 0; var x = 0; var y = 0; byte flip = 0; var b = 0; var vf = 0; var tf = 0; var c = 0; byte rotation = 0; var flipX = default(bool); File = new StreamWriter(new FileStream(path, FileMode.CreateNew), App.UTF8Encoding); if ( map.Tileset == App.Tileset_Arizona ) { text = "DataSet WarzoneDataC1.eds" + Convert.ToString(endChar); } else if ( map.Tileset == App.Tileset_Urban ) { text = "DataSet WarzoneDataC2.eds" + Convert.ToString(endChar); } else if ( map.Tileset == App.Tileset_Rockies ) { text = "DataSet WarzoneDataC3.eds" + Convert.ToString(endChar); } else { text = "DataSet " + Convert.ToString(endChar); } File.Write(text); text = "GrdLand {" + Convert.ToString(endChar); File.Write(text); text = " Version 4" + Convert.ToString(endChar); File.Write(text); text = " 3DPosition 0.000000 3072.000000 0.000000" + Convert.ToString(endChar); File.Write(text); text = " 3DRotation 80.000000 0.000000 0.000000" + Convert.ToString(endChar); File.Write(text); text = " 2DPosition 0 0" + Convert.ToString(endChar); File.Write(text); text = " CustomSnap 16 16" + Convert.ToString(endChar); File.Write(text); text = " SnapMode 0" + Convert.ToString(endChar); File.Write(text); text = " Gravity 1" + Convert.ToString(endChar); File.Write(text); text = " HeightScale " + map.HeightMultiplier.ToStringInvariant() + Convert.ToString(endChar); File.Write(text); text = " MapWidth " + map.Terrain.TileSize.X.ToStringInvariant() + Convert.ToString(endChar); File.Write(text); text = " MapHeight " + map.Terrain.TileSize.Y.ToStringInvariant() + Convert.ToString(endChar); File.Write(text); text = " TileWidth 128" + Convert.ToString(endChar); File.Write(text); text = " TileHeight 128" + Convert.ToString(endChar); File.Write(text); text = " SeaLevel 0" + Convert.ToString(endChar); File.Write(text); text = " TextureWidth 64" + Convert.ToString(endChar); File.Write(text); text = " TextureHeight 64" + Convert.ToString(endChar); File.Write(text); text = " NumTextures 1" + Convert.ToString(endChar); File.Write(text); text = " Textures {" + Convert.ToString(endChar); File.Write(text); if ( map.Tileset == App.Tileset_Arizona ) { text = " texpages\\tertilesc1.pcx" + Convert.ToString(endChar); } else if ( map.Tileset == App.Tileset_Urban ) { text = " texpages\\tertilesc2.pcx" + Convert.ToString(endChar); } else if ( map.Tileset == App.Tileset_Rockies ) { text = " texpages\\tertilesc3.pcx" + Convert.ToString(endChar); } else { text = " " + Convert.ToString(endChar); } File.Write(text); text = " }" + Convert.ToString(endChar); File.Write(text); text = " NumTiles " + (map.Terrain.TileSize.X * map.Terrain.TileSize.Y).ToStringInvariant() + Convert.ToString(endChar); File.Write(text); text = " Tiles {" + Convert.ToString(endChar); File.Write(text); for ( y = 0; y <= map.Terrain.TileSize.Y - 1; y++ ) { for ( x = 0; x <= map.Terrain.TileSize.X - 1; x++ ) { TileUtil.TileOrientation_To_OldOrientation(map.Terrain.Tiles[x, y].Texture.Orientation, ref rotation, ref flipX); flip = 0; if ( map.Terrain.Tiles[x, y].Tri ) { flip += 2; } if ( flipX ) { flip += 4; } flip += (byte)(rotation * 16); if ( map.Terrain.Tiles[x, y].Tri ) { vf = 1; } else { vf = 0; } if ( flipX ) { tf = 1; } else { tf = 0; } text = " TID " + (map.Terrain.Tiles[x, y].Texture.TextureNum + 1) + " VF " + vf.ToStringInvariant() + " TF " + tf.ToStringInvariant() + " F " + (flip).ToStringInvariant() + " VH " + Convert.ToByte(map.Terrain.Vertices[x, y].Height).ToStringInvariant() + " " + map.Terrain.Vertices[x + 1, y].Height.ToStringInvariant() + " " + Convert.ToString(map.Terrain.Vertices[x + 1, y + 1].Height) + " " + Convert.ToByte(map.Terrain.Vertices[x, y + 1].Height).ToStringInvariant() + Convert.ToString(endChar); File.Write(text); } } text = " }" + Convert.ToString(endChar); File.Write(text); text = "}" + Convert.ToString(endChar); File.Write(text); text = "ObjectList {" + Convert.ToString(endChar); File.Write(text); text = " Version 3" + Convert.ToString(endChar); File.Write(text); if ( map.Tileset == App.Tileset_Arizona ) { text = " FeatureSet WarzoneDataC1.eds" + Convert.ToString(endChar); } else if ( map.Tileset == App.Tileset_Urban ) { text = " FeatureSet WarzoneDataC2.eds" + Convert.ToString(endChar); } else if ( map.Tileset == App.Tileset_Rockies ) { text = " FeatureSet WarzoneDataC3.eds" + Convert.ToString(endChar); } else { text = " FeatureSet " + Convert.ToString(endChar); } File.Write(text); text = " NumObjects " + map.Units.Count.ToStringInvariant() + Convert.ToString(endChar); File.Write(text); text = " Objects {" + Convert.ToString(endChar); File.Write(text); var XYZ_int = new XYZInt(0, 0, 0); string Code = null; var CustomDroidCount = 0; foreach ( var unit in map.Units ) { switch ( unit.TypeBase.Type ) { case UnitType.Feature: b = 0; break; case UnitType.PlayerStructure: b = 1; break; case UnitType.PlayerDroid: if ( ((DroidDesign)unit.TypeBase).IsTemplate ) { b = 2; } else { b = -1; } break; default: b = -1; returnResult.WarningAdd("Unit type classification not accounted for."); break; } XYZ_int = lndPos_From_MapPos(map, map.Units[a].Pos.Horizontal); if ( b >= 0 ) { if ( unit.TypeBase.GetCode(ref Code) ) { text = " " + unit.ID.ToStringInvariant() + " " + Convert.ToString(b) + " " + Convert.ToString(quote) + Code + Convert.ToString(quote) + " " + unit.UnitGroup.GetLNDPlayerText() + " " + Convert.ToString(quote) + "NONAME" + Convert.ToString(quote) + " " + XYZ_int.X.ToStringInvariant() + ".00 " + XYZ_int.Y.ToStringInvariant() + ".00 " + XYZ_int.Z.ToStringInvariant() + ".00 0.00 " + unit.Rotation.ToStringInvariant() + ".00 0.00" + Convert.ToString(endChar); File.Write(text); } else { returnResult.WarningAdd("Error. Code not found."); } } else { CustomDroidCount++; } } text = " }" + Convert.ToString(endChar); File.Write(text); text = "}" + Convert.ToString(endChar); File.Write(text); text = "ScrollLimits {" + Convert.ToString(endChar); File.Write(text); text = " Version 1" + Convert.ToString(endChar); File.Write(text); text = " NumLimits 1" + Convert.ToString(endChar); File.Write(text); text = " Limits {" + Convert.ToString(endChar); File.Write(text); text = " " + Convert.ToString(quote) + "Entire Map" + Convert.ToString(quote) + " 0 0 0 " + map.Terrain.TileSize.X.ToStringInvariant() + " " + map.Terrain.TileSize.Y.ToStringInvariant() + Convert.ToString(endChar); File.Write(text); text = " }" + Convert.ToString(endChar); File.Write(text); text = "}" + Convert.ToString(endChar); File.Write(text); text = "Gateways {" + Convert.ToString(endChar); File.Write(text); text = " Version 1" + Convert.ToString(endChar); File.Write(text); text = " NumGateways " + map.Gateways.Count.ToStringInvariant() + Convert.ToString(endChar); File.Write(text); text = " Gates {" + Convert.ToString(endChar); File.Write(text); foreach ( var gateway in map.Gateways ) { text = " " + gateway.PosA.X.ToStringInvariant() + " " + gateway.PosA.Y.ToStringInvariant() + " " + gateway.PosB.X.ToStringInvariant() + " " + gateway.PosB.Y.ToStringInvariant() + Convert.ToString(endChar); File.Write(text); } text = " }" + Convert.ToString(endChar); File.Write(text); text = "}" + Convert.ToString(endChar); File.Write(text); text = "TileTypes {" + Convert.ToString(endChar); File.Write(text); text = " NumTiles " + Convert.ToString(map.Tileset.Tiles.Count) + Convert.ToString(endChar); File.Write(text); text = " Tiles {" + Convert.ToString(endChar); File.Write(text); for ( a = 0; a <= Math.Ceiling(Convert.ToDecimal((map.Tileset.TileCount + 1) / 16.0D)).ToInt() - 1; a++ ) //+1 because the first number is not a tile type { text = " "; c = a * 16 - 1; //-1 because the first number is not a tile type for ( b = 0; b <= Math.Min(16, map.Tileset.Tiles.Count - c) - 1; b++ ) { if ( c + b < 0 ) { text = text + "2 "; } else { text = text + map.TileTypeNum[c + b].ToStringInvariant() + " "; } } text = text + Convert.ToString(endChar); File.Write(text); } text = " }" + Convert.ToString(endChar); File.Write(text); text = "}" + Convert.ToString(endChar); File.Write(text); text = "TileFlags {" + Convert.ToString(endChar); File.Write(text); text = " NumTiles 90" + Convert.ToString(endChar); File.Write(text); text = " Flags {" + Convert.ToString(endChar); File.Write(text); text = " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 " + Convert.ToString(endChar); File.Write(text); text = " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 " + Convert.ToString(endChar); File.Write(text); text = " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 " + Convert.ToString(endChar); File.Write(text); text = " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 " + Convert.ToString(endChar); File.Write(text); text = " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 " + Convert.ToString(endChar); File.Write(text); text = " 0 0 0 0 0 0 0 0 0 0 " + Convert.ToString(endChar); File.Write(text); text = " }" + Convert.ToString(endChar); File.Write(text); text = "}" + Convert.ToString(endChar); File.Write(text); text = "Brushes {" + Convert.ToString(endChar); File.Write(text); text = " Version 2" + Convert.ToString(endChar); File.Write(text); text = " NumEdgeBrushes 0" + Convert.ToString(endChar); File.Write(text); text = " NumUserBrushes 0" + Convert.ToString(endChar); File.Write(text); text = " EdgeBrushes {" + Convert.ToString(endChar); File.Write(text); text = " }" + Convert.ToString(endChar); File.Write(text); text = "}" + Convert.ToString(endChar); File.Write(text); } catch ( Exception ex ) { returnResult.ProblemAdd(ex.Message); } if ( File != null ) { File.Close(); } return returnResult; } private XYZInt lndPos_From_MapPos(Map map, XYInt Horizontal) { return new XYZInt( Horizontal.X - (map.Terrain.TileSize.X * Constants.TerrainGridSpacing / 2.0D).ToInt(), (map.Terrain.TileSize.Y * Constants.TerrainGridSpacing / 2.0D).ToInt() - Horizontal.Y, map.GetTerrainHeight(Horizontal).ToInt() ); } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; using ESRI.ArcGIS.ADF.BaseClasses; using ESRI.ArcGIS.ADF.CATIDs; using ESRI.ArcGIS.ADF.Connection.Local; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Display; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.SystemUI; using OpenGL; namespace DynamicDisplayHUD { /// <summary> /// Adds a HUD (heads up display) showing the map's azimuth to the map /// while in dynamic mode /// </summary> [Guid("7ca05f9c-2c43-4f2b-984e-26605d46c1d5")] [ClassInterface(ClassInterfaceType.None)] [ProgId("DynamicDisplayHUD.DDHUDCmd")] public sealed class DDHUDCmd : BaseCommand { #region COM Registration Function(s) [ComRegisterFunction()] [ComVisible(false)] static void RegisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryRegistration(registerType); // // TODO: Add any COM registration code here // } [ComUnregisterFunction()] [ComVisible(false)] static void UnregisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryUnregistration(registerType); // // TODO: Add any COM unregistration code here // } #region ArcGIS Component Category Registrar generated code /// <summary> /// Required method for ArcGIS Component Category registration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryRegistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); ControlsCommands.Register(regKey); } /// <summary> /// Required method for ArcGIS Component Category unregistration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryUnregistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); ControlsCommands.Unregister(regKey); } #endregion #endregion #region class members private IHookHelper m_hookHelper = null; private IDynamicMap m_dynamicMap = null; private IDynamicGlyph m_textGlyph = null; private IDynamicGlyphFactory m_dynamicGlyphFactory = null; private IDynamicDrawScreen m_dynamicDrawScreen = null; private IDynamicSymbolProperties m_dynamicSymbolProps = null; private IPoint m_point = null; private bool m_bIsDynamicMode = false; private bool m_bOnce = true; #endregion #region class constructor public DDHUDCmd() { base.m_category = ".NET Samples"; base.m_caption = "Dynamic HUD"; base.m_message = "Dynamic Display HUD"; base.m_toolTip = "Dynamic Display HUD"; base.m_name = "DynamicDisplayHUD_DDHUDCmd"; try { string bitmapResourceName = GetType().Name + ".bmp"; base.m_bitmap = new Bitmap(GetType(), bitmapResourceName); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap"); } } #endregion #region Overriden Class Methods /// <summary> /// Occurs when this command is created /// </summary> /// <param name="hook">Instance of the application</param> public override void OnCreate(object hook) { if (hook == null) return; try { m_hookHelper = new HookHelperClass(); m_hookHelper.Hook = hook; if (m_hookHelper.ActiveView == null) m_hookHelper = null; } catch { m_hookHelper = null; } if (m_hookHelper == null) base.m_enabled = false; else base.m_enabled = true; } /// <summary> /// Occurs when this command is clicked /// </summary> public override void OnClick() { //cast into dynamic map. make sure that the current display supports dynamic display mode. m_dynamicMap = m_hookHelper.FocusMap as IDynamicMap; if (null == m_dynamicMap) { MessageBox.Show("The current display does not support dynamic mode.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } if (!m_bIsDynamicMode) { //verify that the display is currently in dynamic mode if (!m_dynamicMap.DynamicMapEnabled) { MessageBox.Show("In order to add the HUD you must enable dynamic mode", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //start listening to DynamicMap's 'After Draw' events ((IDynamicMapEvents_Event)m_dynamicMap).AfterDynamicDraw += new IDynamicMapEvents_AfterDynamicDrawEventHandler(OnAfterDynamicDraw); //need to redraw the screen m_hookHelper.ActiveView.ScreenDisplay.UpdateWindow(); } else { //stop listening to DynamicMap's 'After Draw' events ((IDynamicMapEvents_Event)m_dynamicMap).AfterDynamicDraw -= new IDynamicMapEvents_AfterDynamicDrawEventHandler(OnAfterDynamicDraw); } //redraw the display m_hookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); m_hookHelper.ActiveView.ScreenDisplay.UpdateWindow(); m_bIsDynamicMode = !m_bIsDynamicMode; } /// <summary> /// Controls the appearance of the button (checked or unchecked) /// </summary> public override bool Checked { get { return m_bIsDynamicMode; } } #endregion #region private methods /// <summary> /// DynamicMap AfterDynamicDraw event handler method /// </summary> /// <param name="DynamicMapDrawPhase"></param> /// <param name="Display"></param> /// <param name="dynamicDisplay"></param> private void OnAfterDynamicDraw(esriDynamicMapDrawPhase DynamicMapDrawPhase, IDisplay Display, IDynamicDisplay dynamicDisplay) { try { if (DynamicMapDrawPhase != esriDynamicMapDrawPhase.esriDMDPDynamicLayers) return; //make sure that the display is valid as well as that the layer is visible if (null == dynamicDisplay || null == Display) return; tagRECT rect = Display.DisplayTransformation.get_DeviceFrame(); float rotation = (float)Display.DisplayTransformation.Rotation; if (m_bOnce) { //need to cache all the DynamicDisplay stuff m_dynamicGlyphFactory = dynamicDisplay.DynamicGlyphFactory; m_dynamicDrawScreen = (IDynamicDrawScreen)dynamicDisplay; m_dynamicSymbolProps = (IDynamicSymbolProperties)dynamicDisplay; //set the screen coordinates of the char symbol m_point = new ESRI.ArcGIS.Geometry.PointClass(); CreateDynamicGlyphs(m_dynamicGlyphFactory); m_bOnce = false; } //draw the OpenGL compass GL.glPushMatrix(); GL.glLoadIdentity(); //use OpenGL to do the drawings DrawTicks(rect, rotation); GL.glPopMatrix(); //please note that while you are rotating the map, the numbers showing in the HUD are //different than the number reported by the rotation tool. The reason for that is that //the reported map rotation is the mathematical angle while the HUD shows the angle from //the north (the map's azimuth). DrawAzimuths(rect, rotation); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message, "ERROR", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } } /// <summary> /// Creates the dynamic glyph used to draw the numbers in the HUD /// </summary> /// <param name="pDynamicGlyphFactory"></param> private void CreateDynamicGlyphs(IDynamicGlyphFactory pDynamicGlyphFactory) { try { //create the text glyph using a text symbol ITextSymbol textSymbol = new TextSymbolClass(); textSymbol.Size = 15.0; textSymbol.Angle = 0.0; textSymbol.VerticalAlignment = esriTextVerticalAlignment.esriTVACenter; textSymbol.HorizontalAlignment = esriTextHorizontalAlignment.esriTHACenter; textSymbol.Font = ESRI.ArcGIS.ADF.Connection.Local.Converter.ToStdFont(new Font("Arial", 15.0f, FontStyle.Regular)); m_textGlyph = pDynamicGlyphFactory.CreateDynamicGlyph((ISymbol)textSymbol); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } } /// <summary> /// draw the tick marks of the HUD /// </summary> /// <param name="deviceFrame"></param> /// <param name="azimuth"></param> private void DrawTicks(tagRECT deviceFrame, float azimuth) { //get the floor of the azimuth float floorAzi = (int)(azimuth / 10.0f) * 10.0f; float deltaAzi = (azimuth - floorAzi) * 6.0f; float deltaAziSmall = (azimuth - ((int)(azimuth / 2.0f) * 2.0f)) * 6.0f; float delta = 60.0f; float deltaSmall = 12.0f; float xmin = (float)deviceFrame.left; float xmax = (float)deviceFrame.right; float ymin = (float)deviceFrame.top; float xmiddle = (xmax + xmin) / 2.0f; GL.glDisable(GL.GL_TEXTURE_2D); //draw a line from left to right GL.glColor3f(0.0f, 0.5f, 0.0f); GL.glLineWidth(1.5f); GL.glBegin(GL.GL_LINES); GL.glVertex2f(xmiddle - 150.0f, ymin + 40.0f); GL.glVertex2f(xmiddle + 150.0f, ymin + 40.0f); GL.glEnd(); //draw the 10 degrees big ticks float x = xmiddle - 150.0f + deltaAzi; for (int i = 0; i < 5; i++) { GL.glBegin(GL.GL_LINES); GL.glVertex2f(x, ymin + 40.0f); GL.glVertex2f(x, ymin + 80.0f); GL.glEnd(); x += delta; } //draw the 2 degrees small ticks x = xmiddle - 150.0f + deltaAziSmall; GL.glLineWidth(1.0f); for (int i = 0; i < 25; i++) { GL.glBegin(GL.GL_LINES); GL.glVertex2f(x, ymin + 40.0f); GL.glVertex2f(x, ymin + 60.0f); GL.glEnd(); x += deltaSmall; } GL.glLineWidth(2.0f); GL.glColor3f(0.0f, 0.0f, 0.0f); GL.glBegin(GL.GL_TRIANGLES); GL.glVertex2f(xmiddle, ymin + 40.0f); GL.glVertex2f(xmiddle - 8.0f, ymin + 60.0f); GL.glVertex2f(xmiddle + 8.0f, ymin + 60.0f); GL.glEnd(); GL.glEnable(GL.GL_TEXTURE_2D); } /// <summary> /// draw the numbers (azimuth) in the HUD /// </summary> /// <param name="deviceFrame"></param> /// <param name="angle"></param> private void DrawAzimuths(tagRECT deviceFrame, float angle) { //need to draw the current azimuth m_dynamicSymbolProps.SetColor(esriDynamicSymbolType.esriDSymbolText, 0.0f, 0.8f, 0.0f, 1.0f); // Green //assign the item's glyph to the dynamic-symbol m_dynamicSymbolProps.set_DynamicGlyph(esriDynamicSymbolType.esriDSymbolText, m_textGlyph); //get the floor of the azimuth float azimuth = 180.0f - angle; if (azimuth > 360) azimuth -= 360; else if (azimuth < 0) azimuth += 360; float floorAzi = (int)(azimuth / 10.0f) * 10.0f; double deltaAzi = (angle - (float)((int)(angle / 10.0f) * 10.0f)) * 6.0; //(the shift to the X axis) double xmin = (double)deviceFrame.left; double xmax = (double)deviceFrame.right; double ymin = (double)deviceFrame.top; double xmiddle = (xmax + xmin) / 2.0; double x = xmiddle - 150.0 + deltaAzi; double dAzStartMiddle = (150.0 - 2.0 * deltaAzi) / 6.0; dAzStartMiddle = (int)(dAzStartMiddle / 60.0) * 60.0 + 10.0; int azi = (int)(floorAzi - dAzStartMiddle) - 5; double delta = 60.0; m_dynamicSymbolProps.set_Heading(esriDynamicSymbolType.esriDSymbolText, 0.0f); m_dynamicSymbolProps.set_RotationAlignment(esriDynamicSymbolType.esriDSymbolText, esriDynamicSymbolRotationAlignment.esriDSRAScreen); for (int i = 0; i < 5; i++) { m_point.PutCoords(x, ymin + 28.0); if (azi > 360) azi -= 360; else if (azi < 0) azi += 360; m_dynamicDrawScreen.DrawScreenText(m_point, azi.ToString()); azi += 10; x += delta; } //need to draw the current azimuth m_dynamicSymbolProps.SetColor(esriDynamicSymbolType.esriDSymbolText, 0.0f, 0.0f, 0.0f, 1.0f); // Black m_point.PutCoords(xmiddle, ymin + 95.0); m_dynamicDrawScreen.DrawScreenText(m_point, azimuth.ToString("###")); } #endregion } }
using System; using System.Diagnostics; using System.Linq; using System.Net; using System.Reflection; using System.Threading; using System.Web; using OfficeDevPnP.Core; using OfficeDevPnP.Core.Diagnostics; using OfficeDevPnP.Core.Utilities; using System.Configuration; using System.Threading.Tasks; using System.Net.Http; using Newtonsoft.Json; using OfficeDevPnP.Core.Utilities.Async; using System.IdentityModel.Tokens.Jwt; using System.Collections.Generic; using OfficeDevPnP.Core.Utilities.Context; using OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers; #if !SP2013 && !SP2016 using OfficeDevPnP.Core.Sites; #endif namespace Microsoft.SharePoint.Client { /// <summary> /// Class that deals with cloning client context object, getting access token and validates server version /// </summary> public static partial class ClientContextExtensions { private static string userAgentFromConfig = null; private static string accessToken = null; private static bool hasAuthCookies; /// <summary> /// Static constructor, only executed once per class load /// </summary> static ClientContextExtensions() { ClientContextExtensions.userAgentFromConfig = ConfigurationManager.AppSettings["SharePointPnPUserAgent"]; if (string.IsNullOrWhiteSpace(ClientContextExtensions.userAgentFromConfig)) { ClientContextExtensions.userAgentFromConfig = System.Environment.GetEnvironmentVariable("SharePointPnPUserAgent", EnvironmentVariableTarget.Process); } } #if ONPREMISES private const string MicrosoftSharePointTeamServicesHeader = "MicrosoftSharePointTeamServices"; #endif /// <summary> /// Clones a ClientContext object while "taking over" the security context of the existing ClientContext instance /// </summary> /// <param name="clientContext">ClientContext to be cloned</param> /// <param name="siteUrl">Site URL to be used for cloned ClientContext</param> /// <param name="accessTokens">Dictionary of access tokens for sites URLs</param> /// <returns>A ClientContext object created for the passed site URL</returns> public static ClientContext Clone(this ClientRuntimeContext clientContext, string siteUrl, Dictionary<String, String> accessTokens = null) { if (string.IsNullOrWhiteSpace(siteUrl)) { throw new ArgumentException(CoreResources.ClientContextExtensions_Clone_Url_of_the_site_is_required_, nameof(siteUrl)); } return clientContext.Clone(new Uri(siteUrl), accessTokens); } #if !ONPREMISES /// <summary> /// Executes the current set of data retrieval queries and method invocations and retries it if needed using the Task Library. /// </summary> /// <param name="clientContext">clientContext to operate on</param> /// <param name="retryCount">Number of times to retry the request</param> /// <param name="delay">Milliseconds to wait before retrying the request. The delay will be increased (doubled) every retry</param> /// <param name="userAgent">UserAgent string value to insert for this request. You can define this value in your app's config file using key="SharePointPnPUserAgent" value="PnPRocks"></param> public static Task ExecuteQueryRetryAsync(this ClientRuntimeContext clientContext, int retryCount = 10, int delay = 500, string userAgent = null) { return ExecuteQueryImplementation(clientContext, retryCount, delay, userAgent); } #endif /// <summary> /// Executes the current set of data retrieval queries and method invocations and retries it if needed. /// </summary> /// <param name="clientContext">clientContext to operate on</param> /// <param name="retryCount">Number of times to retry the request</param> /// <param name="delay">Milliseconds to wait before retrying the request. The delay will be increased (doubled) every retry</param> /// <param name="userAgent">UserAgent string value to insert for this request. You can define this value in your app's config file using key="SharePointPnPUserAgent" value="PnPRocks"></param> public static void ExecuteQueryRetry(this ClientRuntimeContext clientContext, int retryCount = 10, int delay = 500, string userAgent = null) { #if !ONPREMISES Task.Run(() => ExecuteQueryImplementation(clientContext, retryCount, delay, userAgent)).GetAwaiter().GetResult(); #else ExecuteQueryImplementation(clientContext, retryCount, delay, userAgent); #endif } #if !ONPREMISES private static async Task ExecuteQueryImplementation(ClientRuntimeContext clientContext, int retryCount = 10, int delay = 500, string userAgent = null) #else private static void ExecuteQueryImplementation(ClientRuntimeContext clientContext, int retryCount = 10, int delay = 500, string userAgent = null) #endif { #if !ONPREMISES await new SynchronizationContextRemover(); // Set the TLS preference. Needed on some server os's to work when Office 365 removes support for TLS 1.0 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; #endif var clientTag = string.Empty; if (clientContext is PnPClientContext) { retryCount = (clientContext as PnPClientContext).RetryCount; delay = (clientContext as PnPClientContext).Delay; clientTag = (clientContext as PnPClientContext).ClientTag; } int retryAttempts = 0; int backoffInterval = delay; #if !ONPREMISES int retryAfterInterval = 0; bool retry = false; ClientRequestWrapper wrapper = null; #endif if (retryCount <= 0) throw new ArgumentException("Provide a retry count greater than zero."); if (delay <= 0) throw new ArgumentException("Provide a delay greater than zero."); // Do while retry attempt is less than retry count while (retryAttempts < retryCount) { try { clientContext.ClientTag = SetClientTag(clientTag); // Make CSOM request more reliable by disabling the return value cache. Given we // often clone context objects and the default value is #if !SP2013 clientContext.DisableReturnValueCache = true; #endif // Add event handler to "insert" app decoration header to mark the PnP Sites Core library as a known application EventHandler<WebRequestEventArgs> appDecorationHandler = AttachRequestUserAgent(userAgent); clientContext.ExecutingWebRequest += appDecorationHandler; // DO NOT CHANGE THIS TO EXECUTEQUERYRETRY #if !ONPREMISES if (!retry) { await clientContext.ExecuteQueryAsync(); } else { if (wrapper != null && wrapper.Value != null) { await clientContext.RetryQueryAsync(wrapper.Value); } } #else clientContext.ExecuteQuery(); #endif // Remove the app decoration event handler after the executequery clientContext.ExecutingWebRequest -= appDecorationHandler; return; } catch (WebException wex) { var response = wex.Response as HttpWebResponse; // Check if request was throttled - http status code 429 // Check is request failed due to server unavailable - http status code 503 if (response != null && (response.StatusCode == (HttpStatusCode)429 || response.StatusCode == (HttpStatusCode)503 // || response.StatusCode == (HttpStatusCode)500 )) { Log.Warning(Constants.LOGGING_SOURCE, CoreResources.ClientContextExtensions_ExecuteQueryRetry, backoffInterval); #if !ONPREMISES wrapper = (ClientRequestWrapper)wex.Data["ClientRequest"]; retry = true; // Determine the retry after value - use the retry-after header when available // Retry-After seems to default to a fixed 120 seconds in most cases, let's revert to our // previous logic //string retryAfterHeader = response.GetResponseHeader("Retry-After"); //if (!string.IsNullOrEmpty(retryAfterHeader)) //{ // if (!Int32.TryParse(retryAfterHeader, out retryAfterInterval)) // { // retryAfterInterval = backoffInterval; // } //} //else //{ retryAfterInterval = backoffInterval; //} //Add delay for retry, retry-after header is specified in seconds await Task.Delay(retryAfterInterval); #else Thread.Sleep(backoffInterval); #endif //Add to retry count and increase delay. retryAttempts++; backoffInterval = backoffInterval * 2; } else { var errorSb = new System.Text.StringBuilder(); errorSb.AppendLine(wex.ToString()); if (response != null) { //if(response.Headers["SPRequestGuid"] != null) if (response.Headers.AllKeys.Any(k => string.Equals(k, "SPRequestGuid", StringComparison.InvariantCultureIgnoreCase))) { var spRequestGuid = response.Headers["SPRequestGuid"]; errorSb.AppendLine($"ServerErrorTraceCorrelationId: {spRequestGuid}"); } } Log.Error(Constants.LOGGING_SOURCE, CoreResources.ClientContextExtensions_ExecuteQueryRetryException, errorSb.ToString()); throw; } } catch (Microsoft.SharePoint.Client.ServerException serverEx) { var errorSb = new System.Text.StringBuilder(); errorSb.AppendLine(serverEx.ToString()); errorSb.AppendLine($"ServerErrorCode: {serverEx.ServerErrorCode}"); errorSb.AppendLine($"ServerErrorTypeName: {serverEx.ServerErrorTypeName}"); errorSb.AppendLine($"ServerErrorTraceCorrelationId: {serverEx.ServerErrorTraceCorrelationId}"); errorSb.AppendLine($"ServerErrorValue: {serverEx.ServerErrorValue}"); errorSb.AppendLine($"ServerErrorDetails: {serverEx.ServerErrorDetails}"); Log.Error(Constants.LOGGING_SOURCE, CoreResources.ClientContextExtensions_ExecuteQueryRetryException, errorSb.ToString()); throw; } } throw new MaximumRetryAttemptedException($"Maximum retry attempts {retryCount}, has be attempted."); } /// <summary> /// Attaches either a passed user agent, or one defined in the App.config file, to the WebRequstExecutor UserAgent property. /// </summary> /// <param name="customUserAgent">a custom user agent to override any defined in App.config</param> /// <returns>An EventHandler of WebRequestEventArgs.</returns> private static EventHandler<WebRequestEventArgs> AttachRequestUserAgent(string customUserAgent) { return (s, e) => { bool overrideUserAgent = true; var existingUserAgent = e.WebRequestExecutor.WebRequest.UserAgent; if (!string.IsNullOrEmpty(existingUserAgent) && existingUserAgent.StartsWith("NONISV|SharePointPnP|PnPPS/")) { overrideUserAgent = false; } if (overrideUserAgent) { if (string.IsNullOrEmpty(customUserAgent) && !string.IsNullOrEmpty(ClientContextExtensions.userAgentFromConfig)) { customUserAgent = userAgentFromConfig; } e.WebRequestExecutor.WebRequest.UserAgent = string.IsNullOrEmpty(customUserAgent) ? $"{PnPCoreUtilities.PnPCoreUserAgent}" : customUserAgent; } }; } /// <summary> /// Sets the client context client tag on outgoing CSOM requests. /// </summary> /// <param name="clientTag">An optional client tag to set on client context requests.</param> /// <returns></returns> private static string SetClientTag(string clientTag = "") { // ClientTag property is limited to 32 chars if (string.IsNullOrEmpty(clientTag)) { clientTag = $"{PnPCoreUtilities.PnPCoreVersionTag}:{GetCallingPnPMethod()}"; } if (clientTag.Length > 32) { clientTag = clientTag.Substring(0, 32); } return clientTag; } /// <summary> /// Clones a ClientContext object while "taking over" the security context of the existing ClientContext instance /// </summary> /// <param name="clientContext">ClientContext to be cloned</param> /// <param name="siteUrl">Site URL to be used for cloned ClientContext</param> /// <param name="accessTokens">Dictionary of access tokens for sites URLs</param> /// <returns>A ClientContext object created for the passed site URL</returns> public static ClientContext Clone(this ClientRuntimeContext clientContext, Uri siteUrl, Dictionary<String, String> accessTokens = null) { return Clone(clientContext, new ClientContext(siteUrl), siteUrl, accessTokens); } /// <summary> /// Clones a ClientContext object while "taking over" the security context of the existing ClientContext instance /// </summary> /// <param name="clientContext">ClientContext to be cloned</param> /// <param name="targetContext">CientContext stub to be used for cloning</param> /// <param name="siteUrl">Site URL to be used for cloned ClientContext</param> /// <param name="accessTokens">Dictionary of access tokens for sites URLs</param> /// <returns>A ClientContext object created for the passed site URL</returns> internal static ClientContext Clone(this ClientRuntimeContext clientContext, ClientContext targetContext, Uri siteUrl, Dictionary<String, String> accessTokens = null) { if (siteUrl == null) { throw new ArgumentException(CoreResources.ClientContextExtensions_Clone_Url_of_the_site_is_required_, nameof(siteUrl)); } ClientContext clonedClientContext = targetContext; #if !NETSTANDARD2_0 clonedClientContext.AuthenticationMode = clientContext.AuthenticationMode; #endif clonedClientContext.ClientTag = clientContext.ClientTag; #if !SP2013 clonedClientContext.DisableReturnValueCache = clientContext.DisableReturnValueCache; #endif // In case of using networkcredentials in on premises or SharePointOnlineCredentials in Office 365 if (clientContext.Credentials != null) { clonedClientContext.Credentials = clientContext.Credentials; // In case of existing Event Handlers clonedClientContext.ExecutingWebRequest += (sender, webRequestEventArgs) => { // Call the ExecutingWebRequest delegate method from the original ClientContext object, but pass along the webRequestEventArgs of // the new delegate method MethodInfo methodInfo = clientContext.GetType().GetMethod("OnExecutingWebRequest", BindingFlags.Instance | BindingFlags.NonPublic); object[] parametersArray = new object[] { webRequestEventArgs }; methodInfo.Invoke(clientContext, parametersArray); }; } else { // Check if we do have context settings var contextSettings = clientContext.GetContextSettings(); if (contextSettings != null) // We do have more information about this client context, so let's use it to do a more intelligent clone { string newSiteUrl = siteUrl.ToString(); // A diffent host = different audience ==> new access token is needed if (contextSettings.UsesDifferentAudience(newSiteUrl)) { // We need to create a new context using a new authentication manager as the token expiration is handled in there OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager(); ClientContext newClientContext = null; if (contextSettings.Type == ClientContextType.SharePointACSAppOnly) { newClientContext = authManager.GetAppOnlyAuthenticatedContext(newSiteUrl, TokenHelper.GetRealmFromTargetUrl(new Uri(newSiteUrl)), contextSettings.ClientId, contextSettings.ClientSecret, contextSettings.AcsHostUrl, contextSettings.GlobalEndPointPrefix); } #if !ONPREMISES else if (contextSettings.Type == ClientContextType.AzureADCredentials) { newClientContext = authManager.GetAzureADCredentialsContext(newSiteUrl, contextSettings.UserName, contextSettings.Password); } else if (contextSettings.Type == ClientContextType.AzureADCertificate) { if (contextSettings.Certificate != null) { newClientContext = authManager.GetAzureADAppOnlyAuthenticatedContext(newSiteUrl, contextSettings.ClientId, contextSettings.Tenant, contextSettings.Certificate, contextSettings.Environment); } else { newClientContext = authManager.GetAzureADAppOnlyAuthenticatedContext(newSiteUrl, contextSettings.ClientId, contextSettings.Tenant, contextSettings.ClientAssertionCertificate, contextSettings.Environment); } } else if(contextSettings.Type == ClientContextType.Cookie) { newClientContext = new ClientContext(newSiteUrl); newClientContext.ExecutingWebRequest += (sender, webRequestEventArgs) => { // Call the ExecutingWebRequest delegate method from the original ClientContext object, but pass along the webRequestEventArgs of // the new delegate method MethodInfo methodInfo = clientContext.GetType().GetMethod("OnExecutingWebRequest", BindingFlags.Instance | BindingFlags.NonPublic); object[] parametersArray = new object[] { webRequestEventArgs }; methodInfo.Invoke(clientContext, parametersArray); }; ClientContextSettings clientContextSettings = new ClientContextSettings() { Type = ClientContextType.Cookie, SiteUrl = newSiteUrl, }; newClientContext.AddContextSettings(clientContextSettings); } #endif if (newClientContext != null) { //Take over the form digest handling setting #if !NETSTANDARD2_0 newClientContext.FormDigestHandlingEnabled = (clientContext as ClientContext).FormDigestHandlingEnabled; #endif newClientContext.ClientTag = clientContext.ClientTag; #if !SP2013 newClientContext.DisableReturnValueCache = clientContext.DisableReturnValueCache; #endif return newClientContext; } else { throw new Exception($"Cloning for context setting type {contextSettings.Type} was not yet implemented"); } } else { // Take over the context settings, this is needed if we later on want to clone this context to a different audience contextSettings.SiteUrl = newSiteUrl; clonedClientContext.AddContextSettings(contextSettings); clonedClientContext.ExecutingWebRequest += delegate (object oSender, WebRequestEventArgs webRequestEventArgs) { // Call the ExecutingWebRequest delegate method from the original ClientContext object, but pass along the webRequestEventArgs of // the new delegate method MethodInfo methodInfo = clientContext.GetType().GetMethod("OnExecutingWebRequest", BindingFlags.Instance | BindingFlags.NonPublic); object[] parametersArray = new object[] { webRequestEventArgs }; methodInfo.Invoke(clientContext, parametersArray); }; } } else // Fallback the default cloning logic if there were not context settings available { //Take over the form digest handling setting #if !NETSTANDARD2_0 clonedClientContext.FormDigestHandlingEnabled = (clientContext as ClientContext).FormDigestHandlingEnabled; #endif var originalUri = new Uri(clientContext.Url); // If the cloned host is not the same as the original one // and if there is an active PnPProvisioningContext if (originalUri.Host != siteUrl.Host && PnPProvisioningContext.Current != null) { // Let's apply that specific Access Token clonedClientContext.ExecutingWebRequest += (sender, args) => { // We get a fresh new Access Token for every request, to avoid using an expired one var accessToken = PnPProvisioningContext.Current.AcquireToken(siteUrl.Authority, null); args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; } // Else if the cloned host is not the same as the original one // and if there is a custom Access Token for it in the input arguments else if (originalUri.Host != siteUrl.Host && accessTokens != null && accessTokens.Count > 0 && accessTokens.ContainsKey(siteUrl.Authority)) { // Let's apply that specific Access Token clonedClientContext.ExecutingWebRequest += (sender, args) => { args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessTokens[siteUrl.Authority]; }; } // Else if the cloned host is not the same as the original one // and if the client context is a PnPClientContext with custom access tokens in its property bag else if (originalUri.Host != siteUrl.Host && accessTokens == null && clientContext is PnPClientContext && ((PnPClientContext)clientContext).PropertyBag.ContainsKey("AccessTokens") && ((Dictionary<string, string>)((PnPClientContext)clientContext).PropertyBag["AccessTokens"]).ContainsKey(siteUrl.Authority)) { // Let's apply that specific Access Token clonedClientContext.ExecutingWebRequest += (sender, args) => { args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + ((Dictionary<string, string>)((PnPClientContext)clientContext).PropertyBag["AccessTokens"])[siteUrl.Authority]; }; } else { // In case of app only or SAML clonedClientContext.ExecutingWebRequest += (sender, webRequestEventArgs) => { // Call the ExecutingWebRequest delegate method from the original ClientContext object, but pass along the webRequestEventArgs of // the new delegate method MethodInfo methodInfo = clientContext.GetType().GetMethod("OnExecutingWebRequest", BindingFlags.Instance | BindingFlags.NonPublic); object[] parametersArray = new object[] { webRequestEventArgs }; methodInfo.Invoke(clientContext, parametersArray); }; } } } return clonedClientContext; } /// <summary> /// Returns the number of pending requests /// </summary> /// <param name="clientContext">Client context to check the pending requests for</param> /// <returns>The number of pending requests</returns> public static int PendingRequestCount(this ClientRuntimeContext clientContext) { int count = 0; if (clientContext.HasPendingRequest) { var result = clientContext.PendingRequest.GetType().GetProperty("Actions", BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic); if (result != null) { var propValue = result.GetValue(clientContext.PendingRequest); if (propValue != null) { count = (propValue as System.Collections.Generic.List<ClientAction>).Count; } } } return count; } /// <summary> /// Gets a site collection context for the passed web. This site collection client context uses the same credentials /// as the passed client context /// </summary> /// <param name="clientContext">Client context to take the credentials from</param> /// <returns>A site collection client context object for the site collection</returns> public static ClientContext GetSiteCollectionContext(this ClientRuntimeContext clientContext) { Site site = (clientContext as ClientContext).Site; if (!site.IsObjectPropertyInstantiated("Url")) { clientContext.Load(site); clientContext.ExecuteQueryRetry(); } return clientContext.Clone(site.Url); } /// <summary> /// Checks if the used ClientContext is app-only /// </summary> /// <param name="clientContext">The ClientContext to inspect</param> /// <returns>True if app-only, false otherwise</returns> public static bool IsAppOnly(this ClientRuntimeContext clientContext) { // Set initial result to false var result = false; // Try to get an access token from the current context var accessToken = clientContext.GetAccessToken(); // If any if (!String.IsNullOrEmpty(accessToken)) { // Try to decode the access token var token = new JwtSecurityToken(accessToken); // Search for the UPN claim, to see if we have user's delegation var upn = token.Claims.FirstOrDefault(claim => claim.Type == "upn")?.Value; if (String.IsNullOrEmpty(upn)) { result = true; } } else if (clientContext.Credentials == null) { result = true; } // As a final check, do we have the auth cookies? else if (clientContext.HasAuthCookies()) { result = false; } return (result); } #if ONPREMISES /// <summary> /// Checks if the used ClientContext is app-only /// </summary> /// <param name="clientContext">The ClientContext to inspect</param> /// <returns>True if app-only, false otherwise</returns> public static bool IsAppOnlyWithDelegation(this ClientRuntimeContext clientContext) { // Set initial result to false var result = false; // Try to get an access token from the current context var accessToken = clientContext.GetAccessToken(); // If any if (!String.IsNullOrEmpty(accessToken)) { // Try to decode the access token try { var token = new JwtSecurityToken(accessToken); if (token.Audiences.Any(x => x.StartsWith(TokenHelper.SharePointPrincipal))) { } // Search for the UPN claim, to see if we have user's delegation var upn = token.Claims.FirstOrDefault(claim => claim.Type == "upn")?.Value; if (!String.IsNullOrEmpty(upn)) { result = true; } } catch (Exception ex) { throw new Exception("Maybe Newtonsoft.Json assembly is not loaded?", ex); } } else if (clientContext.Credentials == null) { result = false; } // As a final check, do we have the auth cookies? if (clientContext.HasAuthCookies()) { result = false; } return (result); } #endif /// <summary> /// Gets an access token from a <see cref="ClientContext"/> instance. Only works when using an add-in or app-only authentication flow. /// </summary> /// <param name="clientContext"><see cref="ClientContext"/> instance to obtain an access token for</param> /// <returns>Access token for the given <see cref="ClientContext"/> instance</returns> public static string GetAccessToken(this ClientRuntimeContext clientContext) { string accessToken = null; if (PnPProvisioningContext.Current != null) { accessToken = PnPProvisioningContext.Current.AcquireToken(new Uri(clientContext.Url).Authority, null); } else { EventHandler<WebRequestEventArgs> handler = (s, e) => { string authorization = e.WebRequestExecutor.RequestHeaders["Authorization"]; if (!string.IsNullOrEmpty(authorization)) { accessToken = authorization.Replace("Bearer ", string.Empty); } }; // Issue a dummy request to get it from the Authorization header clientContext.ExecutingWebRequest += handler; clientContext.ExecuteQueryRetry(); clientContext.ExecutingWebRequest -= handler; } return accessToken; } /// <summary> /// Gets a boolean if the current request contains the FedAuth and rtFa cookies. /// </summary> /// <param name="clientContext"></param> /// <returns></returns> private static bool HasAuthCookies(this ClientRuntimeContext clientContext) { clientContext.ExecutingWebRequest += ClientContext_ExecutingWebRequestCookieCounter; clientContext.ExecuteQueryRetry(); clientContext.ExecutingWebRequest -= ClientContext_ExecutingWebRequestCookieCounter; return hasAuthCookies; } private static void ClientContext_ExecutingWebRequestCookieCounter(object sender, WebRequestEventArgs e) { var fedAuth = false; var rtFa = false; if (e.WebRequestExecutor != null && e.WebRequestExecutor.WebRequest != null && e.WebRequestExecutor.WebRequest.CookieContainer != null) { var cookies = e.WebRequestExecutor.WebRequest.CookieContainer.GetCookies(e.WebRequestExecutor.WebRequest.RequestUri); if (cookies.Count > 0) { for (var q = 0; q < cookies.Count; q++) { if (cookies[q].Name == "FedAuth") { fedAuth = true; } if (cookies[q].Name == "rtFa") { rtFa = true; } } } } hasAuthCookies = fedAuth && rtFa; } /// <summary> /// Gets the CookieCollection by cookie name = FedAuth or rtFa /// </summary> /// <param name="clientContext"></param> /// <returns></returns> internal static CookieCollection GetCookieCollection(this ClientRuntimeContext clientContext) { return GetCookieCollection(clientContext, new List<string> { "FedAuth", "rtFa" }); } /// <summary> /// Gets the CookieCollection by the cookie name. If no cookieNames are passed in it returns all cookies /// </summary> /// <param name="clientContext"></param> /// <param name="cookieNames"></param> /// <returns></returns> internal static CookieCollection GetCookieCollection(this ClientRuntimeContext clientContext, IReadOnlyCollection<string> cookieNames) { CookieCollection cookieCollection = null; void Handler(object sender, WebRequestEventArgs e) => cookieCollection = HandleWebRequest(e, cookieNames); clientContext.ExecutingWebRequest += Handler; clientContext.ExecuteQuery(); clientContext.ExecutingWebRequest -= Handler; return cookieCollection; } private static CookieCollection HandleWebRequest(WebRequestEventArgs e, IReadOnlyCollection<string> cookieNames = null) { var cookieCollection = new CookieCollection(); if (e.WebRequestExecutor?.WebRequest?.CookieContainer == null) { return null; } var cookies = e.WebRequestExecutor.WebRequest.CookieContainer .GetCookies(e.WebRequestExecutor.WebRequest.RequestUri); if (cookies.Count <= 0) { return null; } foreach (Cookie cookie in cookies) { if (cookie == null) { continue; } if (cookieNames == null || !cookieNames.Any()) { cookieCollection.Add(cookie); } else if (cookieNames.Any(r => r.Equals(cookie.Name))) { cookieCollection.Add(cookie); } } return cookieCollection; } /// <summary> /// Defines a Maximum Retry Attemped Exception /// </summary> [Serializable] public class MaximumRetryAttemptedException : Exception { /// <summary> /// Constructor /// </summary> /// <param name="message"></param> public MaximumRetryAttemptedException(string message) : base(message) { } } /// <summary> /// Checks the server library version of the context for a minimally required version /// </summary> /// <param name="clientContext">clientContext to operate on</param> /// <param name="minimallyRequiredVersion">provide version to validate</param> /// <returns>True if it has minimal required version, false otherwise</returns> public static bool HasMinimalServerLibraryVersion(this ClientRuntimeContext clientContext, string minimallyRequiredVersion) { return HasMinimalServerLibraryVersion(clientContext, new Version(minimallyRequiredVersion)); } /// <summary> /// Checks the server library version of the context for a minimally required version /// </summary> /// <param name="clientContext">clientContext to operate on</param> /// <param name="minimallyRequiredVersion">provide version to validate</param> /// <returns>True if it has minimal required version, false otherwise</returns> public static bool HasMinimalServerLibraryVersion(this ClientRuntimeContext clientContext, Version minimallyRequiredVersion) { bool hasMinimalVersion = false; #if !ONPREMISES try { clientContext.ExecuteQueryRetry(); hasMinimalVersion = clientContext.ServerLibraryVersion.CompareTo(minimallyRequiredVersion) >= 0; } catch (PropertyOrFieldNotInitializedException) { // swallow the exception. } #else try { Uri urlUri = new Uri(clientContext.Url); HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"{urlUri.Scheme}://{urlUri.DnsSafeHost}:{urlUri.Port}/_vti_pvt/service.cnf"); request.UseDefaultCredentials = true; var response = request.GetResponse(); using (var dataStream = response.GetResponseStream()) { // Open the stream using a StreamReader for easy access. using (System.IO.StreamReader reader = new System.IO.StreamReader(dataStream)) { // Read the content.Will be in this format // vti_encoding:SR|utf8-nl // vti_extenderversion: SR | 15.0.0.4505 string version = reader.ReadToEnd().Split('|')[2].Trim(); // Only compare the first three digits var compareToVersion = new Version(minimallyRequiredVersion.Major, minimallyRequiredVersion.Minor, minimallyRequiredVersion.Build, 0); hasMinimalVersion = new Version(version.Split('.')[0].ToInt32(), 0, version.Split('.')[3].ToInt32(), 0).CompareTo(compareToVersion) >= 0; } } } catch (WebException ex) { Log.Warning(Constants.LOGGING_SOURCE, CoreResources.ClientContextExtensions_HasMinimalServerLibraryVersion_Error, ex.ToDetailedString(clientContext)); } #endif return hasMinimalVersion; } /// <summary> /// Returns the name of the method calling ExecuteQueryRetry and ExecuteQueryRetryAsync /// </summary> /// <returns>A string with the method name</returns> private static string GetCallingPnPMethod() { StackTrace t = new StackTrace(); string pnpMethod = ""; try { for (int i = 0; i < t.FrameCount; i++) { var frame = t.GetFrame(i); var frameName = frame.GetMethod().Name; if (frameName.Equals("ExecuteQueryRetry") || frameName.Equals("ExecuteQueryRetryAsync")) { var method = t.GetFrame(i + 1).GetMethod(); // Only return the calling method in case ExecuteQueryRetry was called from inside the PnP core library if (method.Module.Name.Equals("OfficeDevPnP.Core.dll", StringComparison.InvariantCultureIgnoreCase)) { pnpMethod = method.Name; } break; } } } catch { // ignored } return pnpMethod; } /// <summary> /// Returns the request digest from the current session/site /// </summary> /// <param name="context"></param> /// <returns></returns> public static async Task<string> GetRequestDigestAsync(this ClientContext context) { await new SynchronizationContextRemover(); //InitializeSecurity(context); using (var handler = new HttpClientHandler()) { string responseString = string.Empty; var accessToken = context.GetAccessToken(); context.Web.EnsureProperty(w => w.Url); if (String.IsNullOrEmpty(accessToken)) { handler.SetAuthenticationCookies(context); } using (var httpClient = new PnPHttpProvider(handler)) { string requestUrl = String.Format("{0}/_api/contextinfo", context.Web.Url); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUrl); request.Headers.Add("accept", "application/json;odata=verbose"); if (!string.IsNullOrEmpty(accessToken)) { request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken); } else { if (context.Credentials is NetworkCredential networkCredential) { handler.Credentials = networkCredential; } } HttpResponseMessage response = await httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { responseString = await response.Content.ReadAsStringAsync(); } else { var errorSb = new System.Text.StringBuilder(); errorSb.AppendLine(await response.Content.ReadAsStringAsync()); if (response.Headers.Contains("SPRequestGuid")) { var values = response.Headers.GetValues("SPRequestGuid"); if (values != null) { var spRequestGuid = values.FirstOrDefault(); errorSb.AppendLine($"ServerErrorTraceCorrelationId: {spRequestGuid}"); } } throw new Exception(errorSb.ToString()); } } var contextInformation = JsonConvert.DeserializeObject<dynamic>(responseString); string formDigestValue = contextInformation.d.GetContextWebInformation.FormDigestValue; return await Task.Run(() => formDigestValue).ConfigureAwait(false); } } private static void Context_ExecutingWebRequest(object sender, WebRequestEventArgs e) { if (!String.IsNullOrEmpty(e.WebRequestExecutor.RequestHeaders.Get("Authorization"))) { accessToken = e.WebRequestExecutor.RequestHeaders.Get("Authorization").Replace("Bearer ", ""); } } #if !SP2013 && !SP2016 /// <summary> /// BETA: Creates a Communication Site Collection /// </summary> /// <param name="clientContext"></param> /// <param name="siteCollectionCreationInformation"></param> /// <returns></returns> public static async Task<ClientContext> CreateSiteAsync(this ClientContext clientContext, CommunicationSiteCollectionCreationInformation siteCollectionCreationInformation) { await new SynchronizationContextRemover(); return await SiteCollection.CreateAsync(clientContext, siteCollectionCreationInformation); } /// <summary> /// BETA: Creates a Team Site Collection with no group /// </summary> /// <param name="clientContext"></param> /// <param name="siteCollectionCreationInformation"></param> /// <returns></returns> public static async Task<ClientContext> CreateSiteAsync(this ClientContext clientContext, TeamNoGroupSiteCollectionCreationInformation siteCollectionCreationInformation) { await new SynchronizationContextRemover(); return await SiteCollection.CreateAsync(clientContext, siteCollectionCreationInformation); } #endif #if !ONPREMISES /// <summary> /// BETA: Creates a Team Site Collection /// </summary> /// <param name="clientContext"></param> /// <param name="siteCollectionCreationInformation"></param> /// <returns></returns> public static async Task<ClientContext> CreateSiteAsync(this ClientContext clientContext, TeamSiteCollectionCreationInformation siteCollectionCreationInformation) { await new SynchronizationContextRemover(); return await SiteCollection.CreateAsync(clientContext, siteCollectionCreationInformation); } /// <summary> /// BETA: Groupifies a classic Team Site Collection /// </summary> /// <param name="clientContext">ClientContext instance of the site to be groupified</param> /// <param name="siteCollectionGroupifyInformation">Information needed to groupify this site</param> /// <returns>The clientcontext of the groupified site</returns> public static async Task<ClientContext> GroupifySiteAsync(this ClientContext clientContext, TeamSiteCollectionGroupifyInformation siteCollectionGroupifyInformation) { await new SynchronizationContextRemover(); return await SiteCollection.GroupifyAsync(clientContext, siteCollectionGroupifyInformation); } /// <summary> /// Checks if an alias is already used for an office 365 group or not /// </summary> /// <param name="clientContext">ClientContext of the site to operate against</param> /// <param name="alias">Alias to verify</param> /// <returns>True if in use, false otherwise</returns> public static async Task<bool> AliasExistsAsync(this ClientContext clientContext, string alias) { await new SynchronizationContextRemover(); return await SiteCollection.AliasExistsAsync(clientContext, alias); } /// <summary> /// Enable MS Teams team on a group connected team site /// </summary> /// <param name="clientContext"></param> /// <returns></returns> public static async Task<string> TeamifyAsync(this ClientContext clientContext) { await new SynchronizationContextRemover(); return await SiteCollection.TeamifySiteAsync(clientContext); } /// <summary> /// Checks whether the teamify prompt is hidden in O365 Group connected sites /// </summary> /// <param name="clientContext">ClientContext of the site to operate against</param> /// <returns></returns> public static async Task<bool> IsTeamifyPromptHiddenAsync(this ClientContext clientContext) { await new SynchronizationContextRemover(); return await SiteCollection.IsTeamifyPromptHiddenAsync(clientContext); } [Obsolete("Use IsTeamifyPromptHiddenAsync")] public static async Task<bool> IsTeamifyPromptHidden(this ClientContext clientContext) { return await IsTeamifyPromptHiddenAsync(clientContext); } /// <summary> /// Hide the teamify prompt displayed in O365 group connected sites /// </summary> /// <param name="clientContext">ClientContext of the site to operate against</param> /// <returns></returns> public static async Task<bool> HideTeamifyPromptAsync(this ClientContext clientContext) { await new SynchronizationContextRemover(); return await SiteCollection.HideTeamifyPromptAsync(clientContext); } /// <summary> /// Deletes a Communication site or a group-less Modern team site /// </summary> /// <param name="clientContext"></param> /// <returns></returns> public static async Task<bool> DeleteSiteAsync(this ClientContext clientContext) { await new SynchronizationContextRemover(); return await SiteCollection.DeleteSiteAsync(clientContext); } #endif } }
using System; using System.Collections.Generic; using UnityEditor; using UnityEngine; using System.IO; namespace AppCenterEditor { public abstract class AppCenterSDKPackage { private static int angle = 0; public static IEnumerable<AppCenterSDKPackage> SupportedPackages = new AppCenterSDKPackage[] { AppCenterAnalyticsPackage.Instance, AppCenterCrashesPackage.Instance, AppCenterDistributePackage.Instance, AppCenterPushPackage.Instance }; public string InstalledVersion { get; private set; } public bool IsInstalled { get; set; } public bool IsPackageInstalling { get; set; } public bool IsObjectFieldActive { get; set; } protected abstract bool IsSupportedForWSA { get; } public abstract string Name { get; } public abstract string DownloadLatestUrl { get; } public abstract string DownloadUrlFormat { get; } public abstract string TypeName { get; } public abstract string VersionFieldName { get; } protected abstract bool IsSdkPackageSupported(); public static IEnumerable<AppCenterSDKPackage> GetInstalledPackages() { var installedPackages = new List<AppCenterSDKPackage>(); foreach (var package in SupportedPackages) { if (package.IsInstalled) { installedPackages.Add(package); } } return installedPackages; } private void RemovePackage(bool prompt = true) { if (prompt && !EditorUtility.DisplayDialog("Confirm SDK Removal", string.Format("This action will remove the current {0} SDK.", Name), "Confirm", "Cancel")) { return; } EdExLogger.LoggerInstance.LogWithTimeStamp(string.Format("Removing {0} package...", Name)); var toDelete = new List<string>(); string pluginsPath = Path.Combine(AppCenterEditorPrefsSO.Instance.SdkPath, "Plugins"); string androidPath = Path.Combine(pluginsPath, "Android"); string sdkPath = Path.Combine(pluginsPath, "AppCenterSDK"); string iosPath = Path.Combine(pluginsPath, "iOS"); string wsaPath = Path.Combine(pluginsPath, "WSA"); toDelete.Add(Path.Combine(androidPath, string.Format("appcenter-{0}-release.aar", Name.ToLower()))); toDelete.AddRange(Directory.GetFiles(Path.Combine(sdkPath, Name))); toDelete.AddRange(Directory.GetDirectories(Path.Combine(sdkPath, Name))); toDelete.Add(Path.Combine(sdkPath, Name)); toDelete.AddRange(Directory.GetFiles(Path.Combine(iosPath, Name))); toDelete.AddRange(Directory.GetDirectories(Path.Combine(iosPath, Name))); toDelete.Add(Path.Combine(iosPath, Name)); if (IsSupportedForWSA) { toDelete.AddRange(Directory.GetFiles(Path.Combine(wsaPath, Name))); toDelete.AddRange(Directory.GetDirectories(Path.Combine(wsaPath, Name))); toDelete.Add(Path.Combine(wsaPath, Name)); } bool deleted = true; foreach (var path in toDelete) { if (!FileUtil.DeleteFileOrDirectory(path)) { if (!path.EndsWith("meta")) { deleted = false; } } FileUtil.DeleteFileOrDirectory(path + ".meta"); } // Remove Core if no packages left. List<AppCenterSDKPackage> installedPackages = new List<AppCenterSDKPackage>(); installedPackages.AddRange(GetInstalledPackages()); if (installedPackages.Count <= 1) { AppCenterEditorSDKTools.RemoveSdk(false); } if (deleted) { EdExLogger.LoggerInstance.LogWithTimeStamp(string.Format("{0} package removed.", Name)); AppCenterEditor.RaiseStateUpdate(AppCenterEditor.EdExStates.OnSuccess, string.Format("App Center {0} SDK removed.", Name)); // HACK for 5.4, AssetDatabase.Refresh(); seems to cause the install to fail. if (prompt) { AssetDatabase.Refresh(); } } else { AppCenterEditor.RaiseStateUpdate(AppCenterEditor.EdExStates.OnError, string.Format("An unknown error occured and the {0} SDK could not be removed.", Name)); } } public void ShowPackageInstalledMenu() { var isPackageSupported = IsSdkPackageSupported(); using (new AppCenterGuiFieldHelper.UnityVertical(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleEmpty"))) { var sdkPackageVersion = InstalledVersion; using (new AppCenterGuiFieldHelper.UnityHorizontal(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleEmpty"))) { GUILayout.FlexibleSpace(); var labelStyle = new GUIStyle(AppCenterEditorHelper.uiStyle.GetStyle("versionText")); EditorGUILayout.LabelField(string.Format("{0} SDK {1} is installed", Name, sdkPackageVersion), labelStyle); GUILayout.FlexibleSpace(); } bool packageVersionIsValid = sdkPackageVersion != null && sdkPackageVersion != Constants.UnknownVersion; if (packageVersionIsValid && sdkPackageVersion.CompareTo(AppCenterEditorSDKTools.InstalledSdkVersion) != 0) { using (new AppCenterGuiFieldHelper.UnityHorizontal(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleEmpty"))) { GUILayout.FlexibleSpace(); EditorGUILayout.LabelField("Warning! Package version is not equal to the AppCenter Core SDK version. ", AppCenterEditorHelper.uiStyle.GetStyle("orTxt")); GUILayout.FlexibleSpace(); } } if (isPackageSupported && AppCenterEditorSDKTools.SdkFolder != null) { using (new AppCenterGuiFieldHelper.UnityHorizontal(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleEmpty"))) { GUILayout.FlexibleSpace(); if (GUILayout.Button("Remove SDK", AppCenterEditorHelper.uiStyle.GetStyle("textButton"))) { RemovePackage(); } GUILayout.FlexibleSpace(); } } } } public void ShowPackageNotInstalledMenu() { using (new AppCenterGuiFieldHelper.UnityVertical(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleEmpty"))) { using (new AppCenterGuiFieldHelper.UnityHorizontal(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleEmpty"))) { GUILayout.FlexibleSpace(); var labelStyle = new GUIStyle(AppCenterEditorHelper.uiStyle.GetStyle("versionText")); EditorGUILayout.LabelField(string.Format("{0} SDK is not installed.", Name), labelStyle); GUILayout.FlexibleSpace(); } using (new AppCenterGuiFieldHelper.UnityHorizontal(AppCenterEditorHelper.uiStyle.GetStyle("gpStyleEmpty"))) { GUILayout.FlexibleSpace(); if (IsPackageInstalling) { var image = DrawUtils.RotateImage(AssetDatabase.LoadAssetAtPath("Assets/AppCenterEditorExtensions/Editor/UI/Images/wheel.png", typeof(Texture2D)) as Texture2D, angle++); GUILayout.Button(new GUIContent(string.Format(" {0} SDK is installing", Name), image), AppCenterEditorHelper.uiStyle.GetStyle("customButton"), GUILayout.MaxWidth(200), GUILayout.MinHeight(32)); } else { if (GUILayout.Button("Install SDK", AppCenterEditorHelper.uiStyle.GetStyle("textButton"))) { AppCenterEditorSDKTools.IsInstalling = true; IsPackageInstalling = true; ImportLatestPackageSDK(); } } GUILayout.FlexibleSpace(); } } } public string GetDownloadUrl(string version) { if (string.IsNullOrEmpty(version) || version == Constants.UnknownVersion) { return DownloadLatestUrl; } else { return string.Format(DownloadUrlFormat, version); } } public void GetInstalledVersion(Type type, string coreVersion) { foreach (var field in type.GetFields()) { if (field.Name == VersionFieldName) { InstalledVersion = field.GetValue(field).ToString(); break; } } if (string.IsNullOrEmpty(InstalledVersion)) { InstalledVersion = Constants.UnknownVersion; } } private void ImportLatestPackageSDK() { PackagesInstaller.ImportLatestSDK(new[] { this }, AppCenterEditorSDKTools.LatestSdkVersion); } } }
namespace XenAdmin.Dialogs { partial class VmSnapshotDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VmSnapshotDialog)); this.labelName = new System.Windows.Forms.Label(); this.textBoxName = new System.Windows.Forms.TextBox(); this.buttonCancel = new System.Windows.Forms.Button(); this.buttonOk = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.textBoxDescription = new System.Windows.Forms.TextBox(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.flowLayoutPanel3 = new System.Windows.Forms.FlowLayoutPanel(); this.memoryRadioButton = new System.Windows.Forms.RadioButton(); this.CheckpointInfoPictureBox = new System.Windows.Forms.PictureBox(); this.flowLayoutPanel2 = new System.Windows.Forms.FlowLayoutPanel(); this.quiesceCheckBox = new System.Windows.Forms.CheckBox(); this.pictureBoxQuiesceInfo = new System.Windows.Forms.PictureBox(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.diskRadioButton = new System.Windows.Forms.RadioButton(); this.pictureBoxSnapshotsInfo = new System.Windows.Forms.PictureBox(); this.toolTip = new System.Windows.Forms.ToolTip(this.components); this.tableLayoutPanel1.SuspendLayout(); this.groupBox1.SuspendLayout(); this.flowLayoutPanel3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.CheckpointInfoPictureBox)).BeginInit(); this.flowLayoutPanel2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxQuiesceInfo)).BeginInit(); this.flowLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxSnapshotsInfo)).BeginInit(); this.SuspendLayout(); // // labelName // resources.ApplyResources(this.labelName, "labelName"); this.labelName.Name = "labelName"; // // textBoxName // resources.ApplyResources(this.textBoxName, "textBoxName"); this.textBoxName.Name = "textBoxName"; this.textBoxName.TextChanged += new System.EventHandler(this.textBoxName_TextChanged); // // buttonCancel // resources.ApplyResources(this.buttonCancel, "buttonCancel"); this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.UseVisualStyleBackColor = true; this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); // // buttonOk // resources.ApplyResources(this.buttonOk, "buttonOk"); this.buttonOk.Name = "buttonOk"; this.buttonOk.UseVisualStyleBackColor = true; this.buttonOk.Click += new System.EventHandler(this.buttonOk_Click); // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // textBoxDescription // resources.ApplyResources(this.textBoxDescription, "textBoxDescription"); this.textBoxDescription.Name = "textBoxDescription"; // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.labelName, 0, 0); this.tableLayoutPanel1.Controls.Add(this.textBoxName, 1, 0); this.tableLayoutPanel1.Controls.Add(this.label1, 0, 1); this.tableLayoutPanel1.Controls.Add(this.textBoxDescription, 1, 1); this.tableLayoutPanel1.Controls.Add(this.groupBox1, 0, 2); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // groupBox1 // this.tableLayoutPanel1.SetColumnSpan(this.groupBox1, 2); this.groupBox1.Controls.Add(this.flowLayoutPanel3); this.groupBox1.Controls.Add(this.flowLayoutPanel2); this.groupBox1.Controls.Add(this.flowLayoutPanel1); resources.ApplyResources(this.groupBox1, "groupBox1"); this.groupBox1.Name = "groupBox1"; this.groupBox1.TabStop = false; // // flowLayoutPanel3 // resources.ApplyResources(this.flowLayoutPanel3, "flowLayoutPanel3"); this.flowLayoutPanel3.Controls.Add(this.memoryRadioButton); this.flowLayoutPanel3.Controls.Add(this.CheckpointInfoPictureBox); this.flowLayoutPanel3.Name = "flowLayoutPanel3"; // // memoryRadioButton // resources.ApplyResources(this.memoryRadioButton, "memoryRadioButton"); this.memoryRadioButton.Name = "memoryRadioButton"; this.memoryRadioButton.TabStop = true; this.memoryRadioButton.UseVisualStyleBackColor = true; this.memoryRadioButton.CheckedChanged += new System.EventHandler(this.RadioButton_CheckedChanged); // // CheckpointInfoPictureBox // this.CheckpointInfoPictureBox.Cursor = System.Windows.Forms.Cursors.Hand; resources.ApplyResources(this.CheckpointInfoPictureBox, "CheckpointInfoPictureBox"); this.CheckpointInfoPictureBox.Image = global::XenAdmin.Properties.Resources._000_Info3_h32bit_16; this.CheckpointInfoPictureBox.Name = "CheckpointInfoPictureBox"; this.CheckpointInfoPictureBox.TabStop = false; this.CheckpointInfoPictureBox.MouseLeave += new System.EventHandler(this.CheckpointInfoPictureBox_MouseLeave); this.CheckpointInfoPictureBox.Click += new System.EventHandler(this.CheckpointInfoPictureBox_Click); // // flowLayoutPanel2 // resources.ApplyResources(this.flowLayoutPanel2, "flowLayoutPanel2"); this.flowLayoutPanel2.Controls.Add(this.quiesceCheckBox); this.flowLayoutPanel2.Controls.Add(this.pictureBoxQuiesceInfo); this.flowLayoutPanel2.Name = "flowLayoutPanel2"; // // quiesceCheckBox // resources.ApplyResources(this.quiesceCheckBox, "quiesceCheckBox"); this.quiesceCheckBox.Name = "quiesceCheckBox"; this.quiesceCheckBox.UseVisualStyleBackColor = true; this.quiesceCheckBox.CheckedChanged += new System.EventHandler(this.quiesceCheckBox_CheckedChanged); // // pictureBoxQuiesceInfo // this.pictureBoxQuiesceInfo.Cursor = System.Windows.Forms.Cursors.Hand; resources.ApplyResources(this.pictureBoxQuiesceInfo, "pictureBoxQuiesceInfo"); this.pictureBoxQuiesceInfo.Image = global::XenAdmin.Properties.Resources._000_Info3_h32bit_16; this.pictureBoxQuiesceInfo.Name = "pictureBoxQuiesceInfo"; this.pictureBoxQuiesceInfo.TabStop = false; this.pictureBoxQuiesceInfo.MouseLeave += new System.EventHandler(this.pictureBoxQuiesceInfo_MouseLeave); this.pictureBoxQuiesceInfo.Click += new System.EventHandler(this.pictureBoxQuiesceInfo_Click); // // flowLayoutPanel1 // resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1"); this.flowLayoutPanel1.Controls.Add(this.diskRadioButton); this.flowLayoutPanel1.Controls.Add(this.pictureBoxSnapshotsInfo); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; // // diskRadioButton // resources.ApplyResources(this.diskRadioButton, "diskRadioButton"); this.diskRadioButton.Checked = true; this.diskRadioButton.Name = "diskRadioButton"; this.diskRadioButton.TabStop = true; this.diskRadioButton.UseVisualStyleBackColor = true; this.diskRadioButton.CheckedChanged += new System.EventHandler(this.RadioButton_CheckedChanged); // // pictureBoxSnapshotsInfo // this.pictureBoxSnapshotsInfo.Cursor = System.Windows.Forms.Cursors.Hand; resources.ApplyResources(this.pictureBoxSnapshotsInfo, "pictureBoxSnapshotsInfo"); this.pictureBoxSnapshotsInfo.Image = global::XenAdmin.Properties.Resources._000_Info3_h32bit_16; this.pictureBoxSnapshotsInfo.Name = "pictureBoxSnapshotsInfo"; this.pictureBoxSnapshotsInfo.TabStop = false; this.pictureBoxSnapshotsInfo.MouseLeave += new System.EventHandler(this.pictureBoxSnapshotsInfo_MouseLeave); this.pictureBoxSnapshotsInfo.Click += new System.EventHandler(this.pictureBoxSnapshotsInfo_Click); // // VmSnapshotDialog // this.AcceptButton = this.buttonOk; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.CancelButton = this.buttonCancel; this.Controls.Add(this.buttonCancel); this.Controls.Add(this.buttonOk); this.Controls.Add(this.tableLayoutPanel1); this.Name = "VmSnapshotDialog"; this.Load += new System.EventHandler(this.VmSnapshotDialog_Load); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.flowLayoutPanel3.ResumeLayout(false); this.flowLayoutPanel3.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.CheckpointInfoPictureBox)).EndInit(); this.flowLayoutPanel2.ResumeLayout(false); this.flowLayoutPanel2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxQuiesceInfo)).EndInit(); this.flowLayoutPanel1.ResumeLayout(false); this.flowLayoutPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxSnapshotsInfo)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label labelName; private System.Windows.Forms.TextBox textBoxName; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.Button buttonOk; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textBoxDescription; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.ToolTip toolTip; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel3; private System.Windows.Forms.RadioButton memoryRadioButton; private System.Windows.Forms.PictureBox CheckpointInfoPictureBox; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel2; private System.Windows.Forms.CheckBox quiesceCheckBox; private System.Windows.Forms.PictureBox pictureBoxQuiesceInfo; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.RadioButton diskRadioButton; private System.Windows.Forms.PictureBox pictureBoxSnapshotsInfo; } }
/* Copyright (c) 2006 Ladislav Prosek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.Xml; using System.Xml.XPath; using System.Xml.Schema; using System.Text; using System.Collections.Generic; using System.Runtime.InteropServices; using PHP.Core; namespace PHP.Library.Xml { /// <summary> /// DOM element. /// </summary> [ImplementsType] public partial class DOMElement : DOMNode { #region Fields and Properties protected internal XmlElement XmlElement { get { return (XmlElement)XmlNode; } set { XmlNode = value; } } private string _name; private string _value; private string _namespaceUri; /// <summary> /// Returns the name of the element. /// </summary> [PhpVisible] public override string nodeName { get { return (IsAssociated ? base.nodeName : _name); } } /// <summary> /// Returns or sets the value (inner text) of the element. /// </summary> [PhpVisible] public override object nodeValue { get { return (IsAssociated ? XmlNode.InnerText : _value); } set { this._value = PHP.Core.Convert.ObjectToString(value); if (IsAssociated) XmlNode.InnerText = this._value; } } /// <summary> /// Returns the namespace URI of the node. /// </summary> [PhpVisible] public override string namespaceURI { get { return (IsAssociated ? base.namespaceURI : _namespaceUri); } } /// <summary> /// Returns the type of the node (<see cref="NodeType.Element"/>). /// </summary> [PhpVisible] public override object nodeType { get { return (int)NodeType.Element; } } /// <summary> /// Returns a map of attributes of this node (see <see cref="DOMNamedNodeMap"/>). /// </summary> [PhpVisible] public override object attributes { get { DOMNamedNodeMap map = new DOMNamedNodeMap(); if (IsAssociated) { foreach (XmlAttribute attr in XmlNode.Attributes) { IXmlDomNode node = Create(attr); if (node != null) map.AddNode(node); } } return map; } } /// <summary> /// Returns the tag name. /// </summary> [PhpVisible] public object tagName { get { return this.nodeName; } } /// <summary> /// Not implemented in PHP 5.1.6. /// </summary> public object schemaTypeInfo { get { return null; } } #endregion #region Construction public DOMElement() : base(ScriptContext.CurrentContext, true) { } internal DOMElement(XmlElement/*!*/ xmlElement) : base(ScriptContext.CurrentContext, true) { this.XmlElement = xmlElement; } protected override PHP.Core.Reflection.DObject CloneObjectInternal(PHP.Core.Reflection.DTypeDesc caller, ScriptContext context, bool deepCopyFields) { if (IsAssociated) return new DOMElement(XmlElement); else { DOMElement copy = new DOMElement(); copy.__construct(this._name, this._value, this._namespaceUri); return copy; } } [PhpVisible] public void __construct(string name, [Optional] string value, [Optional] string namespaceUri) { // just save up the name, value, and ns URI for later XmlElement construction this._name = name; this._value = value; this._namespaceUri = namespaceUri; } #endregion #region Hierarchy protected internal override void Associate(XmlDocument/*!*/ document) { if (!IsAssociated) { XmlElement elem = document.CreateElement(_name, _namespaceUri); if (_value != null) elem.InnerText = _value; XmlElement = elem; } } #endregion #region Attributes /// <summary> /// Returns the value of an attribute. /// </summary> /// <param name="name">The attribute name.</param> /// <returns>The attribute value or empty string.</returns> [PhpVisible] public object getAttribute(string name) { if (IsAssociated) { XmlAttribute attr = XmlElement.Attributes[name]; if (attr != null) return attr.Value; } return String.Empty; } /// <summary> /// Returns the value of an attribute. /// </summary> /// <param name="namespaceUri">The attribute namespace URI.</param> /// <param name="localName">The attribute local name.</param> /// <returns>The attribute value or empty string.</returns> [PhpVisible] public object getAttributeNS(string namespaceUri, string localName) { if (IsAssociated) { XmlAttribute attr = XmlElement.Attributes[localName, namespaceUri]; if (attr != null) return attr.Value; } return String.Empty; } /// <summary> /// Sets the value of a attribute (creates new one if it does not exist). /// </summary> /// <param name="name">The attribute name.</param> /// <param name="value">The attribute value.</param> /// <returns><B>True</B> on success, <B>false</B> on failure.</returns> [PhpVisible] public object setAttribute(string name, string value) { if (!IsAssociated) { DOMException.Throw(ExceptionCode.DomModificationNotAllowed); return false; } XmlAttribute attr = XmlElement.Attributes[name]; if (attr == null) { attr = XmlNode.OwnerDocument.CreateAttribute(name); XmlElement.Attributes.Append(attr); } attr.Value = value; return true; } /// <summary> /// Sets the value of a attribute (creates new one if it does not exist). /// </summary> /// <param name="namespaceUri">The attribute namespace URI.</param> /// <param name="qualifiedName">The attribute qualified name.</param> /// <param name="value">The attribute value.</param> /// <returns><B>True</B> on success, <B>false</B> on failure.</returns> [PhpVisible] public object setAttributeNS(string namespaceUri, string qualifiedName, string value) { if (!IsAssociated) { DOMException.Throw(ExceptionCode.DomModificationNotAllowed); return false; } // parse the qualified name string local_name, prefix; XmlDom.ParseQualifiedName(qualifiedName, out prefix, out local_name); XmlAttribute attr = XmlElement.Attributes[local_name, namespaceUri]; if (attr == null) { attr = XmlNode.OwnerDocument.CreateAttribute(qualifiedName, namespaceUri); XmlElement.Attributes.Append(attr); } else attr.Prefix = prefix; attr.Value = value; return true; } /// <summary> /// Removes an attribute. /// </summary> /// <param name="name">The attribute name.</param> /// <returns><B>True</B> on success, <B>false</B> on failure.</returns> [PhpVisible] public object removeAttribute(string name) { if (!IsAssociated) { DOMException.Throw(ExceptionCode.DomModificationNotAllowed); return false; } XmlAttribute attr = XmlElement.Attributes[name]; if (attr != null) XmlElement.Attributes.Remove(attr); return true; } /// <summary> /// Removes an attribute. /// </summary> /// <param name="namespaceUri">The attribute namespace URI.</param> /// <param name="localName">The attribute local name.</param> /// <returns><B>True</B> on success, <B>false</B> on failure.</returns> [PhpVisible] public object removeAttributeNS(string namespaceUri, string localName) { if (!IsAssociated) { DOMException.Throw(ExceptionCode.DomModificationNotAllowed); return false; } XmlAttribute attr = XmlElement.Attributes[localName, namespaceUri]; if (attr != null) XmlElement.Attributes.Remove(attr); return true; } /// <summary> /// Returns an attribute node. /// </summary> /// <param name="name">The attribute name.</param> /// <returns>The attribute or <B>false</B>.</returns> [PhpVisible] public object getAttributeNode(string name) { if (IsAssociated) { XmlAttribute attr = XmlElement.Attributes[name]; if (attr != null) return new DOMAttr(attr); } return false; } /// <summary> /// Returns an attribute node. /// </summary> /// <param name="namespaceUri">The attribute namespace URI.</param> /// <param name="localName">The attribute local name.</param> /// <returns>The attribute or <B>false</B>.</returns> [PhpVisible] public object getAttributeNodeNS(string namespaceUri, string localName) { if (IsAssociated) { XmlAttribute attr = XmlElement.Attributes[localName, namespaceUri]; if (attr != null) return new DOMAttr(attr); } return false; } /// <summary> /// Adds new attribute node to the element. /// </summary> /// <param name="attribute">The attribute node.</param> /// <returns>Old node if the attribute has been replaced or <B>null</B>.</returns> [PhpVisible] public object setAttributeNode(DOMAttr attribute) { if (!IsAssociated) { DOMException.Throw(ExceptionCode.DomModificationNotAllowed); return false; } attribute.Associate(XmlElement.OwnerDocument); if (XmlNode.OwnerDocument != attribute.XmlNode.OwnerDocument) { DOMException.Throw(ExceptionCode.WrongDocument); return null; } XmlAttribute attr = XmlElement.Attributes[attribute.nodeName]; if (attr != null) { XmlElement.Attributes.Remove(attr); XmlElement.Attributes.Append(attribute.XmlAttribute); return new DOMAttr(attr); } else { XmlElement.Attributes.Append(attribute.XmlAttribute); return null; } } /// <summary> /// Adds new attribute node to the element. /// </summary> /// <param name="attribute">The attribute node.</param> /// <returns>Old node if the attribute has been replaced or <B>null</B>.</returns> [PhpVisible] public object setAttributeNodeNS(DOMAttr attribute) { if (!IsAssociated) { DOMException.Throw(ExceptionCode.DomModificationNotAllowed); return false; } attribute.Associate(XmlElement.OwnerDocument); if (XmlNode.OwnerDocument != attribute.XmlNode.OwnerDocument) { DOMException.Throw(ExceptionCode.WrongDocument); return null; } XmlAttribute attr = XmlElement.Attributes[attribute.localName, attribute.namespaceURI]; if (attr != null) { XmlElement.Attributes.Remove(attr); XmlElement.Attributes.Append(attribute.XmlAttribute); return new DOMAttr(attr); } else { XmlElement.Attributes.Append(attribute.XmlAttribute); return null; } } /// <summary> /// Removes an attribute node from the element. /// </summary> /// <param name="attribute">The attribute node.</param> /// <returns>Old node if the attribute has been removed or <B>null</B>.</returns> [PhpVisible] public object removeAttributeNode(DOMAttr attribute) { if (!IsAssociated) { DOMException.Throw(ExceptionCode.DomModificationNotAllowed); return false; } XmlAttribute attr = XmlElement.Attributes[attribute.nodeName]; if (attr == null) { DOMException.Throw(ExceptionCode.NotFound); return false; } XmlElement.Attributes.Remove(attr); return attribute; } /// <summary> /// Checks whether an attribute exists. /// </summary> /// <param name="name">The attribute name.</param> /// <returns><B>True</B> or <B>false</B>.</returns> [PhpVisible] public object hasAttribute(string name) { if (IsAssociated) { if (XmlElement.Attributes[name] != null) return true; } return false; } /// <summary> /// Checks whether an attribute exists. /// </summary> /// <param name="namespaceUri">The attribute namespace URI.</param> /// <param name="localName">The attribute local name.</param> /// <returns><B>True</B> or <B>false</B>.</returns> [PhpVisible] public object hasAttributeNS(string namespaceUri, string localName) { if (IsAssociated) { if (XmlElement.Attributes[localName, namespaceUri] != null) return true; } return false; } #endregion #region Child elements /// <summary> /// Gets all descendant elements with the matching tag name. /// </summary> /// <param name="name">The tag name. Use <B>*</B> to return all elements within the element tree.</param> /// <returns>A <see cref="DOMNodeList"/>.</returns> [PhpVisible] public object getElementsByTagName(string name) { DOMNodeList list = new DOMNodeList(); if (IsAssociated) { // enumerate elements in the default namespace foreach (XmlNode node in XmlElement.GetElementsByTagName(name)) { IXmlDomNode dom_node = DOMNode.Create(node); if (dom_node != null) list.AppendNode(dom_node); } // enumerate all namespaces XPathNavigator navigator = XmlElement.CreateNavigator(); XPathNodeIterator iterator =navigator.Select("//namespace::*[not(. = ../../namespace::*)]"); while (iterator.MoveNext()) { string prefix = iterator.Current.Name; if (!String.IsNullOrEmpty(prefix) && prefix != "xml") { // enumerate elements in this namespace foreach (XmlNode node in XmlElement.GetElementsByTagName(name, iterator.Current.Value)) { IXmlDomNode dom_node = DOMNode.Create(node); if (dom_node != null) list.AppendNode(dom_node); } } } } return list; } /// <summary> /// Gets all descendant elements with the matching namespace URI and local name. /// </summary> /// <param name="namespaceUri">The namespace URI.</param> /// <param name="localName">The local name. Use <B>*</B> to return all elements within the element tree.</param> /// <returns>A <see cref="DOMNodeList"/>.</returns> [PhpVisible] public object getElementsByTagNameNS(string namespaceUri, string localName) { DOMNodeList list = new DOMNodeList(); if (IsAssociated) { foreach (XmlNode node in XmlElement.GetElementsByTagName(localName, namespaceUri)) { IXmlDomNode dom_node = DOMNode.Create(node); if (dom_node != null) list.AppendNode(dom_node); } } return list; } #endregion #region Validation /// <summary> /// Not implemented in PHP 5.1.6. /// </summary> [PhpVisible] public void setIdAttribute(string name, bool isId) { PhpException.Throw(PhpError.Warning, Resources.NotYetImplemented); } /// <summary> /// Not implemented in PHP 5.1.6. /// </summary> [PhpVisible] public void setIdAttributeNS(string namespaceUri, string localName, bool isId) { PhpException.Throw(PhpError.Warning, Resources.NotYetImplemented); } /// <summary> /// Not implemented in PHP 5.1.6. /// </summary> [PhpVisible] public void setIdAttributeNode(DOMAttr attribute, bool isId) { PhpException.Throw(PhpError.Warning, Resources.NotYetImplemented); } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.GraphAlgorithms; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.Routing.Visibility; namespace Microsoft.Msagl.Routing { /// <summary> /// calculations with obstacles /// </summary> public class InteractiveObstacleCalculator { Dictionary<Polyline,double> tightPolylinesToLooseDistances; double TightPadding { get; set; } internal double LoosePadding { get; set; } internal InteractiveObstacleCalculator(IEnumerable<ICurve> obstacles, double tightPadding, double loosePadding, bool ignoreTightPadding) { Obstacles = obstacles; TightPadding = tightPadding; LoosePadding = loosePadding; IgnoreTightPadding = ignoreTightPadding; } /// <summary> /// the obstacles for routing /// </summary> IEnumerable<ICurve> Obstacles { get; set; } /// <summary> /// Returns true if overlaps are detected in the initial set of TightObstacles. /// TightObstacles will then have been repaired by merging each overlapping group /// of shapes into a single obstacle. /// </summary> public bool OverlapsDetected { get; private set; } Set<Polyline> tightObstacles=new Set<Polyline>(); /// <summary> /// Before routing we pad shapes such that every point of the boundary /// of the padded shape is at least router.Padding outside the boundary of the original shape. /// We also add extra faces to round corners a little. Edge paths are guaranteed not to come /// inside this padded TightObstacle boundary even after spline smoothing. /// </summary> internal Set<Polyline> TightObstacles { get { return tightObstacles; } private set { tightObstacles = value; } } /// <summary> /// We also pad TightObstacles by router.LoosePadding (where possible) to generate the shape /// overwhich the visibility graph is actually generated. /// </summary> internal List<Polyline> LooseObstacles { get; private set; } /// <summary> /// Root of binary space partition tree used for rapid region queries over TightObstacles. /// </summary> // TODO: replace these with the BinarySpacePartitionTree wrapper class internal RectangleNode<Polyline> RootOfTightHierarchy { get; set; } /// <summary> /// Root of binary space partition tree used for rapid region queries over LooseObstacles. /// </summary> // TODO: replace these with the BinarySpacePartitionTree wrapper class internal RectangleNode<Polyline> RootOfLooseHierarchy { get; set; } internal bool IgnoreTightPadding { get; set; } internal const double LooseDistCoefficient = 2.1; /// <summary> /// There are two sets of obstacles: tight and loose. /// We route the shortest path between LooseObstacles, and then smooth it with splines but without /// going inside TightObstacles. /// </summary> /// <returns></returns> internal void Calculate() { if (!IgnoreTightPadding) CreateTightObstacles(); else CreateTightObstaclesIgnoringTightPadding(); if (!IsEmpty()) CreateLooseObstacles(); } /// <summary> /// /// </summary> internal void CreateLooseObstacles() { tightPolylinesToLooseDistances = new Dictionary<Polyline, double>(); LooseObstacles = new List<Polyline>(); foreach (var tightPolyline in TightObstacles) { var distance = FindMaxPaddingForTightPolyline(RootOfTightHierarchy, tightPolyline, LoosePadding); tightPolylinesToLooseDistances[tightPolyline] = distance; LooseObstacles.Add(LoosePolylineWithFewCorners(tightPolyline, distance)); } RootOfLooseHierarchy = CalculateHierarchy(LooseObstacles); Debug.Assert(GetOverlappedPairSet(RootOfLooseHierarchy).Count == 0,"Overlaps are found in LooseObstacles"); } //internal void ShowRectangleNodesHierarchy(RectangleNode<Polyline> node) { // List<ICurve> ls = new List<ICurve>(); // FillList(ls, node); // SugiyamaLayoutSettings.Show(ls.ToArray()); //} //internal void FillList(List<ICurve> ls, RectangleNode<Polyline> node) { // if (node == null) // return; // if (node.UserData != null) // ls.Add(node.UserData); // else { // FillList(ls, node.Left); // FillList(ls, node.Right); // } //} internal static void UpdateRectsForParents(RectangleNode<Polyline> node) { while (node.Parent != null) { node.Parent.rectangle.Add(node.Rectangle); node = node.Parent; } } /// <summary> /// Handling overlapping obstacles: /// - create tightobstacles /// - find overlapping tightobstacles /// - replace with convexhull of overlapping /// /// Not particularly optimal method O(m * n log n) - where m is number of overlaps, n is number of obstacles: /// /// overlapping = 0 /// do /// foreach o in TightObstacles: /// I = set of all other obstacles which intersect o /// if I != 0 /// overlapping = I + o /// break /// if overlapping != 0 /// combinedObstacle = new obstacle from convex hull of overlapping /// tightObstacles.delete(overlapping) /// tightObstacles.add(combinedObstacle) /// while overlapping != 0 /// </summary> void CreateTightObstacles() { RootOfTightHierarchy = CreateTightObstacles(Obstacles, TightPadding, TightObstacles); OverlapsDetected = TightObstacles.Count < Obstacles.Count(); } static internal RectangleNode<Polyline> CreateTightObstacles(IEnumerable<ICurve> obstacles, double tightPadding, Set<Polyline> tightObstacleSet) { Debug.Assert(tightObstacleSet!=null); if(obstacles.Count()==0) return null; foreach (ICurve curve in obstacles) CalculateTightPolyline(tightObstacleSet, tightPadding, curve); return RemovePossibleOverlapsInTightPolylinesAndCalculateHierarchy(tightObstacleSet); } static internal RectangleNode<Polyline> RemovePossibleOverlapsInTightPolylinesAndCalculateHierarchy(Set<Polyline> tightObstacleSet) { var hierarchy = CalculateHierarchy(tightObstacleSet); Set<Tuple<Polyline, Polyline>> overlappingPairSet; while ((overlappingPairSet = GetOverlappedPairSet(hierarchy)).Count > 0) hierarchy = ReplaceTightObstaclesWithConvexHulls(tightObstacleSet, overlappingPairSet); return hierarchy; } void CreateTightObstaclesIgnoringTightPadding() { var polysWithoutPadding = Obstacles.Select(o => Curve.PolylineAroundClosedCurve(o)).ToArray(); var polylineHierarchy = CalculateHierarchy(polysWithoutPadding); var overlappingPairSet = GetOverlappedPairSet(polylineHierarchy); TightObstacles = new Set<Polyline>(); if (overlappingPairSet.Count == 0) { foreach (var polyline in polysWithoutPadding) { var distance = FindMaxPaddingForTightPolyline(polylineHierarchy, polyline, TightPadding); TightObstacles.Insert(LoosePolylineWithFewCorners(polyline, distance)); } RootOfTightHierarchy = CalculateHierarchy(TightObstacles); } else { foreach (var poly in polysWithoutPadding) TightObstacles.Insert(CreatePaddedPolyline(poly, TightPadding)); if (!IsEmpty()) { RootOfTightHierarchy = CalculateHierarchy(TightObstacles); OverlapsDetected = false; while ((overlappingPairSet = GetOverlappedPairSet(RootOfTightHierarchy)).Count > 0) { RootOfTightHierarchy= ReplaceTightObstaclesWithConvexHulls(TightObstacles, overlappingPairSet); OverlapsDetected = true; } } } } static void CalculateTightPolyline(Set<Polyline> tightObstacles, double tightPadding, ICurve curve) { var tightPoly = PaddedPolylineBoundaryOfNode(curve, tightPadding); // if (AdditionalPolylinesContainedInTightPolyline != null) { // var polysToContain = AdditionalPolylinesContainedInTightPolyline(curve); // if (polysToContain.Any(poly => !Curve.CurveIsInsideOther(poly, tightPoly))) { // var points = (IEnumerable<Point>)tightPoly; // points = points.Concat(polysToContain.SelectMany(p => p)); // tightPoly = new Polyline(ConvexHull.CalculateConvexHull(points)) { Closed = true }; // } // } tightObstacles.Insert(tightPoly); } internal static RectangleNode<Polyline> ReplaceTightObstaclesWithConvexHulls(Set<Polyline> tightObsts, IEnumerable<Tuple<Polyline, Polyline>> overlappingPairSet) { var overlapping = new Set<Polyline>(); foreach (var pair in overlappingPairSet) { overlapping.Insert(pair.Item1); overlapping.Insert(pair.Item2); } var intToPoly = overlapping.ToArray(); var polyToInt = MapToInt(intToPoly); var graph = new BasicGraph<IntPair>( overlappingPairSet. Select(pair => new IntPair(polyToInt[pair.Item1], polyToInt[pair.Item2]))); var connectedComponents = ConnectedComponentCalculator<IntPair>.GetComponents(graph); foreach (var component in connectedComponents) { var polys = component.Select(i => intToPoly[i]); var points = polys.SelectMany(p => p); var convexHull = ConvexHull.CreateConvexHullAsClosedPolyline(points); foreach (var poly in polys) tightObsts.Remove(poly); tightObsts.Insert(convexHull); } return CalculateHierarchy(tightObsts); } internal static Dictionary<T, int> MapToInt<T>(T[] objects) { var ret = new Dictionary<T, int>(); for (int i = 0; i < objects.Length; i++) ret[objects[i]] = i; return ret; } internal bool IsEmpty() { return TightObstacles == null || TightObstacles.Count == 0; } internal static Set<Tuple<Polyline, Polyline>> GetOverlappedPairSet(RectangleNode<Polyline> rootOfObstacleHierarchy) { var overlappingPairSet = new Set<Tuple<Polyline, Polyline>>(); RectangleNodeUtils.CrossRectangleNodes<Polyline>(rootOfObstacleHierarchy, rootOfObstacleHierarchy, (a, b) => { if (PolylinesIntersect(a, b)) { overlappingPairSet.Insert( new Tuple<Polyline, Polyline>(a, b)); } }); return overlappingPairSet; } internal static bool PolylinesIntersect(Polyline a, Polyline b) { var ret= Curve.CurvesIntersect(a, b) || OneCurveLiesInsideOfOther(a, b); return ret; } internal static RectangleNode<Polyline> CalculateHierarchy(IEnumerable<Polyline> polylines) { var rectNodes = polylines.Select(polyline => CreateRectNodeOfPolyline(polyline)).ToList(); return RectangleNode<Polyline>.CreateRectangleNodeOnListOfNodes(rectNodes); } static RectangleNode<Polyline> CreateRectNodeOfPolyline(Polyline polyline) { return new RectangleNode<Polyline>(polyline, (polyline as ICurve).BoundingBox); } internal static bool OneCurveLiesInsideOfOther(ICurve polyA, ICurve polyB) { Debug.Assert(!Curve.CurvesIntersect(polyA, polyB), "The curves should not intersect"); return (Curve.PointRelativeToCurveLocation(polyA.Start, polyB) != PointLocation.Outside || Curve.PointRelativeToCurveLocation(polyB.Start, polyA) != PointLocation.Outside); } static internal Polyline CreatePaddedPolyline(Polyline poly, double padding) { Debug.Assert(Point.GetTriangleOrientation(poly[0], poly[1], poly[2]) == TriangleOrientation.Clockwise , "Unpadded polyline is not clockwise"); var ret = new Polyline(); if (!PadCorner(ret, poly.EndPoint.Prev, poly.EndPoint, poly.StartPoint, padding)) return CreatePaddedPolyline(new Polyline(ConvexHull.CalculateConvexHull(poly)) {Closed = true}, padding); if (!PadCorner(ret, poly.EndPoint, poly.StartPoint, poly.StartPoint.Next, padding)) return CreatePaddedPolyline(new Polyline(ConvexHull.CalculateConvexHull(poly)) {Closed = true}, padding); for (var pp = poly.StartPoint; pp.Next.Next != null; pp = pp.Next) if (!PadCorner(ret, pp, pp.Next, pp.Next.Next, padding)) return CreatePaddedPolyline(new Polyline(ConvexHull.CalculateConvexHull(poly)) {Closed = true}, padding); Debug.Assert(Point.GetTriangleOrientation(ret[0], ret[1], ret[2]) != TriangleOrientation.Counterclockwise , "Padded polyline is counterclockwise"); ret.Closed = true; return ret; } /// <summary> /// return true if succeeds and false if it is a non convex case /// </summary> /// <param name="poly"></param> /// <param name="p0"></param> /// <param name="p1"></param> /// <param name="p2"></param> /// <param name="padding"></param> /// <returns></returns> static bool PadCorner(Polyline poly, PolylinePoint p0, PolylinePoint p1, PolylinePoint p2, double padding) { Point a, b; int numberOfPoints = GetPaddedCorner(p0, p1, p2, out a, out b, padding); if (numberOfPoints == -1) return false; poly.AddPoint(a); if (numberOfPoints == 2) poly.AddPoint(b); return true; } /// <summary> /// /// </summary> /// <param name="first"></param> /// <param name="second"></param> /// <param name="third"></param> /// <param name="a"></param> /// <param name="b"></param> /// <param name="padding"></param> /// <returns>number of new points</returns> static int GetPaddedCorner(PolylinePoint first, PolylinePoint second, PolylinePoint third, out Point a, out Point b, double padding) { Point u = first.Point; Point v = second.Point; Point w = third.Point; if (Point.GetTriangleOrientation(u, v, w) == TriangleOrientation.Counterclockwise) { a = new Point(); b = new Point(); return -1; } Point uvPerp = (v - u).Rotate(Math.PI/2).Normalize(); if (CornerIsNotTooSharp(u, v, w)) { //the angle is not too sharp: just continue the offset lines of the sides and return their intersection uvPerp *= padding; Point vwPerp = ((w - v).Normalize()*padding).Rotate(Math.PI/2); bool result = Point.LineLineIntersection(u + uvPerp, v + uvPerp, v + vwPerp, w + vwPerp, out a); Debug.Assert(result); b = a; return 1; } Point l = (v - u).Normalize() + (v - w).Normalize(); if (l.Length < ApproximateComparer.IntersectionEpsilon) { a = b = v + padding*uvPerp; return 1; } Point d = l.Normalize()*padding; Point dp = d.Rotate(Math.PI/2); //look for a in the form d+x*dp //we have: Padding=(d+x*dp)*uvPerp double xp = (padding - d*uvPerp)/(dp*uvPerp); a = d + xp*dp + v; b = d - xp*dp + v; return 2; //number of points to add } static bool CornerIsNotTooSharp(Point u, Point v, Point w) { Point a = (u - v).Rotate(Math.PI/4) + v; return Point.GetTriangleOrientation(v, a, w) == TriangleOrientation.Counterclockwise; // return Point.Angle(u, v, w) > Math.PI / 4; } /// <summary> /// in general works for convex curves /// </summary> /// <param name="iCurve"></param> /// <param name="pointInside"></param> /// <returns></returns> internal static bool CurveIsClockwise(ICurve iCurve, Point pointInside) { return Point.GetTriangleOrientation(pointInside, iCurve.Start, iCurve.Start + iCurve.Derivative(iCurve.ParStart)) == TriangleOrientation.Clockwise; } /// <summary> /// Creates a padded polyline boundary of the node. The polyline offsets at least as the padding from the node boundary. /// </summary> /// <param name="curve"></param> /// <param name="padding"></param> /// <returns></returns> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Polyline")] public static Polyline PaddedPolylineBoundaryOfNode(ICurve curve, double padding) { return CreatePaddedPolyline(Curve.PolylineAroundClosedCurve(curve), padding); } internal static Polyline LoosePolylineWithFewCorners(Polyline tightPolyline, double p) { if (p < ApproximateComparer.DistanceEpsilon) return tightPolyline; Polyline loosePolyline = CreateLoosePolylineOnBisectors(tightPolyline, p); //LayoutAlgorithmSettings.Show(tightPolyline, loosePolyline); return loosePolyline; } static Polyline CreateLoosePolylineOnBisectors(Polyline tightPolyline, double offset) { return new Polyline(ConvexHull.CalculateConvexHull(BisectorPoints(tightPolyline, offset))) { Closed = true }; } static IEnumerable<Point> BisectorPoints(Polyline tightPolyline, double offset){ List<Point> ret=new List<Point>(); for (PolylinePoint pp = tightPolyline.StartPoint; pp != null; pp = pp.Next) { bool skip; Point currentSticking = GetStickingVertexOnBisector(pp, offset, out skip); if (!skip) ret.Add( currentSticking); } return ret; } static Point GetStickingVertexOnBisector(PolylinePoint pp, double p, out bool skip) { Point u = pp.Polyline.Prev(pp).Point; Point v = pp.Point; Point w = pp.Polyline.Next(pp).Point; var z = (v - u).Normalize() + (v - w).Normalize(); var zLen = z.Length; if (zLen < ApproximateComparer.Tolerance) skip = true; else { skip = false; z /= zLen; } return p*z + v; } /// <summary> /// Find tight obstacles close to the specified polyline and find the max amount of padding (up to /// desiredPadding) which can be applied to the polyline such that it will not overlap any of the /// surrounding polylines when they are also padded. That is, we find the minimum separation /// between these shapes and divide by 2 (and a bit) - and if this is less than desiredPadding /// we return this as the amount to padd the polyline to create the looseObstacle. /// </summary> /// <param name="hierarchy"></param> /// <param name="polyline">a polyline to pad (tightObstacle)</param> /// <param name="desiredPadding">desired amount to pad</param> /// <returns>maximum amount we can pad without creating overlaps</returns> internal static double FindMaxPaddingForTightPolyline(RectangleNode<Polyline> hierarchy, Polyline polyline, double desiredPadding ) { var dist = desiredPadding; var polygon = new Polygon(polyline); var boundingBox = polyline.BoundingBox; boundingBox.Pad(2.0*desiredPadding); foreach (var poly in hierarchy.GetNodeItemsIntersectingRectangle(boundingBox).Where(p=>p!=polyline)) { var separation = Polygon.Distance(polygon, new Polygon(poly)); dist = Math.Min(dist, separation/LooseDistCoefficient); } return dist; } internal bool ObstaclesIntersectLine(Point a, Point b) { return ObstaclesIntersectICurve(new LineSegment(a, b)); } internal bool ObstaclesIntersectICurve(ICurve curve) { Rectangle rect = curve.BoundingBox; return CurveIntersectsRectangleNode(curve, ref rect, RootOfTightHierarchy); } static bool CurveIntersectsRectangleNode(ICurve curve, ref Rectangle curveBox, RectangleNode<Polyline> rectNode) { if (!rectNode.Rectangle.Intersects(curveBox)) return false; if (rectNode.UserData != null) { var curveUnderTest = rectNode.UserData; return Curve.CurveCurveIntersectionOne(curveUnderTest, curve, false) != null || Inside(curveUnderTest, curve); } Debug.Assert(rectNode.Left != null && rectNode.Right != null); return CurveIntersectsRectangleNode(curve, ref curveBox, rectNode.Left) || CurveIntersectsRectangleNode(curve, ref curveBox, rectNode.Right); } /// <summary> /// we know here that there are no intersections between "curveUnderTest" and "curve", /// We are testing that curve is inside of "curveUnderTest" /// </summary> /// <param name="curveUnderTest"></param> /// <param name="curve"></param> /// <returns></returns> static bool Inside(ICurve curveUnderTest, ICurve curve) { return Curve.PointRelativeToCurveLocation(curve.Start, curveUnderTest) == PointLocation.Inside; } //internal void HideTightPolylineContainingPoint(Point sourcePortLocation) { // //the source polyline should not participate in // sourceTightNode = InteractiveEdgeRouter.GetFirstHitRectangleNode(sourcePortLocation, this.RootOfTightHierararchy); // sourceTightNode.rectangle = new Rectangle(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity); //need to restore it when edge routing is done //} internal void ScaleLooseObstacles(double coefficient) { LooseObstacles.Clear(); foreach (var tightPolyline in TightObstacles) LooseObstacles.Add(LoosePolylineWithFewCorners(tightPolyline, tightPolylinesToLooseDistances[tightPolyline]*coefficient)); RootOfLooseHierarchy = CalculateHierarchy(LooseObstacles); Debug.Assert(GetOverlappedPairSet(RootOfLooseHierarchy).Count == 0, "Overlaps are found in LooseObstacles"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace QuickCheck.Internal { public abstract class Data { private Data() { } public override string ToString() { return AppendTo(new StringBuilder()).ToString(); } public abstract StringBuilder AppendTo(StringBuilder sb); public abstract DataDiff Diff(Data other); public static Data Value(object x) { return new DataValue(x); } public static Data List(IEnumerable<Data> xs) { return new DataList(xs.ToArray()); } public static Data Object(string type, IEnumerable<KeyValuePair<string, Data>> xs) { return new DataObject(type, xs.ToArray()); } private sealed class DataValue : Data { private readonly object m_Primitive; public DataValue(object primitive) { m_Primitive = primitive; } public override StringBuilder AppendTo(StringBuilder sb) { if (m_Primitive is string) { return sb.Append('"').Append(m_Primitive).Append('"'); } if (m_Primitive is char) { return sb.Append('\'').Append(m_Primitive).Append('\''); } return sb.Append(m_Primitive); } public override DataDiff Diff(Data other) { DataValue value = other as DataValue; if (value != null) { object old = m_Primitive; object new_ = value.m_Primitive; if (Equals(old, new_)) { return DataDiff.Empty; } Type oldType = old.GetType(); Type newType = new_.GetType(); if (oldType == newType) { if (oldType == typeof(float)) { return new FloatDiff((float)old, (float)new_); } if (oldType == typeof(double)) { return new DoubleDiff((double)old, (double)new_); } } } return new GeneralDiff(this, other); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj is DataValue && Equals((DataValue)obj); } private bool Equals(DataValue other) { return m_Primitive.Equals(other.m_Primitive); } public override int GetHashCode() { return m_Primitive.GetHashCode(); } } private sealed class DataList : Data { private readonly Data[] m_Values; public DataList(Data[] values) { m_Values = values; } public override StringBuilder AppendTo(StringBuilder sb) { sb.Append("["); bool comma = false; foreach (var item in m_Values) { if (comma) { sb.Append(", "); } item.AppendTo(sb); comma = true; } return sb.Append("]"); } public override DataDiff Diff(Data other) { if (Equals(this, other)) { return DataDiff.Empty; } return new GeneralDiff(this, other); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj is DataList && Equals((DataList)obj); } private bool Equals(DataList other) { return Sequence.Equals(m_Values, other.m_Values); } public override int GetHashCode() { return Sequence.GetHashCode(m_Values); } } private sealed class DataObject : Data { private readonly string m_Type; private readonly KeyValuePair<string, Data>[] m_Fields; public DataObject(string type, KeyValuePair<string, Data>[] fields) { m_Type = type; m_Fields = fields; } public override StringBuilder AppendTo(StringBuilder sb) { if (m_Fields.Length == 0) { return sb; } sb.Append("{"); bool comma = false; foreach (var field in m_Fields) { if (comma) { sb.Append(", "); } sb.Append(field.Key); sb.Append(": "); if (field.Value == null) { sb.Append("null"); } else { sb.Append(field.Value); } comma = true; } return sb.Append("}"); } public override DataDiff Diff(Data other) { DataObject obj = other as DataObject; if (obj != null && String.Equals(m_Type, obj.m_Type, StringComparison.Ordinal)) { return new ObjectDiff(m_Fields, obj.m_Fields); } return new GeneralDiff(this, other); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj is DataObject && Equals((DataObject)obj); } private bool Equals(DataObject other) { return String.Equals(m_Type, other.m_Type) && Sequence.Equals(m_Fields, other.m_Fields); } public override int GetHashCode() { unchecked { return (m_Type.GetHashCode() * 397) ^ Sequence.GetHashCode(m_Fields); } } } } }
using FarseerGames.FarseerPhysics; using FarseerGames.FarseerPhysics.Collisions; using FarseerGames.FarseerPhysics.Dynamics; using FarseerGames.FarseerPhysics.Dynamics.Joints; using FarseerGames.FarseerPhysics.Factories; using FarseerGames.SimpleSamplesXNA.DrawingSystem; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace FarseerGames.SimpleSamplesXNA.Demos.DemoShare { public class Spider { private const int spiderBodyRadius = 20; private CollisionCategory _collidesWith = CollisionCategory.All; private CollisionCategory _collisionCategory = CollisionCategory.All; private int _collisionGroup; private bool _kneeFlexed; private float _kneeTargetAngle = .4f; private AngleJoint _leftKneeAngleJoint; private Body _leftLowerLegBody; private Geom _leftLowerLegGeom; private AngleJoint _leftShoulderAngleJoint; private Body _leftUpperLegBody; private Geom _leftUpperLegGeom; private Vector2 _lowerLegOrigin; private Vector2 _lowerLegSize = new Vector2(30, 12); private Texture2D _lowerLegTexture; private Vector2 _position; private AngleJoint _rightKneeAngleJoint; private Body _rightLowerLegBody; private Geom _rightLowerLegGeom; private AngleJoint _rightShoulderAngleJoint; private Body _rightUpperLegBody; private Geom _rightUpperLegGeom; private float _s; private bool _shoulderFlexed; private float _shoulderTargetAngle = .2f; private Body _spiderBody; private Geom _spiderGeom; private Vector2 _spiderOrigin; private Texture2D _spiderTexture; private Vector2 _upperLegOrigin; private Vector2 _upperLegSize = new Vector2(40, 12); //x=width, y=height private Texture2D _upperLegTexture; public Spider(Vector2 position) { _position = position; } public Body Body { get { return _spiderBody; } } public CollisionCategory CollisionCategory { get { return _collisionCategory; } set { _collisionCategory = value; } } public CollisionCategory CollidesWith { get { return _collidesWith; } set { _collidesWith = value; } } public int CollisionGroup { get { return _collisionGroup; } set { _collisionGroup = value; } } public void ApplyForce(Vector2 force) { _spiderBody.ApplyForce(force); } public void ApplyTorque(float torque) { _spiderBody.ApplyTorque(torque); } public void Load(GraphicsDevice graphicsDevice, PhysicsSimulator physicsSimulator) { _spiderTexture = DrawingHelper.CreateCircleTexture(graphicsDevice, spiderBodyRadius, Color.White, Color.Black); _spiderOrigin = new Vector2(_spiderTexture.Width/2f, _spiderTexture.Height/2f); _upperLegTexture = DrawingHelper.CreateRectangleTexture(graphicsDevice, (int) _upperLegSize.X, (int) _upperLegSize.Y, Color.White, Color.Black); _upperLegOrigin = new Vector2(_upperLegTexture.Width/2f, _upperLegTexture.Height/2f); _lowerLegTexture = DrawingHelper.CreateRectangleTexture(graphicsDevice, (int) _lowerLegSize.X, (int) _lowerLegSize.Y, Color.Red, Color.Black); _lowerLegOrigin = new Vector2(_lowerLegTexture.Width/2f, _lowerLegTexture.Height/2f); //Load bodies _spiderBody = BodyFactory.Instance.CreateCircleBody(physicsSimulator, spiderBodyRadius, 1); _spiderBody.Position = _position; _spiderBody.IsStatic = false; _leftUpperLegBody = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, _upperLegSize.X, _upperLegSize.Y, 1); _leftUpperLegBody.Position = _spiderBody.Position - new Vector2(spiderBodyRadius, 0) - new Vector2(_upperLegSize.X/2, 0); _leftLowerLegBody = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, _lowerLegSize.X, _lowerLegSize.Y, 1); _leftLowerLegBody.Position = _spiderBody.Position - new Vector2(spiderBodyRadius, 0) - new Vector2(_upperLegSize.X, 0) - new Vector2(_lowerLegSize.X/2, 0); _rightUpperLegBody = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, _upperLegSize.X, _upperLegSize.Y, 1); _rightUpperLegBody.Position = _spiderBody.Position + new Vector2(spiderBodyRadius, 0) + new Vector2(_upperLegSize.X/2, 0); _rightLowerLegBody = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, _lowerLegSize.X, _lowerLegSize.Y, 1); _rightLowerLegBody.Position = _spiderBody.Position + new Vector2(spiderBodyRadius, 0) + new Vector2(_upperLegSize.X, 0) + new Vector2(_lowerLegSize.X/2, 0); //load geometries _spiderGeom = GeomFactory.Instance.CreateCircleGeom(physicsSimulator, _spiderBody, spiderBodyRadius, 14); _leftUpperLegGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, _leftUpperLegBody, _upperLegSize.X, _upperLegSize.Y); _leftLowerLegGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, _leftLowerLegBody, _lowerLegSize.X, _lowerLegSize.Y); _rightUpperLegGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, _rightUpperLegBody, _upperLegSize.X, _upperLegSize.Y); _rightLowerLegGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, _rightLowerLegBody, _lowerLegSize.X, _lowerLegSize.Y); _spiderGeom.CollisionGroup = _collisionGroup; _leftUpperLegGeom.CollisionGroup = _collisionGroup; _leftLowerLegGeom.CollisionGroup = _collisionGroup; _rightUpperLegGeom.CollisionGroup = _collisionGroup; _rightLowerLegGeom.CollisionGroup = _collisionGroup; //load joints JointFactory.Instance.CreateRevoluteJoint(physicsSimulator, _spiderBody, _leftUpperLegBody, _spiderBody.Position - new Vector2(spiderBodyRadius, 0)); _leftShoulderAngleJoint = JointFactory.Instance.CreateAngleJoint(physicsSimulator, _spiderBody, _leftUpperLegBody); _leftShoulderAngleJoint.TargetAngle = -.4f; _leftShoulderAngleJoint.MaxImpulse = 300; JointFactory.Instance.CreateRevoluteJoint(physicsSimulator, _spiderBody, _rightUpperLegBody, _spiderBody.Position + new Vector2(spiderBodyRadius, 0)); _rightShoulderAngleJoint = JointFactory.Instance.CreateAngleJoint(physicsSimulator, _spiderBody, _rightUpperLegBody); _rightShoulderAngleJoint.TargetAngle = .4f; _leftShoulderAngleJoint.MaxImpulse = 300; JointFactory.Instance.CreateRevoluteJoint(physicsSimulator, _leftUpperLegBody, _leftLowerLegBody, _spiderBody.Position - new Vector2(spiderBodyRadius, 0) - new Vector2(_upperLegSize.X, 0)); _leftKneeAngleJoint = JointFactory.Instance.CreateAngleJoint(physicsSimulator, _leftUpperLegBody, _leftLowerLegBody); _leftKneeAngleJoint.TargetAngle = -_kneeTargetAngle; _leftKneeAngleJoint.MaxImpulse = 300; JointFactory.Instance.CreateRevoluteJoint(physicsSimulator, _rightUpperLegBody, _rightLowerLegBody, _spiderBody.Position + new Vector2(spiderBodyRadius, 0) + new Vector2(_upperLegSize.X, 0)); _rightKneeAngleJoint = JointFactory.Instance.CreateAngleJoint(physicsSimulator, _rightUpperLegBody, _rightLowerLegBody); _rightKneeAngleJoint.TargetAngle = _kneeTargetAngle; _rightKneeAngleJoint.MaxImpulse = 300; } public void Update(GameTime gameTime) { _s += gameTime.ElapsedGameTime.Milliseconds; if (_s > 4000) { _s = 0; _kneeFlexed = !_kneeFlexed; _shoulderFlexed = !_shoulderFlexed; if (_kneeFlexed) _kneeTargetAngle = 1.4f; else _kneeTargetAngle = .4f; if (_kneeFlexed) _shoulderTargetAngle = 1.2f; else _shoulderTargetAngle = .2f; } _leftKneeAngleJoint.TargetAngle = -_kneeTargetAngle; _rightKneeAngleJoint.TargetAngle = _kneeTargetAngle; _leftShoulderAngleJoint.TargetAngle = -_shoulderTargetAngle; _rightShoulderAngleJoint.TargetAngle = _shoulderTargetAngle; } public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(_upperLegTexture, _leftUpperLegGeom.Position, null, Color.White, _leftUpperLegGeom.Rotation, _upperLegOrigin, 1, SpriteEffects.None, 0f); spriteBatch.Draw(_lowerLegTexture, _leftLowerLegGeom.Position, null, Color.White, _leftLowerLegGeom.Rotation, _lowerLegOrigin, 1, SpriteEffects.None, 0f); spriteBatch.Draw(_upperLegTexture, _rightUpperLegGeom.Position, null, Color.White, _rightUpperLegGeom.Rotation, _upperLegOrigin, 1, SpriteEffects.None, 0f); spriteBatch.Draw(_lowerLegTexture, _rightLowerLegGeom.Position, null, Color.White, _rightLowerLegGeom.Rotation, _lowerLegOrigin, 1, SpriteEffects.None, 0f); spriteBatch.Draw(_spiderTexture, _spiderGeom.Position, null, Color.White, _spiderGeom.Rotation, _spiderOrigin, 1, SpriteEffects.None, 0f); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: Odometry.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; /// <summary>Holder for reflection information generated from Odometry.proto</summary> public static partial class OdometryReflection { #region Descriptor /// <summary>File descriptor for Odometry.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static OdometryReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cg5PZG9tZXRyeS5wcm90bxoMSGVhZGVyLnByb3RvGhhQb3NlV2l0aENvdmFy", "aWFuY2UucHJvdG8aGVR3aXN0V2l0aENvdmFyaWFuY2UucHJvdG8igwEKCE9k", "b21ldHJ5EhcKBmhlYWRlchgBIAEoCzIHLkhlYWRlchIWCg5jaGlsZF9mcmFt", "ZV9pZBgCIAEoCRIhCgRwb3NlGAMgASgLMhMuUG9zZVdpdGhDb3ZhcmlhbmNl", "EiMKBXR3aXN0GAQgASgLMhQuVHdpc3RXaXRoQ292YXJpYW5jZWIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HeaderReflection.Descriptor, global::PoseWithCovarianceReflection.Descriptor, global::TwistWithCovarianceReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Odometry), global::Odometry.Parser, new[]{ "Header", "ChildFrameId", "Pose", "Twist" }, null, null, null) })); } #endregion } #region Messages public sealed partial class Odometry : pb::IMessage<Odometry> { private static readonly pb::MessageParser<Odometry> _parser = new pb::MessageParser<Odometry>(() => new Odometry()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Odometry> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::OdometryReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Odometry() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Odometry(Odometry other) : this() { Header = other.header_ != null ? other.Header.Clone() : null; childFrameId_ = other.childFrameId_; Pose = other.pose_ != null ? other.Pose.Clone() : null; Twist = other.twist_ != null ? other.Twist.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Odometry Clone() { return new Odometry(this); } /// <summary>Field number for the "header" field.</summary> public const int HeaderFieldNumber = 1; private global::Header header_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Header Header { get { return header_; } set { header_ = value; } } /// <summary>Field number for the "child_frame_id" field.</summary> public const int ChildFrameIdFieldNumber = 2; private string childFrameId_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ChildFrameId { get { return childFrameId_; } set { childFrameId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "pose" field.</summary> public const int PoseFieldNumber = 3; private global::PoseWithCovariance pose_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::PoseWithCovariance Pose { get { return pose_; } set { pose_ = value; } } /// <summary>Field number for the "twist" field.</summary> public const int TwistFieldNumber = 4; private global::TwistWithCovariance twist_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::TwistWithCovariance Twist { get { return twist_; } set { twist_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Odometry); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Odometry other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Header, other.Header)) return false; if (ChildFrameId != other.ChildFrameId) return false; if (!object.Equals(Pose, other.Pose)) return false; if (!object.Equals(Twist, other.Twist)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (header_ != null) hash ^= Header.GetHashCode(); if (ChildFrameId.Length != 0) hash ^= ChildFrameId.GetHashCode(); if (pose_ != null) hash ^= Pose.GetHashCode(); if (twist_ != null) hash ^= Twist.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 (header_ != null) { output.WriteRawTag(10); output.WriteMessage(Header); } if (ChildFrameId.Length != 0) { output.WriteRawTag(18); output.WriteString(ChildFrameId); } if (pose_ != null) { output.WriteRawTag(26); output.WriteMessage(Pose); } if (twist_ != null) { output.WriteRawTag(34); output.WriteMessage(Twist); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (header_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Header); } if (ChildFrameId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ChildFrameId); } if (pose_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Pose); } if (twist_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Twist); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Odometry other) { if (other == null) { return; } if (other.header_ != null) { if (header_ == null) { header_ = new global::Header(); } Header.MergeFrom(other.Header); } if (other.ChildFrameId.Length != 0) { ChildFrameId = other.ChildFrameId; } if (other.pose_ != null) { if (pose_ == null) { pose_ = new global::PoseWithCovariance(); } Pose.MergeFrom(other.Pose); } if (other.twist_ != null) { if (twist_ == null) { twist_ = new global::TwistWithCovariance(); } Twist.MergeFrom(other.Twist); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (header_ == null) { header_ = new global::Header(); } input.ReadMessage(header_); break; } case 18: { ChildFrameId = input.ReadString(); break; } case 26: { if (pose_ == null) { pose_ = new global::PoseWithCovariance(); } input.ReadMessage(pose_); break; } case 34: { if (twist_ == null) { twist_ = new global::TwistWithCovariance(); } input.ReadMessage(twist_); break; } } } } } #endregion #endregion Designer generated code
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Reflection; using System.Diagnostics.Contracts; using System.IO; using System.Runtime.Versioning; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Threading; #if FEATURE_HOST_ASSEMBLY_RESOLVER namespace System.Runtime.Loader { [System.Security.SecuritySafeCritical] public abstract class AssemblyLoadContext { [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern bool OverrideDefaultAssemblyLoadContextForCurrentDomain(IntPtr ptrNativeAssemblyLoadContext); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern bool CanUseAppPathAssemblyLoadContextInCurrentDomain(); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern IntPtr InitializeAssemblyLoadContext(IntPtr ptrAssemblyLoadContext); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern IntPtr LoadFromStream(IntPtr ptrNativeAssemblyLoadContext, IntPtr ptrAssemblyArray, int iAssemblyArrayLen, IntPtr ptrSymbols, int iSymbolArrayLen, ObjectHandleOnStack retAssembly); #if FEATURE_MULTICOREJIT [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern void InternalSetProfileRoot(string directoryPath); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern void InternalStartProfile(string profile, IntPtr ptrNativeAssemblyLoadContext); #endif // FEATURE_MULTICOREJIT [System.Security.SecuritySafeCritical] protected AssemblyLoadContext() { // Initialize the VM side of AssemblyLoadContext if not already done. GCHandle gchALC = GCHandle.Alloc(this); IntPtr ptrALC = GCHandle.ToIntPtr(gchALC); m_pNativeAssemblyLoadContext = InitializeAssemblyLoadContext(ptrALC); } internal AssemblyLoadContext(bool fDummy) { } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, string ilPath, string niPath, ObjectHandleOnStack retAssembly); // These are helpers that can be used by AssemblyLoadContext derivations. // They are used to load assemblies in DefaultContext. protected Assembly LoadFromAssemblyPath(string assemblyPath) { if (assemblyPath == null) { throw new ArgumentNullException("assemblyPath"); } if (Path.IsRelative(assemblyPath)) { throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), "assemblyPath"); } RuntimeAssembly loadedAssembly = null; LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, null, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly)); return loadedAssembly; } protected Assembly LoadFromNativeImagePath(string nativeImagePath, string assemblyPath) { if (nativeImagePath == null) { throw new ArgumentNullException("nativeImagePath"); } if (Path.IsRelative(nativeImagePath)) { throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), "nativeImagePath"); } // Check if the nativeImagePath has ".ni.dll" or ".ni.exe" extension if (!(nativeImagePath.EndsWith(".ni.dll", StringComparison.InvariantCultureIgnoreCase) || nativeImagePath.EndsWith(".ni.exe", StringComparison.InvariantCultureIgnoreCase))) { throw new ArgumentException("nativeImagePath"); } if (assemblyPath != null && Path.IsRelative(assemblyPath)) { throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), "assemblyPath"); } // Basic validation has succeeded - lets try to load the NI image. // Ask LoadFile to load the specified assembly in the DefaultContext RuntimeAssembly loadedAssembly = null; LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, nativeImagePath, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly)); return loadedAssembly; } protected Assembly LoadFromStream(Stream assembly) { return LoadFromStream(assembly, null); } protected Assembly LoadFromStream(Stream assembly, Stream assemblySymbols) { if (assembly == null) { throw new ArgumentNullException("assembly"); } int iAssemblyStreamLength = (int)assembly.Length; int iSymbolLength = 0; // Allocate the byte[] to hold the assembly byte[] arrAssembly = new byte[iAssemblyStreamLength]; // Copy the assembly to the byte array assembly.Read(arrAssembly, 0, iAssemblyStreamLength); // Get the symbol stream in byte[] if provided byte[] arrSymbols = null; if (assemblySymbols != null) { iSymbolLength = (int)assemblySymbols.Length; arrSymbols = new byte[iSymbolLength]; assemblySymbols.Read(arrSymbols, 0, iSymbolLength); } RuntimeAssembly loadedAssembly = null; unsafe { fixed(byte *ptrAssembly = arrAssembly, ptrSymbols = arrSymbols) { LoadFromStream(m_pNativeAssemblyLoadContext, new IntPtr(ptrAssembly), iAssemblyStreamLength, new IntPtr(ptrSymbols), iSymbolLength, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly)); } } return loadedAssembly; } // Custom AssemblyLoadContext implementations can override this // method to perform custom processing and use one of the protected // helpers above to load the assembly. protected abstract Assembly Load(AssemblyName assemblyName); // This method is invoked by the VM when using the host-provided assembly load context // implementation. private static Assembly Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName) { AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target); return context.LoadFromAssemblyName(assemblyName); } public Assembly LoadFromAssemblyName(AssemblyName assemblyName) { // AssemblyName is mutable. Cache the expected name before anybody gets a chance to modify it. string requestedSimpleName = assemblyName.Name; Assembly assembly = Load(assemblyName); if (assembly == null) { throw new FileNotFoundException(Environment.GetResourceString("IO.FileLoad"), requestedSimpleName); } // Get the name of the loaded assembly string loadedSimpleName = null; // Derived type's Load implementation is expected to use one of the LoadFrom* methods to get the assembly // which is a RuntimeAssembly instance. However, since Assembly type can be used build any other artifact (e.g. AssemblyBuilder), // we need to check for RuntimeAssembly. RuntimeAssembly rtLoadedAssembly = assembly as RuntimeAssembly; if (rtLoadedAssembly != null) { loadedSimpleName = rtLoadedAssembly.GetSimpleName(); } // The simple names should match at the very least if (String.IsNullOrEmpty(loadedSimpleName) || (!requestedSimpleName.Equals(loadedSimpleName, StringComparison.InvariantCultureIgnoreCase))) throw new InvalidOperationException(Environment.GetResourceString("Argument_CustomAssemblyLoadContextRequestedNameMismatch")); return assembly; } // Custom AssemblyLoadContext implementations can override this // method to perform the load of unmanaged native dll // This function needs to return the HMODULE of the dll it loads protected virtual IntPtr LoadUnmanagedDll(String unmanagedDllName) { //defer to default coreclr policy of loading unmanaged dll return IntPtr.Zero; } // This method is invoked by the VM when using the host-provided assembly load context // implementation. private static IntPtr ResolveUnmanagedDll(String unmanagedDllName, IntPtr gchManagedAssemblyLoadContext) { AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target); return context.LoadUnmanagedDll(unmanagedDllName); } public static AssemblyLoadContext Default { get { while (m_DefaultAssemblyLoadContext == null) { // Try to initialize the default assembly load context with apppath one if we are allowed to if (AssemblyLoadContext.CanUseAppPathAssemblyLoadContextInCurrentDomain()) { #pragma warning disable 0420 Interlocked.CompareExchange(ref m_DefaultAssemblyLoadContext, new AppPathAssemblyLoadContext(), null); break; #pragma warning restore 0420 } // Otherwise, need to yield to other thread to finish the initialization Thread.Yield(); } return m_DefaultAssemblyLoadContext; } } // This will be used to set the AssemblyLoadContext for DefaultContext, for the AppDomain, // by a host. Once set, the runtime will invoke the LoadFromAssemblyName method against it to perform // assembly loads for the DefaultContext. // // This method will throw if the Default AssemblyLoadContext is already set or the Binding model is already locked. public static void InitializeDefaultContext(AssemblyLoadContext context) { if (context == null) { throw new ArgumentNullException("context"); } // Try to override the default assembly load context if (!AssemblyLoadContext.OverrideDefaultAssemblyLoadContextForCurrentDomain(context.m_pNativeAssemblyLoadContext)) { throw new InvalidOperationException(Environment.GetResourceString("AppDomain_BindingModelIsLocked")); } // Update the managed side as well. m_DefaultAssemblyLoadContext = context; } // This call opens and closes the file, but does not add the // assembly to the domain. [MethodImplAttribute(MethodImplOptions.InternalCall)] static internal extern AssemblyName nGetFileInformation(String s); // Helper to return AssemblyName corresponding to the path of an IL assembly public static AssemblyName GetAssemblyName(string assemblyPath) { if (assemblyPath == null) { throw new ArgumentNullException("assemblyPath"); } String fullPath = Path.GetFullPathInternal(assemblyPath); return nGetFileInformation(fullPath); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern IntPtr GetLoadContextForAssembly(RuntimeAssembly assembly); // Returns the load context in which the specified assembly has been loaded public static AssemblyLoadContext GetLoadContext(Assembly assembly) { if (assembly == null) { throw new ArgumentNullException("assembly"); } AssemblyLoadContext loadContextForAssembly = null; IntPtr ptrAssemblyLoadContext = GetLoadContextForAssembly((RuntimeAssembly)assembly); if (ptrAssemblyLoadContext == IntPtr.Zero) { // If the load context is returned null, then the assembly was bound using the TPA binder // and we shall return reference to the active "Default" binder - which could be the TPA binder // or an overridden CLRPrivBinderAssemblyLoadContext instance. loadContextForAssembly = AssemblyLoadContext.Default; } else { loadContextForAssembly = (AssemblyLoadContext)(GCHandle.FromIntPtr(ptrAssemblyLoadContext).Target); } return loadContextForAssembly; } // Set the root directory path for profile optimization. public void SetProfileOptimizationRoot(string directoryPath) { #if FEATURE_MULTICOREJIT InternalSetProfileRoot(directoryPath); #endif // FEATURE_MULTICOREJIT } // Start profile optimization for the specified profile name. public void StartProfileOptimization(string profile) { #if FEATURE_MULTICOREJIT InternalStartProfile(profile, m_pNativeAssemblyLoadContext); #endif // FEATURE_MULTICOREJI } // Contains the reference to VM's representation of the AssemblyLoadContext private IntPtr m_pNativeAssemblyLoadContext; // Each AppDomain contains the reference to its AssemblyLoadContext instance, if one is // specified by the host. By having the field as a static, we are // making it an AppDomain-wide field. private static volatile AssemblyLoadContext m_DefaultAssemblyLoadContext; } [System.Security.SecuritySafeCritical] class AppPathAssemblyLoadContext : AssemblyLoadContext { internal AppPathAssemblyLoadContext() : base(false) { } [System.Security.SecuritySafeCritical] protected override Assembly Load(AssemblyName assemblyName) { return Assembly.Load(assemblyName); } } } #endif // FEATURE_HOST_ASSEMBLY_RESOLVER
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsAzureResource { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// Resource Flattening for AutoRest /// </summary> public partial class AutoRestResourceFlatteningTestService : ServiceClient<AutoRestResourceFlatteningTestService>, IAutoRestResourceFlatteningTestService, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Gets Azure subscription credentials. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestResourceFlatteningTestService(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestResourceFlatteningTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestResourceFlatteningTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestResourceFlatteningTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestResourceFlatteningTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestResourceFlatteningTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestResourceFlatteningTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestResourceFlatteningTestService(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.BaseUri = new Uri("http://localhost"); this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } /// <summary> /// Put External Resource as an Array /// </summary> /// <param name='resourceArray'> /// External Resource as an Array to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PutArrayWithHttpMessagesAsync(IList<Resource> resourceArray = default(IList<Resource>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceArray", resourceArray); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutArray", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/array").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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; _requestContent = SafeJsonConvert.SerializeObject(resourceArray, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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> /// Get External Resource as an Array /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IList<FlattenedProduct>>> GetArrayWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetArray", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/array").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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<IList<FlattenedProduct>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<IList<FlattenedProduct>>(_responseContent, this.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put External Resource as a Dictionary /// </summary> /// <param name='resourceDictionary'> /// External Resource as a Dictionary to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PutDictionaryWithHttpMessagesAsync(IDictionary<string, FlattenedProduct> resourceDictionary = default(IDictionary<string, FlattenedProduct>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceDictionary", resourceDictionary); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutDictionary", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/dictionary").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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; _requestContent = SafeJsonConvert.SerializeObject(resourceDictionary, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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> /// Get External Resource as a Dictionary /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IDictionary<string, FlattenedProduct>>> GetDictionaryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetDictionary", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/dictionary").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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<IDictionary<string, FlattenedProduct>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<IDictionary<string, FlattenedProduct>>(_responseContent, this.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put External Resource as a ResourceCollection /// </summary> /// <param name='resourceComplexObject'> /// External Resource as a ResourceCollection to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PutResourceCollectionWithHttpMessagesAsync(ResourceCollection resourceComplexObject = default(ResourceCollection), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceComplexObject", resourceComplexObject); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutResourceCollection", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/resourcecollection").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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; _requestContent = SafeJsonConvert.SerializeObject(resourceComplexObject, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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> /// Get External Resource as a ResourceCollection /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ResourceCollection>> GetResourceCollectionWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetResourceCollection", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/resourcecollection").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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<ResourceCollection>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<ResourceCollection>(_responseContent, this.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; } } }
namespace Epi.Windows.Analysis.Controls { partial class ProjectBasedPgmControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region 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() { this.btnFindProject = new System.Windows.Forms.Button(); this.txtProject = new System.Windows.Forms.TextBox(); this.lblProject = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.txtComment = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.lbxPgms = new System.Windows.Forms.ListBox(); this.btnTextFile = new System.Windows.Forms.Button(); this.btnHelp = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.btnDelete = new System.Windows.Forms.Button(); this.lblDateModified = new System.Windows.Forms.Label(); this.lblDateCreated = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.txtPgmName = new System.Windows.Forms.TextBox(); this.txtDateUpdated = new System.Windows.Forms.TextBox(); this.txtDateCreated = new System.Windows.Forms.TextBox(); this.txtAuthor = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // btnFindProject // this.btnFindProject.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btnFindProject.Location = new System.Drawing.Point(400, 40); this.btnFindProject.Name = "btnFindProject"; this.btnFindProject.Size = new System.Drawing.Size(24, 16); this.btnFindProject.TabIndex = 27; this.btnFindProject.Text = "..."; // // txtProject // this.txtProject.Location = new System.Drawing.Point(8, 38); this.txtProject.Name = "txtProject"; this.txtProject.Size = new System.Drawing.Size(384, 20); this.txtProject.TabIndex = 26; this.txtProject.Text = ""; // // lblProject // this.lblProject.Location = new System.Drawing.Point(8, 16); this.lblProject.Name = "lblProject"; this.lblProject.Size = new System.Drawing.Size(408, 16); this.lblProject.TabIndex = 25; this.lblProject.Text = "&Project"; // // label3 // this.label3.Location = new System.Drawing.Point(152, 72); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(264, 23); this.label3.TabIndex = 33; this.label3.Text = "Comments"; // // txtComment // this.txtComment.Location = new System.Drawing.Point(152, 96); this.txtComment.Multiline = true; this.txtComment.Name = "txtComment"; this.txtComment.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.txtComment.Size = new System.Drawing.Size(264, 136); this.txtComment.TabIndex = 32; this.txtComment.Text = ""; // // label1 // this.label1.Location = new System.Drawing.Point(8, 72); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(136, 23); this.label1.TabIndex = 31; this.label1.Text = "Programs"; // // lbxPgms // this.lbxPgms.Location = new System.Drawing.Point(8, 97); this.lbxPgms.Name = "lbxPgms"; this.lbxPgms.Size = new System.Drawing.Size(136, 134); this.lbxPgms.TabIndex = 30; // // btnTextFile // this.btnTextFile.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btnTextFile.Location = new System.Drawing.Point(256, 360); this.btnTextFile.Name = "btnTextFile"; this.btnTextFile.TabIndex = 50; this.btnTextFile.Text = "&Text File"; // // btnHelp // this.btnHelp.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btnHelp.Location = new System.Drawing.Point(336, 360); this.btnHelp.Name = "btnHelp"; btnHelp.Enabled = false; this.btnHelp.TabIndex = 49; this.btnHelp.Text = "&Help"; // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btnCancel.Location = new System.Drawing.Point(88, 360); this.btnCancel.Name = "btnCancel"; this.btnCancel.TabIndex = 47; this.btnCancel.Text = "Cancel"; // // btnOK // this.btnOK.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btnOK.Location = new System.Drawing.Point(8, 360); this.btnOK.Name = "btnOK"; this.btnOK.TabIndex = 46; this.btnOK.Text = "OK"; // // btnDelete // this.btnDelete.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btnDelete.Location = new System.Drawing.Point(176, 360); this.btnDelete.Name = "btnDelete"; this.btnDelete.TabIndex = 48; this.btnDelete.Text = "&Delete"; // // lblDateModified // this.lblDateModified.Location = new System.Drawing.Point(208, 304); this.lblDateModified.Name = "lblDateModified"; this.lblDateModified.Size = new System.Drawing.Size(184, 23); this.lblDateModified.TabIndex = 45; this.lblDateModified.Text = "Date Modified"; // // lblDateCreated // this.lblDateCreated.Location = new System.Drawing.Point(8, 304); this.lblDateCreated.Name = "lblDateCreated"; this.lblDateCreated.Size = new System.Drawing.Size(184, 23); this.lblDateCreated.TabIndex = 44; this.lblDateCreated.Text = "Date Created"; // // label4 // this.label4.Location = new System.Drawing.Point(208, 256); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(184, 23); this.label4.TabIndex = 43; this.label4.Text = "Author"; // // label2 // this.label2.Location = new System.Drawing.Point(8, 256); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(184, 24); this.label2.TabIndex = 42; this.label2.Text = "Program Name"; // // txtPgmName // this.txtPgmName.Location = new System.Drawing.Point(8, 280); this.txtPgmName.Name = "txtPgmName"; this.txtPgmName.Size = new System.Drawing.Size(184, 20); this.txtPgmName.TabIndex = 41; this.txtPgmName.Text = ""; // // txtDateUpdated // this.txtDateUpdated.Location = new System.Drawing.Point(208, 328); this.txtDateUpdated.Name = "txtDateUpdated"; this.txtDateUpdated.ReadOnly = true; this.txtDateUpdated.Size = new System.Drawing.Size(184, 20); this.txtDateUpdated.TabIndex = 39; this.txtDateUpdated.TabStop = false; this.txtDateUpdated.Text = ""; // // txtDateCreated // this.txtDateCreated.Location = new System.Drawing.Point(8, 328); this.txtDateCreated.Name = "txtDateCreated"; this.txtDateCreated.ReadOnly = true; this.txtDateCreated.Size = new System.Drawing.Size(184, 20); this.txtDateCreated.TabIndex = 38; this.txtDateCreated.TabStop = false; this.txtDateCreated.Text = ""; // // txtAuthor // this.txtAuthor.Location = new System.Drawing.Point(208, 280); this.txtAuthor.Name = "txtAuthor"; this.txtAuthor.Size = new System.Drawing.Size(184, 20); this.txtAuthor.TabIndex = 40; this.txtAuthor.Text = ""; // // ProjectBasedPgm // this.Controls.Add(this.btnTextFile); this.Controls.Add(this.btnHelp); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.btnDelete); this.Controls.Add(this.lblDateModified); this.Controls.Add(this.lblDateCreated); this.Controls.Add(this.label4); this.Controls.Add(this.label2); this.Controls.Add(this.txtPgmName); this.Controls.Add(this.txtDateUpdated); this.Controls.Add(this.txtDateCreated); this.Controls.Add(this.txtAuthor); this.Controls.Add(this.label3); this.Controls.Add(this.txtComment); this.Controls.Add(this.label1); this.Controls.Add(this.lbxPgms); this.Controls.Add(this.btnFindProject); this.Controls.Add(this.txtProject); this.Controls.Add(this.lblProject); this.Name = "ProjectBasedPgm"; this.Size = new System.Drawing.Size(432, 400); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnFindProject; private System.Windows.Forms.TextBox txtProject; private System.Windows.Forms.Label lblProject; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox txtComment; private System.Windows.Forms.Label label1; private System.Windows.Forms.ListBox lbxPgms; private System.Windows.Forms.Button btnTextFile; private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnDelete; private System.Windows.Forms.Label lblDateModified; private System.Windows.Forms.Label lblDateCreated; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtPgmName; private System.Windows.Forms.TextBox txtDateUpdated; private System.Windows.Forms.TextBox txtDateCreated; private System.Windows.Forms.TextBox txtAuthor; } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans; using Orleans.Concurrency; using Orleans.Configuration; using Orleans.Placement; using Orleans.Runtime; using Orleans.Runtime.Messaging; using Orleans.Runtime.TestHooks; using UnitTests.GrainInterfaces; namespace UnitTests.Grains { internal abstract class PlacementTestGrainBase : Grain { private readonly OverloadDetector overloadDetector; private readonly TestHooksHostEnvironmentStatistics hostEnvironmentStatistics; private readonly LoadSheddingOptions loadSheddingOptions; public PlacementTestGrainBase( OverloadDetector overloadDetector, TestHooksHostEnvironmentStatistics hostEnvironmentStatistics, IOptions<LoadSheddingOptions> loadSheddingOptions) { this.overloadDetector = overloadDetector; this.hostEnvironmentStatistics = hostEnvironmentStatistics; this.loadSheddingOptions = loadSheddingOptions.Value; } public Task<IPEndPoint> GetEndpoint() { return Task.FromResult(Data.Address.Silo.Endpoint); } public Task<string> GetRuntimeInstanceId() { return Task.FromResult(RuntimeIdentity); } public Task<string> GetActivationId() { return Task.FromResult(Data.ActivationId.ToString()); } public Task Nop() { return Task.CompletedTask; } public Task StartLocalGrains(List<Guid> keys) { // we call Nop() on the grain references to ensure that they're instantiated before the promise is delivered. var grains = keys.Select(i => GrainFactory.GetGrain<ILocalPlacementTestGrain>(i)); var promises = grains.Select(g => g.Nop()); return Task.WhenAll(promises); } public async Task<Guid> StartPreferLocalGrain(Guid key) { // we call Nop() on the grain references to ensure that they're instantiated before the promise is delivered. await GrainFactory.GetGrain<IPreferLocalPlacementTestGrain>(key).Nop(); return key; } private static IEnumerable<Task<IPEndPoint>> SampleLocalGrainEndpoint(ILocalPlacementTestGrain grain, int sampleSize) { for (var i = 0; i < sampleSize; ++i) yield return grain.GetEndpoint(); } public async Task<List<IPEndPoint>> SampleLocalGrainEndpoint(Guid key, int sampleSize) { var grain = GrainFactory.GetGrain<ILocalPlacementTestGrain>(key); var p = await Task<IPEndPoint>.WhenAll(SampleLocalGrainEndpoint(grain, sampleSize)); return p.ToList(); } private static async Task PropigateStatisticsToCluster(IGrainFactory grainFactory) { // force the latched statistics to propigate throughout the cluster. IManagementGrain mgmtGrain = grainFactory.GetGrain<IManagementGrain>(0); var hosts = await mgmtGrain.GetHosts(true); var keys = hosts.Select(kvp => kvp.Key).ToArray(); await mgmtGrain.ForceRuntimeStatisticsCollection(keys); } public Task EnableOverloadDetection(bool enabled) { this.overloadDetector.Enabled = enabled; return Task.CompletedTask; } public Task LatchOverloaded() { this.hostEnvironmentStatistics.CpuUsage = this.loadSheddingOptions.LoadSheddingLimit + 1; return PropigateStatisticsToCluster(GrainFactory); } public Task UnlatchOverloaded() { this.hostEnvironmentStatistics.CpuUsage = null; return PropigateStatisticsToCluster(GrainFactory); } public Task LatchCpuUsage(float value) { this.hostEnvironmentStatistics.CpuUsage = value; return PropigateStatisticsToCluster(GrainFactory); } public Task UnlatchCpuUsage() { this.hostEnvironmentStatistics.CpuUsage = null; return PropigateStatisticsToCluster(GrainFactory); } public Task<SiloAddress> GetLocation() { SiloAddress siloAddress = Data.Address.Silo; return Task.FromResult(siloAddress); } } [RandomPlacement] internal class RandomPlacementTestGrain : PlacementTestGrainBase, IRandomPlacementTestGrain { public RandomPlacementTestGrain( OverloadDetector overloadDetector, TestHooksHostEnvironmentStatistics hostEnvironmentStatistics, IOptions<LoadSheddingOptions> loadSheddingOptions) : base(overloadDetector, hostEnvironmentStatistics, loadSheddingOptions) { } } [PreferLocalPlacement] internal class PreferLocalPlacementTestGrain : PlacementTestGrainBase, IPreferLocalPlacementTestGrain { public PreferLocalPlacementTestGrain( OverloadDetector overloadDetector, TestHooksHostEnvironmentStatistics hostEnvironmentStatistics, IOptions<LoadSheddingOptions> loadSheddingOptions) : base(overloadDetector, hostEnvironmentStatistics, loadSheddingOptions) { } } [StatelessWorker] internal class LocalPlacementTestGrain : PlacementTestGrainBase, ILocalPlacementTestGrain { public LocalPlacementTestGrain( OverloadDetector overloadDetector, TestHooksHostEnvironmentStatistics hostEnvironmentStatistics, IOptions<LoadSheddingOptions> loadSheddingOptions) : base(overloadDetector, hostEnvironmentStatistics, loadSheddingOptions) { } } [ActivationCountBasedPlacement] internal class ActivationCountBasedPlacementTestGrain : PlacementTestGrainBase, IActivationCountBasedPlacementTestGrain { public ActivationCountBasedPlacementTestGrain( OverloadDetector overloadDetector, TestHooksHostEnvironmentStatistics hostEnvironmentStatistics, IOptions<LoadSheddingOptions> loadSheddingOptions) : base(overloadDetector, hostEnvironmentStatistics, loadSheddingOptions) { } } internal class DefaultPlacementGrain : Grain, IDefaultPlacementGrain { public Task<PlacementStrategy> GetDefaultPlacement() { var defaultStrategy = this.ServiceProvider.GetRequiredService<PlacementStrategy>(); return Task.FromResult(defaultStrategy); } } //----------------------------------------------------------// // Grains for LocalContent grain case, when grain is activated on every silo by bootstrap provider. [PreferLocalPlacement] public class LocalContentGrain : Grain, ILocalContentGrain { private ILogger logger; private object cachedContent; internal static ILocalContentGrain InstanceIdForThisSilo; public LocalContentGrain(ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}"); } public override Task OnActivateAsync() { logger.Info("OnActivateAsync"); DelayDeactivation(TimeSpan.MaxValue); // make sure this activation is not collected. cachedContent = RuntimeIdentity; // store your silo identity as a local cached content in this grain. InstanceIdForThisSilo = this.AsReference<ILocalContentGrain>(); return Task.FromResult(0); } public Task Init() { logger.Info("Init LocalContentGrain on silo " + RuntimeIdentity); return Task.FromResult(0); } public Task<object> GetContent() { return Task.FromResult(cachedContent); } } public class TestContentGrain : Grain, ITestContentGrain { private ILogger logger; public TestContentGrain(ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}"); } public override Task OnActivateAsync() { logger.Info("OnActivateAsync"); return base.OnActivateAsync(); } public Task<string> GetRuntimeInstanceId() { logger.Info("GetRuntimeInstanceId"); return Task.FromResult(RuntimeIdentity); } public async Task<object> FetchContentFromLocalGrain() { logger.Info("FetchContentFromLocalGrain"); var localContentGrain = LocalContentGrain.InstanceIdForThisSilo; if (localContentGrain == null) { throw new Exception("LocalContentGrain was not correctly initialized during silo startup!"); } object content = await localContentGrain.GetContent(); logger.Info("Received content = {0}", content); return content; } } }
using Pathfinding.Serialization; namespace Pathfinding { public class PointNode : GraphNode { public GraphNode[] connections; public uint[] connectionCosts; /** Used for internal linked list structure. * \warning Do not modify */ public PointNode next; //public override Int3 Position {get { return position; } } public void SetPosition (Int3 value) { position = value; } public PointNode (AstarPath astar) : base (astar) { } public override void GetConnections (GraphNodeDelegate del) { if (connections == null) return; for (int i=0;i<connections.Length;i++) del (connections[i]); } public override void ClearConnections (bool alsoReverse) { if (alsoReverse && connections != null) { for (int i=0;i<connections.Length;i++) { connections[i].RemoveConnection (this); } } connections = null; connectionCosts = null; } public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) { UpdateG (path,pathNode); handler.PushNode (pathNode); for (int i=0;i<connections.Length;i++) { GraphNode other = connections[i]; PathNode otherPN = handler.GetPathNode (other); if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) { other.UpdateRecursiveG (path, otherPN,handler); } } } public override bool ContainsConnection (GraphNode node) { for (int i=0;i<connections.Length;i++) if (connections[i] == node) return true; return false; } /** Add a connection from this node to the specified node. * If the connection already exists, the cost will simply be updated and * no extra connection added. * * \note Only adds a one-way connection. Consider calling the same function on the other node * to get a two-way connection. */ public override void AddConnection (GraphNode node, uint cost) { if (connections != null) { for (int i=0;i<connections.Length;i++) { if (connections[i] == node) { connectionCosts[i] = cost; return; } } } int connLength = connections != null ? connections.Length : 0; GraphNode[] newconns = new GraphNode[connLength+1]; uint[] newconncosts = new uint[connLength+1]; for (int i=0;i<connLength;i++) { newconns[i] = connections[i]; newconncosts[i] = connectionCosts[i]; } newconns[connLength] = node; newconncosts[connLength] = cost; connections = newconns; connectionCosts = newconncosts; } /** Removes any connection from this node to the specified node. * If no such connection exists, nothing will be done. * * \note This only removes the connection from this node to the other node. * You may want to call the same function on the other node to remove its eventual connection * to this node. */ public override void RemoveConnection (GraphNode node) { if (connections == null) return; for (int i=0;i<connections.Length;i++) { if (connections[i] == node) { int connLength = connections.Length; GraphNode[] newconns = new GraphNode[connLength-1]; uint[] newconncosts = new uint[connLength-1]; for (int j=0;j<i;j++) { newconns[j] = connections[j]; newconncosts[j] = connectionCosts[j]; } for (int j=i+1;j<connLength;j++) { newconns[j-1] = connections[j]; newconncosts[j-1] = connectionCosts[j]; } connections = newconns; connectionCosts = newconncosts; return; } } } public override void Open (Path path, PathNode pathNode, PathHandler handler) { if (connections == null) return; for (int i=0;i<connections.Length;i++) { GraphNode other = connections[i]; if (path.CanTraverse (other)) { PathNode pathOther = handler.GetPathNode (other); if (pathOther.pathID != handler.PathID) { pathOther.parent = pathNode; pathOther.pathID = handler.PathID; pathOther.cost = connectionCosts[i]; pathOther.H = path.CalculateHScore (other); other.UpdateG (path, pathOther); handler.PushNode (pathOther); } else { //If not we can test if the path from this node to the other one is a better one then the one already used uint tmpCost = connectionCosts[i]; if (pathNode.G + tmpCost + path.GetTraversalCost(other) < pathOther.G) { pathOther.cost = tmpCost; pathOther.parent = pathNode; other.UpdateRecursiveG (path, pathOther,handler); //handler.PushNode (pathOther); } else if (pathOther.G+tmpCost+path.GetTraversalCost(this) < pathNode.G && other.ContainsConnection (this)) { //Or if the path from the other node to this one is better pathNode.parent = pathOther; pathNode.cost = tmpCost; UpdateRecursiveG (path, pathNode,handler); //handler.PushNode (pathNode); } } } } } public override void SerializeNode (GraphSerializationContext ctx) { base.SerializeNode (ctx); ctx.writer.Write (position.x); ctx.writer.Write (position.y); ctx.writer.Write (position.z); } public override void DeserializeNode (GraphSerializationContext ctx) { base.DeserializeNode (ctx); position = new Int3 (ctx.reader.ReadInt32(), ctx.reader.ReadInt32(), ctx.reader.ReadInt32()); } public override void SerializeReferences (GraphSerializationContext ctx) { if (connections == null) { ctx.writer.Write(-1); } else { ctx.writer.Write (connections.Length); for (int i=0;i<connections.Length;i++) { ctx.writer.Write (ctx.GetNodeIdentifier (connections[i])); ctx.writer.Write (connectionCosts[i]); } } } public override void DeserializeReferences (GraphSerializationContext ctx) { int count = ctx.reader.ReadInt32(); if (count == -1) { connections = null; connectionCosts = null; } else { connections = new GraphNode[count]; connectionCosts = new uint[count]; for (int i=0;i<count;i++) { connections[i] = ctx.GetNodeFromIdentifier (ctx.reader.ReadInt32()); connectionCosts[i] = ctx.reader.ReadUInt32(); } } } } }
using J2N.Collections.Generic.Extensions; using Lucene.Net.Analysis; using Lucene.Net.Diagnostics; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Index.Extensions; using Lucene.Net.Util.Automaton; using NUnit.Framework; using System; using System.Collections.Generic; using Assert = Lucene.Net.TestFramework.Assert; using JCG = J2N.Collections.Generic; 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 Analyzer = Lucene.Net.Analysis.Analyzer; using AtomicReader = Lucene.Net.Index.AtomicReader; using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using AutomatonTestUtil = Lucene.Net.Util.Automaton.AutomatonTestUtil; using BytesRef = Lucene.Net.Util.BytesRef; using CompiledAutomaton = Lucene.Net.Util.Automaton.CompiledAutomaton; using Directory = Lucene.Net.Store.Directory; using DirectoryReader = Lucene.Net.Index.DirectoryReader; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum; using DocsEnum = Lucene.Net.Index.DocsEnum; using Document = Documents.Document; using English = Lucene.Net.Util.English; using Field = Field; using FieldType = FieldType; using FixedBitSet = Lucene.Net.Util.FixedBitSet; using IBits = Lucene.Net.Util.IBits; using IndexWriter = Lucene.Net.Index.IndexWriter; using IndexWriterConfig = Lucene.Net.Index.IndexWriterConfig; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockFixedLengthPayloadFilter = Lucene.Net.Analysis.MockFixedLengthPayloadFilter; using MockTokenizer = Lucene.Net.Analysis.MockTokenizer; using MockVariableLengthPayloadFilter = Lucene.Net.Analysis.MockVariableLengthPayloadFilter; using OpenMode = Lucene.Net.Index.OpenMode; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using RegExp = Lucene.Net.Util.Automaton.RegExp; using SeekStatus = Lucene.Net.Index.TermsEnum.SeekStatus; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; using TestUtil = Lucene.Net.Util.TestUtil; using TextField = TextField; using TokenFilter = Lucene.Net.Analysis.TokenFilter; using Tokenizer = Lucene.Net.Analysis.Tokenizer; /// <summary> /// Tests partial enumeration (only pulling a subset of the indexed data) /// </summary> [TestFixture] public class TestBlockPostingsFormat3 : LuceneTestCase { internal static readonly int MAXDOC = Lucene41PostingsFormat.BLOCK_SIZE * 20; // creates 8 fields with different options and does "duels" of fields against each other [Test] [Slow] public virtual void Test() { Directory dir = NewDirectory(); Analyzer analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) => { Tokenizer tokenizer = new MockTokenizer(reader); if (fieldName.Contains("payloadsFixed")) { TokenFilter filter = new MockFixedLengthPayloadFilter(new Random(0), tokenizer, 1); return new TokenStreamComponents(tokenizer, filter); } else if (fieldName.Contains("payloadsVariable")) { TokenFilter filter = new MockVariableLengthPayloadFilter(new Random(0), tokenizer); return new TokenStreamComponents(tokenizer, filter); } else { return new TokenStreamComponents(tokenizer); } }, reuseStrategy: Analyzer.PER_FIELD_REUSE_STRATEGY); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer); iwc.SetCodec(TestUtil.AlwaysPostingsFormat(new Lucene41PostingsFormat())); // TODO we could actually add more fields implemented with different PFs // or, just put this test into the usual rotation? RandomIndexWriter iw = new RandomIndexWriter(Random, dir, (IndexWriterConfig)iwc.Clone()); Document doc = new Document(); FieldType docsOnlyType = new FieldType(TextField.TYPE_NOT_STORED); // turn this on for a cross-check docsOnlyType.StoreTermVectors = true; docsOnlyType.IndexOptions = IndexOptions.DOCS_ONLY; FieldType docsAndFreqsType = new FieldType(TextField.TYPE_NOT_STORED); // turn this on for a cross-check docsAndFreqsType.StoreTermVectors = true; docsAndFreqsType.IndexOptions = IndexOptions.DOCS_AND_FREQS; FieldType positionsType = new FieldType(TextField.TYPE_NOT_STORED); // turn these on for a cross-check positionsType.StoreTermVectors = true; positionsType.StoreTermVectorPositions = true; positionsType.StoreTermVectorOffsets = true; positionsType.StoreTermVectorPayloads = true; FieldType offsetsType = new FieldType(positionsType); offsetsType.IndexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS; Field field1 = new Field("field1docs", "", docsOnlyType); Field field2 = new Field("field2freqs", "", docsAndFreqsType); Field field3 = new Field("field3positions", "", positionsType); Field field4 = new Field("field4offsets", "", offsetsType); Field field5 = new Field("field5payloadsFixed", "", positionsType); Field field6 = new Field("field6payloadsVariable", "", positionsType); Field field7 = new Field("field7payloadsFixedOffsets", "", offsetsType); Field field8 = new Field("field8payloadsVariableOffsets", "", offsetsType); doc.Add(field1); doc.Add(field2); doc.Add(field3); doc.Add(field4); doc.Add(field5); doc.Add(field6); doc.Add(field7); doc.Add(field8); for (int i = 0; i < MAXDOC; i++) { string stringValue = Convert.ToString(i) + " verycommon " + English.Int32ToEnglish(i).Replace('-', ' ') + " " + TestUtil.RandomSimpleString(Random); field1.SetStringValue(stringValue); field2.SetStringValue(stringValue); field3.SetStringValue(stringValue); field4.SetStringValue(stringValue); field5.SetStringValue(stringValue); field6.SetStringValue(stringValue); field7.SetStringValue(stringValue); field8.SetStringValue(stringValue); iw.AddDocument(doc); } iw.Dispose(); Verify(dir); TestUtil.CheckIndex(dir); // for some extra coverage, checkIndex before we forceMerge iwc.SetOpenMode(OpenMode.APPEND); IndexWriter iw2 = new IndexWriter(dir, (IndexWriterConfig)iwc.Clone()); iw2.ForceMerge(1); iw2.Dispose(); Verify(dir); dir.Dispose(); } private void Verify(Directory dir) { DirectoryReader ir = DirectoryReader.Open(dir); foreach (AtomicReaderContext leaf in ir.Leaves) { AtomicReader leafReader = (AtomicReader)leaf.Reader; AssertTerms(leafReader.GetTerms("field1docs"), leafReader.GetTerms("field2freqs"), true); AssertTerms(leafReader.GetTerms("field3positions"), leafReader.GetTerms("field4offsets"), true); AssertTerms(leafReader.GetTerms("field4offsets"), leafReader.GetTerms("field5payloadsFixed"), true); AssertTerms(leafReader.GetTerms("field5payloadsFixed"), leafReader.GetTerms("field6payloadsVariable"), true); AssertTerms(leafReader.GetTerms("field6payloadsVariable"), leafReader.GetTerms("field7payloadsFixedOffsets"), true); AssertTerms(leafReader.GetTerms("field7payloadsFixedOffsets"), leafReader.GetTerms("field8payloadsVariableOffsets"), true); } ir.Dispose(); } // following code is almost an exact dup of code from TestDuelingCodecs: sorry! public virtual void AssertTerms(Terms leftTerms, Terms rightTerms, bool deep) { if (leftTerms == null || rightTerms == null) { Assert.IsNull(leftTerms); Assert.IsNull(rightTerms); return; } AssertTermsStatistics(leftTerms, rightTerms); // NOTE: we don't assert hasOffsets/hasPositions/hasPayloads because they are allowed to be different TermsEnum leftTermsEnum = leftTerms.GetEnumerator(); TermsEnum rightTermsEnum = rightTerms.GetEnumerator(); AssertTermsEnum(leftTermsEnum, rightTermsEnum, true); AssertTermsSeeking(leftTerms, rightTerms); if (deep) { int numIntersections = AtLeast(3); for (int i = 0; i < numIntersections; i++) { string re = AutomatonTestUtil.RandomRegexp(Random); CompiledAutomaton automaton = new CompiledAutomaton((new RegExp(re, RegExpSyntax.NONE)).ToAutomaton()); if (automaton.Type == CompiledAutomaton.AUTOMATON_TYPE.NORMAL) { // TODO: test start term too TermsEnum leftIntersection = leftTerms.Intersect(automaton, null); TermsEnum rightIntersection = rightTerms.Intersect(automaton, null); AssertTermsEnum(leftIntersection, rightIntersection, Rarely()); } } } } private void AssertTermsSeeking(Terms leftTerms, Terms rightTerms) { TermsEnum leftEnum = null; TermsEnum rightEnum = null; // just an upper bound int numTests = AtLeast(20); Random random = Random; // collect this number of terms from the left side ISet<BytesRef> tests = new JCG.HashSet<BytesRef>(); int numPasses = 0; while (numPasses < 10 && tests.Count < numTests) { leftEnum = leftTerms.GetEnumerator(leftEnum); BytesRef term = null; while (leftEnum.MoveNext()) { term = leftEnum.Term; int code = random.Next(10); if (code == 0) { // the term tests.Add(BytesRef.DeepCopyOf(term)); } else if (code == 1) { // truncated subsequence of term term = BytesRef.DeepCopyOf(term); if (term.Length > 0) { // truncate it term.Length = random.Next(term.Length); } } else if (code == 2) { // term, but ensure a non-zero offset var newbytes = new byte[term.Length + 5]; Array.Copy(term.Bytes, term.Offset, newbytes, 5, term.Length); tests.Add(new BytesRef(newbytes, 5, term.Length)); } } numPasses++; } List<BytesRef> shuffledTests = new List<BytesRef>(tests); shuffledTests.Shuffle(Random); foreach (BytesRef b in shuffledTests) { leftEnum = leftTerms.GetEnumerator(leftEnum); rightEnum = rightTerms.GetEnumerator(rightEnum); Assert.AreEqual(leftEnum.SeekExact(b), rightEnum.SeekExact(b)); Assert.AreEqual(leftEnum.SeekExact(b), rightEnum.SeekExact(b)); SeekStatus leftStatus; SeekStatus rightStatus; leftStatus = leftEnum.SeekCeil(b); rightStatus = rightEnum.SeekCeil(b); Assert.AreEqual(leftStatus, rightStatus); if (leftStatus != SeekStatus.END) { Assert.AreEqual(leftEnum.Term, rightEnum.Term); } leftStatus = leftEnum.SeekCeil(b); rightStatus = rightEnum.SeekCeil(b); Assert.AreEqual(leftStatus, rightStatus); if (leftStatus != SeekStatus.END) { Assert.AreEqual(leftEnum.Term, rightEnum.Term); } } } /// <summary> /// checks collection-level statistics on Terms /// </summary> public virtual void AssertTermsStatistics(Terms leftTerms, Terms rightTerms) { if (Debugging.AssertsEnabled) Debugging.Assert(leftTerms.Comparer == rightTerms.Comparer); if (leftTerms.DocCount != -1 && rightTerms.DocCount != -1) { Assert.AreEqual(leftTerms.DocCount, rightTerms.DocCount); } if (leftTerms.SumDocFreq != -1 && rightTerms.SumDocFreq != -1) { Assert.AreEqual(leftTerms.SumDocFreq, rightTerms.SumDocFreq); } if (leftTerms.SumTotalTermFreq != -1 && rightTerms.SumTotalTermFreq != -1) { Assert.AreEqual(leftTerms.SumTotalTermFreq, rightTerms.SumTotalTermFreq); } if (leftTerms.Count != -1 && rightTerms.Count != -1) { Assert.AreEqual(leftTerms.Count, rightTerms.Count); } } /// <summary> /// checks the terms enum sequentially /// if deep is false, it does a 'shallow' test that doesnt go down to the docsenums /// </summary> public virtual void AssertTermsEnum(TermsEnum leftTermsEnum, TermsEnum rightTermsEnum, bool deep) { IBits randomBits = new RandomBits(MAXDOC, Random.NextDouble(), Random); DocsAndPositionsEnum leftPositions = null; DocsAndPositionsEnum rightPositions = null; DocsEnum leftDocs = null; DocsEnum rightDocs = null; while (leftTermsEnum.MoveNext()) { Assert.IsTrue(rightTermsEnum.MoveNext()); Assert.AreEqual(leftTermsEnum.Term, rightTermsEnum.Term); AssertTermStats(leftTermsEnum, rightTermsEnum); if (deep) { // with payloads + off AssertDocsAndPositionsEnum(leftPositions = leftTermsEnum.DocsAndPositions(null, leftPositions), rightPositions = rightTermsEnum.DocsAndPositions(null, rightPositions)); AssertDocsAndPositionsEnum(leftPositions = leftTermsEnum.DocsAndPositions(randomBits, leftPositions), rightPositions = rightTermsEnum.DocsAndPositions(randomBits, rightPositions)); AssertPositionsSkipping(leftTermsEnum.DocFreq, leftPositions = leftTermsEnum.DocsAndPositions(null, leftPositions), rightPositions = rightTermsEnum.DocsAndPositions(null, rightPositions)); AssertPositionsSkipping(leftTermsEnum.DocFreq, leftPositions = leftTermsEnum.DocsAndPositions(randomBits, leftPositions), rightPositions = rightTermsEnum.DocsAndPositions(randomBits, rightPositions)); // with payloads only AssertDocsAndPositionsEnum(leftPositions = leftTermsEnum.DocsAndPositions(null, leftPositions, DocsAndPositionsFlags.PAYLOADS), rightPositions = rightTermsEnum.DocsAndPositions(null, rightPositions, DocsAndPositionsFlags.PAYLOADS)); AssertDocsAndPositionsEnum(leftPositions = leftTermsEnum.DocsAndPositions(randomBits, leftPositions, DocsAndPositionsFlags.PAYLOADS), rightPositions = rightTermsEnum.DocsAndPositions(randomBits, rightPositions, DocsAndPositionsFlags.PAYLOADS)); AssertPositionsSkipping(leftTermsEnum.DocFreq, leftPositions = leftTermsEnum.DocsAndPositions(null, leftPositions, DocsAndPositionsFlags.PAYLOADS), rightPositions = rightTermsEnum.DocsAndPositions(null, rightPositions, DocsAndPositionsFlags.PAYLOADS)); AssertPositionsSkipping(leftTermsEnum.DocFreq, leftPositions = leftTermsEnum.DocsAndPositions(randomBits, leftPositions, DocsAndPositionsFlags.PAYLOADS), rightPositions = rightTermsEnum.DocsAndPositions(randomBits, rightPositions, DocsAndPositionsFlags.PAYLOADS)); // with offsets only AssertDocsAndPositionsEnum(leftPositions = leftTermsEnum.DocsAndPositions(null, leftPositions, DocsAndPositionsFlags.OFFSETS), rightPositions = rightTermsEnum.DocsAndPositions(null, rightPositions, DocsAndPositionsFlags.OFFSETS)); AssertDocsAndPositionsEnum(leftPositions = leftTermsEnum.DocsAndPositions(randomBits, leftPositions, DocsAndPositionsFlags.OFFSETS), rightPositions = rightTermsEnum.DocsAndPositions(randomBits, rightPositions, DocsAndPositionsFlags.OFFSETS)); AssertPositionsSkipping(leftTermsEnum.DocFreq, leftPositions = leftTermsEnum.DocsAndPositions(null, leftPositions, DocsAndPositionsFlags.OFFSETS), rightPositions = rightTermsEnum.DocsAndPositions(null, rightPositions, DocsAndPositionsFlags.OFFSETS)); AssertPositionsSkipping(leftTermsEnum.DocFreq, leftPositions = leftTermsEnum.DocsAndPositions(randomBits, leftPositions, DocsAndPositionsFlags.OFFSETS), rightPositions = rightTermsEnum.DocsAndPositions(randomBits, rightPositions, DocsAndPositionsFlags.OFFSETS)); // with positions only AssertDocsAndPositionsEnum(leftPositions = leftTermsEnum.DocsAndPositions(null, leftPositions, DocsAndPositionsFlags.NONE), rightPositions = rightTermsEnum.DocsAndPositions(null, rightPositions, DocsAndPositionsFlags.NONE)); AssertDocsAndPositionsEnum(leftPositions = leftTermsEnum.DocsAndPositions(randomBits, leftPositions, DocsAndPositionsFlags.NONE), rightPositions = rightTermsEnum.DocsAndPositions(randomBits, rightPositions, DocsAndPositionsFlags.NONE)); AssertPositionsSkipping(leftTermsEnum.DocFreq, leftPositions = leftTermsEnum.DocsAndPositions(null, leftPositions, DocsAndPositionsFlags.NONE), rightPositions = rightTermsEnum.DocsAndPositions(null, rightPositions, DocsAndPositionsFlags.NONE)); AssertPositionsSkipping(leftTermsEnum.DocFreq, leftPositions = leftTermsEnum.DocsAndPositions(randomBits, leftPositions, DocsAndPositionsFlags.NONE), rightPositions = rightTermsEnum.DocsAndPositions(randomBits, rightPositions, DocsAndPositionsFlags.NONE)); // with freqs: AssertDocsEnum(leftDocs = leftTermsEnum.Docs(null, leftDocs), rightDocs = rightTermsEnum.Docs(null, rightDocs)); AssertDocsEnum(leftDocs = leftTermsEnum.Docs(randomBits, leftDocs), rightDocs = rightTermsEnum.Docs(randomBits, rightDocs)); // w/o freqs: AssertDocsEnum(leftDocs = leftTermsEnum.Docs(null, leftDocs, DocsFlags.NONE), rightDocs = rightTermsEnum.Docs(null, rightDocs, DocsFlags.NONE)); AssertDocsEnum(leftDocs = leftTermsEnum.Docs(randomBits, leftDocs, DocsFlags.NONE), rightDocs = rightTermsEnum.Docs(randomBits, rightDocs, DocsFlags.NONE)); // with freqs: AssertDocsSkipping(leftTermsEnum.DocFreq, leftDocs = leftTermsEnum.Docs(null, leftDocs), rightDocs = rightTermsEnum.Docs(null, rightDocs)); AssertDocsSkipping(leftTermsEnum.DocFreq, leftDocs = leftTermsEnum.Docs(randomBits, leftDocs), rightDocs = rightTermsEnum.Docs(randomBits, rightDocs)); // w/o freqs: AssertDocsSkipping(leftTermsEnum.DocFreq, leftDocs = leftTermsEnum.Docs(null, leftDocs, DocsFlags.NONE), rightDocs = rightTermsEnum.Docs(null, rightDocs, DocsFlags.NONE)); AssertDocsSkipping(leftTermsEnum.DocFreq, leftDocs = leftTermsEnum.Docs(randomBits, leftDocs, DocsFlags.NONE), rightDocs = rightTermsEnum.Docs(randomBits, rightDocs, DocsFlags.NONE)); } } Assert.IsFalse(rightTermsEnum.MoveNext()); } /// <summary> /// checks term-level statistics /// </summary> public virtual void AssertTermStats(TermsEnum leftTermsEnum, TermsEnum rightTermsEnum) { Assert.AreEqual(leftTermsEnum.DocFreq, rightTermsEnum.DocFreq); if (leftTermsEnum.TotalTermFreq != -1 && rightTermsEnum.TotalTermFreq != -1) { Assert.AreEqual(leftTermsEnum.TotalTermFreq, rightTermsEnum.TotalTermFreq); } } /// <summary> /// checks docs + freqs + positions + payloads, sequentially /// </summary> public virtual void AssertDocsAndPositionsEnum(DocsAndPositionsEnum leftDocs, DocsAndPositionsEnum rightDocs) { if (leftDocs == null || rightDocs == null) { Assert.IsNull(leftDocs); Assert.IsNull(rightDocs); return; } Assert.AreEqual(-1, leftDocs.DocID); Assert.AreEqual(-1, rightDocs.DocID); int docid; while ((docid = leftDocs.NextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { Assert.AreEqual(docid, rightDocs.NextDoc()); int freq = leftDocs.Freq; Assert.AreEqual(freq, rightDocs.Freq); for (int i = 0; i < freq; i++) { Assert.AreEqual(leftDocs.NextPosition(), rightDocs.NextPosition()); // we don't assert offsets/payloads, they are allowed to be different } } Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, rightDocs.NextDoc()); } /// <summary> /// checks docs + freqs, sequentially /// </summary> public virtual void AssertDocsEnum(DocsEnum leftDocs, DocsEnum rightDocs) { if (leftDocs == null) { Assert.IsNull(rightDocs); return; } Assert.AreEqual(-1, leftDocs.DocID); Assert.AreEqual(-1, rightDocs.DocID); int docid; while ((docid = leftDocs.NextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { Assert.AreEqual(docid, rightDocs.NextDoc()); // we don't assert freqs, they are allowed to be different } Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, rightDocs.NextDoc()); } /// <summary> /// checks advancing docs /// </summary> public virtual void AssertDocsSkipping(int docFreq, DocsEnum leftDocs, DocsEnum rightDocs) { if (leftDocs == null) { Assert.IsNull(rightDocs); return; } int docid = -1; int averageGap = MAXDOC / (1 + docFreq); int skipInterval = 16; while (true) { if (Random.NextBoolean()) { // nextDoc() docid = leftDocs.NextDoc(); Assert.AreEqual(docid, rightDocs.NextDoc()); } else { // advance() int skip = docid + (int)Math.Ceiling(Math.Abs(skipInterval + Random.NextDouble() * averageGap)); docid = leftDocs.Advance(skip); Assert.AreEqual(docid, rightDocs.Advance(skip)); } if (docid == DocIdSetIterator.NO_MORE_DOCS) { return; } // we don't assert freqs, they are allowed to be different } } /// <summary> /// checks advancing docs + positions /// </summary> public virtual void AssertPositionsSkipping(int docFreq, DocsAndPositionsEnum leftDocs, DocsAndPositionsEnum rightDocs) { if (leftDocs == null || rightDocs == null) { Assert.IsNull(leftDocs); Assert.IsNull(rightDocs); return; } int docid = -1; int averageGap = MAXDOC / (1 + docFreq); int skipInterval = 16; while (true) { if (Random.NextBoolean()) { // nextDoc() docid = leftDocs.NextDoc(); Assert.AreEqual(docid, rightDocs.NextDoc()); } else { // advance() int skip = docid + (int)Math.Ceiling(Math.Abs(skipInterval + Random.NextDouble() * averageGap)); docid = leftDocs.Advance(skip); Assert.AreEqual(docid, rightDocs.Advance(skip)); } if (docid == DocIdSetIterator.NO_MORE_DOCS) { return; } int freq = leftDocs.Freq; Assert.AreEqual(freq, rightDocs.Freq); for (int i = 0; i < freq; i++) { Assert.AreEqual(leftDocs.NextPosition(), rightDocs.NextPosition()); // we don't compare the payloads, its allowed that one is empty etc } } } new private class RandomBits : IBits { internal FixedBitSet bits; internal RandomBits(int maxDoc, double pctLive, Random random) { bits = new FixedBitSet(maxDoc); for (int i = 0; i < maxDoc; i++) { if (random.NextDouble() <= pctLive) { bits.Set(i); } } } public bool Get(int index) { return bits.Get(index); } public int Length => bits.Length; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.ServiceModel.Syndication { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; [XmlRoot(ElementName = Rss20Constants.RssTag, Namespace = Rss20Constants.Rss20Namespace)] public class Rss20FeedFormatter : SyndicationFeedFormatter { private static readonly XmlQualifiedName s_rss20Domain = new XmlQualifiedName(Rss20Constants.DomainTag, string.Empty); private static readonly XmlQualifiedName s_rss20Length = new XmlQualifiedName(Rss20Constants.LengthTag, string.Empty); private static readonly XmlQualifiedName s_rss20Type = new XmlQualifiedName(Rss20Constants.TypeTag, string.Empty); private static readonly XmlQualifiedName s_rss20Url = new XmlQualifiedName(Rss20Constants.UrlTag, string.Empty); private static List<string> acceptedDays = new List<string> { "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday" }; private const string Rfc822OutputLocalDateTimeFormat = "ddd, dd MMM yyyy HH:mm:ss zzz"; private const string Rfc822OutputUtcDateTimeFormat = "ddd, dd MMM yyyy HH:mm:ss Z"; private Atom10FeedFormatter _atomSerializer; private Type _feedType; private int _maxExtensionSize; private bool _preserveAttributeExtensions; private bool _preserveElementExtensions; private bool _serializeExtensionsAsAtom; //Custom Parsers // value, localname , ns , result public Func<string, string, string, string> StringParser { get; set; } = DefaultStringParser; public Func<string, string, string, DateTimeOffset> DateParser { get; set; } = DefaultDateParser; public Func<string, string, string, Uri> UriParser { get; set; } = DefaultUriParser; static private string DefaultStringParser(string value, string localName, string ns) { return value; } static private Uri DefaultUriParser(string value, string localName, string ns) { return new Uri(value, UriKind.RelativeOrAbsolute); } private async Task<bool> OnReadImage(XmlReaderWrapper reader, SyndicationFeed result) { await reader.ReadStartElementAsync(); string localName = string.Empty; while (await reader.IsStartElementAsync()) { if (await reader.IsStartElementAsync(Rss20Constants.UrlTag, Rss20Constants.Rss20Namespace)) { result.ImageUrl = UriParser(await reader.ReadElementStringAsync(), Rss20Constants.UrlTag, Rss20Constants.Rss20Namespace); } else if(await reader.IsStartElementAsync(Rss20Constants.LinkTag, Rss20Constants.Rss20Namespace)) { result.ImageLink = UriParser(await reader.ReadElementStringAsync(), Rss20Constants.LinkTag, Rss20Constants.Rss20Namespace); } else if (await reader.IsStartElementAsync(Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace)) { result.ImageTitle = new TextSyndicationContent(StringParser(await reader.ReadElementStringAsync(), Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace)); } } await reader.ReadEndElementAsync(); // image return true; } public Rss20FeedFormatter() : this(typeof(SyndicationFeed)) { } public Rss20FeedFormatter(Type feedTypeToCreate) : base() { if (feedTypeToCreate == null) { throw new ArgumentNullException(nameof(feedTypeToCreate)); } if (!typeof(SyndicationFeed).IsAssignableFrom(feedTypeToCreate)) { throw new ArgumentException(string.Format(SR.InvalidObjectTypePassed, nameof(feedTypeToCreate), nameof(SyndicationFeed))); } _serializeExtensionsAsAtom = true; _maxExtensionSize = int.MaxValue; _preserveElementExtensions = true; _preserveAttributeExtensions = true; _atomSerializer = new Atom10FeedFormatter(feedTypeToCreate); _feedType = feedTypeToCreate; } public Rss20FeedFormatter(SyndicationFeed feedToWrite) : this(feedToWrite, true) { } public Rss20FeedFormatter(SyndicationFeed feedToWrite, bool serializeExtensionsAsAtom) : base(feedToWrite) { // No need to check that the parameter passed is valid - it is checked by the c'tor of the base class _serializeExtensionsAsAtom = serializeExtensionsAsAtom; _maxExtensionSize = int.MaxValue; _preserveElementExtensions = true; _preserveAttributeExtensions = true; _atomSerializer = new Atom10FeedFormatter(this.Feed); _feedType = feedToWrite.GetType(); } public bool PreserveAttributeExtensions { get { return _preserveAttributeExtensions; } set { _preserveAttributeExtensions = value; } } public bool PreserveElementExtensions { get { return _preserveElementExtensions; } set { _preserveElementExtensions = value; } } public bool SerializeExtensionsAsAtom { get { return _serializeExtensionsAsAtom; } set { _serializeExtensionsAsAtom = value; } } public override string Version { get { return SyndicationVersions.Rss20; } } protected Type FeedType { get { return _feedType; } } public override bool CanRead(XmlReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } return reader.IsStartElement(Rss20Constants.RssTag, Rss20Constants.Rss20Namespace); } public override Task ReadFromAsync(XmlReader reader, CancellationToken ct) { if (!CanRead(reader)) { throw new XmlException(string.Format(SR.UnknownFeedXml, reader.LocalName, reader.NamespaceURI)); } SetFeed(CreateFeedInstance()); return ReadXmlAsync(XmlReaderWrapper.CreateFromReader(reader), this.Feed); } private Task WriteXmlAsync(XmlWriter writer) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } return WriteFeedAsync(writer); } public override async Task WriteToAsync(XmlWriter writer, CancellationToken ct) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } writer = XmlWriterWrapper.CreateFromWriter(writer); await writer.WriteStartElementAsync(Rss20Constants.RssTag, Rss20Constants.Rss20Namespace); await WriteFeedAsync(writer); await writer.WriteEndElementAsync(); } protected internal override void SetFeed(SyndicationFeed feed) { base.SetFeed(feed); _atomSerializer.SetFeed(this.Feed); } private async Task ReadItemFromAsync(XmlReaderWrapper reader, SyndicationItem result, Uri feedBaseUri) { result.BaseUri = feedBaseUri; await reader.MoveToContentAsync(); bool isEmpty = reader.IsEmptyElement; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string ns = reader.NamespaceURI; string name = reader.LocalName; if (name == "base" && ns == Atom10FeedFormatter.XmlNs) { result.BaseUri = FeedUtils.CombineXmlBase(result.BaseUri, await reader.GetValueAsync()); continue; } if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns)) { continue; } string val = await reader.GetValueAsync(); if (!TryParseAttribute(name, ns, val, result, this.Version)) { if (_preserveAttributeExtensions) { result.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val); } } } } await reader.ReadStartElementAsync(); if (!isEmpty) { string fallbackAlternateLink = null; XmlDictionaryWriter extWriter = null; bool readAlternateLink = false; try { XmlBuffer buffer = null; while (await reader.IsStartElementAsync()) { bool notHandled = false; if (await reader.MoveToContentAsync() == XmlNodeType.Element && reader.NamespaceURI == Rss20Constants.Rss20Namespace) { switch (reader.LocalName) { case Rss20Constants.TitleTag: result.Title = new TextSyndicationContent(StringParser(await reader.ReadElementStringAsync(), Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace)); break; case Rss20Constants.LinkTag: result.Links.Add(await ReadAlternateLinkAsync(reader, result.BaseUri)); readAlternateLink = true; break; case Rss20Constants.DescriptionTag: result.Summary = new TextSyndicationContent(StringParser(await reader.ReadElementStringAsync(), Rss20Constants.DescriptionTag, Rss20Constants.Rss20Namespace)); break; case Rss20Constants.AuthorTag: result.Authors.Add(await ReadPersonAsync(reader, result)); break; case Rss20Constants.CategoryTag: result.Categories.Add(await ReadCategoryAsync(reader, result)); break; case Rss20Constants.EnclosureTag: result.Links.Add(await ReadMediaEnclosureAsync(reader, result.BaseUri)); break; case Rss20Constants.GuidTag: { bool isPermalink = true; string permalinkString = reader.GetAttribute(Rss20Constants.IsPermaLinkTag, Rss20Constants.Rss20Namespace); if (permalinkString != null && permalinkString.Equals("false",StringComparison.OrdinalIgnoreCase)) { isPermalink = false; } string localName = reader.LocalName; string namespaceUri = reader.NamespaceURI; result.Id = StringParser(await reader.ReadElementStringAsync(), localName, namespaceUri); if (isPermalink) { fallbackAlternateLink = result.Id; } break; } case Rss20Constants.PubDateTag: { bool canReadContent = !reader.IsEmptyElement; await reader.ReadStartElementAsync(); if (canReadContent) { string str = await reader.ReadStringAsync(); if (!string.IsNullOrEmpty(str)) { result.PublishDate = DateParser(str, reader.LocalName, reader.NamespaceURI); } await reader.ReadEndElementAsync(); } break; } case Rss20Constants.SourceTag: { SyndicationFeed feed = new SyndicationFeed(); if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string ns = reader.NamespaceURI; string name = reader.LocalName; if (FeedUtils.IsXmlns(name, ns)) { continue; } string val = await reader.GetValueAsync(); if (name == Rss20Constants.UrlTag && ns == Rss20Constants.Rss20Namespace) { feed.Links.Add(SyndicationLink.CreateSelfLink(UriParser(val, Rss20Constants.UrlTag,ns))); } else if (!FeedUtils.IsXmlns(name, ns)) { if (_preserveAttributeExtensions) { feed.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val); } } } } string localName = reader.LocalName; string namespaceUri = reader.NamespaceURI; string feedTitle = StringParser(await reader.ReadElementStringAsync(), localName, namespaceUri); feed.Title = new TextSyndicationContent(feedTitle); result.SourceFeed = feed; break; } default: notHandled = true; break; } } else { notHandled = true; } if (notHandled) { bool parsedExtension = _serializeExtensionsAsAtom && _atomSerializer.TryParseItemElementFromAsync(reader, result).Result; if (!parsedExtension) { parsedExtension = TryParseElement(reader, result, this.Version); } if (!parsedExtension) { if (_preserveElementExtensions) { if (buffer == null) { buffer = new XmlBuffer(_maxExtensionSize); extWriter = buffer.OpenSection(XmlDictionaryReaderQuotas.Max); extWriter.WriteStartElement(Rss20Constants.ExtensionWrapperTag); } await XmlReaderWrapper.WriteNodeAsync(extWriter, reader, false); } else { await reader.SkipAsync(); } } } } LoadElementExtensions(buffer, extWriter, result); } finally { if (extWriter != null) { ((IDisposable)extWriter).Dispose(); } } await reader.ReadEndElementAsync(); // item if (!readAlternateLink && fallbackAlternateLink != null) { result.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(fallbackAlternateLink, UriKind.RelativeOrAbsolute))); readAlternateLink = true; } // if there's no content and no alternate link set the summary as the item content if (result.Content == null && !readAlternateLink) { result.Content = result.Summary; result.Summary = null; } } } internal Task ReadItemFromAsync(XmlReaderWrapper reader, SyndicationItem result) { return ReadItemFromAsync(reader, result, null); } internal Task WriteItemContentsAsync(XmlWriter writer, SyndicationItem item) { writer = XmlWriterWrapper.CreateFromWriter(writer); return WriteItemContentsAsync(writer, item, null); } protected override SyndicationFeed CreateFeedInstance() { return SyndicationFeedFormatter.CreateFeedInstance(_feedType); } protected virtual async Task<SyndicationItem> ReadItemAsync(XmlReader reader, SyndicationFeed feed) { if (feed == null) { throw new ArgumentNullException(nameof(feed)); } if (reader == null) { throw new ArgumentNullException(nameof(reader)); } SyndicationItem item = CreateItem(feed); XmlReaderWrapper readerWrapper = XmlReaderWrapper.CreateFromReader(reader); await ReadItemFromAsync(readerWrapper, item, feed.BaseUri); // delegate => ItemParser(reader,item,feed.BaseUri);// return item; } protected virtual async Task WriteItemAsync(XmlWriter writer, SyndicationItem item, Uri feedBaseUri) { writer = XmlWriterWrapper.CreateFromWriter(writer); await writer.WriteStartElementAsync(Rss20Constants.ItemTag, Rss20Constants.Rss20Namespace); await WriteItemContentsAsync(writer, item, feedBaseUri); await writer.WriteEndElementAsync(); } protected virtual async Task WriteItemsAsync(XmlWriter writer, IEnumerable<SyndicationItem> items, Uri feedBaseUri) { if (items == null) { return; } foreach (SyndicationItem item in items) { await this.WriteItemAsync(writer, item, feedBaseUri); } } private static string NormalizeTimeZone(string rfc822TimeZone, out bool isUtc) { isUtc = false; // return a string in "-08:00" format if (rfc822TimeZone[0] == '+' || rfc822TimeZone[0] == '-') { // the time zone is supposed to be 4 digits but some feeds omit the initial 0 StringBuilder result = new StringBuilder(rfc822TimeZone); if (result.Length == 4) { // the timezone is +/-HMM. Convert to +/-HHMM result.Insert(1, '0'); } result.Insert(3, ':'); return result.ToString(); } switch (rfc822TimeZone) { case "UT": case "Z": isUtc = true; return "-00:00"; case "GMT": return "-00:00"; case "A": return "-01:00"; case "B": return "-02:00"; case "C": return "-03:00"; case "D": case "EDT": return "-04:00"; case "E": case "EST": case "CDT": return "-05:00"; case "F": case "CST": case "MDT": return "-06:00"; case "G": case "MST": case "PDT": return "-07:00"; case "H": case "PST": return "-08:00"; case "I": return "-09:00"; case "K": return "-10:00"; case "L": return "-11:00"; case "M": return "-12:00"; case "N": return "+01:00"; case "O": return "+02:00"; case "P": return "+03:00"; case "Q": return "+04:00"; case "R": return "+05:00"; case "S": return "+06:00"; case "T": return "+07:00"; case "U": return "+08:00"; case "V": return "+09:00"; case "W": return "+10:00"; case "X": return "+11:00"; case "Y": return "+12:00"; default: return ""; } } private async Task ReadSkipHoursAsync(XmlReaderWrapper reader, SyndicationFeed result) { await reader.ReadStartElementAsync(); while (await reader.IsStartElementAsync()) { if(reader.LocalName == Rss20Constants.HourTag) { string val = StringParser(await reader.ReadElementStringAsync(), Rss20Constants.HourTag, Rss20Constants.Rss20Namespace); int hour = int.Parse(val); bool parsed = false; parsed = int.TryParse(val,NumberStyles.Integer,NumberFormatInfo.InvariantInfo,out hour); if(parsed == false) { throw new ArgumentException("The number on skip hours must be an integer betwen 0 and 23."); } if (hour < 0 || hour > 23) { throw new ArgumentException("The hour can't be lower than 0 or greater than 23."); } result.SkipHours.Add(hour); } else { await reader.SkipAsync(); } } await reader.ReadEndElementAsync(); } private bool checkDay(string day) { if (acceptedDays.Contains(day.ToLower())) { return true; } return false; } private async Task ReadSkipDaysAsync(XmlReaderWrapper reader, SyndicationFeed result) { await reader.ReadStartElementAsync(); while (await reader.IsStartElementAsync()) { if (reader.LocalName == Rss20Constants.DayTag) { string day = StringParser(await reader.ReadElementStringAsync(), Rss20Constants.DayTag, Rss20Constants.Rss20Namespace); //Check if the day is actually an accepted day. if (checkDay(day)) { result.SkipDays.Add(day); } } else { await reader.SkipAsync(); } } await reader.ReadEndElementAsync(); } internal static void RemoveExtraWhiteSpaceAtStart(StringBuilder stringBuilder) { int i = 0; while (i < stringBuilder.Length) { if (!char.IsWhiteSpace(stringBuilder[i])) { break; } ++i; } if (i > 0) { stringBuilder.Remove(0, i); } } private static void ReplaceMultipleWhiteSpaceWithSingleWhiteSpace(StringBuilder builder) { int index = 0; int whiteSpaceStart = -1; while (index < builder.Length) { if (char.IsWhiteSpace(builder[index])) { if (whiteSpaceStart < 0) { whiteSpaceStart = index; // normalize all white spaces to be ' ' so that the date time parsing works builder[index] = ' '; } } else if (whiteSpaceStart >= 0) { if (index > whiteSpaceStart + 1) { // there are at least 2 spaces... replace by 1 builder.Remove(whiteSpaceStart, index - whiteSpaceStart - 1); index = whiteSpaceStart + 1; } whiteSpaceStart = -1; } ++index; } // we have already trimmed the start and end so there cannot be a trail of white spaces in the end Debug.Assert(builder.Length == 0 || builder[builder.Length - 1] != ' ', "The string builder doesnt end in a white space"); } private string AsString(DateTimeOffset dateTime) { if (dateTime.Offset == Atom10FeedFormatter.zeroOffset) { return dateTime.ToUniversalTime().ToString(Rfc822OutputUtcDateTimeFormat, CultureInfo.InvariantCulture); } else { StringBuilder sb = new StringBuilder(dateTime.ToString(Rfc822OutputLocalDateTimeFormat, CultureInfo.InvariantCulture)); // the zzz in Rfc822OutputLocalDateTimeFormat makes the timezone e.g. "-08:00" but we require e.g. "-0800" without the ':' sb.Remove(sb.Length - 3, 1); return sb.ToString(); } } private async Task<SyndicationLink> ReadAlternateLinkAsync(XmlReaderWrapper reader, Uri baseUri) { SyndicationLink link = new SyndicationLink(); link.BaseUri = baseUri; link.RelationshipType = Atom10Constants.AlternateTag; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.LocalName == "base" && reader.NamespaceURI == Atom10FeedFormatter.XmlNs) { link.BaseUri = FeedUtils.CombineXmlBase(link.BaseUri, await reader.GetValueAsync()); } else if (!FeedUtils.IsXmlns(reader.LocalName, reader.NamespaceURI)) { if (this.PreserveAttributeExtensions) { link.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), await reader.GetValueAsync()); } } } } string localName = reader.LocalName; string namespaceUri = reader.NamespaceURI; link.Uri = UriParser(await reader.ReadElementStringAsync(), localName, namespaceUri);//new Uri(uri, UriKind.RelativeOrAbsolute); return link; } private async Task<SyndicationCategory> ReadCategoryAsync(XmlReaderWrapper reader, SyndicationFeed feed) { SyndicationCategory result = CreateCategory(feed); await ReadCategoryAsync(reader, result); return result; } private async Task ReadCategoryAsync(XmlReaderWrapper reader, SyndicationCategory category) { bool isEmpty = reader.IsEmptyElement; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string ns = reader.NamespaceURI; string name = reader.LocalName; if (FeedUtils.IsXmlns(name, ns)) { continue; } string val = await reader.GetValueAsync(); if (name == Rss20Constants.DomainTag && ns == Rss20Constants.Rss20Namespace) { category.Scheme = val; } else if (!TryParseAttribute(name, ns, val, category, this.Version)) { if (_preserveAttributeExtensions) { category.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val); } } } } await reader.ReadStartElementAsync(Rss20Constants.CategoryTag, Rss20Constants.Rss20Namespace); if (!isEmpty) { category.Name = StringParser(await reader.ReadStringAsync(), reader.LocalName, Rss20Constants.Rss20Namespace); await reader.ReadEndElementAsync(); } } private async Task<SyndicationCategory> ReadCategoryAsync(XmlReaderWrapper reader, SyndicationItem item) { SyndicationCategory result = CreateCategory(item); await ReadCategoryAsync(reader, result); return result; } private async Task<SyndicationLink> ReadMediaEnclosureAsync(XmlReaderWrapper reader, Uri baseUri) { SyndicationLink link = new SyndicationLink(); link.BaseUri = baseUri; link.RelationshipType = Rss20Constants.EnclosureTag; bool isEmptyElement = reader.IsEmptyElement; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string ns = reader.NamespaceURI; string name = reader.LocalName; if (name == "base" && ns == Atom10FeedFormatter.XmlNs) { link.BaseUri = FeedUtils.CombineXmlBase(link.BaseUri, await reader.GetValueAsync()); continue; } if (FeedUtils.IsXmlns(name, ns)) { continue; } string val = await reader.GetValueAsync(); if (name == Rss20Constants.UrlTag && ns == Rss20Constants.Rss20Namespace) { link.Uri = new Uri(val, UriKind.RelativeOrAbsolute); } else if (name == Rss20Constants.TypeTag && ns == Rss20Constants.Rss20Namespace) { link.MediaType = val; } else if (name == Rss20Constants.LengthTag && ns == Rss20Constants.Rss20Namespace) { link.Length = !string.IsNullOrEmpty(val) ? Convert.ToInt64(val, CultureInfo.InvariantCulture.NumberFormat) : 0; } else if (!FeedUtils.IsXmlns(name, ns)) { if (_preserveAttributeExtensions) { link.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val); } } } } await reader.ReadStartElementAsync(Rss20Constants.EnclosureTag, Rss20Constants.Rss20Namespace); if (!isEmptyElement) { await reader.ReadEndElementAsync(); } return link; } private async Task<SyndicationPerson> ReadPersonAsync(XmlReaderWrapper reader, SyndicationFeed feed) { SyndicationPerson result = CreatePerson(feed); await ReadPersonAsync(reader, result); return result; } private async Task ReadPersonAsync(XmlReaderWrapper reader, SyndicationPerson person) { bool isEmpty = reader.IsEmptyElement; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string ns = reader.NamespaceURI; string name = reader.LocalName; if (FeedUtils.IsXmlns(name, ns)) { continue; } string val = await reader.GetValueAsync(); if (!TryParseAttribute(name, ns, val, person, this.Version)) { if (_preserveAttributeExtensions) { person.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val); } } } } await reader.ReadStartElementAsync(); if (!isEmpty) { string email = StringParser(await reader.ReadStringAsync(),reader.LocalName,reader.NamespaceURI); await reader.ReadEndElementAsync(); person.Email = email; } } private async Task<SyndicationPerson> ReadPersonAsync(XmlReaderWrapper reader, SyndicationItem item) { SyndicationPerson result = CreatePerson(item); await ReadPersonAsync(reader, result); return result; } private bool checkTextInput(SyndicationTextInput textInput) { //All textInput items are required, we check if all items were instantiated. return (textInput.Description != null && textInput.title != null && textInput.name != null && textInput.link != null); } private async Task readTextInputTag(XmlReaderWrapper reader, SyndicationFeed result) { await reader.ReadStartElementAsync(); SyndicationTextInput textInput = new SyndicationTextInput(); string val = String.Empty; while (await reader.IsStartElementAsync()) { string name = reader.LocalName; string namespaceUri = reader.NamespaceURI; val = StringParser(await reader.ReadElementStringAsync(), name, Rss20Constants.Rss20Namespace); switch (name) { case Rss20Constants.DescriptionTag: textInput.Description = val; break; case Rss20Constants.TitleTag: textInput.title = val; break; case Rss20Constants.LinkTag: textInput.link = new SyndicationLink(UriParser(val, name, namespaceUri)); break; case Rss20Constants.NameTag: textInput.name = val; break; default: //ignore! break; } } if(checkTextInput(textInput) == true) { result.TextInput = textInput; } await reader.ReadEndElementAsync(); } private async Task ReadXmlAsync(XmlReaderWrapper reader, SyndicationFeed result) { string baseUri = null; await reader.MoveToContentAsync(); string version = reader.GetAttribute(Rss20Constants.VersionTag, Rss20Constants.Rss20Namespace); if (version != Rss20Constants.Version) { throw new NotSupportedException(FeedUtils.AddLineInfo(reader, (string.Format(SR.UnsupportedRssVersion, version)))); } if (reader.AttributeCount > 1) { string tmp = reader.GetAttribute("base", Atom10FeedFormatter.XmlNs); if (!string.IsNullOrEmpty(tmp)) { baseUri = tmp; } } await reader.ReadStartElementAsync(); await reader.MoveToContentAsync(); if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string ns = reader.NamespaceURI; string name = reader.LocalName; if (name == "base" && ns == Atom10FeedFormatter.XmlNs) { baseUri = await reader.GetValueAsync(); continue; } if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns)) { continue; } string val = await reader.GetValueAsync(); if (!TryParseAttribute(name, ns, val, result, this.Version)) { if (_preserveAttributeExtensions) { result.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val); } } } } if (!string.IsNullOrEmpty(baseUri)) { result.BaseUri = new Uri(baseUri, UriKind.RelativeOrAbsolute); } bool areAllItemsRead = true; await reader.ReadStartElementAsync(Rss20Constants.ChannelTag, Rss20Constants.Rss20Namespace); XmlBuffer buffer = null; XmlDictionaryWriter extWriter = null; NullNotAllowedCollection<SyndicationItem> feedItems = new NullNotAllowedCollection<SyndicationItem>(); try { while (await reader.IsStartElementAsync()) { bool notHandled = false; if (await reader.MoveToContentAsync() == XmlNodeType.Element && reader.NamespaceURI == Rss20Constants.Rss20Namespace) { switch (reader.LocalName) { case Rss20Constants.TitleTag: result.Title = new TextSyndicationContent(StringParser(await reader.ReadElementStringAsync(), Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace)); break; case Rss20Constants.LinkTag: result.Links.Add(await ReadAlternateLinkAsync(reader, result.BaseUri)); break; case Rss20Constants.DescriptionTag: result.Description = new TextSyndicationContent(StringParser(await reader.ReadElementStringAsync(), Rss20Constants.DescriptionTag, Rss20Constants.Rss20Namespace)); break; case Rss20Constants.LanguageTag: result.Language = StringParser(await reader.ReadElementStringAsync(), Rss20Constants.LanguageTag, Rss20Constants.Rss20Namespace); break; case Rss20Constants.CopyrightTag: result.Copyright = new TextSyndicationContent(StringParser(await reader.ReadElementStringAsync(), Rss20Constants.CopyrightTag, Rss20Constants.Rss20Namespace)); break; case Rss20Constants.ManagingEditorTag: result.Authors.Add(await ReadPersonAsync(reader, result)); break; case Rss20Constants.LastBuildDateTag: { bool canReadContent = !reader.IsEmptyElement; await reader.ReadStartElementAsync(); if (canReadContent) { string str = await reader.ReadStringAsync(); if (!string.IsNullOrEmpty(str)) { result.LastUpdatedTime = DateParser(str, Rss20Constants.LastBuildDateTag, reader.NamespaceURI); } await reader.ReadEndElementAsync(); } break; } case Rss20Constants.CategoryTag: result.Categories.Add(await ReadCategoryAsync(reader, result)); break; case Rss20Constants.GeneratorTag: result.Generator = StringParser(await reader.ReadElementStringAsync(), Rss20Constants.GeneratorTag, Rss20Constants.Rss20Namespace); break; case Rss20Constants.ImageTag: { await OnReadImage(reader, result); break; } case Rss20Constants.ItemTag: { NullNotAllowedCollection<SyndicationItem> items = new NullNotAllowedCollection<SyndicationItem>(); while (await reader.IsStartElementAsync(Rss20Constants.ItemTag, Rss20Constants.Rss20Namespace)) { feedItems.Add(await ReadItemAsync(reader, result)); } areAllItemsRead = true; break; } //Optional tags case Rss20Constants.DocumentationTag: result.Documentation = await ReadAlternateLinkAsync(reader, result.BaseUri); break; case Rss20Constants.TimeToLiveTag: string value = StringParser(await reader.ReadElementStringAsync(), Rss20Constants.TimeToLiveTag, Rss20Constants.Rss20Namespace); int timeToLive = int.Parse(value); result.TimeToLive = timeToLive; break; case Rss20Constants.TextInputTag: await readTextInputTag(reader, result); break; case Rss20Constants.SkipHoursTag: await ReadSkipHoursAsync(reader, result); break; case Rss20Constants.SkipDaysTag: await ReadSkipDaysAsync(reader, result); break; default: notHandled = true; break; } } else { notHandled = true; } if (notHandled) { bool parsedExtension = _serializeExtensionsAsAtom && await _atomSerializer.TryParseFeedElementFromAsync(reader, result); if (!parsedExtension) { parsedExtension = TryParseElement(reader, result, this.Version); } if (!parsedExtension) { if (_preserveElementExtensions) { if (buffer == null) { buffer = new XmlBuffer(_maxExtensionSize); extWriter = buffer.OpenSection(XmlDictionaryReaderQuotas.Max); extWriter.WriteStartElement(Rss20Constants.ExtensionWrapperTag); } await XmlReaderWrapper.WriteNodeAsync(extWriter, reader, false); } else { await reader.SkipAsync(); } } } if (!areAllItemsRead) { break; } } //asign all read items to feed items. result.Items = feedItems; LoadElementExtensions(buffer, extWriter, result); } catch (FormatException e) { throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingFeed), e); } catch (ArgumentException e) { throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingFeed), e); } finally { if (extWriter != null) { ((IDisposable)extWriter).Dispose(); } } if (areAllItemsRead) { await reader.ReadEndElementAsync(); // channel await reader.ReadEndElementAsync(); // rss } } private async Task WriteAlternateLinkAsync(XmlWriter writer, SyndicationLink link, Uri baseUri) { await writer.WriteStartElementAsync(Rss20Constants.LinkTag, Rss20Constants.Rss20Namespace); Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, link.BaseUri); if (baseUriToWrite != null) { await writer.WriteAttributeStringAsync("xml", "base", Atom10FeedFormatter.XmlNs, FeedUtils.GetUriString(baseUriToWrite)); } await link.WriteAttributeExtensionsAsync(writer, SyndicationVersions.Rss20); await writer.WriteStringAsync(FeedUtils.GetUriString(link.Uri)); await writer.WriteEndElementAsync(); } private async Task WriteCategoryAsync(XmlWriter writer, SyndicationCategory category) { if (category == null) { return; } await writer.WriteStartElementAsync(Rss20Constants.CategoryTag, Rss20Constants.Rss20Namespace); await WriteAttributeExtensionsAsync(writer, category, this.Version); if (!string.IsNullOrEmpty(category.Scheme) && !category.AttributeExtensions.ContainsKey(s_rss20Domain)) { await writer.WriteAttributeStringAsync(Rss20Constants.DomainTag, Rss20Constants.Rss20Namespace, category.Scheme); } await writer.WriteStringAsync(category.Name); await writer.WriteEndElementAsync(); } private async Task WriteFeedAsync(XmlWriter writer) { if (this.Feed == null) { throw new InvalidOperationException(SR.FeedFormatterDoesNotHaveFeed); } if (_serializeExtensionsAsAtom) { await writer.InternalWriteAttributeStringAsync("xmlns", Atom10Constants.Atom10Prefix, null, Atom10Constants.Atom10Namespace); } await writer.WriteAttributeStringAsync(Rss20Constants.VersionTag, Rss20Constants.Version); await writer.WriteStartElementAsync(Rss20Constants.ChannelTag, Rss20Constants.Rss20Namespace); if (this.Feed.BaseUri != null) { await writer.InternalWriteAttributeStringAsync("xml", "base", Atom10FeedFormatter.XmlNs, FeedUtils.GetUriString(this.Feed.BaseUri)); } await WriteAttributeExtensionsAsync(writer, this.Feed, this.Version); string title = this.Feed.Title != null ? this.Feed.Title.Text : string.Empty; await writer.WriteElementStringAsync(Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace, title); SyndicationLink alternateLink = null; for (int i = 0; i < this.Feed.Links.Count; ++i) { if (this.Feed.Links[i].RelationshipType == Atom10Constants.AlternateTag) { alternateLink = this.Feed.Links[i]; await WriteAlternateLinkAsync(writer, alternateLink, this.Feed.BaseUri); break; } } string description = this.Feed.Description != null ? this.Feed.Description.Text : string.Empty; await writer.WriteElementStringAsync(Rss20Constants.DescriptionTag, Rss20Constants.Rss20Namespace, description); if (this.Feed.Language != null) { await writer.WriteElementStringAsync(Rss20Constants.LanguageTag, this.Feed.Language); } if (this.Feed.Copyright != null) { await writer.WriteElementStringAsync(Rss20Constants.CopyrightTag, Rss20Constants.Rss20Namespace, this.Feed.Copyright.Text); } // if there's a single author with an email address, then serialize as the managingEditor // else serialize the authors as Atom extensions if ((this.Feed.Authors.Count == 1) && (this.Feed.Authors[0].Email != null)) { await WritePersonAsync(writer, Rss20Constants.ManagingEditorTag, this.Feed.Authors[0]); } else { if (_serializeExtensionsAsAtom) { await _atomSerializer.WriteFeedAuthorsToAsync(writer, this.Feed.Authors); } } if (this.Feed.LastUpdatedTime > DateTimeOffset.MinValue) { await writer.WriteStartElementAsync(Rss20Constants.LastBuildDateTag); await writer.WriteStringAsync(AsString(this.Feed.LastUpdatedTime)); await writer.WriteEndElementAsync(); } for (int i = 0; i < this.Feed.Categories.Count; ++i) { await WriteCategoryAsync(writer, this.Feed.Categories[i]); } if (!string.IsNullOrEmpty(this.Feed.Generator)) { await writer.WriteElementStringAsync(Rss20Constants.GeneratorTag, this.Feed.Generator); } if (this.Feed.Contributors.Count > 0) { if (_serializeExtensionsAsAtom) { await _atomSerializer.WriteFeedContributorsToAsync(writer, this.Feed.Contributors); } } if (this.Feed.ImageUrl != null) { await writer.WriteStartElementAsync(Rss20Constants.ImageTag); await writer.WriteElementStringAsync(Rss20Constants.UrlTag, FeedUtils.GetUriString(this.Feed.ImageUrl)); string imageTitle = Feed.ImageTitle == null ? title : Feed.ImageTitle.Text; await writer.WriteElementStringAsync(Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace, imageTitle); string imgAlternateLink = alternateLink != null ? FeedUtils.GetUriString(alternateLink.Uri) : string.Empty; string imageLink = Feed.ImageLink == null ? imgAlternateLink : FeedUtils.GetUriString(Feed.ImageLink); await writer.WriteElementStringAsync(Rss20Constants.LinkTag, Rss20Constants.Rss20Namespace, imageLink); await writer.WriteEndElementAsync(); // image } //Optional spec items //time to live if(this.Feed.TimeToLive != 0) { await writer.WriteElementStringAsync(Rss20Constants.TimeToLiveTag, this.Feed.TimeToLive.ToString()); } //skiphours if(this.Feed.SkipHours.Count > 0) { await writer.WriteStartElementAsync(Rss20Constants.SkipHoursTag); foreach(int hour in this.Feed.SkipHours) { writer.WriteElementString(Rss20Constants.HourTag,hour.ToString()); } await writer.WriteEndElementAsync(); } //skipDays if(this.Feed.SkipDays.Count > 0) { await writer.WriteStartElementAsync(Rss20Constants.SkipDaysTag); foreach(string day in this.Feed.SkipDays) { await writer.WriteElementStringAsync(Rss20Constants.DayTag,day); } await writer.WriteEndElementAsync(); } //textinput if(this.Feed.TextInput != null) { await writer.WriteStartElementAsync(Rss20Constants.TextInputTag); await writer.WriteElementStringAsync(Rss20Constants.DescriptionTag, this.Feed.TextInput.Description); await writer.WriteElementStringAsync(Rss20Constants.TitleTag, this.Feed.TextInput.title); await writer.WriteElementStringAsync(Rss20Constants.LinkTag, this.Feed.TextInput.link.GetAbsoluteUri().ToString()); await writer.WriteElementStringAsync(Rss20Constants.NameTag, this.Feed.TextInput.name); await writer.WriteEndElementAsync(); } if (_serializeExtensionsAsAtom) { await _atomSerializer.WriteElementAsync(writer, Atom10Constants.IdTag, this.Feed.Id); // dont write out the 1st alternate link since that would have been written out anyway bool isFirstAlternateLink = true; for (int i = 0; i < this.Feed.Links.Count; ++i) { if (this.Feed.Links[i].RelationshipType == Atom10Constants.AlternateTag && isFirstAlternateLink) { isFirstAlternateLink = false; continue; } await _atomSerializer.WriteLinkAsync(writer, this.Feed.Links[i], this.Feed.BaseUri); } } await WriteElementExtensionsAsync(writer, this.Feed, this.Version); await WriteItemsAsync(writer, this.Feed.Items, this.Feed.BaseUri); await writer.WriteEndElementAsync(); // channel } private async Task WriteItemContentsAsync(XmlWriter writer, SyndicationItem item, Uri feedBaseUri) { Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(feedBaseUri, item.BaseUri); if (baseUriToWrite != null) { await writer.InternalWriteAttributeStringAsync("xml", "base", Atom10FeedFormatter.XmlNs, FeedUtils.GetUriString(baseUriToWrite)); } await WriteAttributeExtensionsAsync(writer, item, this.Version); string guid = item.Id ?? string.Empty; bool isPermalink = false; SyndicationLink firstAlternateLink = null; for (int i = 0; i < item.Links.Count; ++i) { if (item.Links[i].RelationshipType == Atom10Constants.AlternateTag) { if (firstAlternateLink == null) { firstAlternateLink = item.Links[i]; } if (guid == FeedUtils.GetUriString(item.Links[i].Uri)) { isPermalink = true; break; } } } if (!string.IsNullOrEmpty(guid)) { await writer.WriteStartElementAsync(Rss20Constants.GuidTag); if (isPermalink) { await writer.WriteAttributeStringAsync(Rss20Constants.IsPermaLinkTag, "true"); } else { await writer.WriteAttributeStringAsync(Rss20Constants.IsPermaLinkTag, "false"); } await writer.WriteStringAsync(guid); await writer.WriteEndElementAsync(); } if (firstAlternateLink != null) { await WriteAlternateLinkAsync(writer, firstAlternateLink, (item.BaseUri != null ? item.BaseUri : feedBaseUri)); } if (item.Authors.Count == 1 && !string.IsNullOrEmpty(item.Authors[0].Email)) { await WritePersonAsync(writer, Rss20Constants.AuthorTag, item.Authors[0]); } else { if (_serializeExtensionsAsAtom) { await _atomSerializer.WriteItemAuthorsToAsync(writer, item.Authors); } } for (int i = 0; i < item.Categories.Count; ++i) { await WriteCategoryAsync(writer, item.Categories[i]); } bool serializedTitle = false; if (item.Title != null) { await writer.WriteElementStringAsync(Rss20Constants.TitleTag, item.Title.Text); serializedTitle = true; } bool serializedContentAsDescription = false; TextSyndicationContent summary = item.Summary; if (summary == null) { summary = (item.Content as TextSyndicationContent); serializedContentAsDescription = (summary != null); } // the spec requires the wire to have a title or a description if (!serializedTitle && summary == null) { summary = new TextSyndicationContent(string.Empty); } if (summary != null) { await writer.WriteElementStringAsync(Rss20Constants.DescriptionTag, Rss20Constants.Rss20Namespace, summary.Text); } if (item.SourceFeed != null) { await writer.WriteStartElementAsync(Rss20Constants.SourceTag, Rss20Constants.Rss20Namespace); await WriteAttributeExtensionsAsync(writer, item.SourceFeed, this.Version); SyndicationLink selfLink = null; for (int i = 0; i < item.SourceFeed.Links.Count; ++i) { if (item.SourceFeed.Links[i].RelationshipType == Atom10Constants.SelfTag) { selfLink = item.SourceFeed.Links[i]; break; } } if (selfLink != null && !item.SourceFeed.AttributeExtensions.ContainsKey(s_rss20Url)) { await writer.WriteAttributeStringAsync(Rss20Constants.UrlTag, Rss20Constants.Rss20Namespace, FeedUtils.GetUriString(selfLink.Uri)); } string title = (item.SourceFeed.Title != null) ? item.SourceFeed.Title.Text : string.Empty; await writer.WriteStringAsync(title); await writer.WriteEndElementAsync(); } if (item.PublishDate > DateTimeOffset.MinValue) { await writer.WriteElementStringAsync(Rss20Constants.PubDateTag, Rss20Constants.Rss20Namespace, AsString(item.PublishDate)); } // serialize the enclosures SyndicationLink firstEnclosureLink = null; bool passedFirstAlternateLink = false; for (int i = 0; i < item.Links.Count; ++i) { if (item.Links[i].RelationshipType == Rss20Constants.EnclosureTag) { if (firstEnclosureLink == null) { firstEnclosureLink = item.Links[i]; await WriteMediaEnclosureAsync(writer, item.Links[i], item.BaseUri); continue; } } else if (item.Links[i].RelationshipType == Atom10Constants.AlternateTag) { if (!passedFirstAlternateLink) { passedFirstAlternateLink = true; continue; } } if (_serializeExtensionsAsAtom) { await _atomSerializer.WriteLinkAsync(writer, item.Links[i], item.BaseUri); } } if (item.LastUpdatedTime > DateTimeOffset.MinValue) { if (_serializeExtensionsAsAtom) { await _atomSerializer.WriteItemLastUpdatedTimeToAsync(writer, item.LastUpdatedTime); } } if (_serializeExtensionsAsAtom) { await _atomSerializer.WriteContentToAsync(writer, Atom10Constants.RightsTag, item.Copyright); } if (!serializedContentAsDescription) { if (_serializeExtensionsAsAtom) { await _atomSerializer.WriteContentToAsync(writer, Atom10Constants.ContentTag, item.Content); } } if (item.Contributors.Count > 0) { if (_serializeExtensionsAsAtom) { await _atomSerializer.WriteItemContributorsToAsync(writer, item.Contributors); } } await WriteElementExtensionsAsync(writer, item, this.Version); } private async Task WriteMediaEnclosureAsync(XmlWriter writer, SyndicationLink link, Uri baseUri) { await writer.WriteStartElementAsync(Rss20Constants.EnclosureTag, Rss20Constants.Rss20Namespace); Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, link.BaseUri); if (baseUriToWrite != null) { await writer.InternalWriteAttributeStringAsync("xml", "base", Atom10FeedFormatter.XmlNs, FeedUtils.GetUriString(baseUriToWrite)); } await link.WriteAttributeExtensionsAsync(writer, SyndicationVersions.Rss20); if (!link.AttributeExtensions.ContainsKey(s_rss20Url)) { await writer.WriteAttributeStringAsync(Rss20Constants.UrlTag, Rss20Constants.Rss20Namespace, FeedUtils.GetUriString(link.Uri)); } if (link.MediaType != null && !link.AttributeExtensions.ContainsKey(s_rss20Type)) { await writer.WriteAttributeStringAsync(Rss20Constants.TypeTag, Rss20Constants.Rss20Namespace, link.MediaType); } if (link.Length != 0 && !link.AttributeExtensions.ContainsKey(s_rss20Length)) { await writer.WriteAttributeStringAsync(Rss20Constants.LengthTag, Rss20Constants.Rss20Namespace, Convert.ToString(link.Length, CultureInfo.InvariantCulture)); } await writer.WriteEndElementAsync(); } private async Task WritePersonAsync(XmlWriter writer, string elementTag, SyndicationPerson person) { await writer.WriteStartElementAsync(elementTag, Rss20Constants.Rss20Namespace); await WriteAttributeExtensionsAsync(writer, person, this.Version); await writer.WriteStringAsync(person.Email); await writer.WriteEndElementAsync(); } private static bool OriginalDateParser(string dateTimeString, out DateTimeOffset dto) { StringBuilder dateTimeStringBuilder = new StringBuilder(dateTimeString.Trim()); if (dateTimeStringBuilder.Length < 18) { return false; } int timeZoneStartIndex; for (timeZoneStartIndex = dateTimeStringBuilder.Length-1; dateTimeStringBuilder[timeZoneStartIndex] != ' '; timeZoneStartIndex--); timeZoneStartIndex++; string timeZoneSuffix = dateTimeStringBuilder.ToString().Substring(timeZoneStartIndex); dateTimeStringBuilder.Remove(timeZoneStartIndex, dateTimeStringBuilder.Length - timeZoneStartIndex); bool isUtc; dateTimeStringBuilder.Append(NormalizeTimeZone(timeZoneSuffix, out isUtc)); string wellFormattedString = dateTimeStringBuilder.ToString(); DateTimeOffset theTime; string[] parseFormat = { "ddd, dd MMMM yyyy HH:mm:ss zzz", "dd MMMM yyyy HH:mm:ss zzz", "ddd, dd MMM yyyy HH:mm:ss zzz", "dd MMM yyyy HH:mm:ss zzz", "ddd, dd MMMM yyyy HH:mm zzz", "dd MMMM yyyy HH:mm zzz", "ddd, dd MMM yyyy HH:mm zzz", "dd MMM yyyy HH:mm zzz" }; if (DateTimeOffset.TryParseExact(wellFormattedString, parseFormat, CultureInfo.InvariantCulture.DateTimeFormat, (isUtc ? DateTimeStyles.AdjustToUniversal : DateTimeStyles.None), out theTime)) { dto = theTime; return true; } return false; } // Custom parsers public static DateTimeOffset DefaultDateParser(string dateTimeString, string localName, string ns) { bool parsed = false; DateTimeOffset dto; parsed = DateTimeOffset.TryParse(dateTimeString, out dto); if (parsed) return dto; //original parser here parsed = OriginalDateParser(dateTimeString,out dto); if (parsed) return dto; //Impossible to parse - using a default date; return new DateTimeOffset(); } } [XmlRoot(ElementName = Rss20Constants.RssTag, Namespace = Rss20Constants.Rss20Namespace)] public class Rss20FeedFormatter<TSyndicationFeed> : Rss20FeedFormatter where TSyndicationFeed : SyndicationFeed, new() { // constructors public Rss20FeedFormatter() : base(typeof(TSyndicationFeed)) { } public Rss20FeedFormatter(TSyndicationFeed feedToWrite) : base(feedToWrite) { } public Rss20FeedFormatter(TSyndicationFeed feedToWrite, bool serializeExtensionsAsAtom) : base(feedToWrite, serializeExtensionsAsAtom) { } protected override SyndicationFeed CreateFeedInstance() { return new TSyndicationFeed(); } } internal class ItemParseOptions { public bool readItemsAtLeastOnce; public bool areAllItemsRead; public ItemParseOptions(bool readItemsAtLeastOnce, bool areAllItemsRead) { this.readItemsAtLeastOnce = readItemsAtLeastOnce; this.areAllItemsRead = areAllItemsRead; } } }
// 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.Security.Cryptography.DeriveBytesTests { public class Rfc2898Tests { // 8 bytes is the minimum accepted value, by using it we've already assured that the minimum is acceptable. private static readonly byte[] s_testSalt = new byte[] { 9, 5, 5, 5, 1, 2, 1, 2 }; private static readonly byte[] s_testSaltB = new byte[] { 0, 4, 0, 4, 1, 9, 7, 5 }; private const string TestPassword = "PasswordGoesHere"; private const string TestPasswordB = "FakePasswordsAreHard"; private const int DefaultIterationCount = 1000; [Fact] public static void Ctor_NullPasswordBytes() { Assert.Throws<NullReferenceException>(() => new Rfc2898DeriveBytes((byte[])null, s_testSalt, DefaultIterationCount)); } [Fact] public static void Ctor_NullPasswordString() { Assert.Throws<ArgumentNullException>(() => new Rfc2898DeriveBytes((string)null, s_testSalt, DefaultIterationCount)); } [Fact] public static void Ctor_NullSalt() { Assert.Throws<ArgumentNullException>(() => new Rfc2898DeriveBytes(TestPassword, null, DefaultIterationCount)); } [Fact] public static void Ctor_EmptySalt() { Assert.Throws<ArgumentException>(() => new Rfc2898DeriveBytes(TestPassword, Array.Empty<byte>(), DefaultIterationCount)); } [Fact] public static void Ctor_DiminishedSalt() { Assert.Throws<ArgumentException>(() => new Rfc2898DeriveBytes(TestPassword, new byte[7], DefaultIterationCount)); } [Fact] public static void Ctor_GenerateZeroSalt() { Assert.Throws<ArgumentException>(() => new Rfc2898DeriveBytes(TestPassword, 0)); } [Fact] public static void Ctor_GenerateNegativeSalt() { Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, int.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, int.MinValue / 2)); } [Fact] public static void Ctor_GenerateDiminishedSalt() { Assert.Throws<ArgumentException>(() => new Rfc2898DeriveBytes(TestPassword, 7)); } [Fact] public static void Ctor_TooFewIterations() { Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, s_testSalt, 0)); } [Fact] public static void Ctor_NegativeIterations() { Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, s_testSalt, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, s_testSalt, int.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, s_testSalt, int.MinValue / 2)); } [Fact] public static void Ctor_SaltCopied() { byte[] saltIn = (byte[])s_testSalt.Clone(); using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, saltIn, DefaultIterationCount)) { byte[] saltOut = deriveBytes.Salt; Assert.NotSame(saltIn, saltOut); Assert.Equal(saltIn, saltOut); // Right now we know that at least one of the constructor and get_Salt made a copy, if it was // only get_Salt then this next part would fail. saltIn[0] = (byte)~saltIn[0]; // Have to read the property again to prove it's detached. Assert.NotEqual(saltIn, deriveBytes.Salt); } } [Fact] public static void Ctor_DefaultIterations() { using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt)) { Assert.Equal(DefaultIterationCount, deriveBytes.IterationCount); } } [Fact] public static void Ctor_IterationsRespected() { using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt, 1)) { Assert.Equal(1, deriveBytes.IterationCount); } } [Fact] public static void GetSaltCopies() { byte[] first; byte[] second; using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt, DefaultIterationCount)) { first = deriveBytes.Salt; second = deriveBytes.Salt; } Assert.NotSame(first, second); Assert.Equal(first, second); } [Fact] public static void MinimumAcceptableInputs() { byte[] output; using (var deriveBytes = new Rfc2898DeriveBytes("", new byte[8], 1)) { output = deriveBytes.GetBytes(1); } Assert.Equal(1, output.Length); Assert.Equal(0xA6, output[0]); } [Fact] public static void GetBytes_ZeroLength() { using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt)) { Assert.Throws<ArgumentOutOfRangeException>(() => deriveBytes.GetBytes(0)); } } [Fact] public static void GetBytes_NegativeLength() { Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt); Assert.Throws<ArgumentOutOfRangeException>(() => deriveBytes.GetBytes(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => deriveBytes.GetBytes(int.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => deriveBytes.GetBytes(int.MinValue / 2)); } [Fact] public static void GetBytes_NotIdempotent() { byte[] first; byte[] second; using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt)) { first = deriveBytes.GetBytes(32); second = deriveBytes.GetBytes(32); } Assert.NotEqual(first, second); } [Fact] public static void GetBytes_StreamLike() { byte[] first; using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt)) { first = deriveBytes.GetBytes(32); } byte[] second = new byte[first.Length]; // Reset using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt)) { byte[] secondFirstHalf = deriveBytes.GetBytes(first.Length / 2); byte[] secondSecondHalf = deriveBytes.GetBytes(first.Length - secondFirstHalf.Length); Buffer.BlockCopy(secondFirstHalf, 0, second, 0, secondFirstHalf.Length); Buffer.BlockCopy(secondSecondHalf, 0, second, secondFirstHalf.Length, secondSecondHalf.Length); } Assert.Equal(first, second); } [Fact] public static void GetBytes_KnownValues_1() { TestKnownValue( TestPassword, s_testSalt, DefaultIterationCount, new byte[] { 0x6C, 0x3C, 0x55, 0xA4, 0x2E, 0xE9, 0xD6, 0xAE, 0x7D, 0x28, 0x6C, 0x83, 0xE4, 0xD7, 0xA3, 0xC8, 0xB5, 0x93, 0x9F, 0x45, 0x2F, 0x2B, 0xF3, 0x68, 0xFA, 0xE8, 0xB2, 0x74, 0x55, 0x3A, 0x36, 0x8A, }); } [Fact] public static void GetBytes_KnownValues_2() { TestKnownValue( TestPassword, s_testSalt, DefaultIterationCount + 1, new byte[] { 0x8E, 0x9B, 0xF7, 0xC1, 0x83, 0xD4, 0xD1, 0x20, 0x87, 0xA8, 0x2C, 0xD7, 0xCD, 0x84, 0xBC, 0x1A, 0xC6, 0x7A, 0x7A, 0xDD, 0x46, 0xFA, 0x40, 0xAA, 0x60, 0x3A, 0x2B, 0x8B, 0x79, 0x2C, 0x8A, 0x6D, }); } [Fact] public static void GetBytes_KnownValues_3() { TestKnownValue( TestPassword, s_testSaltB, DefaultIterationCount, new byte[] { 0x4E, 0xF5, 0xA5, 0x85, 0x92, 0x9D, 0x8B, 0xC5, 0x57, 0x0C, 0x83, 0xB5, 0x19, 0x69, 0x4B, 0xC2, 0x4B, 0xAA, 0x09, 0xE9, 0xE7, 0x9C, 0x29, 0x94, 0x14, 0x19, 0xE3, 0x61, 0xDA, 0x36, 0x5B, 0xB3, }); } [Fact] public static void GetBytes_KnownValues_4() { TestKnownValue( TestPasswordB, s_testSalt, DefaultIterationCount, new byte[] { 0x86, 0xBB, 0xB3, 0xD7, 0x99, 0x0C, 0xAC, 0x4D, 0x1D, 0xB2, 0x78, 0x9D, 0x57, 0x5C, 0x06, 0x93, 0x97, 0x50, 0x72, 0xFF, 0x56, 0x57, 0xAC, 0x7F, 0x9B, 0xD2, 0x14, 0x9D, 0xE9, 0x95, 0xA2, 0x6D, }); } private static void TestKnownValue(string password, byte[] salt, int iterationCount, byte[] expected) { byte[] output; using (var deriveBytes = new Rfc2898DeriveBytes(password, salt, iterationCount)) { output = deriveBytes.GetBytes(expected.Length); } Assert.Equal(expected, output); } } }
// 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.Linq; using System.Reflection.Metadata.Tests; using Xunit; namespace System.Reflection.Metadata.Ecma335.Tests { public class MethodBodyStreamEncoderTests { private static void WriteFakeILWithBranches(BlobBuilder builder, ControlFlowBuilder branchBuilder, int size) { Assert.Equal(0, builder.Count); const byte filling = 0x01; int ilOffset = 0; foreach (var branch in branchBuilder.Branches) { builder.WriteBytes(filling, branch.ILOffset - ilOffset); Assert.Equal(branch.ILOffset, builder.Count); builder.WriteByte((byte)branch.OpCode); int operandSize = branch.OpCode.GetBranchOperandSize(); if (operandSize == 1) { builder.WriteSByte(-1); } else { builder.WriteInt32(-1); } ilOffset = branch.ILOffset + sizeof(byte) + operandSize; } builder.WriteBytes(filling, size - ilOffset); Assert.Equal(size, builder.Count); } [Fact] public void AddMethodBody_Errors() { var streamBuilder = new BlobBuilder(); var il = new InstructionEncoder(new BlobBuilder()); Assert.Throws<ArgumentNullException>(() => new MethodBodyStreamEncoder(streamBuilder).AddMethodBody(default(InstructionEncoder))); Assert.Throws<ArgumentOutOfRangeException>(() => new MethodBodyStreamEncoder(streamBuilder).AddMethodBody(il, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => new MethodBodyStreamEncoder(streamBuilder).AddMethodBody(il, ushort.MaxValue + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => new MethodBodyStreamEncoder(streamBuilder).AddMethodBody(codeSize: -1)); Assert.Throws<ArgumentOutOfRangeException>(() => new MethodBodyStreamEncoder(streamBuilder).AddMethodBody(codeSize: 1, maxStack: -1)); Assert.Throws<ArgumentOutOfRangeException>(() => new MethodBodyStreamEncoder(streamBuilder).AddMethodBody(codeSize: 1, maxStack: ushort.MaxValue + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => new MethodBodyStreamEncoder(streamBuilder).AddMethodBody(codeSize: 1, exceptionRegionCount: -1)); Assert.Throws<ArgumentOutOfRangeException>(() => new MethodBodyStreamEncoder(streamBuilder).AddMethodBody(codeSize: 1, exceptionRegionCount: 699051)); } [Fact] public void AddMethodBody_Reserved_Tiny1() { var streamBuilder = new BlobBuilder(32); var encoder = new MethodBodyStreamEncoder(streamBuilder); streamBuilder.WriteBytes(0x01, 3); var body = encoder.AddMethodBody(10); Assert.Equal(3, body.Offset); var segment = body.Instructions.GetBytes(); Assert.Equal(4, segment.Offset); // +1 byte for the header Assert.Equal(10, segment.Count); Assert.Null(body.ExceptionRegions.Builder); new BlobWriter(body.Instructions).WriteBytes(0x02, 10); AssertEx.Equal(new byte[] { 0x01, 0x01, 0x01, 0x2A, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02 }, streamBuilder.ToArray()); } [Fact] public void AddMethodBody_Reserved_Tiny_AttributesIgnored() { var streamBuilder = new BlobBuilder(); var encoder = new MethodBodyStreamEncoder(streamBuilder); var body = encoder.AddMethodBody(10, attributes: MethodBodyAttributes.None); new BlobWriter(body.Instructions).WriteBytes(0x02, 10); AssertEx.Equal(new byte[] { 0x2A, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02 }, streamBuilder.ToArray()); } [Fact] public void AddMethodBody_Reserved_Tiny_MaxStackIgnored() { var streamBuilder = new BlobBuilder(); var encoder = new MethodBodyStreamEncoder(streamBuilder); var body = encoder.AddMethodBody(10, maxStack: 7); new BlobWriter(body.Instructions).WriteBytes(0x02, 10); AssertEx.Equal(new byte[] { 0x2A, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02 }, streamBuilder.ToArray()); } [Fact] public void AddMethodBody_Reserved_Tiny_Empty() { var streamBuilder = new BlobBuilder(); var encoder = new MethodBodyStreamEncoder(streamBuilder); var body = encoder.AddMethodBody(0); Assert.Equal(0, body.Offset); var segment = body.Instructions.GetBytes(); Assert.Equal(1, segment.Offset); // +1 byte for the header Assert.Equal(0, segment.Count); Assert.Null(body.ExceptionRegions.Builder); AssertEx.Equal(new byte[] { 0x02 }, streamBuilder.ToArray()); } [Fact] public void AddMethodBody_Reserved_Fat1() { var streamBuilder = new BlobBuilder(32); var encoder = new MethodBodyStreamEncoder(streamBuilder); streamBuilder.WriteBytes(0x01, 3); var body = encoder.AddMethodBody(10, maxStack: 9); Assert.Equal(4, body.Offset); // 4B aligned var segment = body.Instructions.GetBytes(); Assert.Equal(16, segment.Offset); // +12 byte for the header Assert.Equal(10, segment.Count); Assert.Null(body.ExceptionRegions.Builder); new BlobWriter(body.Instructions).WriteBytes(0x02, 10); AssertEx.Equal(new byte[] { 0x01, 0x01, 0x01, 0x00, // padding 0x13, 0x30, 0x09, 0x00, // max stack 0x0A, 0x00, 0x00, 0x00, // code size 0x00, 0x00, 0x00, 0x00, // local sig 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02 }, streamBuilder.ToArray()); } [Fact] public void AddMethodBody_Reserved_Fat2() { var streamBuilder = new BlobBuilder(32); var encoder = new MethodBodyStreamEncoder(streamBuilder); streamBuilder.WriteBytes(0x01, 3); var body = encoder.AddMethodBody(10, localVariablesSignature: MetadataTokens.StandaloneSignatureHandle(0xABCDEF)); Assert.Equal(4, body.Offset); // 4B aligned var segment = body.Instructions.GetBytes(); Assert.Equal(16, segment.Offset); // +12 byte for the header Assert.Equal(10, segment.Count); Assert.Null(body.ExceptionRegions.Builder); new BlobWriter(body.Instructions).WriteBytes(0x02, 10); AssertEx.Equal(new byte[] { 0x01, 0x01, 0x01, 0x00, // padding 0x13, 0x30, 0x08, 0x00, // max stack 0x0A, 0x00, 0x00, 0x00, // code size 0xEF, 0xCD, 0xAB, 0x11, // local sig 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02 }, streamBuilder.ToArray()); } [Fact] public void AddMethodBody_Reserved_Exceptions_Fat1() { var streamBuilder = new BlobBuilder(32); var encoder = new MethodBodyStreamEncoder(streamBuilder); streamBuilder.WriteBytes(0x01, 3); var body = encoder.AddMethodBody(10, exceptionRegionCount: 699050); Assert.Equal(4, body.Offset); // 4B aligned var segment = body.Instructions.GetBytes(); Assert.Equal(16, segment.Offset); // +12 byte for the header Assert.Equal(10, segment.Count); Assert.Same(streamBuilder, body.ExceptionRegions.Builder); new BlobWriter(body.Instructions).WriteBytes(0x02, 10); AssertEx.Equal(new byte[] { 0x01, 0x01, 0x01, 0x00, // padding 0x1B, 0x30, // flags 0x08, 0x00, // max stack 0x0A, 0x00, 0x00, 0x00, // code size 0x00, 0x00, 0x00, 0x00, // local sig 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, // exception table 0x00, 0x00, // padding 0x41, // kind 0xF4, 0xFF, 0xFF // size fo the table }, streamBuilder.ToArray()); } [Fact] public unsafe void TinyBody() { var streamBuilder = new BlobBuilder(); var codeBuilder = new BlobBuilder(); var flowBuilder = new ControlFlowBuilder(); var il = new InstructionEncoder(codeBuilder, flowBuilder); codeBuilder.WriteBytes(1, 61); var l1 = il.DefineLabel(); il.MarkLabel(l1); Assert.Equal(61, flowBuilder.Labels.Single()); il.Branch(ILOpCode.Br_s, l1); var brInfo = flowBuilder.Branches.Single(); Assert.Equal(61, brInfo.ILOffset); Assert.Equal(l1, brInfo.Label); Assert.Equal(ILOpCode.Br_s, brInfo.OpCode); AssertEx.Equal(new byte[] { 1, (byte)ILOpCode.Br_s, unchecked((byte)-1) }, codeBuilder.ToArray(60, 3)); var streamEncoder = new MethodBodyStreamEncoder(streamBuilder); int bodyOffset = streamEncoder.AddMethodBody( il, maxStack: 2, localVariablesSignature: default, attributes: MethodBodyAttributes.None); var bodyBytes = streamBuilder.ToArray(); AssertEx.Equal(new byte[] { 0xFE, // tiny header 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x2B, 0xFE }, bodyBytes); fixed (byte* bodyPtr = &bodyBytes[0]) { var body = MethodBodyBlock.Create(new BlobReader(bodyPtr, bodyBytes.Length)); Assert.Equal(0, body.ExceptionRegions.Length); Assert.Equal(default, body.LocalSignature); Assert.False(body.LocalVariablesInitialized); Assert.Equal(8, body.MaxStack); Assert.Equal(bodyBytes.Length, body.Size); var ilBytes = body.GetILBytes(); AssertEx.Equal(new byte[] { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x2B, 0xFE }, ilBytes); } } [Fact] public unsafe void FatBody() { var streamBuilder = new BlobBuilder(); var codeBuilder = new BlobBuilder(); var flowBuilder = new ControlFlowBuilder(); var il = new InstructionEncoder(codeBuilder, flowBuilder); codeBuilder.WriteBytes(1, 62); var l1 = il.DefineLabel(); il.MarkLabel(l1); Assert.Equal(62, flowBuilder.Labels.Single()); il.Branch(ILOpCode.Br_s, l1); var brInfo = flowBuilder.Branches.Single(); Assert.Equal(62, brInfo.ILOffset); Assert.Equal(l1, brInfo.Label); Assert.Equal(ILOpCode.Br_s, brInfo.OpCode); AssertEx.Equal(new byte[] { 1, 1, (byte)ILOpCode.Br_s, unchecked((byte)-1) }, codeBuilder.ToArray(60, 4)); var streamEncoder = new MethodBodyStreamEncoder(streamBuilder); int bodyOffset = streamEncoder.AddMethodBody( il, maxStack: 2, localVariablesSignature: default, attributes: MethodBodyAttributes.None); var bodyBytes = streamBuilder.ToArray(); AssertEx.Equal(new byte[] { 0x03, 0x30, 0x02, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // fat header 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x2B, 0xFE }, bodyBytes); fixed (byte* bodyPtr = &bodyBytes[0]) { var body = MethodBodyBlock.Create(new BlobReader(bodyPtr, bodyBytes.Length)); Assert.Equal(0, body.ExceptionRegions.Length); Assert.Equal(default, body.LocalSignature); Assert.False(body.LocalVariablesInitialized); Assert.Equal(2, body.MaxStack); Assert.Equal(bodyBytes.Length, body.Size); var ilBytes = body.GetILBytes(); AssertEx.Equal(new byte[] { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x2B, 0xFE }, ilBytes); } } [Fact, ActiveIssue(26910)] public unsafe void LocAlloc() { var streamBuilder = new BlobBuilder(); var codeBuilder = new BlobBuilder(); var flowBuilder = new ControlFlowBuilder(); var il = new byte[] { 0x1A, // ldc.i4.0 0xFE, 0x0F, // localloc 0x28, 0x01, 0x00, 0x00, 0x06, // call 0x06000001 0x2A // ret }; var streamEncoder = new MethodBodyStreamEncoder(streamBuilder); var methodBody = streamEncoder.AddMethodBody( il.Length, maxStack: 2, localVariablesSignature: default, attributes: MethodBodyAttributes.InitLocals, hasDynamicStackAllocation: true); Assert.Equal(0, methodBody.Offset); Assert.Null(methodBody.ExceptionRegions.Builder); Assert.False(methodBody.ExceptionRegions.HasSmallFormat); new BlobWriter(methodBody.Instructions).WriteBytes(il); var bodyBytes = streamBuilder.ToArray(); AssertEx.Equal(new byte[] { 0x13, 0x30, // flags and header size 0x02, 0x00, // max stack 0x09, 0x00, 0x00, 0x00, // code size 0x00, 0x00, 0x00, 0x00, // local variable signature 0x1A, // ldc.i4.0 0xFE, 0x0F, // localloc 0x28, 0x01, 0x00, 0x00, 0x06, // call 0x06000001 0x2A // ret }, bodyBytes); } [Fact, ActiveIssue(26910)] public unsafe void LocAlloc_WithInstructionEncoder() { var streamBuilder = new BlobBuilder(); var codeBuilder = new BlobBuilder(); var flowBuilder = new ControlFlowBuilder(); var il = new InstructionEncoder(codeBuilder, flowBuilder); il.OpCode(ILOpCode.Ldc_i4_4); il.OpCode(ILOpCode.Localloc); il.Call(MetadataTokens.MethodDefinitionHandle(1)); il.OpCode(ILOpCode.Ret); var streamEncoder = new MethodBodyStreamEncoder(streamBuilder); int bodyOffset = streamEncoder.AddMethodBody( il, maxStack: 2, localVariablesSignature: default, attributes: MethodBodyAttributes.InitLocals, hasDynamicStackAllocation: true); var bodyBytes = streamBuilder.ToArray(); AssertEx.Equal(new byte[] { 0x13, 0x30, // flags and header size 0x02, 0x00, // max stack 0x09, 0x00, 0x00, 0x00, // code size 0x00, 0x00, 0x00, 0x00, // local variable signature 0x1A, // ldc.i4.0 0xFE, 0x0F, // localloc 0x28, 0x01, 0x00, 0x00, 0x06, // call 0x06000001 0x2A // ret }, bodyBytes); fixed (byte* bodyPtr = &bodyBytes[0]) { var body = MethodBodyBlock.Create(new BlobReader(bodyPtr, bodyBytes.Length)); Assert.Equal(0, body.ExceptionRegions.Length); Assert.Equal(default, body.LocalSignature); Assert.Equal(2, body.MaxStack); Assert.True(body.LocalVariablesInitialized); Assert.Equal(bodyBytes.Length, body.Size); var ilBytes = body.GetILBytes(); AssertEx.Equal(new byte[] { 0x1A, // ldc.i4.0 0xFE, 0x0F, // localloc 0x28, 0x01, 0x00, 0x00, 0x06, // call 0x06000001 0x2A // ret }, ilBytes); } } [Fact] public void Branches1() { var flowBuilder = new ControlFlowBuilder(); var l0 = flowBuilder.AddLabel(); var l64 = flowBuilder.AddLabel(); var l255 = flowBuilder.AddLabel(); flowBuilder.MarkLabel(0, l0); flowBuilder.MarkLabel(64, l64); flowBuilder.MarkLabel(255, l255); flowBuilder.AddBranch(0, l255, ILOpCode.Bge); flowBuilder.AddBranch(16, l0, ILOpCode.Bge_un_s); // blob boundary flowBuilder.AddBranch(33, l255, ILOpCode.Ble); // blob boundary flowBuilder.AddBranch(38, l0, ILOpCode.Ble_un_s); // branches immediately next to each other flowBuilder.AddBranch(40, l255, ILOpCode.Blt); // branches immediately next to each other flowBuilder.AddBranch(46, l64, ILOpCode.Blt_un_s); flowBuilder.AddBranch(254, l0, ILOpCode.Brfalse); // long branch at the end var dstBuilder = new BlobBuilder(); var srcBuilder = new BlobBuilder(capacity: 17); WriteFakeILWithBranches(srcBuilder, flowBuilder, size: 259); flowBuilder.CopyCodeAndFixupBranches(srcBuilder, dstBuilder); AssertEx.Equal(new byte[] { (byte)ILOpCode.Bge, 0xFA, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, (byte)ILOpCode.Bge_un_s, 0xEE, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, (byte)ILOpCode.Ble, 0xD9, 0x00, 0x00, 0x00, (byte)ILOpCode.Ble_un_s, 0xD8, (byte)ILOpCode.Blt, 0xD2, 0x00, 0x00, 0x00, 0x01, (byte)ILOpCode.Blt_un_s, 0x10, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, (byte)ILOpCode.Brfalse, 0xFD, 0xFE, 0xFF, 0xFF, }, dstBuilder.ToArray()); } [Fact] public void BranchErrors() { var codeBuilder = new BlobBuilder(); var il = new InstructionEncoder(codeBuilder); Assert.Throws<InvalidOperationException>(() => il.DefineLabel()); il = new InstructionEncoder(codeBuilder, new ControlFlowBuilder()); il.DefineLabel(); il.DefineLabel(); var l2 = il.DefineLabel(); var flowBuilder = new ControlFlowBuilder(); il = new InstructionEncoder(codeBuilder, flowBuilder); var l0 = il.DefineLabel(); AssertExtensions.Throws<ArgumentException>("opCode", () => il.Branch(ILOpCode.Nop, l0)); Assert.Throws<ArgumentNullException>(() => il.Branch(ILOpCode.Br, default(LabelHandle))); AssertExtensions.Throws<ArgumentException>("label", () => il.Branch(ILOpCode.Br, l2)); } [Fact] public void BranchErrors_UnmarkedLabel() { var streamBuilder = new BlobBuilder(); var codeBuilder = new BlobBuilder(); var flowBuilder = new ControlFlowBuilder(); var il = new InstructionEncoder(codeBuilder, flowBuilder); var l = il.DefineLabel(); il.Branch(ILOpCode.Br_s, l); il.OpCode(ILOpCode.Ret); Assert.Throws<InvalidOperationException>(() => new MethodBodyStreamEncoder(streamBuilder).AddMethodBody(il)); } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Net.HttpListenerResponse // // Author: // Gonzalo Paniagua Javier (gonzalo@novell.com) // // Copyright (c) 2005 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Globalization; using System.IO; using System.Text; namespace System.Net { public sealed partial class HttpListenerResponse : IDisposable { private long _contentLength; private Version _version = HttpVersion.Version11; private int _statusCode = 200; internal object _headersLock = new object(); private bool _forceCloseChunked; internal HttpListenerResponse(HttpListenerContext context) { _httpContext = context; } internal bool ForceCloseChunked => _forceCloseChunked; private void EnsureResponseStream() { if (_responseStream == null) { _responseStream = _httpContext.Connection.GetResponseStream(); } } public Version ProtocolVersion { get => _version; set { CheckDisposed(); if (value == null) { throw new ArgumentNullException(nameof(value)); } if (value.Major != 1 || (value.Minor != 0 && value.Minor != 1)) { throw new ArgumentException(SR.net_wrongversion, nameof(value)); } _version = new Version(value.Major, value.Minor); // match Windows behavior, trimming to just Major.Minor } } public int StatusCode { get => _statusCode; set { CheckDisposed(); if (value < 100 || value > 999) throw new ProtocolViolationException(SR.net_invalidstatus); _statusCode = value; } } private void Dispose() => Close(true); public void Close() { if (Disposed) return; Close(false); } public void Abort() { if (Disposed) return; Close(true); } private void Close(bool force) { Disposed = true; _httpContext.Connection.Close(force); } public void Close(byte[] responseEntity, bool willBlock) { CheckDisposed(); if (responseEntity == null) { throw new ArgumentNullException(nameof(responseEntity)); } if (!SentHeaders && _boundaryType != BoundaryType.Chunked) { ContentLength64 = responseEntity.Length; } if (willBlock) { try { OutputStream.Write(responseEntity, 0, responseEntity.Length); } finally { Close(false); } } else { OutputStream.BeginWrite(responseEntity, 0, responseEntity.Length, iar => { var thisRef = (HttpListenerResponse)iar.AsyncState; try { thisRef.OutputStream.EndWrite(iar); } finally { thisRef.Close(false); } }, this); } } public void CopyFrom(HttpListenerResponse templateResponse) { _webHeaders.Clear(); _webHeaders.Add(templateResponse._webHeaders); _contentLength = templateResponse._contentLength; _statusCode = templateResponse._statusCode; _statusDescription = templateResponse._statusDescription; _keepAlive = templateResponse._keepAlive; _version = templateResponse._version; } internal void SendHeaders(bool closing, MemoryStream ms, bool isWebSocketHandshake = false) { if (!isWebSocketHandshake) { if (_webHeaders[HttpKnownHeaderNames.Server] == null) { _webHeaders.Set(HttpKnownHeaderNames.Server, HttpHeaderStrings.NetCoreServerName); } if (_webHeaders[HttpKnownHeaderNames.Date] == null) { _webHeaders.Set(HttpKnownHeaderNames.Date, DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture)); } if (_boundaryType == BoundaryType.None) { if (HttpListenerRequest.ProtocolVersion <= HttpVersion.Version10) { _keepAlive = false; } else { _boundaryType = BoundaryType.Chunked; } if (CanSendResponseBody(_httpContext.Response.StatusCode)) { _contentLength = -1; } else { _boundaryType = BoundaryType.ContentLength; _contentLength = 0; } } if (_boundaryType != BoundaryType.Chunked) { if (_boundaryType != BoundaryType.ContentLength && closing) { _contentLength = CanSendResponseBody(_httpContext.Response.StatusCode) ? -1 : 0; } if (_boundaryType == BoundaryType.ContentLength) { _webHeaders.Set(HttpKnownHeaderNames.ContentLength, _contentLength.ToString("D", CultureInfo.InvariantCulture)); } } /* Apache forces closing the connection for these status codes: * HttpStatusCode.BadRequest 400 * HttpStatusCode.RequestTimeout 408 * HttpStatusCode.LengthRequired 411 * HttpStatusCode.RequestEntityTooLarge 413 * HttpStatusCode.RequestUriTooLong 414 * HttpStatusCode.InternalServerError 500 * HttpStatusCode.ServiceUnavailable 503 */ bool conn_close = (_statusCode == (int)HttpStatusCode.BadRequest || _statusCode == (int)HttpStatusCode.RequestTimeout || _statusCode == (int)HttpStatusCode.LengthRequired || _statusCode == (int)HttpStatusCode.RequestEntityTooLarge || _statusCode == (int)HttpStatusCode.RequestUriTooLong || _statusCode == (int)HttpStatusCode.InternalServerError || _statusCode == (int)HttpStatusCode.ServiceUnavailable); if (!conn_close) { conn_close = !_httpContext.Request.KeepAlive; } // They sent both KeepAlive: true and Connection: close if (!_keepAlive || conn_close) { _webHeaders.Set(HttpKnownHeaderNames.Connection, HttpHeaderStrings.Close); conn_close = true; } if (SendChunked) { _webHeaders.Set(HttpKnownHeaderNames.TransferEncoding, HttpHeaderStrings.Chunked); } int reuses = _httpContext.Connection.Reuses; if (reuses >= 100) { _forceCloseChunked = true; if (!conn_close) { _webHeaders.Set(HttpKnownHeaderNames.Connection, HttpHeaderStrings.Close); conn_close = true; } } if (HttpListenerRequest.ProtocolVersion <= HttpVersion.Version10) { if (_keepAlive) { Headers[HttpResponseHeader.KeepAlive] = "true"; } if (!conn_close) { _webHeaders.Set(HttpKnownHeaderNames.Connection, HttpHeaderStrings.KeepAlive); } } ComputeCookies(); } Encoding encoding = Encoding.Default; StreamWriter writer = new StreamWriter(ms, encoding, 256); writer.Write("HTTP/1.1 {0} ", _statusCode); // "1.1" matches Windows implementation, which ignores the response version writer.Flush(); byte[] statusDescriptionBytes = WebHeaderEncoding.GetBytes(StatusDescription); ms.Write(statusDescriptionBytes, 0, statusDescriptionBytes.Length); writer.Write("\r\n"); writer.Write(FormatHeaders(_webHeaders)); writer.Flush(); int preamble = encoding.GetPreamble().Length; EnsureResponseStream(); /* Assumes that the ms was at position 0 */ ms.Position = preamble; SentHeaders = !isWebSocketHandshake; } private static bool HeaderCanHaveEmptyValue(string name) => !string.Equals(name, HttpKnownHeaderNames.Location, StringComparison.OrdinalIgnoreCase); private static string FormatHeaders(WebHeaderCollection headers) { var sb = new StringBuilder(); for (int i = 0; i < headers.Count; i++) { string key = headers.GetKey(i); string[] values = headers.GetValues(i); int startingLength = sb.Length; sb.Append(key).Append(": "); bool anyValues = false; for (int j = 0; j < values.Length; j++) { string value = values[j]; if (!string.IsNullOrWhiteSpace(value)) { if (anyValues) { sb.Append(", "); } sb.Append(value); anyValues = true; } } if (anyValues || HeaderCanHaveEmptyValue(key)) { // Complete the header sb.Append("\r\n"); } else { // Empty header; remove it. sb.Length = startingLength; } } return sb.Append("\r\n").ToString(); } private bool Disposed { get; set; } internal bool SentHeaders { get; set; } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using SDKTemplate; using System; using System.Text; namespace TextSegmentation { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class Scenario2_GetCurrentTextSegmentFromIndex { // A pointer back to the main page. This is needed if you want to call methods in MainPage such // as NotifyUser() MainPage rootPage = MainPage.Current; public Scenario2_GetCurrentTextSegmentFromIndex() { this.InitializeComponent(); } /// <summary> /// This is the click handler for the 'Word Segments' button. /// /// When this button is activated, the Text Segmentation API will calculate /// the word segment from the given input string and character index for that string, /// and return the WordSegment object that contains the index within its text bounds. /// Segment breaking behavior is based off of the language-tag input, which defines /// which language rules to use. /// /// </summary> /// <param name="sender">The object that raised the event.</param> /// <param name="e">Event data that describes the click action on the button.</param> private void WordSegmentButton_Click(object sender, RoutedEventArgs e) { // Initialize and obtain input values StringBuilder notifyText = new StringBuilder(); // Obtain the input string value, check for non-emptiness String inputStringText = inputStringBox.Text; if (String.IsNullOrEmpty(inputStringText)) { notifyText = new StringBuilder("Cannot compute word segments: input string is empty."); rootPage.NotifyUser(notifyText.ToString(), NotifyType.ErrorMessage); return; } // Obtain the language tag value, check for non-emptiness // Ex. Valid Values: // "en-US" (English (United States)) // "fr-FR" (French (France)) // "de-DE" (German (Germany)) // "ja-JP" (Japanese (Japan)) // "ar-SA" (Arabic (Saudi Arabia)) // "zh-CN" (China (PRC)) String languageTagText = languageTagBox.Text; if (String.IsNullOrEmpty(languageTagText)) { notifyText.AppendLine("Language tag input is empty ... using generic-language segmentation rules."); languageTagText = "und"; // This is used for non language-specific locales. 'und' is short for 'undetermined'. } else { if (!Windows.Globalization.Language.IsWellFormed(languageTagText)) { notifyText = new StringBuilder("Language tag is not well formed: \"" + languageTagText + "\""); rootPage.NotifyUser(notifyText.ToString(), NotifyType.ErrorMessage); return; } } // Obtain the input Index String inputIndexString = indexBox.Text; uint inputIndex = 0; if (String.IsNullOrEmpty(inputIndexString)) { notifyText.AppendLine("No input index provided ... using first segment reference (index = 0) as default."); } else { try { inputIndex = Convert.ToUInt32(indexBox.Text); } catch (FormatException) { notifyText = new StringBuilder("Invalid index supplied.\n\nPlease check that this value is valid, and non-negative."); rootPage.NotifyUser(notifyText.ToString(), NotifyType.ErrorMessage); return; } catch (OverflowException) { notifyText = new StringBuilder("Invalid index supplied: Negative-valued index.\n\nPlease check that this value is valid, and non-negative."); rootPage.NotifyUser(notifyText.ToString(), NotifyType.ErrorMessage); return; } if ((inputIndex < 0) || (inputIndex >= inputStringText.Length)) { notifyText = new StringBuilder("Invalid index supplied ... cannot use a negative index, or an index that is out of bounds of the input string.\n\nPlease re-check the index value, and try again."); rootPage.NotifyUser(notifyText.ToString(), NotifyType.ErrorMessage); return; } } // Notify that we are going to calculate word segment notifyText.AppendLine("\nFinding the word segment for the given index ...\n"); notifyText.AppendLine("Input: \"" + inputStringText + "\""); notifyText.AppendLine("Language Tag: \"" + languageTagText + "\""); notifyText.AppendLine("Index: " + inputIndex + "\n"); // Construct the WordsSegmenter instance var segmenter = new Windows.Data.Text.WordsSegmenter(languageTagText); // Obtain the token segment var tokenSegment = segmenter.GetTokenAt(inputStringText, inputIndex); notifyText.AppendLine("Indexed segment: \"" + tokenSegment.Text + "\""); // Set output box text to the contents of the StringBuilder instance rootPage.NotifyUser(notifyText.ToString(), NotifyType.StatusMessage); } /// <summary> /// This is the click handler for the 'Selection Segment' button. /// /// When this button is activated, the Text Segmentation API will calculate /// the selection segment from the given input string and character index for that string, /// and return the SelectableWordSegment object that contains the index within its text bounds. /// Segment breaking behavior is based off of the language-tag input, which defines /// which language rules to use. /// /// Selection segments differ from word segments in that they describe the bounds /// between active-selection snapping behavior. /// /// </summary> /// <param name="sender">The object that raised the event.</param> /// <param name="e">Event data that describes the click action on the button.</param> private void SelectionSegmentButton_Click(object sender, RoutedEventArgs e) { // Initialize and obtain input values StringBuilder notifyText = new StringBuilder(); // Obtain the input string value, check for non-emptiness String inputStringText = inputStringBox.Text; if (String.IsNullOrEmpty(inputStringText)) { notifyText = new StringBuilder("Cannot compute selection segments: input string is empty."); rootPage.NotifyUser(notifyText.ToString(), NotifyType.ErrorMessage); return; } // Obtain the language tag value, check for non-emptiness // Ex. Valid Values: // "en-US" (English (United States)) // "fr-FR" (French (France)) // "de-DE" (German (Germany)) // "ja-JP" (Japanese (Japan)) // "ar-SA" (Arabic (Saudi Arabia)) // "zh-CN" (China (PRC)) String languageTagText = languageTagBox.Text; if (String.IsNullOrEmpty(languageTagText)) { notifyText.AppendLine("Language tag input is empty ... using generic-language segmentation rules."); languageTagText = "und"; // This is used for non language-specific locales. 'und' is short for 'undetermined'. } else { if (!Windows.Globalization.Language.IsWellFormed(languageTagText)) { notifyText = new StringBuilder("Language tag is not well formed: \"" + languageTagText + "\""); rootPage.NotifyUser(notifyText.ToString(), NotifyType.ErrorMessage); return; } } // Obtain the input Index String inputIndexString = indexBox.Text; uint inputIndex = 0; if (String.IsNullOrEmpty(inputIndexString)) { notifyText.AppendLine("No input index provided ... using first segment reference (index = 0) as default."); } else { try { inputIndex = Convert.ToUInt32(indexBox.Text); } catch (FormatException) { notifyText = new StringBuilder("Invalid index supplied.\n\nPlease check that this value is valid, and non-negative."); rootPage.NotifyUser(notifyText.ToString(), NotifyType.ErrorMessage); return; } catch (OverflowException) { notifyText = new StringBuilder("Invalid index supplied: Negative-valued index.\n\nPlease check that this value is valid, and non-negative."); rootPage.NotifyUser(notifyText.ToString(), NotifyType.ErrorMessage); return; } if ((inputIndex < 0) || (inputIndex >= inputStringText.Length)) { notifyText = new StringBuilder("Invalid index supplied ... cannot use a negative index, or an index that is out of bounds of the input string.\n\nPlease re-check the index value, and try again."); rootPage.NotifyUser(notifyText.ToString(), NotifyType.ErrorMessage); return; } } // Notify that we are going to calculate selection segment notifyText.AppendLine("\nFinding the selection segment for the given index ...\n"); notifyText.AppendLine("Input: \"" + inputStringText + "\""); notifyText.AppendLine("Language Tag: \"" + languageTagText + "\""); notifyText.AppendLine("Index: " + inputIndex + "\n"); // Construct the SelectableWordsSegmenter instance var segmenter = new Windows.Data.Text.SelectableWordsSegmenter(languageTagText); // Obtain the token segment var tokenSegment = segmenter.GetTokenAt(inputStringText, inputIndex); notifyText.AppendLine("Indexed segment: \"" + tokenSegment.Text + "\""); // Set output box text to the contents of the StringBuilder instance rootPage.NotifyUser(notifyText.ToString(), NotifyType.StatusMessage); } } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using System.Globalization; namespace WebApplication2 { /// <summary> /// Summary description for frmEmergencyProcedures. /// </summary> public partial class frmContractProcures : System.Web.UI.Page { private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; protected System.Web.UI.WebControls.Label Label2; public SqlConnection epsDbConn = new SqlConnection(strDB); char StateTypesName; private int GetIndexOfLocations(string s) { return (rblLocs.Items.IndexOf(rblLocs.Items.FindByValue(s))); } protected void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if (!IsPostBack) { lblOrg.Text = Session["OrgName"].ToString(); lblContract.Text = "Contract/Commitment Title: " + Session["ContractTitle"].ToString(); if (Session["MgrOption"].ToString() == "Procure") { GridDeliver.Columns[8].Visible = false; GridDeliver.Columns[2].HeaderText = " Delivery Location "; lblContents1.Text = "Listed below are the procurement items to be acquired as part of contract" + " titled '" + Session["ContractTitle"].ToString() + "' from the following supplier: '" + Session["ContractSupplier"].ToString() + "'." + " To add items being procured through each contract," + " click on 'Add'." + " To remove an item from this list, click on 'Remove'."; GridProcure.Columns[0].Visible = false; GridProcure.Columns[1].Visible = false; GridProcure.Columns[6].HeaderText = " Price (in " + Session["CurrName"].ToString() + ")"; GridProcure.Columns[7].Visible = false; GridProcure.Columns[8].Visible = false; GridProcure.Columns[9].Visible = false; loadProcure(); GridProcure.Visible = true; GridProcureS.Columns[0].Visible = false; GridProcureS.Columns[1].Visible = false; GridProcureS.Columns[6].HeaderText = " Cost (in " + Session["CurrName"].ToString() + ")"; GridProcureS.Columns[7].Visible = false; GridProcureS.Columns[8].Visible = false; GridProcureS.Columns[9].Visible = false; loadProcureS(); GridProcureS.Visible = true; } else if (Session["MgrOption"].ToString() == "Deliver") { lblContents1.Text = "Listed below are the types of resources to be made made" + " available as part of this commitment"; GridDeliver.Columns[1].Visible = false; GridDeliver.Columns[2].Visible = false; loadDeliver(); } } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.GridDeliver.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.GridDeliver_ItemCommand); } #endregion /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ /********************************* PART I Procure********************************************/ /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ private void loadProcure() { Session["Part"] = "Procure"; GridProcure.Visible = true; lblContents1.Visible = true; SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_RetrievePSEPResInvG"; cmd.Parameters.Add("@ContractId", SqlDbType.Int); cmd.Parameters["@ContractId"].Value = Session["ContractId"].ToString(); cmd.Connection = this.epsDbConn; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "ConItems"); if (ds.Tables["ConItems"].Rows.Count == 0) { lblContents1.Text = "There are no procurement items identified for this contract." + " Click on 'Add' to identify outstanding procurement requests (if any) that you may" + " acquire as part of this contract"; GridDeliver.Visible = false; GridProcure.Visible = false; } else { Session["ds"] = ds; GridProcure.DataSource = ds; GridProcure.DataBind(); refreshGridG(); } } private void refreshGridG() { foreach (DataGridItem i in GridProcure.Items) { TextBox tQ = (TextBox)(i.Cells[4].FindControl("txtQty")); TextBox tP = (TextBox)(i.Cells[6].FindControl("txtPrice")); if (i.Cells[8].Text.StartsWith("&") == false) { tQ.Text = i.Cells[8].Text; } if (i.Cells[9].Text.StartsWith("&") == false) { tP.Text = i.Cells[9].Text; } } } private void loadProcureS() { Session["Part"] = "Procure"; GridProcure.Visible = true; lblContents1.Visible = true; SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_RetrievePSEPResInvS"; cmd.Parameters.Add("@ContractId", SqlDbType.Int); cmd.Parameters["@ContractId"].Value = Session["ContractId"].ToString(); cmd.Connection = this.epsDbConn; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "ConItems"); if (ds.Tables["ConItems"].Rows.Count == 0) { lblContents1.Text = "There are no procurement items identified for this contract." + " Click on 'Add' to identify outstanding procurement requests (if any) that you may" + " acquire as part of this contract"; GridProcureS.Visible = false; } else { Session["ds"] = ds; GridProcureS.DataSource = ds; GridProcureS.DataBind(); refreshGridS(); } } private void refreshGridS() { foreach (DataGridItem i in GridProcureS.Items) { TextBox tP = (TextBox)(i.Cells[6].FindControl("txtCost")); if (i.Cells[9].Text.StartsWith("&") == false) { tP.Text = i.Cells[9].Text; } } } /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ /********************************* PART II Deliver ******************************************/ /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ /********************************************************************************************/ /********** Section Deliver: List Supplies provided under contract ****************************/ /********************************************************************************************/ private void loadDeliver() { Session["Part"] = "Deliver"; GridDeliver.Visible = true; lblContents1.Visible = true; SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_RetrieveContractSupplies"; cmd.Parameters.Add("@ContractId", SqlDbType.Int); cmd.Parameters["@ContractId"].Value = Session["ContractId"].ToString(); cmd.Connection = this.epsDbConn; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "ConItems"); if (ds.Tables["ConItems"].Rows.Count == 0) { lblContents1.Text = "There are no supply items identified for the above contract or commitment." + " Click on 'Add' to identify the identify the resources you wish to supply as part of this contract or " + " contract"; GridDeliver.Visible = false; } Session["ds"] = ds; GridDeliver.DataSource = ds; GridDeliver.DataBind(); refreshGridDeliver(); } private void refreshGridDeliver() { foreach (DataGridItem i in GridDeliver.Items) { Button btLoc = (Button)(i.Cells[8].FindControl("btnLocations")); if (i.Cells[10].Text == "1") { btLoc.Enabled = false; btLoc.Text = "Anywhere"; } } } /********************************************************************************************/ /********************************************* ADD SUPPLIES UNDER CONTRACT *****************/ /********************************************************************************************/ protected void btnAdd_Click(object sender, System.EventArgs e) { if (Session["MgrOption"].ToString() == "Procure") { Session["CCPAll"] = "frmContractProcures"; Response.Redirect(strURL + "frmContractProcuresAll.aspx?"); } else if (Session["MgrOption"].ToString() == "Deliver") { if (Session["Part"].ToString() == "Deliver") { Session["RType"] = null; Session["TableFlag"] = "1"; Session["CallerRTA"] = "frmContractProcures"; Response.Redirect(strURL + "frmResourceTypesAll.aspx?"); } else if (Session["Part"].ToString() == "SCountries") { DataGrid2.Visible = false; Countries(); } else if (Session["Part"].ToString() == "SStates") { DataGrid4.Visible = false; States(); } else if (Session["Part"].ToString() == "SLocs") { DataGrid4.Visible = false; Locs(); } else if (Session["Part"].ToString() == "Locs") { DataGrid4.Visible = false; LocsAdd(); } else if (Session["Part"].ToString() == "LocsAdd") { addLocation(); Locs(); } } } //INSERT ITEMCOMMANDGRIDDELIVERHRE private void loadCSCountries() { Session["Part"] = "SCountries"; btnAdd.Text = "Add Countries"; lblContents2.Visible = true; SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_RetrieveContractSuppliesCountries"; cmd.Parameters.Add("@ContractSuppliesId", SqlDbType.Int); cmd.Parameters["@ContractSuppliesId"].Value = Int32.Parse(Session["Id"].ToString()); cmd.Connection = this.epsDbConn; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "ServiceCtrys"); if (ds.Tables["ServiceCtrys"].Rows.Count == 0) { DataGrid2.Visible = false; lblContents2.Text = "You have not yet identified any country where the above service is avaiable. " + " Click on the button titled 'Add Countries' to continue. If the service is available " + " from anywhere, click on 'OK', to return to the previous menu. From there select " + " 'Details' for this service to indicate that the service is available from any location."; } else { Session["ds"] = ds; DataGrid2.DataSource = ds; DataGrid2.DataBind(); DataGrid2.Visible = true; lblContents2.Text = "The list below shows the country (or countries) where you have indicated the " + " above service as being available. If the service is available only at selected locations" + " within a given country, click on the button to its right titled 'State' or 'Province' to " + "continue."; refreshGrid2(); } } private void refreshGrid2() { foreach (DataGridItem j in DataGrid2.Items) { CheckBox cb = (CheckBox)(j.Cells[2].FindControl("cbxSel")); Button bt = (Button)(j.Cells[3].FindControl("btnStates")); Button btL = (Button)(j.Cells[3].FindControl("btnLocs")); if (j.Cells[5].Text == "1") { cb.Checked = true; if (j.Cells[8].Text == "1") { bt.Text = "Entire Country"; bt.Enabled = false; } else { btL.Text = "Entire Country"; btL.Enabled = false; } } else { if (j.Cells[8].Text == "1") { bt.Text = j.Cells[6].Text; bt.Enabled = true; btL.Visible = false; } else { bt.Visible = false; } } } } private void refreshGrid2a() { foreach (DataGridItem j in DataGrid2.Items) { CheckBox cb = (CheckBox)(j.Cells[2].FindControl("cbxSel")); Button bt = (Button)(j.Cells[3].FindControl("btnStates")); Button btL = (Button)(j.Cells[3].FindControl("btnLocs")); if (cb.Checked) { if (j.Cells[8].Text == "1") { bt.Text = "Entire Country"; bt.Enabled = false; } else { btL.Text = "Entire Country"; btL.Enabled = false; } } else { if (j.Cells[8].Text == "1") { bt.Text = j.Cells[6].Text; bt.Enabled = true; } else { btL.Text = "Locations"; btL.Enabled = true; } } } } protected void cbxSel_CheckedChanged(object sender, EventArgs e) { refreshGrid2a(); } private void updateCSCountries() { foreach (DataGridItem j in DataGrid2.Items) { CheckBox cb = (CheckBox)(j.Cells[2].FindControl("cbxSel")); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_UpdateCSCountriesFlag"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@Id", SqlDbType.Int); cmd.Parameters["@Id"].Value = Int32.Parse(j.Cells[7].Text); if (cb.Checked) { cmd.Parameters.Add("@StatesFlag", SqlDbType.Int); cmd.Parameters["@StatesFlag"].Value = 1; } cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } /********************************************************************************************/ /********** Item Commands: Contract Service Countries*************************************************************/ /********************************************************************************************/ protected void DataGrid2_ItemCommand(object source, DataGridCommandEventArgs e) { if (e.CommandName == "Remove") { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_DeleteContractSuppliesCountries"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@CSCId", SqlDbType.Int); cmd.Parameters["@CSCId"].Value = e.Item.Cells[7].Text; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); updateCSCountries(); loadCSCountries(); } else if (e.CommandName == "States") { Session["CountriesId"] = Int32.Parse(e.Item.Cells[0].Text); DataGrid2.Visible = false; Session["CountryName"] = e.Item.Cells[1].Text; Session["States"] = e.Item.Cells[6].Text; updateCSCountries(); loadCSStates(); } else if (e.CommandName == "Locations") { Session["CountriesId"] = Int32.Parse(e.Item.Cells[0].Text); DataGrid2.Visible = false; Session["CountryName"] = e.Item.Cells[1].Text; updateCSCountries(); loadCSLocs(); } } /********************************************************************************************/ /********** Part: All Countries*************************************************************/ /********************************************************************************************/ private void Countries() { Session["Part"] = "Countries"; SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "wms_RetrieveCountries"; cmd.Connection = this.epsDbConn; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "Countries"); Session["ds"] = ds; DataGrid3.DataSource = ds; DataGrid3.DataBind(); DataGrid3.Visible = true; refreshGrid3(); } private void refreshGrid3() { foreach (DataGridItem k in DataGrid3.Items) { CheckBox cb = (CheckBox)(k.Cells[2].FindControl("cbxSel")); SqlCommand cmd = new SqlCommand(); cmd.Connection = this.epsDbConn; cmd.CommandType = CommandType.Text; if (Session["Part"].ToString() == "Countries") { cmd.CommandText = "Select Id from ContractSuppliesCountries" + " Where CountriesId = " + Int32.Parse(k.Cells[0].Text) + " and ContractSuppliesId =" + Int32.Parse(Session["Id"].ToString()); cmd.Connection.Open(); if (cmd.ExecuteScalar() != null) { cb.Checked = true; cb.Enabled = false; } cmd.Connection.Close(); } } } /********************************************************************************************/ /********** Part: Update Contract Service Countries *************************************************************/ /********************************************************************************************/ private void updateGrid3() { foreach (DataGridItem k in DataGrid3.Items) { CheckBox cb = (CheckBox)(k.Cells[2].FindControl("cbxSel")); if ((cb.Checked) & (cb.Enabled)) { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_UpdateContractSuppliesCountries"; if (Session["Part"].ToString() == "Countries") { cmd.Parameters.Add("@ContractSuppliesId", SqlDbType.Int); cmd.Parameters["@ContractSuppliesId"].Value = Session["Id"].ToString(); cmd.Parameters.Add("@CountriesId", SqlDbType.Int); cmd.Parameters["@CountriesId"].Value = k.Cells[0].Text; } cmd.Connection = this.epsDbConn; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } } /****END OF COUNTRIES ******************************************************** * * /********************************************************************************************/ /*********************** Part: Service States ***********************************************/ /********************************************************************************************/ private void loadCSStates() { Session["Part"] = "SStates"; lblCountryName.Text = "Country: " + Session["CountryName"].ToString(); lblStateName.Text = ""; btnAdd.Text = "Add " + Session["States"].ToString(); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_RetrieveContractSuppliesStates"; cmd.Parameters.Add("@ContractSuppliesId", SqlDbType.Int); cmd.Parameters["@ContractSuppliesId"].Value = Int32.Parse(Session["Id"].ToString()); cmd.Parameters.Add("@CountriesId", SqlDbType.Int); cmd.Parameters["@CountriesId"].Value = Int32.Parse(Session["CountriesId"].ToString()); cmd.Connection = this.epsDbConn; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "ServiceStates"); if (ds.Tables["ServiceStates"].Rows.Count == 0) { DataGrid4.Visible = false; lblContents2.Text = "You have not yet identified any " + Session["States"].ToString() + " where the above service is avaiable. " + " Click on the button titled 'Add " + Session["States"].ToString() + " ' to continue. If the service is available " + " from anywhere in the " + Session["States"].ToString() + ", click on 'OK', to return to the previous menu. From there select " + " 'Details' for this service to indicate that the service is available from any location."; } else { Session["ds"] = ds; DataGrid4.DataSource = ds; DataGrid4.DataBind(); DataGrid4.Visible = true; lblContents2.Text = "The list below shows the " + Session["States"].ToString() + " where you have indicated the " + " above service as being available."; refreshGrid4(); } } private void refreshGrid4() { foreach (DataGridItem j in DataGrid4.Items) { CheckBox cb = (CheckBox)(j.Cells[2].FindControl("cbxSelStates")); Button bt = (Button)(j.Cells[3].FindControl("btnLocs")); if (j.Cells[5].Text == "1") { cb.Checked = true; bt.Text = "All Locations"; bt.Enabled = false; } else { bt.Text = "Locations"; bt.Enabled = true; } } } private void refreshGrid4a() { foreach (DataGridItem j in DataGrid4.Items) { CheckBox cb = (CheckBox)(j.Cells[2].FindControl("cbxSelStates")); Button bt = (Button)(j.Cells[3].FindControl("btnLocs")); if (cb.Checked) { bt.Enabled = false; bt.Text = "All Locations"; } else { bt.Enabled = true; bt.Text = "Locations"; } } } protected void cbxSelStates_CheckedChanged(object sender, EventArgs e) { refreshGrid4a(); } private void updateCSStates() { foreach (DataGridItem j in DataGrid4.Items) { CheckBox cb = (CheckBox)(j.Cells[2].FindControl("cbxSelStates")); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_UpdateCSStatesFlag"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@Id", SqlDbType.Int); cmd.Parameters["@Id"].Value = Int32.Parse(j.Cells[6].Text); if (cb.Checked) { cmd.Parameters.Add("@LocsFlag", SqlDbType.Int); cmd.Parameters["@LocsFlag"].Value = 1; } cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } /********************************************************************************************/ /********** Item Commands: Contract Service States*************************************************************/ /********************************************************************************************/ protected void DataGrid4_ItemCommand(object source, DataGridCommandEventArgs e) { if (e.CommandName == "Remove") { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = this.epsDbConn; if (Session["Part"].ToString() == "SStates") { cmd.CommandText = "fms_DeleteContractSuppliesStates"; cmd.Parameters.Add("@CSSId", SqlDbType.Int); cmd.Parameters["@CSSId"].Value = Int32.Parse(e.Item.Cells[6].Text); } else if (Session["Part"].ToString() == "SLocs") { cmd.CommandText = "fms_DeleteContractSuppliesLocs"; cmd.Parameters.Add("@CSLId", SqlDbType.Int); cmd.Parameters["@CSLId"].Value = Int32.Parse(e.Item.Cells[6].Text); } cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); if (Session["Part"].ToString() == "States") { updateCSStates(); loadCSStates(); } else if (Session["Part"].ToString() == "SLocs") { loadCSLocs(); } } else if (e.CommandName == "Locs") { Session["StatesId"] = Int32.Parse(e.Item.Cells[0].Text); Session["StateName"] = e.Item.Cells[1].Text; updateCSStates();//sets ContractSuppliesStates.LocsFlag to indicate if service is statewide loadCSLocs(); } } /********************************************************************************************/ /********** Part: All States *************************************************************/ /********************************************************************************************/ private void States() { Session["Part"] = "States"; SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "wms_RetrieveStates"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@CountriesId", SqlDbType.Int); cmd.Parameters["@CountriesId"].Value = Int32.Parse(Session["CountriesId"].ToString()); DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "States"); if (ds.Tables["States"].Rows.Count == 0) { lblContents2.Text = "There are no " + Session["States"].ToString() + " identified for this country. Click on 'Add States' to Continue."; } else { Session["ds"] = ds; DataGrid5.DataSource = ds; DataGrid5.DataBind(); DataGrid5.Visible = true; refreshGrid5(); lblContents2.Text = "Please select" + Session["States"].ToString() + " where the above service is available"; } } private void refreshGrid5() { foreach (DataGridItem k in DataGrid5.Items) { CheckBox cb = (CheckBox)(k.Cells[2].FindControl("cbxSel")); SqlCommand cmd = new SqlCommand(); cmd.Connection = this.epsDbConn; cmd.CommandType = CommandType.Text; if (Session["Part"].ToString() == "States") { cmd.CommandText = "Select Id from ContractSuppliesStates" + " Where StatesId = " + Int32.Parse(k.Cells[0].Text) + " and ContractSuppliesId =" + Int32.Parse(Session["Id"].ToString()); } else if (Session["Part"].ToString() == "Locs") { cmd.CommandText = "Select Id from ContractSuppliesLocs" + " Where LocsId = " + Int32.Parse(k.Cells[0].Text) + " and ContractSuppliesId =" + Int32.Parse(Session["Id"].ToString()); } cmd.Connection.Open(); if (cmd.ExecuteScalar() != null) { cb.Checked = true; cb.Enabled = false; } cmd.Connection.Close(); } } /********************************************************************************************/ /********** Part: Update Contract Service States *************************************************************/ /********************************************************************************************/ private void updateGrid5() { foreach (DataGridItem k in DataGrid5.Items) { CheckBox cb = (CheckBox)(k.Cells[2].FindControl("cbxSel")); if ((cb.Checked) & (cb.Enabled)) { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; if (Session["Part"].ToString() == "States") { cmd.CommandText = "fms_UpdateContractSuppliesStates"; cmd.Parameters.Add("@StatesId", SqlDbType.Int); cmd.Parameters["@StatesId"].Value = k.Cells[0].Text; } else if (Session["Part"].ToString() == "Locs") { cmd.CommandText = "fms_UpdateContractSuppliesLocs"; cmd.Parameters.Add("@LocsId", SqlDbType.Int); cmd.Parameters["@LocsId"].Value = k.Cells[0].Text; } cmd.Parameters.Add("@ContractSuppliesId", SqlDbType.Int); cmd.Parameters["@ContractSuppliesId"].Value = Session["Id"].ToString(); cmd.Connection = this.epsDbConn; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } } /********************STATE ENDS HERE*********************************************************/ /********************************************************************************************/ /********************************************************************************************/ /*********************** Part: Service Locs ***********************************************/ /********************************************************************************************/ private void loadCSLocs() { Session["Part"] = "SLocs"; btnAdd.Text = "Add Locations"; lblCountryName.Text = "Country: " + Session["CountryName"].ToString(); if (Session["StatesId"] != null) { lblStateName.Text = Session["States"].ToString() + ": " + Session["StateName"].ToString(); } else { DataGrid4.Columns[1].HeaderText = "Locations"; } SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_RetrieveContractSuppliesLocs"; cmd.Parameters.Add("@ContractSuppliesId", SqlDbType.Int); cmd.Parameters["@ContractSuppliesId"].Value = Int32.Parse(Session["Id"].ToString()); if (Session["StatesId"] != null) { cmd.Parameters.Add("@StatesId", SqlDbType.Int); cmd.Parameters["@StatesId"].Value = Int32.Parse(Session["StatesId"].ToString()); } cmd.Parameters.Add("@CountriesId", SqlDbType.Int); cmd.Parameters["@CountriesId"].Value = Int32.Parse(Session["CountriesId"].ToString()); cmd.Connection = this.epsDbConn; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "ServiceLocs"); if (ds.Tables["ServiceLocs"].Rows.Count == 0) { DataGrid4.Visible = false; lblContents2.Text = "You have not yet identified any locations where the above service is avaiable. " + " Click on the button titled 'Add Locations' to continue."; } else { Session["ds"] = ds; DataGrid4.DataSource = ds; DataGrid4.DataBind(); DataGrid4.Columns[2].Visible = false; DataGrid4.Columns[3].Visible = false; DataGrid4.Visible = true; lblContents2.Text = "The list below shows the locations" + " where you have indicated the " + " above service as being available."; // refreshGrid4L(); } } /* private void refreshGrid4L() { foreach (DataGridItem j in DataGrid4.Items) { CheckBox cb = (CheckBox)(j.Cells[2].FindControl("cbxSelStates")); Button bt = (Button)(j.Cells[3].FindControl("btnLocs")); if (j.Cells[5].Text == "1") { cb.Checked = true; bt.Text = "All Locations"; bt.Enabled = false; } else { bt.Text = "Locations"; bt.Enabled = true; } } }*/ /********** Part: All Locations *************************************************************/ /********************************************************************************************/ private void Locs() { Session["Part"] = "Locs"; lblCountryName.Text = "Country: " + Session["CountryName"].ToString(); if (Session["StatesId"] != null) { lblStateName.Text = Session["States"].ToString() + ": " + Session["StateName"].ToString(); } btnAdd.Text = "Add Locations"; SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "wms_RetrieveLocs"; cmd.Connection = this.epsDbConn; if (Session["StatesId"] != null) { cmd.Parameters.Add("@StatesId", SqlDbType.Int); cmd.Parameters["@StatesId"].Value = Int32.Parse(Session["StatesId"].ToString()); } cmd.Parameters.Add("@CountriesId", SqlDbType.Int); cmd.Parameters["@CountriesId"].Value = Int32.Parse(Session["CountriesId"].ToString()); DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "Locs"); if (ds.Tables["Locs"].Rows.Count == 0) { lblContents2.Text = "There are no locations" + " identified. Click on 'Add Locations' to continue."; } else { Session["ds"] = ds; DataGrid5.DataSource = ds; DataGrid5.DataBind(); DataGrid5.Visible = true; refreshGrid5(); lblContents2.Text = "Please select all locations where the above service is available"; } } private void LocsAdd() { Session["Part"] = "LocsAdd"; btnAdd.Visible = false; lblURL.Text = "Please Enter the location name below"; lblURL.Visible = true; txtURL.Visible = true; } private void addLocation() { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_AddLoc"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Name",SqlDbType.NVarChar); cmd.Parameters["@Name"].Value= txtURL.Text; cmd.Parameters.Add ("@Desc",SqlDbType.NText); cmd.Parameters["@Desc"].Value= txtDesc.Text; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@Vis",SqlDbType.Int); cmd.Parameters["@Vis"].Value=0; if (Session["StatesId"] != null) { cmd.Parameters.Add("@StatesId", SqlDbType.Int); cmd.Parameters["@StatesId"].Value = Int32.Parse(Session["StatesId"].ToString()); } cmd.Parameters.Add("@CountriesId", SqlDbType.Int); cmd.Parameters["@CountriesId"].Value = Int32.Parse(Session["CountriesId"].ToString()); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } /********************************************************************************************/ /********************************************* EXIT ****************************************/ /********************************************************************************************/ /* private static void TryToParse(string value) { int number; bool result = Int32.TryParse(value, out number); if (result) { } else { //break; } }*/ protected void btnExit_Click(object sender, System.EventArgs e) { if (Session["Part"].ToString() == "Procure") { foreach (DataGridItem i in GridProcure.Items) { TextBox tQ = (TextBox)(i.Cells[4].FindControl("txtQty")); TextBox tP = (TextBox)(i.Cells[6].FindControl("txtPrice")); float Result; if (float.TryParse(tQ.Text.Trim(), out Result) == false) { lblContents1.Text = "Please enter valid number in the Column titled 'Quantity'."; break; } else if (float.TryParse(tP.Text.Trim(), out Result) == false) { lblContents1.Text = "Please enter valid number in the Column titled 'Price'."; break; } else { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_UpdatePSEPResInv"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@Id", SqlDbType.Int); cmd.Parameters["@Id"].Value = Int32.Parse(i.Cells[0].Text); cmd.Parameters.Add("@Qty", SqlDbType.Float); cmd.Parameters["@Qty"].Value = Int32.Parse(tQ.Text); cmd.Parameters.Add("@Price", SqlDbType.Float); cmd.Parameters["@Price"].Value = Int32.Parse(tP.Text); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } foreach (DataGridItem i in GridProcureS.Items) { TextBox tC = (TextBox)(i.Cells[2].FindControl("txtCost")); float Result; if (float.TryParse(tC.Text.Trim(), out Result) == false) { lblContents1.Text = "Please enter valid number in the Column titled 'Cost'."; break; } else { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_UpdatePSEPResInv"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@Id", SqlDbType.Int); cmd.Parameters["@Id"].Value = Int32.Parse(i.Cells[0].Text); cmd.Parameters.Add("@Price", SqlDbType.Float); cmd.Parameters["@Price"].Value = Int32.Parse(tC.Text); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } Exit(); } else if (Session["Part"].ToString() == "Deliver") { Session["Id"] = null; Session["CountriesId"] = null; Session["CountryName"] = null; Session["States"] = null; Session["StatesId"] = null; Session["StateName"] = null; Exit(); } else if (Session["Part"].ToString() == "Details") { btnAdd.Visible = true; SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "wms_UpdateContractSuppliesDesc"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@Id", SqlDbType.Int); cmd.Parameters["@Id"].Value = Int32.Parse(Session["Id"].ToString()); cmd.Parameters.Add("@Desc", SqlDbType.NText); cmd.Parameters["@Desc"].Value = txtDesc.Text; cmd.Parameters.Add("@URL", SqlDbType.NVarChar); cmd.Parameters["@URL"].Value = txtURL.Text; if (rblLocs.SelectedValue == "Any") { cmd.Parameters.Add("@LocsFlag", SqlDbType.Int); cmd.Parameters["@LocsFlag"].Value = 1; } cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); lblDesc.Visible = false; txtDesc.Visible = false; lblURL.Visible = false; txtURL.Visible = false; lblLocs.Visible = false; rblLocs.Visible = false; loadDeliver(); } else if (Session["Part"].ToString() == "SCountries") { DataGrid2.Visible = false; lblContents2.Visible = false; updateCSCountries(); loadDeliver(); } else if (Session["Part"].ToString() == "Countries") { updateGrid3(); DataGrid3.Visible = false; loadCSCountries(); } else if (Session["Part"].ToString() == "SStates") { DataGrid4.Visible = false; lblCountryName.Text = ""; updateCSStates(); loadCSCountries(); } else if (Session["Part"].ToString() == "States") { updateGrid5(); Session["StatesId"]= null; Session["StateName"] = null; DataGrid5.Visible = false; loadCSStates(); } else if (Session["Part"].ToString() == "SLocs") { DataGrid4.Columns[2].Visible = true; DataGrid4.Columns[3].Visible = true; if (Session["StatesId"] != null) { loadCSStates(); } else { DataGrid4.Visible = false; loadCSCountries(); } } else if (Session["Part"].ToString() == "Locs") { updateGrid5(); DataGrid5.Visible = false; loadCSLocs(); } else if (Session["Part"].ToString() == "LocsAdd") { //updateLocs(); lblURL.Visible = false; txtURL.Visible = false; btnAdd.Visible = false; addLocation(); Locs(); } } private void Exit() { Response.Redirect(strURL + Session["CCP"].ToString() + ".aspx?"); } protected void GridDeliver_ItemCommand(object source, DataGridCommandEventArgs e) { if (e.CommandName == "Remove") { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; if (Session["MgrOption"].ToString() == "Procure") { cmd.CommandText = "fms_DeleteContractProcure"; } else if (Session["MgrOption"].ToString() == "Supply") { cmd.CommandText = "fms_DeleteContractSupplies"; } cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@Id", SqlDbType.Int); cmd.Parameters["@Id"].Value = e.Item.Cells[0].Text; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); loadDeliver(); } else /********** Leaving Part Deliver****************************************************************/ /********************************************************************************************/ { GridDeliver.Visible = false; lblContents1.Visible = false; Session["Id"] = e.Item.Cells[0].Text; lblContractItem.Text = "Supply Item: " + e.Item.Cells[3].Text; /********************************************************************************************/ /********** Part Service Details: Description, URL and Locations****************************************/ /********************************************************************************************/ if (e.CommandName == "Details") { Session["Part"] = "Details"; btnAdd.Visible = false; lblContents1.Text = "Please provide further details for this item as indicated below."; lblDesc.Visible = true; txtDesc.Visible = true; lblURL.Text = "If you have a website that describes" + " this good or service and/or allows the user to order it online, " + "please enter the complete website address below."; lblURL.Visible = true; txtURL.Visible = true; lblLocs.Visible = true; rblLocs.Visible = true; SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_RetreiveContractSupplies"; cmd.Parameters.Add("@Id", SqlDbType.Int); cmd.Parameters["@Id"].Value = e.Item.Cells[0].Text; cmd.Connection = this.epsDbConn; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "Details"); if (ds.Tables["Details"].Rows.Count == 1) { txtDesc.Text = ds.Tables["Details"].Rows[0][0].ToString(); if (ds.Tables["Details"].Rows[0][1].ToString() == "1") { rblLocs.SelectedIndex = GetIndexOfLocations("Any"); } else { rblLocs.SelectedIndex = GetIndexOfLocations("Specified"); } } } /********************************************************************************************/ /********** Part: Contract Service Countries*************************************************************/ /********************************************************************************************/ else if (e.CommandName == "CSCountries") { loadCSCountries(); } } } } }
// Lucene version compatibility level 4.8.1 using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Analysis.Util; using Lucene.Net.Util; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Text; using Console = Lucene.Net.Util.SystemConsole; using Version = Lucene.Net.Util.LuceneVersion; namespace Lucene.Net.Analysis.Core { /* * 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. */ public class TestStopFilter : BaseTokenStreamTestCase { // other StopFilter functionality is already tested by TestStopAnalyzer [Test] public virtual void TestExactCase() { StringReader reader = new StringReader("Now is The Time"); CharArraySet stopWords = new CharArraySet(TEST_VERSION_CURRENT, new string[] { "is", "the", "Time" }, false); TokenStream stream = new StopFilter(TEST_VERSION_CURRENT, new MockTokenizer(reader, MockTokenizer.WHITESPACE, false), stopWords); AssertTokenStreamContents(stream, new string[] { "Now", "The" }); } [Test] public virtual void TestStopFilt() { StringReader reader = new StringReader("Now is The Time"); string[] stopWords = new string[] { "is", "the", "Time" }; CharArraySet stopSet = StopFilter.MakeStopSet(TEST_VERSION_CURRENT, stopWords); TokenStream stream = new StopFilter(TEST_VERSION_CURRENT, new MockTokenizer(reader, MockTokenizer.WHITESPACE, false), stopSet); AssertTokenStreamContents(stream, new string[] { "Now", "The" }); } /// <summary> /// Test Position increments applied by StopFilter with and without enabling this option. /// </summary> [Test] public virtual void TestStopPositons() { StringBuilder sb = new StringBuilder(); List<string> a = new List<string>(); for (int i = 0; i < 20; i++) { string w = English.Int32ToEnglish(i).Trim(); sb.Append(w).Append(" "); if (i % 3 != 0) { a.Add(w); } } log(sb.ToString()); string[] stopWords = a.ToArray(); for (int i = 0; i < a.Count; i++) { log("Stop: " + stopWords[i]); } CharArraySet stopSet = StopFilter.MakeStopSet(TEST_VERSION_CURRENT, stopWords); // with increments StringReader reader = new StringReader(sb.ToString()); #pragma warning disable 612, 618 StopFilter stpf = new StopFilter(Version.LUCENE_40, new MockTokenizer(reader, MockTokenizer.WHITESPACE, false), stopSet); DoTestStopPositons(stpf, true); // without increments reader = new StringReader(sb.ToString()); stpf = new StopFilter(Version.LUCENE_43, new MockTokenizer(reader, MockTokenizer.WHITESPACE, false), stopSet); #pragma warning restore 612, 618 DoTestStopPositons(stpf, false); // with increments, concatenating two stop filters List<string> a0 = new List<string>(); List<string> a1 = new List<string>(); for (int i = 0; i < a.Count; i++) { if (i % 2 == 0) { a0.Add(a[i]); } else { a1.Add(a[i]); } } string[] stopWords0 = a0.ToArray(); for (int i = 0; i < a0.Count; i++) { log("Stop0: " + stopWords0[i]); } string[] stopWords1 = a1.ToArray(); for (int i = 0; i < a1.Count; i++) { log("Stop1: " + stopWords1[i]); } CharArraySet stopSet0 = StopFilter.MakeStopSet(TEST_VERSION_CURRENT, stopWords0); CharArraySet stopSet1 = StopFilter.MakeStopSet(TEST_VERSION_CURRENT, stopWords1); reader = new StringReader(sb.ToString()); StopFilter stpf0 = new StopFilter(TEST_VERSION_CURRENT, new MockTokenizer(reader, MockTokenizer.WHITESPACE, false), stopSet0); // first part of the set #pragma warning disable 612, 618 stpf0.SetEnablePositionIncrements(true); #pragma warning restore 612, 618 StopFilter stpf01 = new StopFilter(TEST_VERSION_CURRENT, stpf0, stopSet1); // two stop filters concatenated! DoTestStopPositons(stpf01, true); } // LUCENE-3849: make sure after .end() we see the "ending" posInc [Test] public virtual void TestEndStopword() { CharArraySet stopSet = StopFilter.MakeStopSet(TEST_VERSION_CURRENT, "of"); StopFilter stpf = new StopFilter(TEST_VERSION_CURRENT, new MockTokenizer(new StringReader("test of"), MockTokenizer.WHITESPACE, false), stopSet); AssertTokenStreamContents(stpf, new string[] { "test" }, new int[] { 0 }, new int[] { 4 }, null, new int[] { 1 }, null, 7, 1, null, true, null); } private void DoTestStopPositons(StopFilter stpf, bool enableIcrements) { log("---> test with enable-increments-" + (enableIcrements ? "enabled" : "disabled")); #pragma warning disable 612, 618 stpf.SetEnablePositionIncrements(enableIcrements); #pragma warning restore 612, 618 ICharTermAttribute termAtt = stpf.GetAttribute<ICharTermAttribute>(); IPositionIncrementAttribute posIncrAtt = stpf.GetAttribute<IPositionIncrementAttribute>(); stpf.Reset(); for (int i = 0; i < 20; i += 3) { assertTrue(stpf.IncrementToken()); log("Token " + i + ": " + stpf); string w = English.Int32ToEnglish(i).Trim(); assertEquals("expecting token " + i + " to be " + w, w, termAtt.ToString()); assertEquals("all but first token must have position increment of 3", enableIcrements ? (i == 0 ? 1 : 3) : 1, posIncrAtt.PositionIncrement); } assertFalse(stpf.IncrementToken()); stpf.End(); stpf.Dispose(); } // print debug info depending on VERBOSE private static void log(string s) { if (Verbose) { Console.WriteLine(s); } } // stupid filter that inserts synonym of 'hte' for 'the' private sealed class MockSynonymFilter : TokenFilter { internal State bufferedState; internal ICharTermAttribute termAtt; internal IPositionIncrementAttribute posIncAtt; internal MockSynonymFilter(TokenStream input) : base(input) { termAtt = AddAttribute<ICharTermAttribute>(); posIncAtt = AddAttribute<IPositionIncrementAttribute>(); } public override sealed bool IncrementToken() { if (bufferedState != null) { RestoreState(bufferedState); posIncAtt.PositionIncrement = 0; termAtt.SetEmpty().Append("hte"); bufferedState = null; return true; } else if (m_input.IncrementToken()) { if (termAtt.ToString().Equals("the", StringComparison.Ordinal)) { bufferedState = CaptureState(); } return true; } else { return false; } } public override void Reset() { base.Reset(); bufferedState = null; } } [Test] public virtual void TestFirstPosInc() { Analyzer analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) => { Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); TokenFilter filter = new MockSynonymFilter(tokenizer); #pragma warning disable 612, 618 StopFilter stopfilter = new StopFilter(Version.LUCENE_43, filter, StopAnalyzer.ENGLISH_STOP_WORDS_SET); stopfilter.SetEnablePositionIncrements(false); #pragma warning restore 612, 618 return new TokenStreamComponents(tokenizer, stopfilter); }); AssertAnalyzesTo(analyzer, "the quick brown fox", new string[] { "hte", "quick", "brown", "fox" }, new int[] { 1, 1, 1, 1 }); } } }